hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8869c530483f17355d8fb24b24a2f801b994fc7a
| 811
|
cpp
|
C++
|
EDCBSupport/EDCBSupport/StatusBar.cpp
|
abt8WG/EDCB
|
669262b158a25e1c84443ff00597fc981fa78aa6
|
[
"MIT"
] | 13
|
2016-04-26T09:00:46.000Z
|
2021-04-17T00:24:01.000Z
|
EDCBSupport/EDCBSupport/StatusBar.cpp
|
abt8WG/EDCB
|
669262b158a25e1c84443ff00597fc981fa78aa6
|
[
"MIT"
] | 16
|
2016-07-02T07:43:51.000Z
|
2016-10-13T23:03:32.000Z
|
EDCBSupport/EDCBSupport/StatusBar.cpp
|
abt8WG/EDCB
|
669262b158a25e1c84443ff00597fc981fa78aa6
|
[
"MIT"
] | 9
|
2015-11-26T12:12:24.000Z
|
2019-09-23T02:40:02.000Z
|
#include "stdafx.h"
#include "EDCBSupport.h"
#include "StatusBar.h"
namespace EDCBSupport
{
CStatusBar::CStatusBar()
{
}
CStatusBar::~CStatusBar()
{
Destroy();
}
bool CStatusBar::Create(HWND hwndParent,INT_PTR ID)
{
Destroy();
m_hwnd=::CreateWindowEx(0,STATUSCLASSNAME,NULL,
WS_CHILD | WS_CLIPSIBLINGS | SBARS_SIZEGRIP,
0,0,0,0,
hwndParent,
reinterpret_cast<HMENU>(ID),
g_hinstDLL,NULL);
if (m_hwnd==NULL)
return false;
return true;
}
bool CStatusBar::SetText(LPCTSTR pszText)
{
if (m_hwnd==NULL)
return false;
::SendMessage(m_hwnd,SB_SETTEXT,SB_SIMPLEID,reinterpret_cast<LPARAM>(pszText));
::SendMessage(m_hwnd,SB_SIMPLE,TRUE,0);
return true;
}
} // namespace EDCBSupport
| 16.55102
| 82
| 0.633785
|
abt8WG
|
886b9a9a31b4a81273f54697a992fa197c725052
| 3,238
|
cc
|
C++
|
server/core/test/test_service.cc
|
tut-blog/MaxScale
|
cabd6dba0665cb8025c694acf98cffaa68d10de0
|
[
"MIT"
] | null | null | null |
server/core/test/test_service.cc
|
tut-blog/MaxScale
|
cabd6dba0665cb8025c694acf98cffaa68d10de0
|
[
"MIT"
] | 1
|
2019-07-02T09:59:27.000Z
|
2019-07-02T09:59:49.000Z
|
server/core/test/test_service.cc
|
tut-blog/MaxScale
|
cabd6dba0665cb8025c694acf98cffaa68d10de0
|
[
"MIT"
] | null | null | null |
/*
* Copyright (c) 2016 MariaDB Corporation Ab
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file and at www.mariadb.com/bsl11.
*
* Change Date: 2022-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2 or later of the General
* Public License.
*/
/**
*
* @verbatim
* Revision History
*
* Date Who Description
* 08-09-2014 Martin Brampton Initial implementation
*
* @endverbatim
*/
// To ensure that ss_info_assert asserts also when builing in non-debug mode.
#if !defined (SS_DEBUG)
#define SS_DEBUG
#endif
#if defined (NDEBUG)
#undef NDEBUG
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <maxscale/maxscale_test.h>
#include <maxscale/paths.h>
#include <maxscale/alloc.h>
#include "../internal/service.hh"
#include "test_utils.h"
#include "../config.cc"
/**
* test1 Allocate a service and do lots of other things
*
*/
static int test1()
{
Service* service;
MXS_SESSION* session;
DCB* dcb;
int result;
int argc = 3;
init_test_env(NULL);
set_libdir(MXS_STRDUP_A("../../modules/authenticator/MySQLAuth/"));
load_module("mysqlauth", MODULE_AUTHENTICATOR);
set_libdir(MXS_STRDUP_A("../../modules/protocol/MySQL/mariadbclient/"));
load_module("mariadbclient", MODULE_PROTOCOL);
set_libdir(MXS_STRDUP_A("../../modules/routing/readconnroute/"));
load_module("readconnroute", MODULE_ROUTER);
/* Service tests */
fprintf(stderr,
"testservice : creating service called MyService with router nonexistent");
service = service_alloc("MyService", "non-existent", NULL);
mxb_assert_message(NULL == service, "New service with invalid router should be null");
mxb_assert_message(0 == service_isvalid(service), "Service must not be valid after incorrect creation");
fprintf(stderr, "\t..done\nValid service creation, router testroute.");
service = service_alloc("MyService", "readconnroute", NULL);
mxb_assert_message(NULL != service, "New service with valid router must not be null");
mxb_assert_message(0 != service_isvalid(service), "Service must be valid after creation");
mxb_assert_message(0 == strcmp("MyService", service->name), "Service must have given name");
fprintf(stderr, "\t..done\nAdding protocol testprotocol.");
mxb_assert_message(serviceCreateListener(service,
"TestProtocol",
"mariadbclient",
"localhost",
9876,
"MySQLAuth",
NULL,
NULL),
"Add Protocol should succeed");
mxb_assert_message(0 != serviceHasListener(service, "TestProtocol", "mariadbclient", "localhost", 9876),
"Service should have new protocol as requested");
return 0;
}
int main(int argc, char** argv)
{
int result = 0;
result += test1();
exit(result);
}
| 32.38
| 108
| 0.622915
|
tut-blog
|
886e28f31fc3ecf418f93e2e80ff6995594f4255
| 1,122
|
hpp
|
C++
|
tests/utils/include/utils/test.hpp
|
hhb584520/DML
|
014eb9894e85334f03ec74435933c972f3d05b50
|
[
"MIT"
] | null | null | null |
tests/utils/include/utils/test.hpp
|
hhb584520/DML
|
014eb9894e85334f03ec74435933c972f3d05b50
|
[
"MIT"
] | null | null | null |
tests/utils/include/utils/test.hpp
|
hhb584520/DML
|
014eb9894e85334f03ec74435933c972f3d05b50
|
[
"MIT"
] | 1
|
2022-03-28T07:52:21.000Z
|
2022-03-28T07:52:21.000Z
|
/*******************************************************************************
* Copyright (C) 2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
******************************************************************************/
#ifndef DML_TESTING_ACTUAL_API_HPP
#define DML_TESTING_ACTUAL_API_HPP
#if !defined(OS_WINDOWS) && !defined(OS_UNIX)
#error "Operating system is undefined!"
#endif
#if !defined(C_API) && !defined(CPP_API)
#error "API is undefined!"
#endif
#if !defined(SW_PATH) && !defined(HW_PATH) && !defined(AUTO_PATH)
#error "Execution path is undefined!"
#endif
#ifdef C_API
#include <dml/dml.h>
#include <utils/job.hpp>
#ifdef SW_PATH
constexpr auto execution_path = DML_PATH_SW;
#endif
#ifdef HW_PATH
constexpr auto execution_path = DML_PATH_HW;
#endif
#ifdef AUTO_PATH
constexpr auto execution_path = DML_PATH_AUTO;
#endif
#endif
#ifdef CPP_API
#include <dml/dml.hpp>
#ifdef SW_PATH
using execution_path = dml::software;
#endif
#ifdef HW_PATH
using execution_path = dml::hardware;
#endif
#ifdef AUTO_PATH
using execution_path = dml::automatic;
#endif
#endif
#endif// ACTUAL_API_HPP
| 20.035714
| 80
| 0.651515
|
hhb584520
|
886ef9a9c147b1c0edd663e41011c9498d00fdd1
| 5,241
|
cxx
|
C++
|
example/example-1/main.cxx
|
usagi/wonderland.subsystem
|
342b3dc2489f9a12d6dba43fca7d7a2a0854e144
|
[
"MIT"
] | 1
|
2015-08-29T00:14:05.000Z
|
2015-08-29T00:14:05.000Z
|
example/example-1/main.cxx
|
usagi/wonderland.subsystem
|
342b3dc2489f9a12d6dba43fca7d7a2a0854e144
|
[
"MIT"
] | null | null | null |
example/example-1/main.cxx
|
usagi/wonderland.subsystem
|
342b3dc2489f9a12d6dba43fca7d7a2a0854e144
|
[
"MIT"
] | null | null | null |
#include <chrono>
#include <thread>
#include <iostream>
#include <iomanip>
#include <boost/property_tree/ini_parser.hpp>
#ifdef EMSCRIPTEN
#include <emscripten/emscripten.h>
#endif
// define or take a compiler option: c++ ... -DWRP_WONDERLAND_SUBSYSTEM_GLFW3 main.cxx
//#define WRP_WONDERLAND_SUBSYSTEM_GLFW3
//#define WRP_WONDERLAND_SUBSYSTEM_GLFW2
// include subsystem
#include <wonder_rabbit_project/wonderland.subsystem.hxx>
int main()
{
// using
using wonder_rabbit_project::wonderland::subsystem::subsystem_t;
using wonder_rabbit_project::wonderland::subsystem::key;
// generate the subsystem
auto subsystem = std::make_shared<subsystem_t>();
// get initialize params ( not need if initilize with default settings )
auto ips = subsystem -> default_initialize_params();
// print ips in INI(1)
std::cerr << "\n -- print ips in INI(1) -- \n";
boost::property_tree::write_ini(std::cerr, ips);
// change title
ips.put
("title"
, std::string("hello, subsystem ") + subsystem->name()
+ " version " + subsystem->version().to_string()
);
// print ips in INI(2)
std::cerr << "\n -- print ips in INI(2) -- \n";
boost::property_tree::write_ini(std::cerr, ips);
// initialize the subsystem
subsystem -> initialize( std::move(ips) );
// invoke world pattern 1: consign main-loop to subsystem
// set your world update code
const auto keyboard_test = [ &subsystem ]
{
auto key_counter = 0;
for ( auto key = 0; key < 255; ++key )
if ( subsystem -> keyboard_state( key ) )
{
++key_counter;
std::cerr << key << " ";
}
if ( key_counter )
std::cerr << "\n";
};
const auto pointing_test = [ &subsystem ]
{
auto button_counter = 0;
for ( auto button = 0; button < 8; ++button )
if ( subsystem -> pointing_states_button( button ) )
{
++button_counter;
std::cerr << "pointing_button[" << button << "] ";
}
if ( button_counter )
{
const auto position = subsystem -> pointing_states_position();
std::cerr
<< " with position("
<< position.x << ", "
<< position.y << ")\n";
}
const auto wheel = subsystem -> pointing_states_wheel();
if ( wheel.x not_eq 0 )
std::cerr << "wheel-dx: " << wheel.x << "\n";
if ( wheel.y not_eq 0 )
std::cerr << "wheel-dy: " << wheel.y << "\n";
};
const auto joystick_test = [ &subsystem ]
{
for ( const auto joystick : subsystem -> joysticks_states() )
{
const auto& digitals = joystick.digitals();
const auto& analogs = joystick.analogs();
const auto& balls = joystick.balls();
const auto& hats = joystick.hats();
if
( std::any_of(std::begin(digitals), std::end(digitals), [](const bool v){ return v; } )
or std::any_of(std::begin(hats), std::end(hats), [](const glm::vec2& v){ return v not_eq glm::vec2(); } )
)
{
std::cerr << joystick.name() << ": D{ ";
for ( const auto digital : digitals )
std::cerr << digital << " ";
std::cerr << "} A{ ";
for ( const auto analog : analogs )
std::cerr << std::setw(5) << std::right << std::setprecision(2) << std::fixed << analog << " ";
std::cerr << "} B{ ";
for ( const auto ball : balls )
std::cerr << "(" << ball.x << "," << ball.y << ") ";
std::cerr << "} H{ ";
for ( const auto hat : hats )
std::cerr << "(" << hat.x << "," << hat.y << ") ";
std::cerr << "}\n";
}
}
};
const auto esc_to_exit = [ &subsystem ]
{
if ( subsystem -> keyboard_state< key::escape >() )
subsystem -> to_continue( false );
};
subsystem -> update_functors.emplace_front( keyboard_test );
subsystem -> update_functors.emplace_front( pointing_test );
subsystem -> update_functors.emplace_front( joystick_test );
subsystem -> update_functors.emplace_front( esc_to_exit );
subsystem -> update_functors.emplace_front( []
{
// do update your world
} );
// set your world render code
//#ifndef EMSCRIPTEN
const auto adjust_wait = [ ]
{
static auto before = std::chrono::high_resolution_clock::now();
const auto elapsed = std::chrono::high_resolution_clock::now() - before;
const auto wait = std::chrono::milliseconds(100) - elapsed;
std::this_thread::sleep_for(wait);
before = std::chrono::high_resolution_clock::now();
};
//#endif
subsystem -> render_functors.emplace_front( []
{
// do render your world
} );
//#ifndef EMSCRIPTEN
subsystem -> render_functors.emplace_front( adjust_wait );
//#endif
// invoke your world
subsystem -> invoke();
// invoke world pattern 2: original main-loop system with use subsystem
/*
#ifdef EMSCRIPTEN
emscripten_set_main_loop( []
#else
do
#endif
{
subsystem -> before_update();
// do update world
{ }
subsystem -> after_update();
subsystem -> before_render();
// do render with GL(glXxx)
{ }
subsystem -> after_render();
}
#ifdef EMSCRIPTEN
, 0, 1);
#else
while ( subsystem -> to_continue );
#endif
*/
}
| 27.584211
| 111
| 0.589964
|
usagi
|
8872016682c7b970e1df80ba5ceed3b6c0728a8d
| 611
|
hpp
|
C++
|
include/lol/def/LolAccountVerificationSendTokenRequest.hpp
|
Maufeat/LeagueAPI
|
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
|
[
"BSD-3-Clause"
] | 1
|
2020-07-22T11:14:55.000Z
|
2020-07-22T11:14:55.000Z
|
include/lol/def/LolAccountVerificationSendTokenRequest.hpp
|
Maufeat/LeagueAPI
|
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
|
[
"BSD-3-Clause"
] | null | null | null |
include/lol/def/LolAccountVerificationSendTokenRequest.hpp
|
Maufeat/LeagueAPI
|
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
|
[
"BSD-3-Clause"
] | 4
|
2018-12-01T22:48:21.000Z
|
2020-07-22T11:14:56.000Z
|
#pragma once
#include "../base_def.hpp"
namespace lol {
struct LolAccountVerificationSendTokenRequest {
std::string mediator;
std::string locale;
std::string device;
};
inline void to_json(json& j, const LolAccountVerificationSendTokenRequest& v) {
j["mediator"] = v.mediator;
j["locale"] = v.locale;
j["device"] = v.device;
}
inline void from_json(const json& j, LolAccountVerificationSendTokenRequest& v) {
v.mediator = j.at("mediator").get<std::string>();
v.locale = j.at("locale").get<std::string>();
v.device = j.at("device").get<std::string>();
}
}
| 32.157895
| 83
| 0.653028
|
Maufeat
|
887c90e853811beaba1fe90e0e5808fad420a766
| 1,965
|
cpp
|
C++
|
src/Frontends/CleanupResources.cpp
|
VANDAL/Sigil2
|
67e0762201d79575a25bdfe59eab257d206cff39
|
[
"BSD-3-Clause"
] | 8
|
2018-12-08T15:35:34.000Z
|
2021-10-25T00:10:51.000Z
|
src/Frontends/CleanupResources.cpp
|
VANDAL/Sigil2
|
67e0762201d79575a25bdfe59eab257d206cff39
|
[
"BSD-3-Clause"
] | 6
|
2018-06-01T23:09:25.000Z
|
2021-01-05T20:15:44.000Z
|
src/Frontends/CleanupResources.cpp
|
mdlui/Sigil2
|
67e0762201d79575a25bdfe59eab257d206cff39
|
[
"BSD-3-Clause"
] | 3
|
2019-11-17T16:13:06.000Z
|
2021-07-23T01:27:59.000Z
|
#include <csignal>
#include <cstdlib>
#include <cstring>
#include <dirent.h>
#include <iostream>
#include <mutex>
namespace Cleanup
{
namespace
{
std::mutex cleanupMtx;
bool initialized;
std::string cleanupDir;
std::terminate_handler prev_terminate_handler;
using signal_handler = void(*)(int);
signal_handler prev_sigint_handler;
signal_handler prev_sigsegv_handler;
auto cleanupHandler()
{
if (cleanupDir.empty() == false)
{
DIR *d = opendir(cleanupDir.c_str());
if (d != nullptr)
{
dirent *dir = readdir(d);
char fullPath[256];
while (dir != nullptr)
{
/* TODO check path length */
sprintf(fullPath, "%s/%s", cleanupDir.c_str(), dir->d_name);
remove(fullPath);
dir = readdir(d);
}
int ret = remove(cleanupDir.c_str());
if (ret < 0)
std::cerr << "error removing " + cleanupDir + " -- " + strerror(errno) << std::endl;
}
}
}
};
auto setCleanupDir(std::string dir) -> void
{
std::lock_guard<std::mutex> lock(cleanupMtx);
if (initialized == false)
{
cleanupDir = dir;
/* Cleanup at normal exit */
std::atexit(cleanupHandler);
/* or SIGINT/SIGSEGV */
auto dummy = [](int){};
prev_sigint_handler = std::signal(SIGINT, dummy);
prev_sigsegv_handler = std::signal(SIGSEGV, dummy);
std::signal(SIGINT, [](int signum){ cleanupHandler(); prev_sigint_handler(signum); });
std::signal(SIGSEGV, [](int signum){ cleanupHandler(); prev_sigsegv_handler(signum); });
/* or unhandled exception */
#if __GNUC__ < 5
prev_terminate_handler = std::abort;
#else
prev_terminate_handler = std::get_terminate();
#endif
std::set_terminate([]{ cleanupHandler(); prev_terminate_handler(); });
initialized = true;
}
}
}; //end namespace Cleanup
| 24.873418
| 100
| 0.588295
|
VANDAL
|
887e2ba4297878ba8019c3f1b93fac2f19b5338e
| 1,218
|
hpp
|
C++
|
src/database/net.hpp
|
martun/verilog_netlist_parser
|
bf616bc5b5dab3e1b93f7740b29774d7dbc72281
|
[
"MIT"
] | 1
|
2018-12-18T02:16:16.000Z
|
2018-12-18T02:16:16.000Z
|
src/database/net.hpp
|
martun/verilog_netlist_parser
|
bf616bc5b5dab3e1b93f7740b29774d7dbc72281
|
[
"MIT"
] | null | null | null |
src/database/net.hpp
|
martun/verilog_netlist_parser
|
bf616bc5b5dab3e1b93f7740b29774d7dbc72281
|
[
"MIT"
] | null | null | null |
#ifndef NET_H
#define NET_H
#include <string>
#include <vector>
class Port;
/// Class for Net.
class Net
{
public:
/** \brief Constructor by name.
* \param[in] name - Name of the Net.
* \param[in] source_port - Source port for the net, if not provided sets to NULL.
*/
Net(const std::string name, const Port * source_port = 0);
/// \brief Getter for the name of the Net.
const std::string& get_name() const;
/// \brief Returns the source port if exists, else throws an exception.
const Port& get_source_port() const;
/** \brief Sets source port.
* \param[in] source_port - New Source Port.
*/
void set_source_port(const Port& source_port);
/// \brief Getter for all the destination ports of the Net.
const std::vector<const Port* >& get_destination_ports() const;
/** \brief Adds a destination port to the Net.
* \param[in] destination_port - New destination Port for this net.
*/
void add_destination_port( const Port * destination_port);
private:
/// Name of the wire.
std::string m_name;
/// Source port for current Net.
const Port * m_source_port;
/// The collection of destination ports for this net.
std::vector<const Port*> m_destination_ports;
};
#endif // NET_H
| 22.981132
| 83
| 0.698686
|
martun
|
88876c8b894fedadd892e259ed9892a30f93f902
| 5,900
|
hpp
|
C++
|
include/circular_buffer.hpp
|
Algorithms-and-Data-Structures-2021/semester-work-circular-buffer
|
7520845b51fd2e16cccfcac247140dd8cc8a459d
|
[
"MIT"
] | null | null | null |
include/circular_buffer.hpp
|
Algorithms-and-Data-Structures-2021/semester-work-circular-buffer
|
7520845b51fd2e16cccfcac247140dd8cc8a459d
|
[
"MIT"
] | null | null | null |
include/circular_buffer.hpp
|
Algorithms-and-Data-Structures-2021/semester-work-circular-buffer
|
7520845b51fd2e16cccfcac247140dd8cc8a459d
|
[
"MIT"
] | 1
|
2021-04-25T19:14:57.000Z
|
2021-04-25T19:14:57.000Z
|
#pragma once
#include <cstddef>
#include <optional>
#include <stdexcept> // logic_error
#include <cassert> // assert
using std::size_t;
// Заголовочный файл с объявлением структуры данных
namespace itis {
// Tip 1: объявите здесь необходимые структуры, функции, константы и прочее
// Пример: объявление константы времени компиляции в заголовочном файле
inline constexpr auto kStringConstant = "Hello, stranger!";
// Пример: объявление структуры с полями и методами
template<class T>
struct circular_buffer {
private:
size_t size_{0};
size_t capacity_{0};
T *data_{nullptr};
size_t tail_{0};
size_t head_{0};
void incrementHead() {
head_ = (head_ + 1) % capacity_;
}
// замыкание кольцевого буфера - после последнего элемента в массиве data_ будет следовать первый
void incrementTail() {
tail_ = (tail_ + 1) % capacity_;
}
void decrementHead() {
if (head_ == 0) /* т.к. тип size_t не может принять отриц. значение, проврка такая */{
head_ = capacity_ - 1;
} else {
head_ -= 1;
}
}
void decrementTail() {
if (tail_ == 0) /* т.к. тип size_t не может принять отриц. значение, проврка такая */{
tail_ = capacity_ - 1;
} else {
tail_ -= 1;
}
}
// Tip 2: На начальном этапе разработки структуры данных можете определения методов задавать в
// заголовочном файле, как только работа будет завершена, можно будет оставить здесь только объявления.
public:
explicit circular_buffer(size_t max_size_) :
data_(new T[max_size_]), capacity_(max_size_) {}
// добавление элемента в конец
void EnqueueBack(T &elem) {
if (isFull()) {
// буфер полон - перезаписываем данные
incrementHead();
incrementTail();
data_[tail_] = elem;
} else if (isEmpty()) {
// буфер пуст - добавляем первый элемент куда угодно, но я решил, что на нулевую позицию
head_ = 0;
tail_ = 0;
data_[tail_] = elem;
size_ += 1;
} else {
// просто добавляем новый элемент в конец
incrementTail();
data_[tail_] = elem;
size_ += 1;
}
}
// добавление элемента в начало
void EnqueueFront(T &elem) {
if (isFull()) {
// буфер полон - перезаписываем данные
decrementHead();
decrementTail();
data_[head_] = elem;
} else if (isEmpty()) {
// буфер пуст - добавляем первый элемент куда угодно, но я решил, что на нулевую позицию
head_ = 0;
tail_ = 0;
data_[head_] = elem;
size_ += 1;
} else {
// просто добавляем новый элемент в конец
decrementHead();
data_[head_] = elem;
size_ += 1;
}
}
// взятие элемента с конца и его удаление
T DequeueBack() {
if (isEmpty()) {
// из пустого буфера нечего удалять
throw std::logic_error("cannot dequeue from empty buffer");
}
T to_return;
if (size() == 1) {
// в случае одного элемента нет нужды в том чтобы перемещать индекс после очищения буфера
to_return = data_[tail_];
size_ = 0;
} else {
// просто перемещаем указатель, тем самым разрешая перезаписать элемент, к нему больше не будет доступа
to_return = data_[tail_];
decrementTail();
size_ -= 1;
}
return to_return;
}
// взятие элемента с начала и его удаление
T DequeueFront() {
if (isEmpty()) {
// из пустого буфера нечего удалять
throw std::logic_error("cannot dequeue from empty buffer");
}
T to_return;
if (size() == 1) {
// в случае одного элемента нет нужды в том чтобы перемещать индекс после очищения буфера
to_return = data_[head_];
size_ = 0;
} else {
// просто перемещаем указатель, тем самым разрешая перезаписать элемент, к нему больше не будет доступа
to_return = data_[head_];
incrementHead();
size_ -= 1;
}
return to_return;
}
// получение элемента с конца без его удаления
std::optional<T> getFront() const {
return size_ == 0 ? std::nullopt : std::make_optional(data_[head_]);
}
// получение элемента с начала без его удаления
std::optional<T> getBack() const {
return size_ == 0 ? std::nullopt : std::make_optional(data_[tail_]);
}
bool isFull() const {
return size_ == capacity_;
}
bool isEmpty() const {
return size_ == 0;
}
size_t size() const {
return size_;
}
size_t capacity() const {
return capacity_;
}
// увеличение вместительности буфера
void Resize(size_t new_capacity) {
assert(new_capacity > capacity_);
T *new_data = new T[new_capacity];
if (head_ <= tail_) {
// первый случай - начало левее конца: [x, x, 1, 2, 3, 4, x]
std::copy(data_ + head_, data_ + tail_ + 1, new_data);
} else {
// второй случай - начало правее конца: [3, 4, x, x, x, 1, 2]
std::copy(data_ + head_, data_ + capacity_, new_data);
std::copy(data_, data_ + tail_ + 1, new_data + capacity_ - head_);
}
if (size_ > 0) {
// данные переместились в начало массива - обновим указатели
head_ = 0;
tail_ = size_ - 1;
}
capacity_ = new_capacity;
// высвободим память из-под старого массива
delete[] data_;
data_ = new_data;
}
void Clear() {
// менять значения указателей необязательно, они все равно поменяются, если добавить в пустой буфер элемент
size_ = 0;
}
~circular_buffer() {
tail_ = 0;
head_ = 0;
size_ = 0;
capacity_ = 0;
// не забываем высвободить память
delete[] data_;
data_ = nullptr;
}
};
} // namespace itis
| 27.962085
| 113
| 0.589492
|
Algorithms-and-Data-Structures-2021
|
88884f168d3fc8582b42bf0cbcb746c51033c860
| 1,144
|
cpp
|
C++
|
leetCode/MajorityElement.cpp
|
ChairInkitchenAmer/study
|
56650ccb1c9879f22cbd692883db7f26f5a8c54b
|
[
"Apache-2.0"
] | null | null | null |
leetCode/MajorityElement.cpp
|
ChairInkitchenAmer/study
|
56650ccb1c9879f22cbd692883db7f26f5a8c54b
|
[
"Apache-2.0"
] | null | null | null |
leetCode/MajorityElement.cpp
|
ChairInkitchenAmer/study
|
56650ccb1c9879f22cbd692883db7f26f5a8c54b
|
[
"Apache-2.0"
] | null | null | null |
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
class Solution {
public:
int majorityElement(vector<int>& nums) {
unordered_map<int,int> map;
if(nums.size() == 1){
return nums[0];
}
for(int i=0; i < nums.size(); i++){
auto item = map.find(nums[i]);
if(item != map.end() && item->second +1 > nums.size()/2){
return item->first;
} else {
map[nums[i]]++;
}
}
return -1;
}
};
class Solution1 {
public:
int majorityElement(vector<int>& nums) {
sort(nums.begin(), nums.end());
int lastValue=0;
int lastCount=0;
for(int i=0; i< nums.size(); i++){
if(nums[i]== lastValue){
lastCount++;
} else{
lastValue=nums[i];
lastCount=1;
}
if(lastCount > nums.size() / 2){
return lastValue;
}
}
return -1;
}
};
| 21.185185
| 69
| 0.414336
|
ChairInkitchenAmer
|
8888ca65a0b111d92522e95eeb4592d34962bd30
| 1,100
|
cpp
|
C++
|
CPPProgramExample/LAB04/LAB04/CLASS02.cpp
|
mahmoudShaheen/RandomCollegeProjects
|
6bcede0ad8b09ac738d8f49e6fed6d2b7a111cfd
|
[
"MIT"
] | null | null | null |
CPPProgramExample/LAB04/LAB04/CLASS02.cpp
|
mahmoudShaheen/RandomCollegeProjects
|
6bcede0ad8b09ac738d8f49e6fed6d2b7a111cfd
|
[
"MIT"
] | null | null | null |
CPPProgramExample/LAB04/LAB04/CLASS02.cpp
|
mahmoudShaheen/RandomCollegeProjects
|
6bcede0ad8b09ac738d8f49e6fed6d2b7a111cfd
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <windows.h>
#include <process.h>
#include <conio.h>
using namespace std;
class point{
int x,y;
public:
point (int u, int v){x=u; y=v;}
// function definition -- requires windows.h
void gotoxy()
{
HANDLE hConsoleOutput;
COORD dwCursorPosition;
cout.flush();
dwCursorPosition.X= x;
dwCursorPosition.Y= y;
hConsoleOutput= GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(hConsoleOutput,dwCursorPosition);
}
int operator <=(point p)
{return (x<=p.x && y<=p.y);}
int operator >=(point p)
{return (x>=p.x && y>=p.y);}
point operator +=(point p)
{return point(x+=p.x, y+=p.y);}
};
int main()
{
system("cls"); // function definition -- requires process.h
for (point p1(20,5);p1<=point(60,5);p1+=point(1,0))
{p1.gotoxy(); _putch('*');}
for (point p4(60,5);p4<=point(60,20);p4+=point(0,1))
{p4.gotoxy(); _putch('*');}
for (point p2(60,20);p2>=point(20,20);p2+=point(-1,0))
{p2.gotoxy (); _putch('*');}
for (point p3(20,5);p3<=point(20,20);p3+=point(0,1))
{p3.gotoxy(); _putch('*');}
cout<<"\n";
return 0;
}
| 22.44898
| 63
| 0.621818
|
mahmoudShaheen
|
888a058571d9a181953e547daae797b61c5b4041
| 17,894
|
cpp
|
C++
|
esp32/TinyCPCEMttgovga32/CPCem/FDC.cpp
|
rpsubc8/ESP32TinyCPC
|
386a0d1d47fc6f32c0b3dace67a6c2197a846a9d
|
[
"WTFPL"
] | 19
|
2020-12-04T15:12:45.000Z
|
2022-02-07T19:46:36.000Z
|
esp32/TinyCPCEMttgovga32/CPCem/FDC.cpp
|
rpsubc8/ESP32TinyCPC
|
386a0d1d47fc6f32c0b3dace67a6c2197a846a9d
|
[
"WTFPL"
] | 3
|
2021-02-20T08:42:09.000Z
|
2022-03-11T05:11:26.000Z
|
esp32/TinyCPCEMttgovga32/CPCem/FDC.cpp
|
rpsubc8/ESP32TinyCPC
|
386a0d1d47fc6f32c0b3dace67a6c2197a846a9d
|
[
"WTFPL"
] | 4
|
2021-02-20T08:07:04.000Z
|
2022-03-27T21:52:45.000Z
|
//C72B - try command
//A9B0
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "FDC.h"
#include "gb_globals.h"
#include "dataFlash/gbdsk.h"
#include <iostream>
//unsigned char gb_select_dsk_disk=0;
//int gb_ptrBeginDataDisc[42][11]; //Donde empieza el disco
int startreal;
unsigned char discon;
int endread;
int fdcint=0;
unsigned char fdcstatus=0x80;
int params=0;
int readparams=0;
unsigned char paramdat[16]; //Escrive disco revisar
unsigned char command;
unsigned char st0,st1,st2,st3;
int fdctrack;
int starttrack,startsector,endsector;
int posinsector;
unsigned char reading=0;
Tdiscsect *discsects;
//JJ int disctracks; //no lo necesito
//JJ int discsects[40]; //esta en rom
//JJ unsigned char discdat[42][11][512];
//unsigned char discid[42][11][4];
Tdiscid *discid;
Tdiscdat *discdat;
using namespace std;
void dumpdisc()
{
//JJ FILE *f=fopen("disk.dmp","wb");
//JJ fwrite(discdat[0][0],512,1,f);
//JJ fclose(f);
}
void loaddsk2Flash(unsigned char id)
{
discid = (Tdiscid *)gb_list_dsk_discid[id];
discdat = (Tdiscdat *)gb_list_dsk_discdat[id];;
/* int contBuffer=0;
int numsect;
int c,d;
char head[40];
unsigned char dskhead[256],trkhead[256];
gb_select_dsk_disk = id;
memcpy(dskhead,&gb_list_dsk_data[id][contBuffer],256);
cout<<"Fichero "<<dskhead<<"\n";
contBuffer+= 256;
for (c=0;c<40;c++) head[c]=0;
for (c=0;c<0x21;c++) head[c]=dskhead[c];
disctracks=dskhead[0x30];
//printf ("Head\nDisc tracks %d ",disctracks);
for (d=0;d<disctracks;d++)
{
memcpy(trkhead,&gb_list_dsk_data[id][contBuffer],256);
contBuffer+= 256;
//cout<< "cont " <<contBuffer<<"\n";
while (strncmp((const char *)trkhead,"Track-Info",10) && contBuffer< gb_list_dsk_size[id])
{//194816 bytes normalmente
memcpy(trkhead,&gb_list_dsk_data[id][contBuffer],256);
contBuffer+= 256;
//printf ("cont %d\n", contBuffer);
if (contBuffer > gb_list_dsk_size[id])
return;
}
discsects[d]=numsect=trkhead[0x15];
//printf ("Num sects %d\n", numsect);
for (c=0;c<numsect;c++)
{
//if (c == 0)
//{
// gb_ptrBeginDataDisc[d] = contBuffer; //Donde empieza disco
// printf("Disco begin %d Track ",gb_ptrBeginDataDisc[d],d);
//}
discid[d][c][0]=trkhead[0x18+(c<<3)];
discid[d][c][1]=trkhead[0x19+(c<<3)];
discid[d][c][2]=trkhead[0x1A+(c<<3)];
discid[d][c][3]=trkhead[0x1B+(c<<3)];
//printf("%i %i %i %i ",discid[d][c][0],discid[d][c][1],discid[d][c][2],discid[d][c][3]);
//JJ memcpy(&(discdat[d][(discid[d][c][2]-1)&15]),&(gb_list_dsk_data[id][contBuffer]),512);
gb_ptrBeginDataDisc[d][c]=contBuffer;
//printf("Begin Track:%d Sector:%d Address:%d\n",d,c,gb_ptrBeginDataDisc[d][c]);
contBuffer+= 512;
}
}
//printf ("\n");
*/
}
/*
void loaddsk()
{
int numsect;
int c,d;
char head[40];
unsigned char dskhead[256],trkhead[256];
FILE *f=fopen(discname,"rb");
if (!f) return;
fread(dskhead,256,1,f);
for (c=0;c<40;c++) head[c]=0;
for (c=0;c<0x21;c++) head[c]=dskhead[c];
disctracks=dskhead[0x30];
// printf("%i tracks\n",dskhead[0x30]);
// printf("%s\n",head);
for (d=0;d<disctracks;d++)
{
fread(trkhead,256,1,f);
//JJ while (strncmp(trkhead,"Track-Info",10) && !feof(f))
while (strncmp((const char *)trkhead,"Track-Info",10) && !feof(f))
fread(trkhead,256,1,f);
// printf("Track %i ftell %05X : ",d,ftell(f)-256);
if (feof(f))
{
fclose(f);
return;
}
discsects[d]=numsect=trkhead[0x15];
// printf("%i sectors\n",discsects[d]);
for (c=0;c<numsect;c++)
{
discid[d][c][0]=trkhead[0x18+(c<<3)];
discid[d][c][1]=trkhead[0x19+(c<<3)];
discid[d][c][2]=trkhead[0x1A+(c<<3)];
discid[d][c][3]=trkhead[0x1B+(c<<3)];
// printf("%i %i %i %i ",discid[d][c][0],discid[d][c][1],discid[d][c][2],discid[d][c][3]);
//JJ fread(discdat[d][(discid[d][c][2]-1)&15],512,1,f);
}
// printf("\n");
}
// printf("DSK pos %i\n",ftell(f));
fclose(f);
}
*/
unsigned char readfdc(unsigned short addr)
{
unsigned char aux_discdat/*[11]*/[1024];
int c;
unsigned char temp;
// printf("Read %04X %04X\n",addr,pc);
if (addr&1)
{
if (!readparams)
{
//printf("Reading but no params - last command %02X\n",command);
exit(-1);
}
switch (command)
{
case 0x04: //Sense drive status
readparams=0;
fdcstatus=0x80;
return st3;
case 0x06: //Read sectors
if (reading)
{
temp=discdat->datos[fdctrack][startsector-1][posinsector];
// printf("Read track %i sector %i pos %i\n",fdctrack,startreal,posinsector);
// printf("%c",temp);
posinsector++;
if (posinsector==512)
{
if ((startsector&15)==(endsector&15))
{
reading=0;
readparams=7;
// output=1;
fdcstatus=0xD0;
// if (startsector==4) output=1;
// printf("Done it %04X\n",pc);
endread=1;
fdcint=1;
discon=0;
// output=1;
// dumpregs();
// dumpram();
// exit(-1);
}
else
{
posinsector=0;
startsector++;
//JJ if ((startsector&15)==(discsects[fdctrack]+1))
if ((startsector&15)==(discsects->datos[fdctrack]+1))
{
if (command&0x80)
fdctrack++;
startsector=0xC1;
}
startreal=0;
for (c=0;c<11;c++)
{
if ((discid->datos[starttrack][c][2]&15)==(startsector&15))
{
startreal=c;
break;
}
}
}
}
return temp;
}
readparams--;
switch (readparams)
{
case 6: st0=0x40; st1=0x80; st2=0; return st0;
case 5: return st1;
case 4: return st2;
case 3: return fdctrack;
case 2: return 0;
case 1: return startsector;
case 0: fdcstatus=0x80; return 2;
}
break;
case 0x86: /*Read sector fail*/
readparams--;
switch (readparams)
{
case 6: st0=0x40; st1=0x84; st2=0; return st0;
case 5: return st1;
case 4: return st2;
case 3: return fdctrack;
case 2: return 0;
case 1: return startsector;
case 0: fdcstatus=0x80; return 2;
}
break;
case 0x08: /*Sense interrupt state*/
readparams--;
if (readparams==1)
return st0;
fdcstatus=0x80;
return fdctrack;
case 0x0A: /*Read sector ID*/
readparams--;
switch (readparams)
{
case 6: return st0;
case 5: return st1;
case 4: return st2;
case 3: return discid->datos[fdctrack][startsector][0];
case 2: return discid->datos[fdctrack][startsector][1];
case 1: return discid->datos[fdctrack][startsector][2];
case 0: fdcstatus=0x80; return discid->datos[fdctrack][startsector][3];
}
break;
default:
//printf("Reading command %02X\n",command);
exit(-1);
}
}
else
{
// if (reading)
// fdcstatus^=0x80;
return fdcstatus;
}
}
void writefdc(unsigned short addr, unsigned char val)
{
int c;
// printf("Write %04X %02X %04X\n",addr,val,pc);
if (addr==0xFA7E)
{
//JJ motoron=val&1;//No necesito estado motor disco
return;
}
if (addr&1)
{
if (params)
{
paramdat[params-1]=val;
params--;
if (!params)
{
switch (command)
{
case 0x03: /*Specify*/
// printf("Specified %02X %02X\n",paramdat[1],paramdat[0]);
fdcstatus=0x80;
break;
case 0x04: /*Sense drive status*/
st3=0x60;
if (!fdctrack) st3|=0x10;
fdcstatus=0xD0;
readparams=1;
break;
case 0x06: /*Read sectors*/
// printf("Read sectors %02X %02X %02X %02X %02X %02X %02X %02X\n",paramdat[7],paramdat[6],paramdat[5],paramdat[4],paramdat[3],paramdat[2],paramdat[1],paramdat[0]);
starttrack=paramdat[6];
startsector=paramdat[4]&15;
endsector=paramdat[2]&15;
startreal=0;
/* for (c=0;c<11;c++)
{
printf("Sector %i ID %02X\n",c,discid[starttrack][c][2]);
if (discid[starttrack][c][2]==paramdat[4])
{
startreal=c;
break;
}
}
if (c==11)
{
printf("Sector %02X not found on track %02X\n",startsector,starttrack);
command=0x86;
reading=0;
readparams=7;
fdcstatus=0xD0;
// exit(-1);
}
else
{*/
// printf("FDC read %02X %02X %i %i %i\n",paramdat[4],endsector,startreal,c,starttrack);
// printf("FDC Read sector track %i start %i end %i\n",starttrack,startsector,endsector);
posinsector=0;
readparams=1;
reading=1;
fdcstatus=0xF0;
// }
// printf("Start - track %i sector %i\n",starttrack,startsector);
break;
case 0x07: /*Recalibrate*/
// printf("Recalibrate %02X\n",paramdat[0]);
fdcstatus=0x80;
fdctrack=0;
fdcint=1;
break;
case 0x0A: /*Read sector ID*/
fdcstatus|=0x60;
readparams=7;
break;
case 0x0F: /*Seek*/
// printf("Seek %02X %02X\n",paramdat[1],paramdat[0]);
fdcstatus=0x80;
fdctrack=paramdat[0];
fdcint=1;
// output=1;
break;
default:
//printf("Executing bad command %02X\n",command);
exit(-1);
}
}
}
else
{
command=val&0x1F;
switch (command)
{
case 0: case 0x1F: return; /*Invalid*/
case 0x03: /*Specify*/
params=2;
fdcstatus|=0x10;
break;
case 0x04: /*Sense drive status*/
params=1;
fdcstatus|=0x10;
break;
case 0x06: /*Read sectors*/
// if (output) exit(0);
params=8;
fdcstatus|=0x10;
discon=1;
break;
case 0x07: /*Recalibrate*/
params=1;
fdcstatus|=0x10;
break;
case 0x08: /*Sense interrupt state*/
st0=0x21;
if (!fdcint) st0|=0x80;
else fdcint=0;
fdcstatus|=0xD0;
readparams=2;
break;
case 0x0A: /*Read sector ID*/
params=1;
fdcstatus|=0x10;
break;
case 0x0F: /*Seek*/
params=2;
fdcstatus|=0x10;
break;
default:
//printf("Starting bad command %02X\n",command);
exit(-1);
}
}
}
}
| 42.402844
| 204
| 0.323181
|
rpsubc8
|
888dad20edcc4f53d38f434073758c9fbba5f948
| 3,302
|
cpp
|
C++
|
src/dxapi/native/tickdb/http/xml/validate_qql_request.cpp
|
noop-dev/TimeBaseClientCpp
|
3cbbee85f2a8f1f38a31fc14a993fceb05d650f1
|
[
"Apache-2.0"
] | null | null | null |
src/dxapi/native/tickdb/http/xml/validate_qql_request.cpp
|
noop-dev/TimeBaseClientCpp
|
3cbbee85f2a8f1f38a31fc14a993fceb05d650f1
|
[
"Apache-2.0"
] | null | null | null |
src/dxapi/native/tickdb/http/xml/validate_qql_request.cpp
|
noop-dev/TimeBaseClientCpp
|
3cbbee85f2a8f1f38a31fc14a993fceb05d650f1
|
[
"Apache-2.0"
] | 2
|
2021-05-14T09:39:50.000Z
|
2022-03-24T23:42:41.000Z
|
/*
* Copyright 2021 EPAM Systems, Inc
*
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. 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 "tickdb/common.h"
#include "validate_qql_request.h"
using namespace std;
using namespace tinyxml2;
using namespace DxApiImpl;
ValidateQqlRequest::ValidateQqlRequest(TickDbImpl &db, const std::string &qql) : XmlRequest(db, "validateQQL", false)
{
add("qql", qql);
}
using namespace XmlParse;
template<> bool XmlParse::parse(QqlTokenType &type, const char * from)
{
return NULL == from ? false : (type = QqlTokenType(from), true);
}
template<> bool XmlParse::parse(QqlState::Range &range, const char * from)
{
return NULL == from ? false : parse(range.value, from);
}
static bool parse(QqlState::Token &token, XMLElement * element)
{
return parse(token.type, getText(element, "type")) && parse(token.location, getText(element, "location"));
}
bool ValidateQqlRequest::getState(QqlState &state)
{
state.tokens.reset();
state.errorLocation.value = -1;
if (!executeAndParseResponse()) {
return false;
}
XMLElement * rootElement = response_.root();
if (!nameEquals(rootElement, "validateQQLResponse")) {
return false;
}
XMLElement * resultElement = rootElement->FirstChildElement("result");
if (NULL == resultElement) {
DBGLOGERR((string*)NULL, "ERR: 'result' element not found!");
return false;
}
XMLElement * tokensElement = resultElement->FirstChildElement("tokens");
/*if (NULL == tokensElement) {
DBGLOGERR((string*)NULL, "ERR: 'tokens' element not found!");
return false;
}*/
auto errorLocationText = getText(resultElement, "errorLocation");
state.errorLocation.value = -1;
if (NULL != errorLocationText && !parse(state.errorLocation, errorLocationText)) {
DBGLOGERR((string*)NULL, "ERR: Unable to parse 'errorLocation' field!");
return false;
}
if (NULL != tokensElement) {
std::vector<QqlState::Token> tokens;
for (XMLElement * item = (XMLElement *)tokensElement; NULL != item; item = item->NextSiblingElement("tokens")) {
QqlState::Token token;
if (!parse(token, item)) {
DBGLOGERR((string*)NULL, "ERR: Unable to parse qql state token!");
return false;
}
tokens.push_back(token);
//tokens.push_back(QqlState::Token());
/*if (!parse(tokens[tokens.size() - 1], getText(item))) {
DBGLOGERR((string*)NULL, "ERR: Unable to parse qql state token!");
return false;
}*/
}
state.tokens = tokens;
}
return true;
}
| 29.221239
| 120
| 0.650515
|
noop-dev
|
888f003791b7375286b79eec304e33195f88bcca
| 1,567
|
cpp
|
C++
|
Src/renderer/loading_screen/LoadingScreen.cpp
|
Kataglyphis/GraphicEngine
|
f3b87a36b761fe13e747011be9301f6f9fe0c3f0
|
[
"BSD-3-Clause"
] | null | null | null |
Src/renderer/loading_screen/LoadingScreen.cpp
|
Kataglyphis/GraphicEngine
|
f3b87a36b761fe13e747011be9301f6f9fe0c3f0
|
[
"BSD-3-Clause"
] | null | null | null |
Src/renderer/loading_screen/LoadingScreen.cpp
|
Kataglyphis/GraphicEngine
|
f3b87a36b761fe13e747011be9301f6f9fe0c3f0
|
[
"BSD-3-Clause"
] | null | null | null |
#include "LoadingScreen.h"
#include <sstream>
LoadingScreen::LoadingScreen() {
create_shader_program();
}
void LoadingScreen::init()
{
std::stringstream texture_base_dir;
texture_base_dir << CMAKELISTS_DIR;
texture_base_dir << "/Resources/Textures/";
std::stringstream texture_loading_screen;
texture_loading_screen << texture_base_dir.str()
<< "Loading_Screen/ukraine.jpg";
loading_screen_tex = Texture( texture_loading_screen.str().c_str(),
std::make_shared<RepeatMode>());
loading_screen_tex.load_texture_without_alpha_channel();
std::stringstream texture_logo;
texture_logo << texture_base_dir.str()
<< "Loading_Screen/Engine_logo.png";
logo_tex = Texture(texture_logo.str().c_str(), std::make_shared<RepeatMode>());
logo_tex.load_texture_with_alpha_channel();
}
void LoadingScreen::render()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
loading_screen_tex.use_texture(0);
loading_screen_shader_program->use_shader_program();
loading_screen_quad.render();
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
void LoadingScreen::create_shader_program() {
loading_screen_shader_program =
std::make_shared<ShaderProgram>(ShaderProgram{});
loading_screen_shader_program->create_from_files( "loading_screen/loading_screen.vert",
"loading_screen/loading_screen.frag");
}
LoadingScreen::~LoadingScreen()
{
}
| 25.274194
| 94
| 0.675814
|
Kataglyphis
|
88941a2351f5a90aab7045ed95a69a096fd3c8be
| 9,866
|
cxx
|
C++
|
MUON/MUONmapping/AliMpBusPatch.cxx
|
AllaMaevskaya/AliRoot
|
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
|
[
"BSD-3-Clause"
] | 52
|
2016-12-11T13:04:01.000Z
|
2022-03-11T11:49:35.000Z
|
MUON/MUONmapping/AliMpBusPatch.cxx
|
AllaMaevskaya/AliRoot
|
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
|
[
"BSD-3-Clause"
] | 1,388
|
2016-11-01T10:27:36.000Z
|
2022-03-30T15:26:09.000Z
|
MUON/MUONmapping/AliMpBusPatch.cxx
|
AllaMaevskaya/AliRoot
|
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
|
[
"BSD-3-Clause"
] | 275
|
2016-06-21T20:24:05.000Z
|
2022-03-31T13:06:19.000Z
|
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
// $Id$
// $MpId: AliMpBusPatch.cxx,v 1.4 2006/05/24 13:58:34 ivana Exp $
//-----------------------------------------------------------------------------
// Class AliMpBusPatch
// --------------------
// The class defines the properties of BusPatch
// Author: Ivana Hrivnacova, IPN Orsay
//-----------------------------------------------------------------------------
#include "AliMpBusPatch.h"
#include "AliDAQ.h"
#include "AliMpConstants.h"
#include "AliMpDEManager.h"
#include "AliMpSegmentation.h"
#include "AliMpSlat.h"
#include "AliMpPCB.h"
#include "AliMpMotifPosition.h"
#include "AliLog.h"
#include <Riostream.h>
using std::cout;
using std::endl;
/// \cond CLASSIMP
ClassImp(AliMpBusPatch)
/// \endcond
const Int_t AliMpBusPatch::fgkOffset = 100;
//
// static methods
//
//____________________________________________________________________
Int_t AliMpBusPatch::GetGlobalBusID(Int_t localID, Int_t ddlID)
{
/// return global bus id from local bus and ddl id
return ddlID*fgkOffset + localID;
}
//____________________________________________________________________
Int_t AliMpBusPatch::GetLocalBusID(Int_t globalID, Int_t ddlID)
{
/// return local bus id from local bus id
return globalID - ddlID*fgkOffset;
}
//______________________________________________________________________________
AliMpBusPatch::AliMpBusPatch(Int_t id, Int_t detElemId, Int_t ddlId)
: TObject(),
fId(id),
fDEId(detElemId),
fDdlId(ddlId),
fManus(false),
fNofManusPerModule(false),
fCableLength(-1),
fCableLabel(),
fTranslatorLabel(),
fFrtId(0)
{
/// Standard constructor
}
//______________________________________________________________________________
AliMpBusPatch::AliMpBusPatch(TRootIOCtor* /*ioCtor*/)
: TObject(),
fId(),
fDEId(),
fDdlId(),
fManus(false),
fNofManusPerModule(false),
fCableLength(-1),
fCableLabel(),
fTranslatorLabel(),
fFrtId(0)
{
/// Root IO constructor
}
//______________________________________________________________________________
AliMpBusPatch::~AliMpBusPatch()
{
/// Destructor
}
//
// public methods
//
//______________________________________________________________________________
Bool_t AliMpBusPatch::AddManu(Int_t manuId)
{
/// Add detection element with given detElemId.
/// Return true if the detection element was added
if ( HasManu(manuId) ) {
AliWarningStream()
<< "Manu with manuId=" << manuId << " already present."
<< endl;
return false;
}
fManus.Add(manuId);
return true;
}
//______________________________________________________________________________
Bool_t AliMpBusPatch::SetNofManusPerModule(Int_t manuNumber)
{
/// Set the number of manus per patch module (PCB):
/// - for stations 1 all manus are connected to one PCB,
/// - for stations 2 there maximum two PCBs per buspatch,
/// - for slat stations there are maximum three PCBs per buspatch
if ( AliMpDEManager::GetStation12Type(fDEId) == AliMq::kStation1) {
// simply fill the number of manus, no bridge for station 1
fNofManusPerModule.Add(GetNofManus());
return true;
}
if ( AliMpDEManager::GetStation12Type(fDEId) == AliMq::kStation2) {
// there is max two patch modules per buspatch
fNofManusPerModule.Add(manuNumber);
if (manuNumber != GetNofManus())
fNofManusPerModule.Add(GetNofManus() - manuNumber);
return true;
}
if ( AliMpDEManager::GetStationType(fDEId) == AliMp::kStation345 ) {
const AliMpSlat* kSlat0
= AliMpSegmentation::Instance()->GetSlat(fDEId, AliMp::kCath0);
const AliMpSlat* kSlat1
= AliMpSegmentation::Instance()->GetSlat(fDEId, AliMp::kCath1);
Int_t iPcb = 0;
Int_t iPcbPrev = -1;
Int_t manuPerPcb = 0;
Double_t x = 0.;
Double_t length = 0.;
// Loop over manu
for (Int_t iManu = 0; iManu < GetNofManus(); ++iManu) {
Int_t manuId = GetManuId(iManu);
AliMpMotifPosition* motifPos0 = kSlat0->FindMotifPosition(manuId);
AliMpMotifPosition* motifPos1 = kSlat1->FindMotifPosition(manuId);
if ( !motifPos0 && !motifPos1 ) {
// should never happen
AliErrorStream()
<< "Motif position for manuId = " << manuId << "not found" << endl;
return false;
}
// find PCB id
if ( motifPos0 ) {
x = motifPos0->GetPositionX();
length = kSlat0->GetPCB(0)->DX()*2.;
}
if ( motifPos1 ) {
x = motifPos1->GetPositionX();
length = kSlat1->GetPCB(0)->DX()*2.;
}
iPcb = Int_t(x/length + AliMpConstants::LengthTolerance());
// check when going to next PCB
if ( iPcb == iPcbPrev )
manuPerPcb++;
else if ( iPcbPrev != -1 ) {
//vec.Set(vec.GetSize()+1);
//vec[vec.GetSize()-1] = manuPerPcb+1;
fNofManusPerModule.Add(manuPerPcb+1);
manuPerPcb = 0;
}
iPcbPrev = iPcb;
}
// store last PCB
//vec.Set(vec.GetSize()+1);
//vec[vec.GetSize()-1] = manuPerPcb+1;
fNofManusPerModule.Add(manuPerPcb+1);
return true;
}
return false;
}
//______________________________________________________________________________
void AliMpBusPatch::RevertReadout()
{
/// Revert order of manus
fManus.Revert();
}
//______________________________________________________________________________
void AliMpBusPatch::ResetReadout()
{
/// Revert order of manus
fManus.Reset();
}
//______________________________________________________________________________
Int_t AliMpBusPatch::GetNofManus() const
{
/// Return the number of detection elements connected to this DDL
return fManus.GetSize();
}
//______________________________________________________________________________
Int_t AliMpBusPatch::GetManuId(Int_t index) const
{
/// Return the detection element by index (in loop)
return fManus.GetValue(index);
}
//______________________________________________________________________________
Bool_t AliMpBusPatch::HasManu(Int_t manuId) const
{
/// Return true if bus patch has manu with given manuId
return fManus.HasValue(manuId);
}
//______________________________________________________________________________
Int_t AliMpBusPatch::GetNofPatchModules() const
{
/// Return the number of patch modules (PCB) connected to this bus patch.
return fNofManusPerModule.GetSize();
}
//______________________________________________________________________________
TString
AliMpBusPatch::GetFRTPosition() const
{
/// Return CRXX-Y-Z where XX is the Crocus number, Y the FRT number
/// and Z the local bus patch number.
return Form("CR%2d-%d-%d",fDdlId,fFrtId+1,GetLocalBusID(fId,fDdlId));
}
//______________________________________________________________________________
Int_t AliMpBusPatch::GetNofManusPerModule(Int_t patchModule) const
{
/// Return the number of manus per patch module (PCB)
if ( patchModule < 0 || patchModule >= GetNofPatchModules() ) {
AliErrorStream() << "Invalid patch module number = " << patchModule << endl;
return 0;
}
return fNofManusPerModule.GetValue(patchModule);
}
//______________________________________________________________________________
void
AliMpBusPatch::Print(Option_t* opt) const
{
/// Printout
cout << Form("BusPatch %04d DDL %d : %s <> %s / %s",
fId,
AliDAQ::DdlID("MUONTRK",fDdlId),
GetFRTPosition().Data(),
fCableLabel.Data(),
fTranslatorLabel.Data()) << endl;
TString sopt(opt);
sopt.ToUpper();
if ( sopt.Contains("FULL") )
{
cout << Form("Nof of PCBs (i.e. patch modules) = %d",fNofManusPerModule.GetSize()) << endl;
for ( Int_t i = 0; i < fNofManusPerModule.GetSize(); ++i )
{
cout << Form("\t\t %d manus in patch module %d",fNofManusPerModule.GetValue(i),i) << endl;
}
if ( sopt.Contains("MANU") )
{
cout << "Manus of that buspatch=" << endl;
for ( Int_t i = 0; i < fManus.GetSize(); ++i )
{
cout << Form("%4d,",fManus.GetValue(i));
}
cout << endl;
}
}
// Int_t fId; ///< Identifier (unique)
// Int_t fDEId; ///< Detection element to which this bus patch is connected
// Int_t fDdlId; ///< DDL to which this bus patch is connected
// AliMpArrayI fManus; ///< Manu Ids connected to this bus patch
// AliMpArrayI fNofManusPerModule; ///< Nof Manus per patch modules (PCBs)
// Float_t fCableLength; ///< length of the buspatch cable
// TString fCableLabel; ///< label of the buspatch cable
// TString fTranslatorLabel; ///< label of the translator board
// Int_t fFrtId; ///< FRT Ids connected to this bus patch
}
| 29.538922
| 96
| 0.647476
|
AllaMaevskaya
|
889b7fa955d64191cebb708ce71eafc6590b632f
| 231
|
hpp
|
C++
|
include/toy/gadget/IntToChar.hpp
|
ToyAuthor/ToyBox
|
f517a64d00e00ccaedd76e33ed5897edc6fde55e
|
[
"Unlicense"
] | 4
|
2017-07-06T22:18:41.000Z
|
2021-05-24T21:28:37.000Z
|
include/toy/gadget/IntToChar.hpp
|
ToyAuthor/ToyBox
|
f517a64d00e00ccaedd76e33ed5897edc6fde55e
|
[
"Unlicense"
] | null | null | null |
include/toy/gadget/IntToChar.hpp
|
ToyAuthor/ToyBox
|
f517a64d00e00ccaedd76e33ed5897edc6fde55e
|
[
"Unlicense"
] | 1
|
2020-08-02T13:00:38.000Z
|
2020-08-02T13:00:38.000Z
|
#pragma once
#include "toy/Standard.hpp"
#include "toy/gadget/Export.hpp"
namespace toy{
namespace gadget{
// 1 -> '1'
// 2 -> '2'
// 9 -> '9'
// 10 -> [error]
// -1 -> [error]
TOY_API_GADGET extern char IntToChar(int);
}}
| 12.833333
| 42
| 0.597403
|
ToyAuthor
|
889c45242a1cd2c573d08386e06c9a181851cb3f
| 454
|
cpp
|
C++
|
final/pointers/pointers_to_functions.cpp
|
coderica/effective_cpp
|
456d30cf42c6c71dc7187d88e362651dd79ac3fe
|
[
"MIT"
] | null | null | null |
final/pointers/pointers_to_functions.cpp
|
coderica/effective_cpp
|
456d30cf42c6c71dc7187d88e362651dd79ac3fe
|
[
"MIT"
] | null | null | null |
final/pointers/pointers_to_functions.cpp
|
coderica/effective_cpp
|
456d30cf42c6c71dc7187d88e362651dd79ac3fe
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int addThem(int, int);
int subtractThem(int, int);
int main()
{
int addResult, subResult;
int (*opPtr)(int, int);
opPtr = addThem;
addResult = opPtr(3, 2);
opPtr = subtractThem;
subResult = opPtr(3, 2);
cout << "Adding: " << addResult << " Subtracting: " << subResult << endl;
}
int addThem(int a, int b)
{
return a + b;
}
int subtractThem(int a, int b)
{
return a - b;
}
| 16.214286
| 75
| 0.599119
|
coderica
|
889c8b9fa38c3010c71d1e2b7426666342bb5772
| 571
|
hpp
|
C++
|
src/Main/buildLIZandCommLists.hpp
|
pmu2022/lsms
|
3c5f266812cad0b6d570bef9f5abb590d044ef92
|
[
"BSD-3-Clause"
] | 1
|
2022-01-27T14:45:51.000Z
|
2022-01-27T14:45:51.000Z
|
src/Main/buildLIZandCommLists.hpp
|
pmu2022/lsms
|
3c5f266812cad0b6d570bef9f5abb590d044ef92
|
[
"BSD-3-Clause"
] | 3
|
2021-09-14T01:30:26.000Z
|
2021-09-25T14:05:10.000Z
|
src/Main/buildLIZandCommLists.hpp
|
pmu2022/lsms
|
3c5f266812cad0b6d570bef9f5abb590d044ef92
|
[
"BSD-3-Clause"
] | 1
|
2022-01-03T18:16:26.000Z
|
2022-01-03T18:16:26.000Z
|
#ifndef LSMS_BUILDLIZANDCOMMLISTS_HPP
#define LSMS_BUILDLIZANDCOMMLISTS_HPP
#include "Real.hpp"
#include "SystemParameters.hpp"
#include "SingleSite/AtomData.hpp"
#include "Communication/LSMSCommunication.hpp"
class LIZInfoType {
public:
int idx;
Real p1, p2, p3;
Real dSqr;
};
class NodeIdxInfo {
public:
int node, localIdx, globalIdx;
};
void buildLIZandCommLists(LSMSCommunication &comm,
LSMSSystemParameters &lsms,
CrystalParameters &crystal,
LocalTypeInfo &local);
#endif
| 19.033333
| 53
| 0.676007
|
pmu2022
|
889e2e4d0c63113975d8ec6fb0621891e6e0b794
| 3,470
|
cpp
|
C++
|
PGTests/PGTests/GeometryTests.cpp
|
mcdreamer/PG
|
a047615d9eae7f2229a203a262f239106cf7f39c
|
[
"MIT"
] | 2
|
2018-01-14T17:47:22.000Z
|
2021-11-15T10:34:24.000Z
|
PGTests/PGTests/GeometryTests.cpp
|
mcdreamer/PG
|
a047615d9eae7f2229a203a262f239106cf7f39c
|
[
"MIT"
] | 23
|
2017-07-31T19:43:00.000Z
|
2018-11-11T18:51:28.000Z
|
PGTests/PGTests/GeometryTests.cpp
|
mcdreamer/PG
|
a047615d9eae7f2229a203a262f239106cf7f39c
|
[
"MIT"
] | null | null | null |
#include "GeometryTests.h"
#include "gtest/gtest.h"
#include "PG/core/RectUtils.h"
#include "PG/core/Rect.h"
#include "PG/core/Point.h"
#include "PG/entities/TilePositionCalculator.h"
#include "PG/app/GameConstants.h"
using namespace PG;
//--------------------------------------------------------
TEST(GeometryTests,testTilePositionCalculator)
{
TilePositionCalculator tpc;
EXPECT_EQ(2, GameConstants::tileSize());
EXPECT_EQ(TileCoord(0, 0), tpc.calculateTileCoord(Point(0, 0)));
EXPECT_EQ(TileCoord(0, 0), tpc.calculateTileCoord(Point(0.5, 0.5)));
EXPECT_EQ(TileCoord(0, 0), tpc.calculateTileCoord(Point(1, 1)));
EXPECT_EQ(TileCoord(0, 0), tpc.calculateTileCoord(Point(1.5, 1.5)));
EXPECT_EQ(TileCoord(1, 1), tpc.calculateTileCoord(Point(2, 2)));
EXPECT_EQ(Point(1, 1), tpc.calculatePoint(TileCoord(0, 0)));
EXPECT_EQ(Point(3, 1), tpc.calculatePoint(TileCoord(1, 0)));
EXPECT_EQ(Point(1, 3), tpc.calculatePoint(TileCoord(0, 1)));
EXPECT_EQ(Point(3, 3), tpc.calculatePoint(TileCoord(1, 1)));
}
//--------------------------------------------------------
TEST(GeometryTests,testPGRectUtils_ContainsPoint)
{
const Rect rect(Point(100, 100), Size(50, 50));
EXPECT_TRUE(RectUtils::containsPoint(rect, Point(100, 100)));
EXPECT_TRUE(RectUtils::containsPoint(rect, Point(80, 100)));
EXPECT_TRUE(RectUtils::containsPoint(rect, Point(100, 80)));
EXPECT_TRUE(RectUtils::containsPoint(rect, Point(80, 80)));
EXPECT_TRUE(RectUtils::containsPoint(rect, Point(100, 120)));
EXPECT_TRUE(RectUtils::containsPoint(rect, Point(120, 100)));
EXPECT_TRUE(RectUtils::containsPoint(rect, Point(120, 120)));
EXPECT_FALSE(RectUtils::containsPoint(rect, Point(70, 70)));
EXPECT_FALSE(RectUtils::containsPoint(rect, Point(130, 130)));
}
//--------------------------------------------------------
TEST(GeometryTests,testPGRectUtils_CombineRects)
{
{
const auto r = RectUtils::combineRects(Rect(Point(100, 100), Size(50, 50)),
Rect(Point(100, 100), Size(50, 50)));
EXPECT_EQ(Rect(Point(100, 100), Size(50, 50)), r);
}
{
const auto r = RectUtils::combineRects(Rect(Point(100, 100), Size(50, 100)),
Rect(Point(100, 100), Size(50, 50)));
EXPECT_EQ(Rect(Point(100, 100), Size(50, 100)), r);
}
{
const auto r = RectUtils::combineRects(Rect(Point(0, 0), Size(50, 50)),
Rect(Point(100, 100), Size(50, 50)));
EXPECT_EQ(Rect(Point(50, 50), Size(150, 150)), r);
}
}
//--------------------------------------------------------
TEST(GeometryTests,testPGRectUtils_isEmpty)
{
EXPECT_TRUE(RectUtils::isEmpty(Rect(Point(100, 100), Size(0, 0))));
EXPECT_TRUE(RectUtils::isEmpty(Rect(Point(100, 100), Size(10, 0))));
EXPECT_TRUE(RectUtils::isEmpty(Rect(Point(100, 100), Size(0, 10))));
EXPECT_FALSE(RectUtils::isEmpty(Rect(Point(100, 100), Size(10, 10))));
}
//--------------------------------------------------------
TEST(GeometryTests,testPGRectUtils_getIntersection)
{
const Rect rect(Point(100, 100), Size(50, 50));
{
const auto i = RectUtils::getIntersection(rect, Rect(Point(100, 49), Size(50, 50)));
EXPECT_TRUE(RectUtils::isEmpty(i));
}
{
const auto i = RectUtils::getIntersection(rect, Rect(Point(100, 50), Size(50, 50)));
EXPECT_TRUE(RectUtils::isEmpty(i));
}
}
| 36.526316
| 86
| 0.597118
|
mcdreamer
|
88a8e8c0a917c63a5bbc9709faca4b4637b9e4b1
| 26,514
|
cpp
|
C++
|
samsung/hardware/exynos3/s5pc110/libhwcomposer/SecHWC.cpp
|
DrDoubt/android_device_samsung_universal9810-common-1
|
5a937d2994044c041c3c19192d7744200a036cc8
|
[
"Apache-2.0"
] | null | null | null |
samsung/hardware/exynos3/s5pc110/libhwcomposer/SecHWC.cpp
|
DrDoubt/android_device_samsung_universal9810-common-1
|
5a937d2994044c041c3c19192d7744200a036cc8
|
[
"Apache-2.0"
] | null | null | null |
samsung/hardware/exynos3/s5pc110/libhwcomposer/SecHWC.cpp
|
DrDoubt/android_device_samsung_universal9810-common-1
|
5a937d2994044c041c3c19192d7744200a036cc8
|
[
"Apache-2.0"
] | 2
|
2021-07-04T19:41:36.000Z
|
2021-07-29T12:59:47.000Z
|
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
*
* @author Rama, Meka(v.meka@samsung.com)
Sangwoo, Park(sw5771.park@samsung.com)
Jamie Oh (jung-min.oh@samsung.com)
* @date 2011-07-28
*
*/
#define HWC_REMOVE_DEPRECATED_VERSIONS 1
#include <sys/resource.h>
#include <cutils/log.h>
#include <cutils/atomic.h>
#include <EGL/egl.h>
#include <GLES/gl.h>
#include <hardware_legacy/uevent.h>
#include "SecHWCUtils.h"
static IMG_gralloc_module_public_t *gpsGrallocModule;
static int hwc_device_open(const struct hw_module_t* module, const char* name,
struct hw_device_t** device);
static struct hw_module_methods_t hwc_module_methods = {
open: hwc_device_open
};
hwc_module_t HAL_MODULE_INFO_SYM = {
common: {
tag: HARDWARE_MODULE_TAG,
module_api_version: HWC_MODULE_API_VERSION_0_1,
hal_api_version: HARDWARE_HAL_API_VERSION,
id: HWC_HARDWARE_MODULE_ID,
name: "Samsung S5PC11X hwcomposer module",
author: "SAMSUNG",
methods: &hwc_module_methods,
}
};
static void dump_layer(hwc_layer_1_t const* l) {
ALOGD("\ttype=%d, flags=%08x, handle=%p, tr=%02x, blend=%04x, {%d,%d,%d,%d}, {%d,%d,%d,%d}",
l->compositionType, l->flags, l->handle, l->transform, l->blending,
l->sourceCrop.left,
l->sourceCrop.top,
l->sourceCrop.right,
l->sourceCrop.bottom,
l->displayFrame.left,
l->displayFrame.top,
l->displayFrame.right,
l->displayFrame.bottom);
}
static int set_src_dst_info(hwc_layer_1_t *cur,
struct hwc_win_info_t *win,
struct sec_img *src_img,
struct sec_img *dst_img,
struct sec_rect *src_rect,
struct sec_rect *dst_rect,
int win_idx)
{
IMG_native_handle_t *prev_handle = (IMG_native_handle_t *)(cur->handle);
// set src image
src_img->w = prev_handle->iWidth;
src_img->h = prev_handle->iHeight;
src_img->format = prev_handle->iFormat;
src_img->base = 0;
src_img->offset = 0;
src_img->mem_id = 0;
src_img->mem_type = HWC_PHYS_MEM_TYPE;
src_img->w = (src_img->w + 15) & (~15);
src_img->h = (src_img->h + 1) & (~1) ;
//set src rect
src_rect->x = SEC_MAX(cur->sourceCrop.left, 0);
src_rect->y = SEC_MAX(cur->sourceCrop.top, 0);
src_rect->w = SEC_MAX(cur->sourceCrop.right - cur->sourceCrop.left, 0);
src_rect->w = SEC_MIN(src_rect->w, src_img->w - src_rect->x);
src_rect->h = SEC_MAX(cur->sourceCrop.bottom - cur->sourceCrop.top, 0);
src_rect->h = SEC_MIN(src_rect->h, src_img->h - src_rect->y);
//set dst image
dst_img->w = win->lcd_info.xres;
dst_img->h = win->lcd_info.yres;
switch (win->lcd_info.bits_per_pixel) {
case 32:
dst_img->format = HAL_PIXEL_FORMAT_RGBX_8888;
break;
default:
dst_img->format = HAL_PIXEL_FORMAT_RGB_565;
break;
}
dst_img->base = win->addr[win->buf_index];
dst_img->offset = 0;
dst_img->mem_id = 0;
dst_img->mem_type = HWC_PHYS_MEM_TYPE;
//set dst rect
//fimc dst image will be stored from left top corner
dst_rect->x = 0;
dst_rect->y = 0;
dst_rect->w = win->rect_info.w;
dst_rect->h = win->rect_info.h;
ALOGV("%s::sr_x %d sr_y %d sr_w %d sr_h %d dr_x %d dr_y %d dr_w %d dr_h %d ",
__func__, src_rect->x, src_rect->y, src_rect->w, src_rect->h,
dst_rect->x, dst_rect->y, dst_rect->w, dst_rect->h);
return 0;
}
static int get_hwc_compos_decision(hwc_layer_1_t* cur)
{
if(cur->flags & HWC_SKIP_LAYER || !cur->handle) {
ALOGV("%s::is_skip_layer %d cur->handle %x",
__func__, cur->flags & HWC_SKIP_LAYER, (uint32_t)cur->handle);
return HWC_FRAMEBUFFER;
}
IMG_native_handle_t *prev_handle = (IMG_native_handle_t *)(cur->handle);
int compositionType = HWC_FRAMEBUFFER;
/* check here....if we have any resolution constraints */
if (((cur->sourceCrop.right - cur->sourceCrop.left) < 16) ||
((cur->sourceCrop.bottom - cur->sourceCrop.top) < 8))
return compositionType;
if ((cur->transform == HAL_TRANSFORM_ROT_90) ||
(cur->transform == HAL_TRANSFORM_ROT_270)) {
if(((cur->displayFrame.right - cur->displayFrame.left) < 4)||
((cur->displayFrame.bottom - cur->displayFrame.top) < 8))
return compositionType;
} else if (((cur->displayFrame.right - cur->displayFrame.left) < 8) ||
((cur->displayFrame.bottom - cur->displayFrame.top) < 4))
return compositionType;
if((prev_handle->usage & GRALLOC_USAGE_PHYS_CONTIG) &&
(cur->blending == HWC_BLENDING_NONE))
compositionType = HWC_OVERLAY;
else
compositionType = HWC_FRAMEBUFFER;
ALOGV("%s::compositionType %d bpp %d format %x usage %x",
__func__,compositionType, prev_handle->uiBpp, prev_handle->iFormat,
prev_handle->usage & GRALLOC_USAGE_PHYS_CONTIG);
return compositionType;
}
static int assign_overlay_window(struct hwc_context_t *ctx,
hwc_layer_1_t *cur,
int win_idx,
int layer_idx)
{
struct hwc_win_info_t *win;
sec_rect rect;
int ret = 0;
if(NUM_OF_WIN <= win_idx)
return -1;
win = &ctx->win[win_idx];
rect.x = SEC_MAX(cur->displayFrame.left, 0);
rect.y = SEC_MAX(cur->displayFrame.top, 0);
rect.w = SEC_MIN(cur->displayFrame.right - rect.x, win->lcd_info.xres - rect.x);
rect.h = SEC_MIN(cur->displayFrame.bottom - rect.y, win->lcd_info.yres - rect.y);
win->set_win_flag = 0;
if((rect.x != win->rect_info.x) || (rect.y != win->rect_info.y) ||
(rect.w != win->rect_info.w) || (rect.h != win->rect_info.h)){
win->rect_info.x = rect.x;
win->rect_info.y = rect.y;
win->rect_info.w = rect.w;
win->rect_info.h = rect.h;
win->set_win_flag = 1;
win->layer_prev_buf = 0;
}
win->layer_index = layer_idx;
win->status = HWC_WIN_RESERVED;
ALOGV("%s:: win_x %d win_y %d win_w %d win_h %d lay_idx %d win_idx %d",
__func__, win->rect_info.x, win->rect_info.y, win->rect_info.w,
win->rect_info.h, win->layer_index, win_idx );
return 0;
}
static void reset_win_rect_info(hwc_win_info_t *win)
{
win->rect_info.x = 0;
win->rect_info.y = 0;
win->rect_info.w = 0;
win->rect_info.h = 0;
return;
}
static int hwc_prepare(hwc_composer_device_1_t *dev,
size_t numDisplays, hwc_display_contents_1_t** displays)
{
struct hwc_context_t* ctx = (struct hwc_context_t*)dev;
int overlay_win_cnt = 0;
int compositionType = 0;
int ret;
// Compat
hwc_display_contents_1_t* list = NULL;
if (numDisplays > 0) {
list = displays[0];
}
//if geometry is not changed, there is no need to do any work here
if( !list || (!(list->flags & HWC_GEOMETRY_CHANGED)))
return 0;
//all the windows are free here....
for (int i = 0; i < NUM_OF_WIN; i++) {
ctx->win[i].status = HWC_WIN_FREE;
ctx->win[i].buf_index = 0;
}
ctx->num_of_hwc_layer = 0;
ctx->num_of_fb_layer = 0;
ALOGV("%s:: hwc_prepare list->numHwLayers %d", __func__, list->numHwLayers);
for (int i = 0; i < list->numHwLayers ; i++) {
hwc_layer_1_t* cur = &list->hwLayers[i];
if (overlay_win_cnt < NUM_OF_WIN) {
compositionType = get_hwc_compos_decision(cur);
if (compositionType == HWC_FRAMEBUFFER) {
cur->compositionType = HWC_FRAMEBUFFER;
ctx->num_of_fb_layer++;
} else {
ret = assign_overlay_window(ctx, cur, overlay_win_cnt, i);
if (ret != 0) {
cur->compositionType = HWC_FRAMEBUFFER;
ctx->num_of_fb_layer++;
continue;
}
cur->compositionType = HWC_OVERLAY;
cur->hints = HWC_HINT_CLEAR_FB;
overlay_win_cnt++;
ctx->num_of_hwc_layer++;
}
} else {
cur->compositionType = HWC_FRAMEBUFFER;
ctx->num_of_fb_layer++;
}
}
if(list->numHwLayers != (ctx->num_of_fb_layer + ctx->num_of_hwc_layer))
ALOGV("%s:: numHwLayers %d num_of_fb_layer %d num_of_hwc_layer %d ",
__func__, list->numHwLayers, ctx->num_of_fb_layer,
ctx->num_of_hwc_layer);
if (overlay_win_cnt < NUM_OF_WIN) {
//turn off the free windows
for (int i = overlay_win_cnt; i < NUM_OF_WIN; i++) {
window_hide(&ctx->win[i]);
reset_win_rect_info(&ctx->win[i]);
}
}
return 0;
}
static int hwc_set(hwc_composer_device_1_t *dev,
size_t numDisplays, hwc_display_contents_1_t** displays)
{
struct hwc_context_t *ctx = (struct hwc_context_t *)dev;
unsigned int phyAddr[MAX_NUM_PLANES];
int skipped_window_mask = 0;
hwc_layer_1_t* cur;
struct hwc_win_info_t *win;
int ret;
struct sec_img src_img;
struct sec_img dst_img;
struct sec_rect src_rect;
struct sec_rect dst_rect;
// Only support one display
hwc_display_t dpy = displays[0]->dpy;
hwc_surface_t sur = displays[0]->sur;
hwc_display_contents_1_t* list = displays[0];
if (dpy == NULL && sur == NULL && list == NULL) {
// release our resources, the screen is turning off
// in our case, there is nothing to do.
ctx->num_of_fb_layer_prev = 0;
return 0;
}
bool need_swap_buffers = ctx->num_of_fb_layer > 0;
/*
* H/W composer documentation states:
* There is an implicit layer containing opaque black
* pixels behind all the layers in the list.
* It is the responsibility of the hwcomposer module to make
* sure black pixels are output (or blended from).
*
* Since we're using a blitter, we need to erase the frame-buffer when
* switching to all-overlay mode.
*
*/
if (ctx->num_of_hwc_layer &&
ctx->num_of_fb_layer==0 && ctx->num_of_fb_layer_prev) {
/* we're clearing the screen using GLES here, this is very
* hack-ish, ideal we would use the fimc (if it can do it) */
glDisable(GL_SCISSOR_TEST);
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
glEnable(GL_SCISSOR_TEST);
need_swap_buffers = true;
}
ctx->num_of_fb_layer_prev = ctx->num_of_fb_layer;
if (need_swap_buffers || !list) {
EGLBoolean sucess = eglSwapBuffers((EGLDisplay)dpy, (EGLSurface)sur);
if (!sucess) {
return HWC_EGL_ERROR;
}
}
if (!list) {
/* turn off the all windows */
for (int i = 0; i < NUM_OF_WIN; i++) {
window_hide(&ctx->win[i]);
reset_win_rect_info(&ctx->win[i]);
ctx->win[i].status = HWC_WIN_FREE;
}
ctx->num_of_hwc_layer = 0;
return 0;
}
if(ctx->num_of_hwc_layer > NUM_OF_WIN)
ctx->num_of_hwc_layer = NUM_OF_WIN;
/* compose hardware layers here */
for (uint32_t i = 0; i < ctx->num_of_hwc_layer; i++) {
win = &ctx->win[i];
if (win->status == HWC_WIN_RESERVED) {
cur = &list->hwLayers[win->layer_index];
if (cur->compositionType == HWC_OVERLAY) {
ret = gpsGrallocModule->GetPhyAddrs(gpsGrallocModule,
cur->handle, phyAddr);
if (ret) {
ALOGE("%s::GetPhyAddrs fail : ret=%d\n", __func__, ret);
skipped_window_mask |= (1 << i);
continue;
}
/* initialize the src & dist context for fimc */
set_src_dst_info (cur, win, &src_img, &dst_img, &src_rect,
&dst_rect, i);
ret = runFimc(ctx, &src_img, &src_rect, &dst_img, &dst_rect,
phyAddr, cur->transform);
if (ret < 0){
ALOGE("%s::runFimc fail : ret=%d\n", __func__, ret);
skipped_window_mask |= (1 << i);
continue;
}
if (win->set_win_flag == 1) {
/* turnoff the window and set the window position with new conf... */
if (window_set_pos(win) < 0) {
ALOGE("%s::window_set_pos is failed : %s", __func__,
strerror(errno));
skipped_window_mask |= (1 << i);
continue;
}
win->set_win_flag = 0;
}
/* is the frame didn't change, it needs to be composited
* because something else below it could have changed, however
* it doesn't need to be swapped.
*/
if (win->layer_prev_buf != (uint32_t)cur->handle) {
win->layer_prev_buf = (uint32_t)cur->handle;
window_pan_display(win);
win->buf_index = (win->buf_index + 1) % NUM_OF_WIN_BUF;
}
if(win->power_state == 0)
window_show(win);
} else {
ALOGE("%s:: error : layer %d compositionType should have been \
HWC_OVERLAY", __func__, win->layer_index);
skipped_window_mask |= (1 << i);
continue;
}
} else {
ALOGE("%s:: error : window status should have been HWC_WIN_RESERVED \
by now... ", __func__);
skipped_window_mask |= (1 << i);
continue;
}
}
if (skipped_window_mask) {
//turn off the free windows
for (int i = 0; i < NUM_OF_WIN; i++) {
if (skipped_window_mask & (1 << i))
window_hide(&ctx->win[i]);
}
}
#if defined(BOARD_USES_HDMI)
hdmi_device_t* hdmi = ctx->hdmi;
if (ctx->num_of_hwc_layer == 1 && hdmi) {
if ((src_img.format == HAL_PIXEL_FORMAT_CUSTOM_YCbCr_420_SP_TILED)||
(src_img.format == HAL_PIXEL_FORMAT_CUSTOM_YCrCb_420_SP)) {
ADDRS * addr = (ADDRS *)(src_img.base);
hdmi->blit(hdmi,
src_img.w,
src_img.h,
src_img.format,
(unsigned int)addr->addr_y,
(unsigned int)addr->addr_cbcr,
(unsigned int)addr->addr_cbcr,
0, 0,
HDMI_MODE_VIDEO,
ctx->num_of_hwc_layer);
} else if ((src_img.format == HAL_PIXEL_FORMAT_YCbCr_420_SP) ||
(src_img.format == HAL_PIXEL_FORMAT_YCrCb_420_SP) ||
(src_img.format == HAL_PIXEL_FORMAT_YCbCr_420_P) ||
(src_img.format == HAL_PIXEL_FORMAT_YV12)) {
hdmi->blit(hdmi,
src_img.w,
src_img.h,
src_img.format,
(unsigned int)ctx->fimc.params.src.buf_addr_phy_rgb_y,
(unsigned int)ctx->fimc.params.src.buf_addr_phy_cb,
(unsigned int)ctx->fimc.params.src.buf_addr_phy_cr,
0, 0,
HDMI_MODE_VIDEO,
ctx->num_of_hwc_layer);
} else {
ALOGE("%s: Unsupported format = %d for hdmi", __func__, src_img.format);
}
}
#endif
return 0;
}
static void hwc_registerProcs(struct hwc_composer_device_1* dev,
hwc_procs_t const* procs)
{
struct hwc_context_t* ctx = (struct hwc_context_t*)dev;
ctx->procs = const_cast<hwc_procs_t *>(procs);
}
static int hwc_blank(struct hwc_composer_device_1 *dev,
int disp, int blank)
{
struct hwc_context_t* ctx = (struct hwc_context_t*)dev;
if (blank) {
// release our resources, the screen is turning off
// in our case, there is nothing to do.
ctx->num_of_fb_layer_prev = 0;
return 0;
}
else {
// No need to unblank, will unblank on set()
return 0;
}
}
static int hwc_query(struct hwc_composer_device_1* dev,
int what, int* value)
{
struct hwc_context_t* ctx = (struct hwc_context_t*)dev;
switch (what) {
case HWC_BACKGROUND_LAYER_SUPPORTED:
// we don't support the background layer yet
value[0] = 0;
break;
case HWC_VSYNC_PERIOD:
// vsync period in nanosecond
value[0] = 1000000000.0 / gpsGrallocModule->psFrameBufferDevice->base.fps;
break;
default:
// unsupported query
return -EINVAL;
}
return 0;
}
#ifdef VSYNC_IOCTL
// Linux version of a manual reset event to control when
// and when not to ask the video card for a VSYNC. This
// stops the worker thread from asking for a VSYNC when
// there is nothing useful to do with it and more closely
// mimicks the original uevent mechanism
int vsync_enable = 0;
pthread_mutex_t vsync_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t vsync_condition = PTHREAD_COND_INITIALIZER;
#endif
static int hwc_eventControl(struct hwc_composer_device_1* dev, int dpy,
int event, int enabled)
{
struct hwc_context_t* ctx = (struct hwc_context_t*)dev;
switch (event) {
case HWC_EVENT_VSYNC:
int val = !!enabled;
int err = ioctl(ctx->global_lcd_win.fd, S3CFB_SET_VSYNC_INT, &val);
if (err < 0)
return -errno;
#if VSYNC_IOCTL
// Enable or disable the ability for the worker thread
// to ask for VSYNC events from the video driver
pthread_mutex_lock(&vsync_mutex);
if(enabled) {
vsync_enable = 1;
pthread_cond_broadcast(&vsync_condition);
}
else vsync_enable = 0;
pthread_mutex_unlock(&vsync_mutex);
#endif
return 0;
}
return -EINVAL;
}
void handle_vsync_uevent(hwc_context_t *ctx, const char *buff, int len)
{
uint64_t timestamp = 0;
const char *s = buff;
if(!ctx->procs || !ctx->procs->vsync)
return;
s += strlen(s) + 1;
while(*s) {
if (!strncmp(s, "VSYNC=", strlen("VSYNC=")))
timestamp = strtoull(s + strlen("VSYNC="), NULL, 0);
s += strlen(s) + 1;
if (s - buff >= len)
break;
}
ctx->procs->vsync(ctx->procs, 0, timestamp);
}
static void *hwc_vsync_thread(void *data)
{
hwc_context_t *ctx = (hwc_context_t *)(data);
#ifdef VSYNC_IOCTL
uint64_t timestamp = 0;
#else
char uevent_desc[4096];
memset(uevent_desc, 0, sizeof(uevent_desc));
#endif
setpriority(PRIO_PROCESS, 0, HAL_PRIORITY_URGENT_DISPLAY);
#ifndef VSYNC_IOCTL
uevent_init();
#endif
while(true) {
#ifdef VSYNC_IOCTL
// Only continue if hwc_eventControl is enabled, otherwise
// just sit here and wait until it is. This stops the code
// from constantly looking for the VSYNC event with the screen
// turned off.
pthread_mutex_lock(&vsync_mutex);
if(!vsync_enable) pthread_cond_wait(&vsync_condition, &vsync_mutex);
pthread_mutex_unlock(&vsync_mutex);
timestamp = 0; // Reset the timestamp value
// S3CFB_WAIT_FOR_VSYNC is a custom IOCTL I added to wait for
// the VSYNC interrupt, and then return the timestamp that was
// originally being communicated via a uevent. The uevent was
// spamming the UEventObserver and events/0 process with more
// information than this device could really deal with every 18ms
int res = ioctl(ctx->global_lcd_win.fd, S3CFB_WAIT_FOR_VSYNC, ×tamp);
if(res > 0) {
if(!ctx->procs || !ctx->procs->vsync) continue;
ctx->procs->vsync(ctx->procs, 0, timestamp);
}
#else
int len = uevent_next_event(uevent_desc, sizeof(uevent_desc) - 2);
bool vsync = !strcmp(uevent_desc, "change@/devices/platform/s3cfb");
if(vsync)
handle_vsync_uevent(ctx, uevent_desc, len);
#endif
}
return NULL;
}
static int hwc_device_close(struct hw_device_t *dev)
{
struct hwc_context_t* ctx = (struct hwc_context_t*)dev;
int ret = 0;
int i;
if (ctx) {
if (destroyFimc(&ctx->fimc) < 0) {
ALOGE("%s::destroyFimc fail", __func__);
ret = -1;
}
if (window_close(&ctx->global_lcd_win) < 0) {
ALOGE("%s::window_close() fail", __func__);
ret = -1;
}
for (i = 0; i < NUM_OF_WIN; i++) {
if (window_close(&ctx->win[i]) < 0) {
ALOGE("%s::window_close() fail", __func__);
ret = -1;
}
}
// TODO: stop vsync_thread
free(ctx);
}
return ret;
}
static int hwc_device_open(const struct hw_module_t* module, const char* name,
struct hw_device_t** device)
{
int status = 0;
int err;
struct hwc_win_info_t *win;
#if defined(BOARD_USES_HDMI)
struct hw_module_t *hdmi_module;
#endif
if(hw_get_module(GRALLOC_HARDWARE_MODULE_ID,
(const hw_module_t**)&gpsGrallocModule))
return -EINVAL;
if(strcmp(gpsGrallocModule->base.common.author, "Imagination Technologies"))
return -EINVAL;
if (strcmp(name, HWC_HARDWARE_COMPOSER))
return -EINVAL;
struct hwc_context_t *dev;
dev = (hwc_context_t*)malloc(sizeof(*dev));
/* initialize our state here */
memset(dev, 0, sizeof(*dev));
/* initialize the procs */
dev->device.common.tag = HARDWARE_DEVICE_TAG;
dev->device.common.version = HWC_DEVICE_API_VERSION_1_0;
dev->device.common.module = const_cast<hw_module_t*>(module);
dev->device.common.close = hwc_device_close;
dev->device.prepare = hwc_prepare;
dev->device.set = hwc_set;
dev->device.eventControl = hwc_eventControl;
dev->device.blank = hwc_blank;
dev->device.query = hwc_query;
dev->device.registerProcs = hwc_registerProcs;
*device = &dev->device.common;
#if defined(BOARD_USES_HDMI)
dev->hdmi = NULL;
if(hw_get_module(HDMI_HARDWARE_MODULE_ID,
(const hw_module_t**)&hdmi_module)) {
ALOGE("%s:: HDMI device not present", __func__);
} else {
int ret = module->methods->open(hdmi_module, "hdmi-composer",
(hw_device_t **)&dev->hdmi);
if(ret < 0) {
ALOGE("%s:: Failed to open hdmi device : %s", __func__, strerror(ret));
}
}
#endif
/* initializing */
memset(&(dev->fimc), 0, sizeof(s5p_fimc_t));
dev->fimc.dev_fd = -1;
/* open WIN0 & WIN1 here */
for (int i = 0; i < NUM_OF_WIN; i++) {
if (window_open(&(dev->win[i]), i) < 0) {
ALOGE("%s:: Failed to open window %d device ", __func__, i);
status = -EINVAL;
goto err;
}
}
/* open window 2, used to query global LCD info */
if (window_open(&dev->global_lcd_win, 2) < 0) {
ALOGE("%s:: Failed to open window 2 device ", __func__);
status = -EINVAL;
goto err;
}
/* get default window config */
if (window_get_global_lcd_info(dev) < 0) {
ALOGE("%s::window_get_global_lcd_info is failed : %s",
__func__, strerror(errno));
status = -EINVAL;
goto err;
}
dev->lcd_info.yres_virtual = dev->lcd_info.yres * NUM_OF_WIN_BUF;
/* initialize the window context */
for (int i = 0; i < NUM_OF_WIN; i++) {
win = &dev->win[i];
memcpy(&win->lcd_info, &dev->lcd_info, sizeof(struct fb_var_screeninfo));
memcpy(&win->var_info, &dev->lcd_info, sizeof(struct fb_var_screeninfo));
win->rect_info.x = 0;
win->rect_info.y = 0;
win->rect_info.w = win->var_info.xres;
win->rect_info.h = win->var_info.yres;
if (window_set_pos(win) < 0) {
ALOGE("%s::window_set_pos is failed : %s",
__func__, strerror(errno));
status = -EINVAL;
goto err;
}
if (window_get_info(win) < 0) {
ALOGE("%s::window_get_info is failed : %s",
__func__, strerror(errno));
status = -EINVAL;
goto err;
}
win->size = win->fix_info.line_length * win->var_info.yres;
if (!win->fix_info.smem_start){
ALOGE("%s:: win-%d failed to get the reserved memory", __func__, i);
status = -EINVAL;
goto err;
}
for (int j = 0; j < NUM_OF_WIN_BUF; j++) {
win->addr[j] = win->fix_info.smem_start + (win->size * j);
ALOGI("%s::win-%d add[%d] %x ", __func__, i, j, win->addr[j]);
}
}
/* open pp */
if (createFimc(&dev->fimc) < 0) {
ALOGE("%s::creatFimc() fail", __func__);
status = -EINVAL;
goto err;
}
err = pthread_create(&dev->vsync_thread, NULL, hwc_vsync_thread, dev);
if (err) {
ALOGE("%s::pthread_create() failed : %s", __func__, strerror(err));
status = -err;
goto err;
}
ALOGD("%s:: success\n", __func__);
return 0;
err:
if (destroyFimc(&dev->fimc) < 0)
ALOGE("%s::destroyFimc() fail", __func__);
if (window_close(&dev->global_lcd_win) < 0)
ALOGE("%s::window_close() fail", __func__);
for (int i = 0; i < NUM_OF_WIN; i++) {
if (window_close(&dev->win[i]) < 0)
ALOGE("%s::window_close() fail", __func__);
}
return status;
}
| 32.373626
| 96
| 0.575092
|
DrDoubt
|
88ae512084cae3dce1817e54429e2a9f2947912d
| 1,095
|
cc
|
C++
|
codeforces/Round582-Div.3/D.cc
|
OFShare/Algorithm-challenger
|
43336871a5e48f8804d6e737c813d9d4c0dc2731
|
[
"MIT"
] | 67
|
2019-07-14T05:38:41.000Z
|
2021-12-23T11:52:51.000Z
|
codeforces/Round582-Div.3/D.cc
|
OFShare/Algorithm-challenger
|
43336871a5e48f8804d6e737c813d9d4c0dc2731
|
[
"MIT"
] | null | null | null |
codeforces/Round582-Div.3/D.cc
|
OFShare/Algorithm-challenger
|
43336871a5e48f8804d6e737c813d9d4c0dc2731
|
[
"MIT"
] | 12
|
2020-01-16T10:48:01.000Z
|
2021-06-11T16:49:04.000Z
|
//
// Created by OFShare on 2019-09-10
//
#include <bits/stdc++.h>
const int maxn = 2e5 + 5;
int n, k;
int A[maxn];
// canNumber[i]记录可以变成i这个数,的个数
int canNumber[maxn];
// cntNumber[i][j]记录变成i时需要j次操作,的个数
int cntNumber[maxn][30];
void preprocess(int x) {
int cnt = 0;
while(x){
canNumber[x]++;
cntNumber[x][cnt]++;
x /= 2;
cnt++;
}
canNumber[0]++;
cntNumber[x][cnt]++;
}
int main() {
scanf("%d %d", &n, &k);
for(int i = 1; i <= n; ++i){
scanf("%d", &A[i]);
preprocess(A[i]);
}
int ans = 1e9;
// 枚举最后k个相等的数为i时
for(int i = 0; i <= 2e5; ++i) {
if(canNumber[i] >= k) {
int sum = 0, number = 0;
for(int j = 0; j <= 30; ++j) {
// 一个一个的贡献
while(cntNumber[i][j] > 0 && number < k) {
cntNumber[i][j]--;
number++;
sum += j;
}
if(number == k) break;
}
ans = std::min(ans, sum);
}
}
printf("%d", ans);
return 0;
}
| 20.660377
| 58
| 0.415525
|
OFShare
|
88b4111e7ee5665a71371b9f5090bb8392bc44a4
| 397
|
cc
|
C++
|
result.cc
|
espindola/libcthulhu
|
8ab74385abd257abcd49f780675b0849a8c69bfb
|
[
"0BSD"
] | 12
|
2020-09-10T03:01:45.000Z
|
2022-03-10T09:03:03.000Z
|
result.cc
|
espindola/libcthulhu
|
8ab74385abd257abcd49f780675b0849a8c69bfb
|
[
"0BSD"
] | null | null | null |
result.cc
|
espindola/libcthulhu
|
8ab74385abd257abcd49f780675b0849a8c69bfb
|
[
"0BSD"
] | 1
|
2021-05-13T06:27:19.000Z
|
2021-05-13T06:27:19.000Z
|
// Copyright (C) 2019 ScyllaDB
#include <cthulhu/result.hh>
#include <errno.h>
#include <string.h>
using namespace cthulhu;
posix_error::posix_error(int error_number) : error_number(error_number) {
assert(error_number && "not an error");
}
posix_error posix_error::current() {
return errno;
}
void posix_error::print_error(FILE *stream) {
fprintf(stream, "%s", strerror(error_number));
}
| 18.904762
| 73
| 0.732997
|
espindola
|
88b89dbd5d774ccf7b6a7014d649875ec9b40fd8
| 4,327
|
cpp
|
C++
|
80/prog.cpp
|
alexsyrom/ProjectEuler
|
78c3e2a0e2d4948ef4faa5d65ff58defd5835620
|
[
"MIT"
] | null | null | null |
80/prog.cpp
|
alexsyrom/ProjectEuler
|
78c3e2a0e2d4948ef4faa5d65ff58defd5835620
|
[
"MIT"
] | null | null | null |
80/prog.cpp
|
alexsyrom/ProjectEuler
|
78c3e2a0e2d4948ef4faa5d65ff58defd5835620
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
#include <algorithm>
template <class Class>
void Print(Class instance) {
std::cout << instance << std::endl;
}
void Print() {
std::cout << std::endl;
}
class UnsignedDecimalFloat {
public:
static const size_t kBase = 10;
static const size_t kPrecision = 204;
UnsignedDecimalFloat(size_t number = 0)
: digits_(kPrecision, 0)
{
digits_[0] = number;
}
UnsignedDecimalFloat operator* (const UnsignedDecimalFloat& multiplier) const {
UnsignedDecimalFloat result = 0;
for (size_t result_index = 0; result_index < kPrecision; ++result_index) {
for (size_t this_index = 0; this_index <= result_index; ++ this_index) {
size_t multiplier_index = result_index - this_index;
result.digits_[result_index] += this->digits_[this_index] *
multiplier.digits_[multiplier_index];
}
}
for (size_t result_index = kPrecision - 1; result_index > 0; --result_index) {
result.digits_[result_index - 1] += result.digits_[result_index] / kBase;
result.digits_[result_index] %= kBase;
}
return result;
}
UnsignedDecimalFloat operator+ (const UnsignedDecimalFloat& other) const {
UnsignedDecimalFloat result = 0;
for (size_t index = 0; index < kPrecision; ++index) {
result.digits_[index] = this->digits_[index] + other.digits_[index];
}
for (size_t index = kPrecision - 1; index > 0; --index) {
result.digits_[index - 1] += result.digits_[index] / kBase;
result.digits_[index] %= kBase;
}
return result;
}
UnsignedDecimalFloat operator/ (size_t other) const {
UnsignedDecimalFloat result = *this;
for (size_t index = 0; index < kPrecision - 1; ++index) {
result.digits_[index + 1] += kBase * (result.digits_[index] % other);
result.digits_[index] /= other;
}
result.digits_[kPrecision - 1] /= other;
return result;
}
bool operator< (const UnsignedDecimalFloat& other) const {
return digits_ < other.digits_;
}
size_t ComputeNFirstDigitsSum(size_t first_digits_number) {
first_digits_number = std::min(first_digits_number, kPrecision);
return std::accumulate(digits_.begin(), digits_.begin() + first_digits_number, 0);
}
static UnsignedDecimalFloat GetMinimumNonZeroNumber() {
UnsignedDecimalFloat result = 0;
result.digits_[kPrecision - 1] = 1;
return result;
}
static UnsignedDecimalFloat GetMinimumNonZeroNumberWithHalvedPrecision() {
UnsignedDecimalFloat result = 0;
result.digits_[kPrecision / 2 - 1] = 1;
return result;
}
private:
// digits_[0] is the integer part of the number, others are true digits after the point
std::vector<size_t> digits_;
};
const UnsignedDecimalFloat kEpsilon = UnsignedDecimalFloat::GetMinimumNonZeroNumber();
const UnsignedDecimalFloat kEpsilonSqrt =
UnsignedDecimalFloat::GetMinimumNonZeroNumberWithHalvedPrecision();
bool IsSquare(size_t number) {
uint64_t root = std::sqrt(number);
for (uint64_t index = root - 1; index < root + 2; ++index) {
if (index * index == number) {
return true;
}
}
return false;
}
UnsignedDecimalFloat Sqrt(
const UnsignedDecimalFloat& number,
UnsignedDecimalFloat left,
UnsignedDecimalFloat right,
const UnsignedDecimalFloat& epsilon = kEpsilonSqrt)
{
while (left + epsilon < right) {
auto medium = (left + right) / 2;
if (number < medium * medium) {
right = medium;
} else {
left = medium;
}
}
return left;
}
int main() {
std::ofstream output_stream("output.txt");
size_t digit_sum = 0;
UnsignedDecimalFloat previous_root = 1;
for (size_t index = 2; index < 100; ++index) {
if (IsSquare(index)) {
continue;
}
UnsignedDecimalFloat root = Sqrt(index, previous_root, index);
previous_root = root;
digit_sum += root.ComputeNFirstDigitsSum(100);
}
output_stream << digit_sum;
return 0;
}
| 30.471831
| 92
| 0.623758
|
alexsyrom
|
88ba1214b01266b549602efee89b52bd888e7983
| 1,744
|
cpp
|
C++
|
src/domain/finite_element/finite_element.cpp
|
SlaybaughLab/Transport
|
8eb32cb8ae50c92875526a7540350ef9a85bc050
|
[
"MIT"
] | 12
|
2018-03-14T12:30:53.000Z
|
2022-01-23T14:46:44.000Z
|
src/domain/finite_element/finite_element.cpp
|
SlaybaughLab/Transport
|
8eb32cb8ae50c92875526a7540350ef9a85bc050
|
[
"MIT"
] | 194
|
2017-07-07T01:38:15.000Z
|
2021-05-19T18:21:19.000Z
|
src/domain/finite_element/finite_element.cpp
|
SlaybaughLab/Transport
|
8eb32cb8ae50c92875526a7540350ef9a85bc050
|
[
"MIT"
] | 10
|
2017-07-06T22:58:59.000Z
|
2021-03-15T07:01:21.000Z
|
#include "domain/finite_element/finite_element.hpp"
namespace bart::domain::finite_element {
template <int dim>
auto FiniteElement<dim>::SetCell(const domain::CellPtr<dim> &to_set) -> bool {
bool already_set{ false };
if (values_reinit_called_) {
already_set = (values_->get_cell()->id() == to_set->id());
}
if (!already_set) {
values_->reinit(to_set);
values_reinit_called_ = true;
}
return !already_set;
}
template <int dim>
auto FiniteElement<dim>::SetFace(const domain::CellPtr<dim> &to_set, const domain::FaceIndex face) -> bool{
bool already_set{ false };
bool cell_already_set{ false };
if (face_values_reinit_called_) {
cell_already_set = (face_values_->get_cell()->id() == to_set->id());
bool face_already_set = (static_cast<int>(face_values_->get_face_index()) == face.get());
already_set = (cell_already_set && face_already_set);
}
if (!already_set) {
face_values_->reinit(to_set, face.get());
face_values_reinit_called_ = true;
}
return !cell_already_set;
}
template<int dim>
auto FiniteElement<dim>::ValueAtQuadrature(const DealiiVector& values_at_dofs) const -> std::vector<double> {
std::vector<double> return_vector(n_cell_quad_pts(), 0);
values_->get_function_values(values_at_dofs, return_vector);
return return_vector;
}
template<int dim>
auto FiniteElement<dim>::ValueAtFaceQuadrature(const DealiiVector& values_at_dofs) const -> std::vector<double> {
std::vector<double> return_vector(n_face_quad_pts(), 0);
face_values_->get_function_values(values_at_dofs, return_vector);
return return_vector;
}
template class FiniteElement<1>;
template class FiniteElement<2>;
template class FiniteElement<3>;
} // namespace bart::domain::finite_element
| 30.068966
| 113
| 0.735092
|
SlaybaughLab
|
88bc4a6f30756e262d4acab589acca2a10e72e0d
| 1,410
|
cpp
|
C++
|
Minigin/ColliderComponent.cpp
|
Zakatos/Component-Game-Engine
|
c52f49ada5c23cdee502f4d3a8ce09392d6bcae9
|
[
"MIT"
] | null | null | null |
Minigin/ColliderComponent.cpp
|
Zakatos/Component-Game-Engine
|
c52f49ada5c23cdee502f4d3a8ce09392d6bcae9
|
[
"MIT"
] | null | null | null |
Minigin/ColliderComponent.cpp
|
Zakatos/Component-Game-Engine
|
c52f49ada5c23cdee502f4d3a8ce09392d6bcae9
|
[
"MIT"
] | null | null | null |
#include "MiniginPCH.h"
#include "ECS/ColliderComponent.h"
#include "RendererComponent.h"
ColliderComponent::ColliderComponent(const std::string& t)
:m_Tag(t)
{
}
ColliderComponent::ColliderComponent(const std::string& t, int xpos, int ypos, int size)
:m_Tag(t)
{
m_Collider.x = xpos;
m_Collider.y = ypos;
m_Collider.h = m_Collider.w = size;
}
ColliderComponent::~ColliderComponent()
{
SDL_DestroyTexture(m_pTex);
//delete m_pRenderer;
//m_pRenderer = nullptr;
}
void ColliderComponent::init()
{
if (!m_pEntity->hasComponent<TransformComponent>())
{
m_pEntity->addComponent<TransformComponent>();
}
m_pTransform = &m_pEntity->getComponent<TransformComponent>();
m_pRenderer = &m_pEntity->getComponent<RendererComponent>();
m_pTex = m_pRenderer->LoadTexture("assets/coltex.png");
m_SrcR = { 0, 0, 32, 32 };
m_destR = { m_Collider.x, m_Collider.y, m_Collider.w, m_Collider.h };
}
void ColliderComponent::update()
{
if (m_Tag != "terrain")
{
m_Collider.x = static_cast<int>(m_pTransform->GetPosition().m_X);
m_Collider.y = static_cast<int>(m_pTransform->GetPosition().m_Y);
m_Collider.w = m_pTransform->GetWidth() * m_pTransform->GetScale();
m_Collider.h = m_pTransform->GetHeight() * m_pTransform->GetScale();
}
m_destR.x = m_Collider.x;
m_destR.y = m_Collider.y;
}
void ColliderComponent::draw()
{
m_pRenderer->Draw(m_pTex, m_SrcR, m_destR, SDL_FLIP_NONE);
}
| 21.692308
| 88
| 0.721986
|
Zakatos
|
88c74c39378a3adb3eb8fb80d7c50d248aecc6d0
| 721
|
cpp
|
C++
|
Aula24/P1_GrowlingGears/GrowlingGears.cpp
|
VanessaMMH/ProgComp2021A
|
03a3e0394b26eb78801246c7d6b7888fe53141bd
|
[
"BSD-3-Clause"
] | null | null | null |
Aula24/P1_GrowlingGears/GrowlingGears.cpp
|
VanessaMMH/ProgComp2021A
|
03a3e0394b26eb78801246c7d6b7888fe53141bd
|
[
"BSD-3-Clause"
] | null | null | null |
Aula24/P1_GrowlingGears/GrowlingGears.cpp
|
VanessaMMH/ProgComp2021A
|
03a3e0394b26eb78801246c7d6b7888fe53141bd
|
[
"BSD-3-Clause"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
/*
link:https://open.kattis.com/problems/growlinggears
*/
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int q;
cin >> q;
for (int i = 0; i < q; i++)
{
int n, index;
double max = -500000.0;
cin >> n;
for (int j = 0; j < n; j++)
{
double a, b, c, T = 1;
cin >> a >> b >> c;
b /= a;
c /= a;
T /= a;
b /= 2;
b *= b;
c += b;
c /= T;
if (c > max)
{
max = c;
index = j + 1;
}
}
cout << index << "\n";
}
}
| 18.973684
| 51
| 0.330097
|
VanessaMMH
|
88c84d9159cc16011dcbf448c36abe10bf766683
| 1,848
|
cpp
|
C++
|
Problem/src/SampleProblem.cpp
|
tut-cc/DiceTilingMeu
|
d07d6e27370385ff7b4bce48f34f64bb1caa41ee
|
[
"MIT"
] | 8
|
2015-10-12T05:39:06.000Z
|
2016-08-20T06:12:26.000Z
|
Problem/src/SampleProblem.cpp
|
tut-cc/DiceTilingMeu
|
d07d6e27370385ff7b4bce48f34f64bb1caa41ee
|
[
"MIT"
] | null | null | null |
Problem/src/SampleProblem.cpp
|
tut-cc/DiceTilingMeu
|
d07d6e27370385ff7b4bce48f34f64bb1caa41ee
|
[
"MIT"
] | null | null | null |
#include "SampleProblem.hpp"
#include <string>
#include <iostream>
#include <fstream>
#include <cstdlib>
SampleProblem::SampleProblem(std::string p) {
std::ifstream ifs(p);
if (ifs.fail()) {
std::cout << "failed" << std::endl;
}
std::string str;
for (int i = 0; i < 32; i++) {
ifs >> str;
field.push_back(str);
// std::cout << str << std::endl;
}
/*
ifs >> num;
std::cout << num << std::endl;
*/
ifs >> str;
num = std::atoi(str.c_str());
// std::cout << num << std::endl;
for (int i = 0; i < num; i++) {
std::vector<std::string> tmp_stone;
for (int j = 0; j < 8; j++) {
ifs >> str;
tmp_stone.push_back(str);
// std::cout << str << std::endl;
}
stones.push_back(tmp_stone);
// std::cout << std::endl;
}
/*
std::cout << "test" << std::endl;
std::cin >> str;
*/
}
SampleProblem::SampleProblem(){
std::ifstream ifs("problem/53.txt");
if (ifs.fail()){
std::cout << "failed" << std::endl;
}
std::string str;
for (int i = 0; i < 32; i++){
ifs >> str;
field.push_back(str);
// std::cout << str << std::endl;
}
/*
ifs >> num;
std::cout << num << std::endl;
*/
ifs >> str;
num = std::atoi(str.c_str());
// std::cout << num << std::endl;
for (int i = 0; i < num; i++){
std::vector<std::string> tmp_stone;
for (int j = 0; j < 8; j++){
ifs >> str;
tmp_stone.push_back(str);
// std::cout << str << std::endl;
}
stones.push_back(tmp_stone);
// std::cout << std::endl;
}
/*
std::cout << "test" << std::endl;
std::cin >> str;
*/
}
std::vector<std::string> SampleProblem::get_field_str() const
{
return field;
}
std::vector<std::vector<std::string>> SampleProblem::get_stones_str() const
{
return stones;
}
std::vector<std::string> SampleProblem::get_stone_str(int idx) const
{
return stones[idx];
}
int SampleProblem::num_of_stones() const
{
return num;
}
| 18.29703
| 75
| 0.573593
|
tut-cc
|
88cea4245e1afd4b8b01c0337241f46a7b92f1b1
| 589
|
cpp
|
C++
|
src/semantic/semantic-utils.cpp
|
noct-lang/noct-bootstrap
|
6fd5ef91feda665dc3f1d8f5dca6403512ac44be
|
[
"0BSD"
] | 1
|
2019-07-01T02:02:40.000Z
|
2019-07-01T02:02:40.000Z
|
src/semantic/semantic-utils.cpp
|
noct-lang/noct-bootstrap
|
6fd5ef91feda665dc3f1d8f5dca6403512ac44be
|
[
"0BSD"
] | null | null | null |
src/semantic/semantic-utils.cpp
|
noct-lang/noct-bootstrap
|
6fd5ef91feda665dc3f1d8f5dca6403512ac44be
|
[
"0BSD"
] | null | null | null |
#include "semantic-utils.hpp"
#include "semantic-pass.hpp"
#include "ast/ast.hpp"
namespace Noctis
{
StdUnorderedSet<QualNameSPtr> ExtractImportModules(AstTree& tree)
{
class ImportExtractor : public AstSemanticPass
{
public:
ImportExtractor()
: AstSemanticPass("import extractor")
{
}
void Visit(AstImportStmt& node) override
{
QualNameSPtr qualName = QualName::Create(node.moduleIdens);
qualNames.insert(qualName);
}
StdUnorderedSet<QualNameSPtr> qualNames;
} extractor;
extractor.Process(tree);
return extractor.qualNames;
}
}
| 19
| 66
| 0.714771
|
noct-lang
|
88cef625917719a69838ff753fbbfb149edf66ee
| 2,982
|
cpp
|
C++
|
storage/sstable/writer/sharding_sstable_writer.cpp
|
hjinlin/toft
|
ebf3ebb3d37e9a59e27b197cefe8fdc3e8810441
|
[
"BSD-3-Clause"
] | 264
|
2015-01-03T11:50:17.000Z
|
2022-03-17T02:38:34.000Z
|
storage/sstable/writer/sharding_sstable_writer.cpp
|
hjinlin/toft
|
ebf3ebb3d37e9a59e27b197cefe8fdc3e8810441
|
[
"BSD-3-Clause"
] | 12
|
2015-04-27T15:17:34.000Z
|
2021-05-01T04:31:18.000Z
|
storage/sstable/writer/sharding_sstable_writer.cpp
|
hjinlin/toft
|
ebf3ebb3d37e9a59e27b197cefe8fdc3e8810441
|
[
"BSD-3-Clause"
] | 128
|
2015-02-07T18:13:10.000Z
|
2022-02-21T14:24:14.000Z
|
// Copyright (c) 2013, The Toft Authors.
// All rights reserved.
//
// Author: Ye Shunping <yeshunping@gmail.com>
#include "toft/storage/sstable/writer/sharding_sstable_writer.h"
#include "toft/base/stl_util.h"
#include "toft/base/string/format.h"
#include "toft/base/string/number.h"
#include "toft/hash/fingerprint.h"
#include "toft/storage/sharding/sharding.h"
#include "toft/storage/sstable/writer/composited_sstable_writer.h"
#include "thirdparty/glog/logging.h"
namespace toft {
const std::string ShardingSSTableWriter::GetShardingPath(const std::string &path,
int shard_index,
int shard_num) {
return StringPrint("%s-%05d-of-%05d", path.c_str(), shard_index, shard_num);
}
ShardingSSTableWriter::ShardingSSTableWriter(int shard_num, const SSTableWriteOption &option)
: SSTableWriter(option),
shard_num_(shard_num),
set_id_(0) {
std::string policy = option.sharding_policy();
sharding_policy_.reset(TOFT_CREATE_SHARDING_POLICY(policy));
CHECK(sharding_policy_.get()) << "sharding policy is invalid: " << policy;
sharding_policy_->SetShardingNumber(shard_num_);
std::string set_finger = StringPrint("%s/%ld", option.path().c_str(), time(NULL));
set_id_ = Fingerprint64(set_finger);
VLOG(1) << "set_id_:" << set_id_;
for (int i = 0; i < shard_num_; ++i) {
SSTableWriteOption opt(option);
opt.set_path(GetShardingPath(option.path(), i, shard_num_));
builders_.push_back(new CompositedSSTableWriter(opt));
}
}
ShardingSSTableWriter::~ShardingSSTableWriter() {
DeleteElements(&builders_);
}
bool ShardingSSTableWriter::Add(const std::string &key, const std::string &value) {
int index = sharding_policy_->Shard(key);
CHECK_GE(index, 0) << "bad index, key:" << key;
return builders_[index]->Add(key, value);
}
void ShardingSSTableWriter::AddMetaData(const std::string &key, const std::string &value) {
file_info_meta_[key] = value;
}
bool ShardingSSTableWriter::Flush() {
SetMetaData();
bool result = true;
for (int i = 0; i < shard_num_; ++i) {
if (!builders_[i]->Flush())
result = false;
}
return result;
}
void ShardingSSTableWriter::SetMetaData() {
std::string total_shard = NumberToString(shard_num_);
for (int i = 0; i < shard_num_; ++i) {
for (std::map<std::string, std::string>::const_iterator it = file_info_meta_.begin();
it != file_info_meta_.end(); ++it)
builders_[i]->AddMetaData(it->first, it->second);
builders_[i]->AddMetaData(kShardID, NumberToString(i));
builders_[i]->AddMetaData(kShardTotalNum, total_shard);
builders_[i]->AddMetaData(kShardPolicy, option_.sharding_policy());
builders_[i]->AddMetaData(kSSTableSetID, NumberToString(set_id_));
}
}
} // namespace toft
| 35.5
| 93
| 0.653588
|
hjinlin
|
88d3df327a998aec29ea949377ccf13648683831
| 15,051
|
cpp
|
C++
|
src/main.cpp
|
GlyphXTools/chunk-viewer
|
d5163969e8986d557b6cfbb524279f36235fda02
|
[
"MIT"
] | 7
|
2017-01-22T09:09:40.000Z
|
2021-11-13T08:51:31.000Z
|
src/main.cpp
|
GlyphXTools/chunk-viewer
|
d5163969e8986d557b6cfbb524279f36235fda02
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
GlyphXTools/chunk-viewer
|
d5163969e8986d557b6cfbb524279f36235fda02
|
[
"MIT"
] | 1
|
2019-04-07T05:09:11.000Z
|
2019-04-07T05:09:11.000Z
|
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <commdlg.h>
#include <commctrl.h>
#include <shlobj.h>
#include "resource.h"
#include <afxres.h>
#include <tchar.h>
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include "ChunkFile.h"
#include "Exceptions.h"
using namespace std;
typedef basic_string<TCHAR> tstring;
typedef basic_stringstream<TCHAR> tstringstream;
// Global info about the applications
struct ApplicationInfo
{
HINSTANCE hInstance;
HWND hMainWnd;
HWND hNodeTree;
HWND hNodeInfo;
HWND hWidthLabel;
HWND hWidthUpDown;
HWND hWidthEdit;
tstring filename;
vector<pair<int, char*> > nodeData;
};
static bool IsProbablyMiniChunk(int size, char* data)
{
while (size > 2 && data[1] != 0)
{
int msize = (unsigned char)data[1] + 2;
size -= msize;
data += msize;
}
return (size == 0);
}
static void RemoveChildren( HWND hTree, HTREEITEM hItem)
{
HTREEITEM hChild;
while ((hChild = TreeView_GetChild(hTree, hItem)) != NULL)
{
RemoveChildren(hTree, hChild);
TreeView_DeleteItem(hTree, hChild);
}
}
static void SetNodes( vector<pair<int, char*> >& nodeData, HWND hTree, HTREEITEM hParent, File* input)
{
HTREEITEM hItem = TreeView_GetChild(hTree, hParent);
while (!input->eof())
{
Chunk chunk(input);
unsigned long start = input->tell();
tstringstream str;
str << hex << setw(8) << setfill(TEXT('0')) << chunk.getType() << "h (" << setw(8) << chunk.getSize() << "h)";
tstring title = str.str();
TVINSERTSTRUCT item;
item.item.mask = TVIF_CHILDREN | TVIF_TEXT | TVIF_PARAM;
item.item.hItem = hItem;
item.item.cChildren = (chunk.isGroup() ? 1 : 0);
item.item.pszText = const_cast<tstring::value_type*>(title.c_str());
item.item.lParam = (chunk.isGroup() ? -1 : nodeData.size());
if (hItem == NULL)
{
// Add it
item.hParent = hParent;
item.hInsertAfter = TVI_LAST;
hItem = TreeView_InsertItem(hTree, &item);
}
else
{
// Edit it
if (!chunk.isGroup())
{
// Remove all the node's children
RemoveChildren(hTree, hItem);
}
TreeView_SetItem(hTree, &item.item);
}
if (chunk.isGroup())
{
SetNodes(nodeData, hTree, hItem, chunk.getStream() );
}
else
{
// Set the node data
int size = chunk.getSize();
char* data = chunk.getData();
if (size < 0x1000 && IsProbablyMiniChunk(size, data))
{
size = -size;
}
nodeData.push_back( make_pair(size, data) );
}
input->seek( start + chunk.getSize() );
hItem = TreeView_GetNextSibling(hTree, hItem);
}
// Remove any trailing nodes
while (hItem != NULL)
{
RemoveChildren(hTree, hItem);
HTREEITEM hNext = TreeView_GetNextSibling(hTree, hItem);
TreeView_DeleteItem(hTree, hItem);
hItem = hNext;
}
}
static void FillNodeTree( ApplicationInfo* info, File* file )
{
// Clear previous
for (vector<pair<int, char*> >::iterator i = info->nodeData.begin(); i != info->nodeData.end(); i++)
{
delete[] i->second;
}
info->nodeData.clear();
HTREEITEM hRoot = TreeView_GetRoot(info->hNodeTree);
if (hRoot == NULL)
{
TVINSERTSTRUCT item;
item.hParent = NULL;
item.hInsertAfter = TVI_ROOT;
item.item.mask = TVIF_CHILDREN | TVIF_TEXT | TVIF_PARAM;
item.item.cChildren = 1;
item.item.pszText = TEXT("Chunk File");
item.item.lParam = -1;
hRoot = TreeView_InsertItem(info->hNodeTree, &item);
}
SetNodes(info->nodeData, info->hNodeTree, hRoot, file);
TreeView_Expand( info->hNodeTree, hRoot, TVE_EXPAND);
}
static tstring FormatNodeInfo( int size, char* data, int width, const char* prefix = "")
{
tstringstream str;
str << hex;
for (int i = 0; i < size; i++)
{
if (i % width == 0) str << prefix;
str << setw(2) << setfill(TEXT('0')) << (int)(unsigned char)data[i] << " ";
if (i % width == width - 1 || i == size - 1)
{
for (int k = i; k % width < width - 1; k++) str << " ";
str << " | ";
for (int j = (i / width) * width; j <= i; j++)
{
str << (isprint((unsigned char)data[j]) ? data[j] : '.');
}
str << "\r\n";
}
}
return str.str();
}
static void SetNodeInfo( HWND hWnd, int size, char* data, int width = 16 )
{
width = max(1, width);
tstring text;
if (size < 0)
{
// Parse as mini-chunks
size = -size;
tstringstream str;
while (size > 0)
{
int type = (unsigned char)data[0];
int msize = (unsigned char)data[1];
tstring chunk = FormatNodeInfo(msize, data + 2, width, " ");
if (!chunk.empty()) chunk = chunk.substr(7);
str << hex << setw(2) << setfill(TEXT('0')) << type << " "
<< setw(2) << setfill(TEXT('0')) << msize << ": " << chunk;
size -= msize + 2;
data += msize + 2;
}
text = str.str();
}
else
{
text = FormatNodeInfo(size, data, width);
}
SetWindowText(hWnd, text.c_str());
}
static void OnNodeSelected(ApplicationInfo* info, int index)
{
if (index >= 0 && (size_t)index < info->nodeData.size())
{
int size = info->nodeData[ index ].first;
char* data = info->nodeData[ index ].second;
BOOL error;
int width = (int)SendMessage(info->hWidthUpDown, UDM_GETPOS32, 0, (LPARAM)&error);
if (error) width = 16;
SetNodeInfo( info->hNodeInfo, size, data, width );
}
else
{
SetWindowText(info->hNodeInfo, TEXT(""));
}
}
static void DlgOpenFile( ApplicationInfo *info )
{
try
{
TCHAR filename[MAX_PATH];
filename[0] = TEXT('\0');
OPENFILENAME ofn;
memset(&ofn, 0, sizeof(OPENFILENAME));
ofn.lStructSize = sizeof(OPENFILENAME);
ofn.hwndOwner = info->hMainWnd;
ofn.hInstance = info->hInstance;
ofn.lpstrFilter = TEXT("Alamo Chunk Files (*.alo, *.ala, *.ted, *.tem, *.bui, *.rec)\0*.ALO; *.ALA; *.TED; *.TEM; *.BUI; *.REC\0All Files (*.*)\0*.*\0\0");
ofn.nFilterIndex = 0;
ofn.lpstrFile = filename;
ofn.nMaxFile = MAX_PATH;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
if (GetOpenFileName( &ofn ) != 0)
{
// Clear previous
info->filename = filename;
File* file = new PhysicalFile(info->filename);
SetWindowText(info->hNodeInfo, TEXT(""));
FillNodeTree( info, file );
EnableMenuItem(GetMenu(info->hMainWnd), ID_FILE_REFRESH, MF_BYCOMMAND | MF_ENABLED);
SetFocus(info->hNodeTree);
SAFE_RELEASE(file);
}
}
catch (exception&)
{
MessageBox(NULL, TEXT("Unable to open the specified file"), NULL, MB_OK | MB_ICONHAND );
}
}
static void RefreshFile(ApplicationInfo* info)
{
try
{
File* file = new PhysicalFile(info->filename);
FillNodeTree( info, file );
SAFE_RELEASE(file);
// Refresh selection
TVITEM item;
if ((item.hItem = TreeView_GetSelection(info->hNodeTree)) != NULL)
{
item.mask = TVIF_PARAM;
TreeView_GetItem(info->hNodeTree, &item);
OnNodeSelected(info, (int)item.lParam);
}
}
catch (exception&)
{
MessageBox(NULL, TEXT("Unable to refresh the opened file"), NULL, MB_OK | MB_ICONHAND );
}
}
static void DoSelectAll()
{
HWND hFocus = GetFocus();
TCHAR classname[256];
GetClassName(hFocus, classname, 256);
if (_tcscmp(classname, TEXT("Edit")) == 0)
{
// Select all text
SendMessage(hFocus, EM_SETSEL, 0, -1);
}
}
static LRESULT CALLBACK MainWindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
ApplicationInfo* info = (ApplicationInfo*)(LONG_PTR)GetWindowLongPtr(hWnd, GWLP_USERDATA);
switch (uMsg)
{
case WM_CREATE:
{
CREATESTRUCT* pcs = (CREATESTRUCT*)lParam;
info = (ApplicationInfo*)pcs->lpCreateParams;
SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)info );
RECT client;
GetClientRect(hWnd, &client);
if ((info->hNodeTree = CreateWindowEx(WS_EX_CLIENTEDGE, WC_TREEVIEW, TEXT(""),
WS_CHILD | WS_VISIBLE | TVS_HASLINES | TVS_HASBUTTONS | TVS_LINESATROOT,
0, 0, 400, client.bottom, hWnd, NULL, pcs->hInstance, NULL)) == NULL) return -1;
if ((info->hWidthLabel = CreateWindow(TEXT("STATIC"), TEXT("Width:"),
WS_CHILD | WS_VISIBLE,
410, 6, 40, 12, hWnd, NULL, pcs->hInstance, NULL)) == NULL) return -1;
if ((info->hWidthEdit = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("EDIT"), TEXT(""),
WS_CHILD | WS_VISIBLE | ES_RIGHT | ES_NUMBER,
450, 4, 75, 20, hWnd, NULL, pcs->hInstance, NULL)) == NULL) return -1;
if ((info->hWidthUpDown = CreateWindow(UPDOWN_CLASS, TEXT(""),
WS_CHILD | WS_VISIBLE | UDS_NOTHOUSANDS | UDS_SETBUDDYINT | UDS_AUTOBUDDY | UDS_ARROWKEYS | UDS_ALIGNRIGHT,
400, 0, 10, 10, hWnd, NULL, pcs->hInstance, NULL)) == NULL) return -1;
if ((info->hNodeInfo = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("EDIT"), TEXT(""),
WS_CHILD | WS_VISIBLE | ES_MULTILINE | ES_READONLY | WS_VSCROLL | WS_HSCROLL,
400, 30, client.right - 600, client.bottom, hWnd, NULL, pcs->hInstance, NULL)) == NULL) return -1;
SendMessage(info->hWidthUpDown, UDM_SETRANGE32, (WPARAM)1, (LPARAM)INT_MAX);
SendMessage(info->hWidthUpDown, UDM_SETPOS32, 0, (LPARAM)16);
HFONT hFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT);
SendMessage(info->hNodeTree, WM_SETFONT, (WPARAM)hFont, FALSE);
SendMessage(info->hWidthLabel, WM_SETFONT, (WPARAM)hFont, FALSE);
SendMessage(info->hWidthEdit, WM_SETFONT, (WPARAM)hFont, FALSE);
SendMessage(info->hNodeInfo, WM_SETFONT, (WPARAM)GetStockObject(OEM_FIXED_FONT), FALSE);
break;
}
case WM_SETFOCUS:
SetFocus(info->hNodeTree);
break;
case WM_COMMAND:
if (lParam == 0)
{
// Menu or accelerator
switch (LOWORD(wParam))
{
case ID_FILE_OPEN:
if (info != NULL)
{
DlgOpenFile(info);
}
break;
case ID_FILE_REFRESH:
if (info != NULL)
{
RefreshFile(info);
}
break;
case ID_FILE_EXIT:
PostQuitMessage(0);
break;
case ID_EDIT_COPY:
SendMessage(GetFocus(), WM_COPY, 0, 0);
break;
case ID_EDIT_SELECTALL:
DoSelectAll();
break;
case ID_HELP_ABOUT:
MessageBox(hWnd, TEXT("Alamo Chunk Viewer 1.0\n\nBy Mike Lankamp"), TEXT("About"), MB_OK);
break;
}
}
else if (info != NULL)
{
// Control
switch (HIWORD(wParam))
{
case EN_CHANGE:
{
TCHAR strWidth[32];
GetWindowText( info->hWidthEdit, strWidth, 32 );
TVITEM item;
item.mask = TVIF_PARAM;
item.hItem = TreeView_GetSelection(info->hNodeTree);
TreeView_GetItem(info->hNodeTree, &item);
if (item.hItem != NULL && item.lParam != -1)
{
int width = _tcstoul(strWidth, 0, NULL);
int size = info->nodeData[ item.lParam ].first;
char* data = info->nodeData[ item.lParam ].second;
SetNodeInfo( info->hNodeInfo, size, data, width );
}
break;
}
}
}
break;
case WM_NOTIFY:
if (info != NULL)
{
NMHDR* nmhdr = (NMHDR*)lParam;
switch (nmhdr->code)
{
case TVN_SELCHANGED:
{
NMTREEVIEW* pnmtv = (NMTREEVIEW*)lParam;
OnNodeSelected(info, (int)pnmtv->itemNew.lParam);
break;
}
case UDN_DELTAPOS:
{
NM_UPDOWN* nmud = (NM_UPDOWN*)nmhdr;
int width = nmud->iPos + nmud->iDelta;
TVITEM item;
item.mask = TVIF_PARAM;
item.hItem = TreeView_GetSelection(info->hNodeTree);
TreeView_GetItem(info->hNodeTree, &item);
if (item.hItem != NULL && item.lParam != -1)
{
int size = info->nodeData[ item.lParam ].first;
char* data = info->nodeData[ item.lParam ].second;
SetNodeInfo( info->hNodeInfo, size, data, width );
}
break;
}
}
}
break;
case WM_SIZE:
if (info != NULL)
{
RECT client;
GetClientRect(info->hMainWnd, &client);
MoveWindow(info->hNodeTree, 0, 0, 400, client.bottom, TRUE);
MoveWindow(info->hNodeInfo, 400, 30, client.right - 400, client.bottom - 30, TRUE);
}
break;
case WM_SIZING:
{
const int MIN_WIDTH = 750;
const int MIN_HEIGHT = 300;
RECT* rect = (RECT*)lParam;
bool left = (wParam == WMSZ_BOTTOMLEFT) || (wParam == WMSZ_LEFT) || (wParam == WMSZ_TOPLEFT);
bool top = (wParam == WMSZ_TOPLEFT) || (wParam == WMSZ_TOP) || (wParam == WMSZ_TOPRIGHT);
if (rect->right - rect->left < MIN_WIDTH)
{
if (left) rect->left = rect->right - MIN_WIDTH;
else rect->right = rect->left + MIN_WIDTH;
}
if (rect->bottom - rect->top < MIN_HEIGHT)
{
if (top) rect->top = rect->bottom - MIN_HEIGHT;
else rect->bottom = rect->top + MIN_HEIGHT;
}
break;
}
case WM_CLOSE:
PostQuitMessage(0);
break;
}
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
void main( ApplicationInfo* info )
{
ShowWindow(info->hMainWnd, SW_SHOW);
HACCEL hAccel = LoadAccelerators( info->hInstance, MAKEINTRESOURCE(IDR_ACCELERATOR1));
MSG msg;
while (GetMessage(&msg, NULL, 0, 0) != 0)
{
if (!TranslateAccelerator(info->hMainWnd, hAccel, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
}
// Create the main window and its child windows
static void CreateMainWindow( ApplicationInfo* info )
{
WNDCLASSEX wcx;
wcx.cbSize = sizeof wcx;
wcx.style = CS_HREDRAW | CS_VREDRAW;
wcx.lpfnWndProc = MainWindowProc;
wcx.cbClsExtra = 0;
wcx.cbWndExtra = 0;
wcx.hInstance = info->hInstance;
wcx.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wcx.hCursor = LoadCursor(NULL, IDC_ARROW);
wcx.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1);
wcx.lpszMenuName = MAKEINTRESOURCE(IDR_MENU1);
wcx.lpszClassName = TEXT("ChunkViewer");
wcx.hIconSm = NULL;
if (RegisterClassEx(&wcx) == 0)
{
throw runtime_error("Unable to register window class");
}
if ((info->hMainWnd = CreateWindowEx(0, TEXT("ChunkViewer"), TEXT("Chunk File Viewer"), WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, info->hInstance, info)) == NULL)
{
UnregisterClass(TEXT("ChunkViewer"), info->hInstance);
throw runtime_error("Unable to create main window");
}
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int)
{
try
{
ApplicationInfo info;
info.hInstance = hInstance;
CreateMainWindow( &info );
main( &info );
}
catch (exception& e)
{
MessageBoxA(NULL, e.what(), NULL, MB_OK );
}
return 0;
}
| 27.718232
| 158
| 0.601156
|
GlyphXTools
|
88d87eaf52fd28adfa40899cfc5a491398f4e95b
| 1,209
|
cpp
|
C++
|
src/types/cons.cpp
|
rationalis-petra/hydra
|
a1c14e560f5f1c64983468e5fd0be7b32824971d
|
[
"MIT"
] | 2
|
2021-01-14T11:19:02.000Z
|
2021-03-07T03:08:08.000Z
|
src/types/cons.cpp
|
rationalis-petra/hydra
|
a1c14e560f5f1c64983468e5fd0be7b32824971d
|
[
"MIT"
] | null | null | null |
src/types/cons.cpp
|
rationalis-petra/hydra
|
a1c14e560f5f1c64983468e5fd0be7b32824971d
|
[
"MIT"
] | null | null | null |
#include <string>
#include <list>
#include "operations/types.hpp"
#include "expressions.hpp"
#include "types.hpp"
#include "utils.hpp"
using std::string;
using namespace type;
using namespace interp;
Cons::Cons() {
type_car = new Any;
type_cdr = new Any;
set_invoker(op::mk_cons_type);
}
Cons::Cons(Type* tcar, Type* tcdr) {
type_car = tcar;
type_cdr = tcdr;
set_invoker(op::mk_cons_type);
}
void Cons::mark_node() {
if (marked) return;
Object::mark_node();
type_car->mark_node();
type_cdr->mark_node();
}
string Cons::to_string(LocalRuntime &r, LexicalScope &s) {
return "Cons";
}
expr::Object *Cons::check_type(expr::Object *obj) {
if (expr::Cons *cns = get_inbuilt<expr::Cons *>(obj)) {
if (type_car->check_type(cns->car)->null()) {
return expr::nil::get();
}
if (type_cdr->check_type(cns->cdr)->null()) {
return expr::nil::get();
}
return expr::t::get();
} else {
return expr::nil::get();
}
}
expr::Object *Cons::subtype(Type *obj) {
if (Cons *tcons = dynamic_cast<Cons*>(obj)) {
if (type_car->subtype(tcons->type_car) &&
type_cdr->subtype(tcons->type_cdr))
return expr::t::get();
}
return expr::nil::get();
}
| 20.491525
| 58
| 0.632754
|
rationalis-petra
|
88e307413a54906a6923035771943e45d0d427d6
| 3,246
|
cpp
|
C++
|
Solutions/DK_LM3S9B96/DeviceCode/Bootstrap_HAL/CortexM3_functions_bootstrap.cpp
|
yangjunjiao/NetmfSTM32
|
62ddb8aa0362b83d2e73f3621a56593988e3620f
|
[
"Apache-2.0"
] | 4
|
2019-01-21T11:47:53.000Z
|
2020-06-09T02:14:15.000Z
|
Solutions/DK_LM3S9B96/DeviceCode/Bootstrap_HAL/CortexM3_functions_bootstrap.cpp
|
yisea123/NetmfSTM32
|
62ddb8aa0362b83d2e73f3621a56593988e3620f
|
[
"Apache-2.0"
] | null | null | null |
Solutions/DK_LM3S9B96/DeviceCode/Bootstrap_HAL/CortexM3_functions_bootstrap.cpp
|
yisea123/NetmfSTM32
|
62ddb8aa0362b83d2e73f3621a56593988e3620f
|
[
"Apache-2.0"
] | 4
|
2019-01-21T11:48:00.000Z
|
2021-05-04T12:37:55.000Z
|
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//
// This file is part of the Microsoft .NET Micro Framework Porting Kit Code Samples and is unsupported.
// Copyright (C) Microsoft Corporation. All rights reserved. Use of this sample source code is subject to
// the terms of the Microsoft license agreement under which you licensed this sample source code.
//
// THIS SAMPLE CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
//
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <tinyhal.h>
#include "inc/hw_ints.h"
#include "inc/hw_memmap.h"
#include "inc/hw_types.h"
#include "driverlib/gpio.h"
#include "driverlib/sysctl.h"
#include "driverlib/uart.h"
#include "set_pinout.h"
#include "../BlockStorage_HAL/ssiflash.h"
//#define CODE_IN_EXT_MEM 1
extern void PrepareImageRegions();
//*****************************************************************************
//
// Send a string to the UART.
//
//*****************************************************************************
void UARTSend(unsigned long ulUartAddr, const char *pucBuffer)
{
// Loop while there are more characters to send.
while(*pucBuffer)
{
//
// Write the next character to the UART.
//
UARTCharPut(ulUartAddr, *pucBuffer++);
}
}
//--//
void BootstrapCode()
{
const char CompanyStr[] = "Golden IC Technology Co.,Ltd.\n";
const char CompanyWebStr[] = "Web: www.Golden-IC.com\n";
#ifdef CODE_IN_EXT_MEM
PrepareImageRegions();
g_eDaughterType = DAUGHTER_NONE;//DAUGHTER_SRAM_FLASH;
#else
// Set the system clock to run at 80MHz from the PLL
SysCtlClockSet(SYSCTL_SYSDIV_3 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN | SYSCTL_XTAL_16MHZ);
// Set the device pinout appropriately for this board. This also enables
// all the GPIO ports required.
PinoutSet();
PrepareImageRegions();
#endif
//Enable UART0 ,Configure the UART for 115,200, 8-N-1 operation.
SysCtlPeripheralEnable(SYSCTL_PERIPH_UART0);
SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);
GPIOPinTypeUART(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1);
UARTConfigSetExpClk(UART0_BASE, SysCtlClockGet(), 115200,(UART_CONFIG_WLEN_8 | UART_CONFIG_STOP_ONE | UART_CONFIG_PAR_NONE));
UARTSend(UART0_BASE,CompanyStr);
UARTSend(UART0_BASE,CompanyWebStr);
//Enable UART1 ,Configure the UART for 115,200, 8-N-1 operation.
SysCtlPeripheralEnable(SYSCTL_PERIPH_UART1);
SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
GPIOPinTypeUART(GPIO_PORTB_BASE, GPIO_PIN_0 | GPIO_PIN_1);
UARTConfigSetExpClk(UART1_BASE, SysCtlClockGet(), 115200,(UART_CONFIG_WLEN_8 | UART_CONFIG_STOP_ONE | UART_CONFIG_PAR_NONE));
UARTSend(UART1_BASE,CompanyStr);
UARTSend(UART1_BASE,CompanyWebStr);
//
}
| 39.585366
| 200
| 0.60382
|
yangjunjiao
|
88f126095c5f840d7be7903ce6288711c15f9443
| 2,425
|
hpp
|
C++
|
manager/lib/borealis/library/include/borealis/dropdown.hpp
|
lunixoid/sys-clk
|
731d0de5f580a7fa853804e0c776ba2f1623c932
|
[
"Beerware"
] | 492
|
2019-02-14T16:10:55.000Z
|
2022-03-31T00:01:27.000Z
|
manager/lib/borealis/library/include/borealis/dropdown.hpp
|
lunixoid/sys-clk
|
731d0de5f580a7fa853804e0c776ba2f1623c932
|
[
"Beerware"
] | 51
|
2019-02-14T17:31:08.000Z
|
2022-03-24T00:10:09.000Z
|
manager/lib/borealis/library/include/borealis/dropdown.hpp
|
lunixoid/sys-clk
|
731d0de5f580a7fa853804e0c776ba2f1623c932
|
[
"Beerware"
] | 75
|
2019-02-14T17:46:32.000Z
|
2022-03-28T07:19:25.000Z
|
/*
Borealis, a Nintendo Switch UI Library
Copyright (C) 2019-2020 natinusala
Copyright (C) 2019-2020 p-sam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <borealis/event.hpp>
#include <borealis/list.hpp>
#include <borealis/view.hpp>
#include <string>
namespace brls
{
// Fired when the user has selected a value
//
// Parameter is either the selected value index
// or -1 if the user cancelled
//
// Assume that the Dropdown is deleted
// as soon as this function is called
typedef Event<int> ValueSelectedEvent;
// Allows the user to select between multiple
// values
// Use Dropdown::open()
class Dropdown : public View
{
private:
Dropdown(std::string title, std::vector<std::string> values, ValueSelectedEvent::Callback cb, size_t selected = 0);
std::string title;
int valuesCount;
ValueSelectedEvent valueEvent;
List* list;
Hint* hint;
float topOffset; // for slide in animation
protected:
unsigned getShowAnimationDuration(ViewAnimation animation) override;
public:
~Dropdown();
void draw(NVGcontext* vg, int x, int y, unsigned width, unsigned height, Style* style, FrameContext* ctx) override;
void layout(NVGcontext* vg, Style* style, FontStash* stash) override;
View* getDefaultFocus() override;
virtual bool onCancel();
void show(std::function<void(void)> cb, bool animate = true, ViewAnimation animation = ViewAnimation::FADE) override;
void willAppear(bool resetState = false) override;
void willDisappear(bool resetState = false) override;
static void open(std::string title, std::vector<std::string> values, ValueSelectedEvent::Callback cb, int selected = -1);
bool isTranslucent() override
{
return true || View::isTranslucent();
}
};
} // namespace brls
| 29.938272
| 125
| 0.718351
|
lunixoid
|
88f40d44b9d726b071d7f417f5c1b5075f28b583
| 239
|
hpp
|
C++
|
include/dungeon/horizontal_wall.hpp
|
tanacchi/rogue_game
|
fd8f655f95932513f6aa63e0c413bbe110a4418a
|
[
"MIT"
] | 10
|
2018-09-13T14:47:07.000Z
|
2022-01-10T11:46:12.000Z
|
include/dungeon/horizontal_wall.hpp
|
tanacchi/rogue_game
|
fd8f655f95932513f6aa63e0c413bbe110a4418a
|
[
"MIT"
] | 13
|
2018-09-18T19:36:32.000Z
|
2020-11-12T16:26:22.000Z
|
include/dungeon/horizontal_wall.hpp
|
tanacchi/rogue_game
|
fd8f655f95932513f6aa63e0c413bbe110a4418a
|
[
"MIT"
] | null | null | null |
#ifndef INCLUDED_HORIZONTAL_WALL_HPP
#define INCLUDED_HORIZONTAL_WALL_HPP
#include <dungeon/dungeon_elem.hpp>
// '-'
class HorizontalWall : public DungeonElem
{
public:
HorizontalWall();
};
#endif // INCLUDED_HORIZONTAL_WALL_HPP
| 17.071429
| 41
| 0.778243
|
tanacchi
|
88f6e054906565a72309755b609a32cb3b2d9bd6
| 2,138
|
cpp
|
C++
|
Basil/src/Renderer/Renderer.cpp
|
Tamookk/Basil
|
bdcdf4e6e13e64a34416b4412d366594f9d46f56
|
[
"Apache-2.0"
] | null | null | null |
Basil/src/Renderer/Renderer.cpp
|
Tamookk/Basil
|
bdcdf4e6e13e64a34416b4412d366594f9d46f56
|
[
"Apache-2.0"
] | null | null | null |
Basil/src/Renderer/Renderer.cpp
|
Tamookk/Basil
|
bdcdf4e6e13e64a34416b4412d366594f9d46f56
|
[
"Apache-2.0"
] | null | null | null |
#include "pch.h"
#include "Platform/OpenGL/OpenGLRendererAPI.h"
#include "Renderer/Renderer.h"
#include "Renderer/Renderer2D.h"
namespace Basil
{
// Set the render API currently in use
Unique<RendererAPI> Renderer::rendererAPI = makeUnique<OpenGLRendererAPI>();
// Screate the scene data struct
Unique<Renderer::SceneData> Renderer::sceneData = makeUnique<Renderer::SceneData>();
// Initialise renderer
void Renderer::init()
{
PROFILE_FUNCTION();
rendererAPI->init();
Renderer2D::init();
}
// Shutdown renderer
void Renderer::shutdown()
{
Renderer2D::shutdown();
}
// On window resize event
void Renderer::onWindowResize(unsigned int width, unsigned int height)
{
rendererAPI->setViewport(0, 0, width, height);
}
// Begin a scene
void Renderer::beginScene(OrthographicCamera& camera)
{
sceneData->viewProjectionMatrix = camera.getViewProjectionMatrix();
}
// End a scene
void Renderer::endScene()
{
}
// Submit data to be rendered
void Renderer::submit(const Shared<Shader>& shader, const Shared<VertexArray>& vao, const glm::mat4& transform)
{
PROFILE_FUNCTION();
// Bind the shader and upload the uniform
shader->bind();
shader->setMat4("u_ViewProjection", sceneData->viewProjectionMatrix);
shader->setMat4("u_Transform", transform);
// Bind the vertex array and draw the data
vao->bind();
Renderer::drawIndexed(vao);
}
// Set the clear colour
void Renderer::setClearColor(const glm::vec4& color)
{
rendererAPI->setClearColor(color);
}
// Clear the screen
void Renderer::clear()
{
rendererAPI->clear();
}
// Draw the object(s) in the VAO
void Renderer::drawIndexed(const Shared<VertexArray>& vao, uint32_t count)
{
rendererAPI->drawIndexed(vao, count);
}
// Draw lines
void Renderer::drawLines(const Shared<VertexArray>& vertexArray, uint32_t vertexCount)
{
rendererAPI->drawLines(vertexArray, vertexCount);
}
// Set line width
void Renderer::setLineWidth(float width)
{
rendererAPI->setLineWidth(width);
}
// Return the rendering API currently being used
RendererAPI::API Renderer::getAPI()
{
return RendererAPI::getAPI();
}
}
| 22.270833
| 112
| 0.721703
|
Tamookk
|
88fc0c8a0edad19a664de5dd9329f4a4c959c4e2
| 372
|
hpp
|
C++
|
src/rover/gps.hpp
|
2535Rover/RoverSystem
|
300dd4d754bac2e4caff25ed1da244c109d289be
|
[
"Apache-2.0"
] | 1
|
2018-10-16T02:32:49.000Z
|
2018-10-16T02:32:49.000Z
|
src/rover/gps.hpp
|
2535Rover/RoverSystem
|
300dd4d754bac2e4caff25ed1da244c109d289be
|
[
"Apache-2.0"
] | 13
|
2018-10-23T20:35:10.000Z
|
2018-11-23T22:44:32.000Z
|
src/subsystems_computer/gps.hpp
|
2535Rover/RoverSystem
|
300dd4d754bac2e4caff25ed1da244c109d289be
|
[
"Apache-2.0"
] | 1
|
2018-10-16T03:11:39.000Z
|
2018-10-16T03:11:39.000Z
|
#include "../network/network.hpp"
#include "../util/util.hpp"
namespace gps {
struct Position {
float latitude;
float longitude;
};
enum class Error {
OK,
OPEN,
GET_ATTR,
SET_ATTR
};
Error init(const char* device_id, util::Clock* global_clock);
Position get_position();
float get_heading();
network::LocationMessage::FixStatus get_fix();
}
| 13.777778
| 61
| 0.680108
|
2535Rover
|
88fe57dc7905b93b0e001c26362393f0d9c90f4c
| 1,199
|
hpp
|
C++
|
core/src/utils/NoiseUtils.hpp
|
lonnibesancon/utymap
|
6d14a3d1386aade8c2755da4abc00269284c90d4
|
[
"Apache-2.0"
] | 1
|
2019-04-04T14:20:37.000Z
|
2019-04-04T14:20:37.000Z
|
core/src/utils/NoiseUtils.hpp
|
lonnibesancon/utymap
|
6d14a3d1386aade8c2755da4abc00269284c90d4
|
[
"Apache-2.0"
] | null | null | null |
core/src/utils/NoiseUtils.hpp
|
lonnibesancon/utymap
|
6d14a3d1386aade8c2755da4abc00269284c90d4
|
[
"Apache-2.0"
] | null | null | null |
#ifndef UTILS_NOISEUTILS_HPP_DEFINED
#define UTILS_NOISEUTILS_HPP_DEFINED
#include "math/Vector2.hpp"
#include "math/Vector3.hpp"
namespace utymap { namespace utils {
/// Provides noise generation functions.
/// Ported from C# code from here : http ://catlikecoding.com/unity/tutorials/noise/
class NoiseUtils final
{
public:
/// Calculates perlin 2D noise.
static double perlin2D(double x, double y, double frequency);
/// Calculates perlin 3D noise.
static double perlin3D(double x, double y, double z, double freq);
private:
static double dot(const utymap::math::Vector3& g, double x, double y, double z)
{
return g.x*x + g.y*y + g.z*z;
}
static double dot(const utymap::math::Vector2& g, double x, double y)
{
return g.x*x + g.y*y;
}
static double smooth(double t)
{
return t*t*t*(t*(t * 6 - 15) + 10);
}
static const int HashMask = 255;
static const int GradientsMask2D = 7;
static const int GradientsMask3D = 15;
static const utymap::math::Vector2 Gradients2D[];
static const utymap::math::Vector3 Gradients3D[];
static const int Hash[];
};
}}
#endif // UTILS_NOISEUTILS_HPP_DEFINED
| 25.510638
| 84
| 0.672227
|
lonnibesancon
|
0002baa9008ce6d632eddd1c9323b18dacee890a
| 1,369
|
cpp
|
C++
|
JMap_Xbox.cpp
|
Gallard88/ROSV_Joystick
|
de44334526571a3b814bcee18ae873907f38ec57
|
[
"MIT"
] | null | null | null |
JMap_Xbox.cpp
|
Gallard88/ROSV_Joystick
|
de44334526571a3b814bcee18ae873907f38ec57
|
[
"MIT"
] | null | null | null |
JMap_Xbox.cpp
|
Gallard88/ROSV_Joystick
|
de44334526571a3b814bcee18ae873907f38ec57
|
[
"MIT"
] | null | null | null |
#include <unistd.h>
#include <fcntl.h>
#include "JMap_Xbox.h"
using namespace std;
/*
* Generix X-Box pad.
* 8x Axis
* 11x Buttons
*
*/
JMap_Xbox::JMap_Xbox(JoyStickDriver *driver):
Joy(driver), Depth(0),
IncEdge(false), DecEdge(false)
{
}
float JMap_Xbox::GetVectorValue(ControlVectors vector)
{
switch ( vector ) {
case vecForward:
return (Joy->GetAxis(1) * -100.0) / 32767;
case vecTurn:
return (Joy->GetAxis(0) * 100) / 32767;
case vecStrafe:
return (Joy->GetAxis(3) * 100.0) / 32767;
case vecDepth:
return (float)Depth;
}
return 0;
}
void JMap_Xbox::Run_Task(void)
{
int rv = 1;
while ( rv > 0 ) {
fd_set readFD;
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 1;
int j_fd = Joy->GetFileDescript();
FD_ZERO(&readFD);
FD_SET(j_fd, &readFD);
rv = select(j_fd+1, &readFD, NULL, NULL, &timeout);
if ( rv > 0 ) {
if ( FD_ISSET(j_fd, &readFD) ) {
Joy->Run();
}
}
CalcDepth();
}
}
void JMap_Xbox::CalcDepth(void)
{
bool edge = Joy->GetButton(5);
if (( IncEdge == false ) &&
( edge == true ) &&
( Depth < 100 )) {
Depth += 10;
}
IncEdge = edge;
edge = Joy->GetButton(4);
if (( DecEdge == false ) &&
( edge == true ) &&
( Depth > 0 )) {
Depth -= 10;
}
DecEdge = edge;
}
| 15.735632
| 55
| 0.558072
|
Gallard88
|
322dcbfd67fdb62dd60f01ce589c0914e162206a
| 2,195
|
cpp
|
C++
|
USBCamera/readAndSave.cpp
|
sdbzzhaotq/DemoCollection
|
94cd136e7a67ee60634139886d45b69e1ffd0e4c
|
[
"MIT"
] | null | null | null |
USBCamera/readAndSave.cpp
|
sdbzzhaotq/DemoCollection
|
94cd136e7a67ee60634139886d45b69e1ffd0e4c
|
[
"MIT"
] | null | null | null |
USBCamera/readAndSave.cpp
|
sdbzzhaotq/DemoCollection
|
94cd136e7a67ee60634139886d45b69e1ffd0e4c
|
[
"MIT"
] | null | null | null |
#include <opencv2/opencv.hpp>
#include <iostream>
#include <chrono>
#include <ctime>
#include "MatIO.h"
const int ROAD_CAMERA_ID = 0;
#define FRAME_WIDTH 1164
#define FRAME_HEIGHT 874
void write_mb() {
//VideoCapture capture(ROAD_CAMERA_ID, cv::CAP_V4L2);
cv::VideoCapture capture("ns.mov");
capture.set(cv::CAP_PROP_FRAME_WIDTH, 853);
capture.set(cv::CAP_PROP_FRAME_HEIGHT, 480);
capture.set(cv::CAP_PROP_FPS, 20);
capture.set(cv::CAP_PROP_AUTOFOCUS, 0);
capture.set(cv::CAP_PROP_FOCUS, 0);
float ts[9] = {1.50330396, 0.0, -59.40969163,
0.0, 1.50330396, 76.20704846,
0.0, 0.0, 1.0};
assert(capture.isOpened());
cv::Size size(FRAME_WIDTH,FRAME_HEIGHT);
const cv::Mat transform = cv::Mat(3, 3, CV_32F, ts);
cv::Mat frame_mat, transformed_mat;
char szFilename[20] = {};
std::string name;
static int index = 0;
for(;;) {
capture >> frame_mat;
cv::warpPerspective(frame_mat, transformed_mat, transform, size, cv::INTER_LINEAR, cv::BORDER_CONSTANT, 0);
sprintf(szFilename,"mb/%d.mb",index);
name.assign(szFilename);
Utils::write(name,transformed_mat);
cv::imshow("video", transformed_mat);
index++;
if (cv::waitKey(10) == 27) {
std::cout << "Esc key is pressed by user. Stoppig the video" << std::endl;
break;
}
}
}
void read_mb() {
for(auto i=0;i<8991;i++) {
char szFilename[20] = {};
std::string name;
sprintf(szFilename,"mb/%d.mb",i);
name.assign(szFilename);
cv::Mat frame_mat = Utils::read(name);
cv::imshow("video", frame_mat);
if (cv::waitKey(10) == 27) {
std::cout << "Esc key is pressed by user. Stoppig the video" << std::endl;
break;
}
}
}
int main(int argc, char** argv) {
if(argc < 2) {
printf("argument is error, write or read\n");
return 0;
}
std::string arg = argv[1];
if("read" == arg){
read_mb();
} else if("write" == arg){
write_mb();
} else {
printf("argument is error, write or read\n");
}
return 0;
}
| 28.141026
| 115
| 0.575399
|
sdbzzhaotq
|
322dfc8c02df49b996c3784d8e77b2864bb655eb
| 531
|
cpp
|
C++
|
source/discord/gateway.cpp
|
kociap/Discord-
|
fcbf30d199ec217e0e6289aee96e365de383dbda
|
[
"MIT"
] | null | null | null |
source/discord/gateway.cpp
|
kociap/Discord-
|
fcbf30d199ec217e0e6289aee96e365de383dbda
|
[
"MIT"
] | 2
|
2019-01-15T07:38:54.000Z
|
2019-01-15T07:44:35.000Z
|
source/discord/gateway.cpp
|
kociap/Discord-
|
fcbf30d199ec217e0e6289aee96e365de383dbda
|
[
"MIT"
] | 1
|
2018-10-25T12:12:34.000Z
|
2018-10-25T12:12:34.000Z
|
#include "gateway.hpp"
#include "nlohmann/json.hpp"
#include "rpp/rpp.hpp"
#include "urls.hpp"
namespace discord {
namespace gateway {
String get_gateway() {
rpp::Request req;
req.set_verbose(true);
req.set_verify_ssl(false);
rpp::Response res = req.get(url::gateway);
nlohmann::json json = nlohmann::json::parse(res.text);
return json.at("url").get<String>() + "/?v=6&encoding=json";
}
} // namespace gateway
} // namespace discord
| 27.947368
| 72
| 0.585687
|
kociap
|
323426d24d8492974a62c33e7327e1a5a8b0deb2
| 76
|
cpp
|
C++
|
test/compile_include_text_view_2.cpp
|
eightysquirrels/text
|
d935545648777786dc196a75346cde8906da846a
|
[
"BSL-1.0"
] | null | null | null |
test/compile_include_text_view_2.cpp
|
eightysquirrels/text
|
d935545648777786dc196a75346cde8906da846a
|
[
"BSL-1.0"
] | 1
|
2021-03-05T12:56:59.000Z
|
2021-03-05T13:11:53.000Z
|
test/compile_include_text_view_2.cpp
|
eightysquirrels/text
|
d935545648777786dc196a75346cde8906da846a
|
[
"BSL-1.0"
] | 3
|
2019-10-30T18:38:15.000Z
|
2021-03-05T12:10:13.000Z
|
#include <boost/text/string_view.hpp>
#include <boost/text/string_view.hpp>
| 25.333333
| 37
| 0.789474
|
eightysquirrels
|
3243202609864bdcaf4f693bc60b9af583121b1a
| 1,329
|
cpp
|
C++
|
AI/Src/SteeringBehavior_OffsetPursuit.cpp
|
ArvydasSlekaitis/ReginaGameEngine
|
4b6af9b5fbf9aad4025b0387260c31019fd8f8c8
|
[
"MIT"
] | 1
|
2020-09-02T06:00:14.000Z
|
2020-09-02T06:00:14.000Z
|
AI/Src/SteeringBehavior_OffsetPursuit.cpp
|
ArvydasSlekaitis/ReginaGameEngine
|
4b6af9b5fbf9aad4025b0387260c31019fd8f8c8
|
[
"MIT"
] | null | null | null |
AI/Src/SteeringBehavior_OffsetPursuit.cpp
|
ArvydasSlekaitis/ReginaGameEngine
|
4b6af9b5fbf9aad4025b0387260c31019fd8f8c8
|
[
"MIT"
] | null | null | null |
///////////////////////////////////////////////////////////
// SteeringBehavior_OffsetPursuit.cpp
// Created on: 11-10-2009
// Last modified: 11-10-2009
// Original author: Arvydas Slekaitis (C)
///////////////////////////////////////////////////////////
#include <SteeringBehavior_OffsetPursuit.h>
using namespace Regina;
//*****************************************************************************
CSteeringBehavior_OffsetPursuit::CSteeringBehavior_OffsetPursuit(CMovingEntity* const iMovingEntity, const CMovingEntity* iLeader, const D3DXVECTOR2& iOffset) : CSteeringBehavior("OffsetPursuit", 6, 0.9, iMovingEntity), leader(iLeader), offset(iOffset)
{
}
//*****************************************************************************
D3DXVECTOR2 CSteeringBehavior_OffsetPursuit::CalculateForce()
{
D3DXVECTOR3 worldOffset;
D3DXVec3TransformCoord(&worldOffset, &D3DXVECTOR3(Offset().x, 0, Offset().y), &(Leader()->Transformation()));
float lookAheadTime = Distance(worldOffset.x, worldOffset.y, Entity()->PositionXZ().x, Entity()->PositionXZ().y) / ( Entity()->MaxSpeed() + Leader()->Speed());
CSteeringBehavior_Arrive arrive(Entity(), D3DXVECTOR2(worldOffset.x, worldOffset.z), 1);
return arrive.CalculateForce();
}
//*****************************************************************************
| 44.3
| 252
| 0.5538
|
ArvydasSlekaitis
|
324c668049c4a4374cc8ae171461f16914510fab
| 25,057
|
cpp
|
C++
|
steamfilter/replace.cpp
|
Pez42/steam-limiter
|
df95d2460faa0316573013d09db086826b3c825a
|
[
"BSD-2-Clause"
] | 2
|
2016-02-24T09:49:07.000Z
|
2019-05-31T14:38:06.000Z
|
steamfilter/replace.cpp
|
Pez42/steam-limiter
|
df95d2460faa0316573013d09db086826b3c825a
|
[
"BSD-2-Clause"
] | null | null | null |
steamfilter/replace.cpp
|
Pez42/steam-limiter
|
df95d2460faa0316573013d09db086826b3c825a
|
[
"BSD-2-Clause"
] | 2
|
2015-09-22T15:53:59.000Z
|
2020-06-14T12:50:24.000Z
|
/**@addtogroup Filter Steam limiter filter hook DLL.
* @{@file
*
* This defines a data structure to be used for managing replacement HTTP
* content to be used when certain URL patterns are seen.
*
* @author Nigel Bree <nigel.bree@gmail.com>
*
* Copyright (C) 2013 Nigel Bree; 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.
*/
/*
* The fundamental idea here is that we maintain a small set of data for
* replacement documents (or document templates; although there doesn't seem
* to be an immediate need for it here, obviously it would be desirable in some
* contexts for the replacement document to be generated by template expansion)
* along with a simple kind of state-tracking structure for socket handles.
*
* Since replacement events are expected to be rare, there is generally only
* likely to be a single outstanding one, and generally it will be consumed in
* a single read call, so a simple linked list should do for matching things.
*
* When a replacement URL is detected, the replacement data structure is set up
* and the caller's request is discarded so that the connected peer does not
* see the request being replaced at all (which saves the need to edit the
* replaced response out of the data stream). In general, requests are sent as
* a single write call - the problems caused by the behaviour of socket reads
* (even in synchronous mode, even a single byte of data available causes an
* immediate return to the caller) tend not to affect write processing.
*
* Then, on read processing if a replacement is set to occur for a socket
* handle the replacement data is written to the user buffer (typically all of
* it, although for robustness it's best to allow it to be drained in parts),
* and once the replacement is drained then we can return to the caller.
*
* The final detail is the question of where the replacement documents are read
* from, and when they are read. Potentially the reading could take place at
* the time a filter rule is established, which would be most prudent if the
* replacement is taken from a disk file and is thus likely to be expensive and
* high-latency. However it seems more product to read the document from the
* system registry if the document is likely to be small (as it is for Steam
* content filtering) which means that the data encoding is better-specified
* and due to aggressive system caching of the registry hive data is very
* likely to be low-latency to access.
*/
#define WIN32_LEAN_AND_MEAN 1
#include <windows.h>
#include <winsock2.h>
#include "replace.h"
/**
* Cliche for measuring array lengths, to avoid mistakes with sizeof ().
*/
#define ARRAY_LENGTH(x) (sizeof (x) / sizeof (* (x)))
/**
* Base object for implementing socket state tracking.
*
* This is set up for binding sockets and event handles so that applications
* get notified when a socket becomes readable, since the lack of true AIO in
* classic sockets requires separate eventing mechanisms (from the simple to
* the absurd as in epoll (), which is essentially socket-specific as well as
* baroque and hard to use compared to a universal AIO model).
*/
class SocketTrack {
/*
* Friend-ing an entire template is not something you see often, but
* it's been a part of the language for a while.
*/
template <class T>
friend class SocketList;
private:
SocketTrack * m_next;
SocketTrack * m_prev;
SOCKET m_handle;
public:
WSAEVENT m_event;
private:
/* NOCOPY */ SocketTrack (const SocketTrack &);
void operator = (const SocketTrack &);
public:
SocketTrack (SOCKET handle);
SOCKET handle (void) const { return m_handle; }
static void * operator new (size_t length) throw ();
static void * operator new (size_t length, void * mem) throw ();
static void operator delete (void * mem) throw ();
};
/**
* Regular replacement new, non-throwing.
*/
/* static */
void * SocketTrack :: operator new (size_t length) throw () {
return HeapAlloc (GetProcessHeap (), 0, length);
}
/**
* Non-throwing placement new, generally used with manual calls to the plain
* operator function to allocate variable-sized memory blocks.
*/
/* static */
void * SocketTrack :: operator new (size_t length, void * mem) throw () {
return mem;
}
/**
* Trivial deallocator to match the replacement new.
*/
/* static */
void SocketTrack :: operator delete (void * mem) throw () {
HeapFree (GetProcessHeap (), 0, mem);
}
/**
* Trivial constructor.
*/
SocketTrack :: SocketTrack (SOCKET handle) : m_next (0), m_prev (0),
m_handle (handle), m_event (0) {
}
/**
* Simple list-holder.
*
* Intrusive lists have been a part of C++ forever, since they were the common
* thing done in C for many years before. However, in early C++ what was done
* in most programs was to convert a common node structure and extend it using
* virtual functions.
*
* Although this could be done to be typesafe, it had problems not the least of
* which was typesafety required constantly injecting new virtual functions
* into the base classes or the moral equivalent (e.g. COM-style QueryInterface
* which was elegant but not being integrated into the language, lots of work).
*
* Templates in the 1990 ARM promised to help with this by introducing some
* parametric genericity, but being mostly a system pf complex hygenic macro-
* expanders the quality of implementation was low and remained low for well
* into the 2000s and even then tended to cause code explosion. Finally, around
* the late 2000's quality implementations of templates style could really
* rival the old pre-1990s one in total efficiency thanks to function-level
* linking and deduplication (although that's not entirely free either, as it
* can make for a disorienting debug experience).
*/
template <class T>
struct SocketList {
typedef CRITICAL_SECTION Mutex;
Mutex m_lock [1];
T * m_head;
SocketList ();
~ SocketList ();
void free (void);
void add (T & item);
T * find (SOCKET handle);
void remove (T * item, bool free = false);
void remove (SOCKET handle);
};
/**
* Initialize an empty list.
*/
template <class T>
SocketList<T> :: SocketList () : m_head (0) {
InitializeCriticalSection (m_lock);
}
/**
* Deinitialize the list and locking structure.
*/
template <class T>
SocketList<T> :: ~ SocketList () {
free ();
DeleteCriticalSection (m_lock);
}
/**
* Free all the list members, deallocating them.
*/
template <class T>
void SocketList<T> :: free (void) {
EnterCriticalSection (m_lock);
while (m_head != 0)
remove (m_head, true);
LeaveCriticalSection (m_lock);
}
/**
* Add a new item.
*/
template <class T>
void SocketList<T> :: add (T & item) {
EnterCriticalSection (m_lock);
item.m_next = m_head;
item.m_prev = 0;
m_head = & item;
LeaveCriticalSection (m_lock);
}
/**
* Find an item.
*
* In a more general template, this would be a member template so that the
* key type and comparison function could be parameterized, but this is just
* a simplified example of the general style so I haven't bothered.
*
* The key reason this is here is to show a clean example of something memory-
* light, which nothing in the modern STL can really claim to be (even for the
* few good parts of classic STL, the retrofitting of exceptions into the STL
* containers meant it's usually easier to ditch them in memory-constrained or
* code-size-limited environments).
*/
template <class T>
T * SocketList<T> :: find (SOCKET handle) {
EnterCriticalSection (m_lock);
T * scan = m_head;
while (scan != 0) {
if (scan->m_handle == handle)
break;
scan = (T *) scan->m_next;
}
LeaveCriticalSection (m_lock);
return scan;
}
/**
* Remove an item from the list, optionally freeing it.
*/
template <class T>
void SocketList<T> :: remove (T * item, bool free) {
EnterCriticalSection (m_lock);
T * prev = (T *) item->m_prev;
T * next = (T *) item->m_next;
if (prev == 0) {
m_head = next;
} else
prev->m_next = next;
if (next != 0)
next->m_prev = prev;
LeaveCriticalSection (m_lock);
if (free)
delete item;
}
/**
* Remove and free an item based on a key.
*/
template <class T>
void SocketList<T> :: remove (SOCKET handle) {
EnterCriticalSection (m_lock);
T ** link = & m_head;
T * scan = m_head;
T * prev = 0;
while ((scan = * link) != 0) {
if (scan->m_handle == handle) {
* link = (T *) scan->m_next;
scan->m_prev = prev;
break;
}
prev = scan;
link = (T **) & scan->m_next;
}
LeaveCriticalSection (m_lock);
if (scan != 0)
delete scan;
}
/**
* Structure for representing a replacement context.
*/
struct Replacement : public SocketTrack {
unsigned long m_length;
unsigned long m_offset;
unsigned char * m_data;
Replacement (SOCKET handle) : SocketTrack (handle) { }
};
/**
* Structure for representing an context where we're discarding output.
*/
struct Discarding : public SocketTrack {
unsigned long m_length;
Discarding (SOCKET handle) : SocketTrack (handle) { }
};
/**
* The global list of bound event handles for sockets.
*/
SocketList<SocketTrack> l_events;
/**
* The global list of active replacement items.
*/
SocketList<Replacement> l_replace;
/**
* Global list of sockets where we are discarding sent data.
*/
SocketList<Discarding> l_discard;
/**
* Root registry key in which replacement items are located.
*/
HKEY l_rootKey;
/**
* Set the root path used as the context for the names of replacement items.
*
* It would presumably be nice to support either or both of registry and file
* paths here, so that users could choose. In the first instance I'll probably
* only implement registry-hosted item support, but it would be sensible to
* have the filesystem path setup present in the hosting machinery.
*/
void g_initReplacement (ReplaceHKEY key, const wchar_t * regPath) {
LSTATUS status = ERROR_NOT_FOUND;
HKEY result = 0;
if (regPath != 0) {
status = RegOpenKeyExW ((HKEY) key, regPath, 0, KEY_READ,
& result);
}
if (status == ERROR_SUCCESS)
l_rootKey = result;
}
/**
* Do any unload-time cleanup.
*/
void g_unloadReplacement (void) {
if (l_rootKey != 0) {
RegCloseKey (l_rootKey);
l_rootKey = 0;
}
l_replace.free ();
l_events.free ();
}
/**
* Add tracking for an event handle bound to a socket.
*
* This might potentially be used to change a binding from one event or even to
* remove a binding, although most socket client applications don't do that.
*/
void g_addEventHandle (SOCKET handle, WSAEVENT event) {
SocketTrack * item = l_events.find (handle);
if (item != 0) {
item->m_event = event;
return;
}
item = new SocketTrack (handle);
l_events.add (* item);
}
/**
* When a socket handle is being closed, remove any tracking data for it.
*/
void g_removeTracking (SOCKET handle) {
l_events.remove (handle);
l_replace.remove (handle);
l_discard.remove (handle);
}
/**
* Add a potential replacement document to the replacement set.
*
* This is a hook into us performed during rule parsing, although if we're
* sourcing data from the registry we will probably do nothing.
*
* Whether file or registry is preferred, the name of the source is always
* going to be relative to something; another problem with file access is that
* the source directory for such content is unlikely to be one we can arrange
* as such in the context of Steam itself, and it will need to have been set up
* for us during the filter load somehow.
*/
void g_replacementCache (const wchar_t * /* name */) {
}
/**
* Format the current local date and time as an RFC 822/RFC 1123 string.
*/
bool l_formatDate (char * buffer, size_t length) {
if (length < 32)
return false;
static char * days [7] = {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
};
static char * months [13] = {
"",
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
SYSTEMTIME now;
GetSystemTime (& now);
wsprintfA (buffer, "%s, %d %s %04d %02d:%02d:%02d GMT",
days [now.wDayOfWeek], now.wDay, months [now.wMonth],
now.wYear, now.wHour, now.wMinute, now.wSecond);
return true;
}
/**
* Helper for g_addReplacement (), create a replacement item record.
*/
bool g_addReplacement (SOCKET handle, const wchar_t * replacement, int status,
const char * extraText) {
/*
* Compute the space required to hold a UTF-8 version of the input, and
* any template-type substitution needed (not that we support that as
* yet).
*/
int utf8 = 0;
if (replacement != 0) {
utf8 = WideCharToMultiByte (CP_UTF8, 0, replacement, - 1, 0, 0, 0, 0);
if (utf8 == 0)
return false;
-- utf8;
}
/*
* Given the size of the replacement document, we can prepare the HTTP
* headers for it and thus know the size of the header and thus the
* total combined space to allocate.
*/
char date [80];
if (! l_formatDate (date, ARRAY_LENGTH (date)))
return false;
char redirect [512];
const char * location = "";
const char * statusText = "UNKNOWN";
switch (status) {
case 200:
if (replacement == 0 && extraText != 0)
utf8 = strlen (extraText);
statusText = "OK";
break;
case 302:
if (extraText == 0)
return false;
wsprintfA (redirect, "Location: %s\r\n", extraText);
location = redirect;
statusText = "REDIRECT";
break;
default:
if (extraText != 0)
statusText = extraText;
break;
}
char header [1024];
wsprintfA (header,
"HTTP/1.1 %d %s\r\n"
"Date: %s\r\n"
"Expires: %s\r\n"
"Content-Type: text/html; charset=UTF8\r\n"
"Content-Length: %ld\r\n"
"Connection: Keep-Alive\r\n"
"%s"
"\r\n", status, statusText, date, date, utf8, location);
size_t headerLength = strlen (header);
unsigned long size = sizeof (Replacement) + headerLength + utf8 + 1;
/*
* Allocate the replacement control structure, and copy the replacement
* document text into it (converting to UTF-8).
*/
void * mem = Replacement :: operator new (size);
if (mem == 0)
return false;
Replacement * item = new (mem) Replacement (handle);
item->m_data = (unsigned char *) (item + 1);
memcpy (item->m_data, header, headerLength);
if (replacement != 0) {
utf8 = WideCharToMultiByte (CP_UTF8, 0, replacement, - 1,
(LPSTR) item->m_data + headerLength,
utf8, 0, 0);
if (utf8 == 0) {
delete item;
return false;
}
-- utf8;
} else if (utf8 > 0) {
/*
* An alternative way to supply content via a #200 rule. In
* this mode, we use ~ as an escape for '\n';
*/
unsigned char * dest = item->m_data + headerLength;
unsigned long count = utf8;
while (count > 0) {
unsigned char ch = * extraText;
++ extraText;
if (ch == '~')
ch = '\n';
* dest = ch;
++ dest;
-- count;
}
}
item->m_length = headerLength + utf8;
item->m_offset = 0;
l_replace.add (* item);
/*
* Look for a bound event handle for the owner socket, and signal it as
* we're making read data available.
*/
SocketTrack * track = l_events.find (item->handle ());
if (track != 0)
SetEvent (track->m_event);
return true;
}
/**
* Add a named replacement document item to be substituted on the indicated handle.
*/
bool g_addReplacement (SOCKET handle, const char * name, const char * /* url */) {
wchar_t tempName [80];
int result;
result = MultiByteToWideChar (CP_UTF8, 0, name, - 1,
tempName, ARRAY_LENGTH (tempName));
if (result == 0)
return false;
/*
* Determine whether the named item exists, and what its size in UTF-16
* characters is.
*/
LSTATUS status;
unsigned long length = 0;
status = RegQueryValueExW (l_rootKey, tempName, 0, 0, 0, & length);
if (status != ERROR_SUCCESS) {
OutputDebugStringA ("HTTP replacement not found\r\n");
return false;
}
wchar_t * replacement;
replacement = (wchar_t *) HeapAlloc (GetProcessHeap (), 0, length);
if (replacement == 0)
return false;
unsigned long type;
status = RegQueryValueExW (l_rootKey, tempName, 0, & type,
(LPBYTE) replacement, & length);
if (status != ERROR_SUCCESS) {
HeapFree (GetProcessHeap (), 0, replacement);
return false;
}
if (type == REG_MULTI_SZ) {
/*
* For MULTI_SZ just join all the component strings by changing
* the interior terminator bytes into newlines.
*/
length = length / sizeof (wchar_t);
wchar_t * scan = replacement;
wchar_t * end = scan + length - 1;
for (; scan != end ; ++ scan)
if (* scan == 0)
* scan = '\n';
} else if (type == REG_SZ || type == REG_EXPAND_SZ) {
length = length / sizeof (wchar_t);
} else {
HeapFree (GetProcessHeap (), 0, replacement);
return false;
}
/*
* Since a registry value has the potential to not be terminated,
* ensure that a terminator is present.
*/
if (replacement [length - 1] != 0) {
replacement [length] = 0;
++ length;
}
bool value;
value = g_addReplacement (handle, replacement, 200, 0);
HeapFree (GetProcessHeap (), 0, replacement);
return value;
}
/**
* Attempt to find a replacement item (and optionally, release it).
*/
Replacement * g_findReplacement (SOCKET handle) {
return l_replace.find (handle);
}
/**
* Given a replacement item, consume part of it for the caller.
*
* This is the simplest signature; it's up to the caller to adapt the incoming
* API format to suit this (if we wanted to support multiple WSABUF structures,
* for example, although for now we don't).
*
* Note that we're assuming here that a given source socket is only being read
* on a single thread, so there is no need for locking here. That's probably
* not a safe assumption in general to make if we ever get used with clients
* written for high performance, but it's true of simple things like Steam.
*/
bool g_consumeReplacement (Replacement * item, unsigned long length, void * buf,
unsigned long * copied) {
if (item == 0 || buf == 0)
return false;
unsigned long avail = item->m_length - item->m_offset;
if (length < avail)
avail = length;
memcpy (buf, item->m_data, avail);
if (copied != 0)
* copied = avail;
item->m_offset += avail;
if (item->m_offset != item->m_length)
return true;
/*
* The replacement item has been consumed, remove it.
*/
l_replace.remove (item, true);
return true;
}
/**
* Add a notice to discard data from a handle
*/
bool g_addDiscard (SOCKET handle, unsigned long length) {
if (length == 0)
return false;
/*
* Allocate the replacement control structure, and copy the replacement
* document text into it (converting to UTF-8).
*/
Discarding * item = new Discarding (handle);
if (item == 0)
return false;
item->m_length = length;
l_discard.add (* item);
return true;
}
/**
* Determine if we're discarding output from this socket.
*/
Discarding * g_findDiscard (SOCKET handle) {
return l_discard.find (handle);
}
/**
* Consume some amount of data from the discard record.
*/
bool g_consumeDiscard (Discarding * item, unsigned long length, unsigned long * skip) {
unsigned long used = item->m_length;
if (length < used)
used = length;
item->m_length -= used;
length -= used;
if (skip != 0)
* skip = used;
if (item->m_length == 0)
l_discard.remove (item, true);
return true;
}
/**@}*/
| 31.677623
| 88
| 0.563914
|
Pez42
|
3251bc8b1cde3aa927595ec3645a882894603708
| 1,181
|
cpp
|
C++
|
Backtracking/CountN-Queen.cpp
|
divyanshi23/CB-Algo
|
cd3702d715d2f269dacd065ad5fc300af86e55d8
|
[
"MIT"
] | null | null | null |
Backtracking/CountN-Queen.cpp
|
divyanshi23/CB-Algo
|
cd3702d715d2f269dacd065ad5fc300af86e55d8
|
[
"MIT"
] | null | null | null |
Backtracking/CountN-Queen.cpp
|
divyanshi23/CB-Algo
|
cd3702d715d2f269dacd065ad5fc300af86e55d8
|
[
"MIT"
] | null | null | null |
/*You are given an empty chess board of size N*N. Find the number of ways to place N queens on the board, such that no two queens can kill each other in one move. A queen can move vertically, horizontally and diagonally.
Input Format
A single integer N, denoting the size of chess board.
Constraints
1<=N<=11
Output Format
A single integer denoting the count of solutions.
Sample Input
4
Sample Output
2*/
#include <iostream>
#include<bitset>
using namespace std;
bitset<11> d1,d2,col;
void countNQueen(int r,int n,int &ans)
{
//Base case
if(r==n)
{
ans++;
return;
}
//Recursive case
for(int c=0;c<n;c++) //try to place the queen in a particular column of the selected row
{
if(!col[c] && !d1[r-c+n-1] && !d2[r+c])
{
col[c]=1;
d1[r-c+n-1]=1;
d2[r+c]=1;
countNQueen(r+1,n,ans);
col[c]=0;
d1[r-c+n-1]=0;
d2[r+c]=0;
}
}
}
int main() {
int n;
cin>>n; //chess board size
int ans=0;
int r=0; //starting row
countNQueen(r,n,ans);
cout<<ans;
}
| 21.472727
| 221
| 0.546994
|
divyanshi23
|
32527ad159a454c0af64769e08a4aa0d978a048e
| 827
|
cpp
|
C++
|
src/Function.cpp
|
Deukhoofd/ELF_Reader
|
92b732ea3a351f88d9612293f8b9aa8349c7ec49
|
[
"MIT"
] | null | null | null |
src/Function.cpp
|
Deukhoofd/ELF_Reader
|
92b732ea3a351f88d9612293f8b9aa8349c7ec49
|
[
"MIT"
] | null | null | null |
src/Function.cpp
|
Deukhoofd/ELF_Reader
|
92b732ea3a351f88d9612293f8b9aa8349c7ec49
|
[
"MIT"
] | null | null | null |
#include "Function.hpp"
Function::Function(const File& file, Block* block) {
_name = block->GetName();
_fileName = file.GetFileName();
_returnType = ((block->GetAtType() == 0) ? Type() : Type(file, file.GetBlock(block->GetAtType())));
auto c= block->GetNext();
while (c != nullptr){
if (c->GetLevel() == block->GetLevel())
break;
if (c->GetType() == TagType::DW_TAG_formal_parameter && c->GetLevel() == block->GetLevel() + 1){
auto parameter = FunctionParameter(file, c);
_parameters.push_back(parameter);
}
c = c->GetNext();
}
}
FunctionParameter::FunctionParameter(const File& file, Block* block) {
_name = block->GetName();
_type = ((block->GetAtType() == 0) ? Type() : Type(file, file.GetBlock(block->GetAtType())));
}
| 34.458333
| 105
| 0.591294
|
Deukhoofd
|
3259e46a5834cf2b69b7d9c3b0c78188b4042656
| 683
|
cpp
|
C++
|
Mean Inequality.cpp
|
manu-karenite/Codeforces-Solutions
|
c963a0186c6530ea8a785780fc4d68ed539e8c6e
|
[
"MIT"
] | 1
|
2021-04-07T05:13:21.000Z
|
2021-04-07T05:13:21.000Z
|
Mean Inequality.cpp
|
manu-karenite/Codeforces-Solutions
|
c963a0186c6530ea8a785780fc4d68ed539e8c6e
|
[
"MIT"
] | null | null | null |
Mean Inequality.cpp
|
manu-karenite/Codeforces-Solutions
|
c963a0186c6530ea8a785780fc4d68ed539e8c6e
|
[
"MIT"
] | null | null | null |
/*
This code is written by Manavesh Narendra
E-mail : manu.karenite@gmail.com
LinkedIn : https://www.linkedin.com/in/manavesh-narendra-489833196/
*/
#include <bits/stdc++.h>
using namespace std;
int main()
{
int test;
cin>>test;
while(test--)
{
int n;
cin>>n;
vector<int> num ;
int entry;
for(int i=0;i<2*n;i++)
{
cin>>entry;
num.push_back(entry);
}
sort(num.begin(),num.end());
//orinting
for(int p=0 , q = 2*n-1;p<=q;p++,q--)
{
cout<<num[p]<<" "<<num[q]<<" ";
}
cout<<endl;
}
}
| 17.512821
| 67
| 0.445095
|
manu-karenite
|
325b92c7534256bb162a8f8c5f5f99d688984ce2
| 2,778
|
cpp
|
C++
|
Common/util/src/encoding_ansi.cpp
|
deeptexas-ai/test
|
f06b798d18f2d53c9206df41406d02647004ce84
|
[
"MIT"
] | 4
|
2021-10-20T09:18:06.000Z
|
2022-03-27T05:08:26.000Z
|
Common/util/src/encoding_ansi.cpp
|
deeptexas-ai/test
|
f06b798d18f2d53c9206df41406d02647004ce84
|
[
"MIT"
] | 1
|
2021-11-05T03:28:41.000Z
|
2021-11-06T07:48:05.000Z
|
Common/util/src/encoding_ansi.cpp
|
deeptexas-ai/test
|
f06b798d18f2d53c9206df41406d02647004ce84
|
[
"MIT"
] | 1
|
2021-12-13T16:04:22.000Z
|
2021-12-13T16:04:22.000Z
|
/**
* \file encoding_ansi.cpp
* \brief ANSI 编码转换实现代码
*/
#include "pch.h"
#include "encoding_ansi.h"
namespace dtutil
{
/**
* \brief 获取编码实例
* \return 编码实例
*/
Encoding & ANSIEncoding::GetInstance()
{
static ANSIEncoding ansi;
return ansi;
}
/**
* \brief 把 Unicode 字符串转换为指定编码的字符串
* \param wstr Unicode字符串
* \return 输出字符串
*/
std::string ANSIEncoding::Transcode(const std::wstring &wstr)
{
return Convert(wstr.c_str());
}
/**
* \brief 把 Unicode 字符串转换为指定编码的字符串
* \param wstr Unicode字符串
* \return 输出字符串
*/
std::string ANSIEncoding::Transcode(const wchar_t *wstr)
{
return Convert(wstr);
}
/**
* \brief 把 Unicode 字符串转换为指定编码的字符串
* \param wstr Unicode字符串
* \return 输出字符串
*/
std::string ANSIEncoding::Transcode(wchar_t *wstr)
{
return Convert(wstr);
}
/**
* \brief 把指定编码的字符串转换为 Unicode 字符串
* \param str 输入字符串
* \return Unicode字符串
*/
std::wstring ANSIEncoding::Transcode(const std::string &str)
{
return Convert(str.c_str());
}
/**
* \brief 把指定编码的字符串转换为 Unicode 字符串
* \param str 输入字符串
* \return Unicode字符串
*/
std::wstring ANSIEncoding::Transcode(const char *str)
{
return Convert(str);
}
/**
* \brief 把指定编码的字符串转换为 Unicode 字符串
* \param str 输入字符串
* \return Unicode字符串
*/
std::wstring ANSIEncoding::Transcode(char *str)
{
return Convert(str);
}
/**
* \brief 把指定编码的字符串转换为 Unicode 字符串
* \param str 输入字符串
* \return Unicode字符串
*/
std::wstring ANSIEncoding::Convert(const char *str)
{
setlocale(LC_CTYPE, ""); // 使用系统默认编码
size_t size = strlen(str) + 1;
wchar_t *buf = new wchar_t[size]; // wcs 的字符数要比 mbs 的字节数少
memset(buf, 0, sizeof(wchar_t) * size);
size = mbstowcs(buf, str, size);
if ((size_t)(-1) == size)
{
throw EncodingErrorException("invalid multibyte character");
}
std::wstring wstr = buf;
delete [] buf;
return wstr;
}
/**
* \brief 把 Unicode 字符串转换为特定编码的字符串
* \param wstr Unicode字符串
* \return 输出字符串
*/
std::string ANSIEncoding::Convert(const wchar_t *wstr)
{
setlocale(LC_CTYPE, ""); // 使用系统默认编码
size_t size = wcstombs(NULL, wstr, 0) + 1; // 取得需要的尺寸
char *buf = new char[size];
memset(buf, 0, size);
size = wcstombs(buf, wstr, size);
if ((size_t)(-1) == size)
{
throw EncodingErrorException("some wide character cannot be convert to multibyte character.");
}
std::string str = buf;
delete [] buf;
return str;
}
}
| 21.369231
| 106
| 0.559755
|
deeptexas-ai
|
325de760fb323573959be371c3c8d01d3044de2a
| 6,637
|
cc
|
C++
|
Bucatini.cc
|
EdoPro98/Bucatini
|
a904d9a8c48ec90b3dfe9d370ae51f0653b14def
|
[
"MIT"
] | null | null | null |
Bucatini.cc
|
EdoPro98/Bucatini
|
a904d9a8c48ec90b3dfe9d370ae51f0653b14def
|
[
"MIT"
] | null | null | null |
Bucatini.cc
|
EdoPro98/Bucatini
|
a904d9a8c48ec90b3dfe9d370ae51f0653b14def
|
[
"MIT"
] | null | null | null |
//**************************************************
// \file Bucatini.cc
// \brief: main() of Bucatini project
// \author: Lorenzo Pezzotti (CERN EP-SFT-sim) @lopezzot
// \start date: 7 July 2021
//**************************************************
// Includers from project files
//
#include "BucatiniActionInitialization.hh"
#include "BucatiniDetectorConstruction.hh"
// Includers from Geant4
#include "G4FastSimulationPhysics.hh"
#include "G4RunManagerFactory.hh"
#include "G4UIExecutive.hh"
#include "G4UIcommand.hh"
#include "G4UImanager.hh"
#include "G4VisExecutive.hh"
#include "Randomize.hh"
#include "G4PhysListFactoryAlt.hh"
#include "G4PhysListRegistry.hh"
#include "G4PhysicsConstructorFactory.hh"
#include "G4PhysListStamper.hh"
#include "G4VModularPhysicsList.hh"
#include "G4OpticalParameters.hh"
#include "G4StepLimiter.hh"
#include "G4StepLimiterPhysics.hh"
namespace PrintUsageError {
void UsageError() {
G4cerr << "->Bucatini usage: " << G4endl;
G4cerr << "Bucatini [-m macro ] [-u UIsession] [-t nThreads] [-pl PhysicsList]" << G4endl;
}
} // namespace PrintUsageError
namespace{
void PrintAvailable(G4int verbosity) {
G4cout << G4endl;
G4cout << "extensibleFactory: here are the available physics lists:"
<< G4endl;
g4alt::G4PhysListFactory factory;
factory.PrintAvailablePhysLists();
// if user asked for extra verbosity then print physics ctors as well
if ( verbosity > 1 ) {
G4cout << G4endl;
G4cout << "extensibleFactory: "
<< "here are the available physics ctors that can be added:"
<< G4endl;
G4PhysicsConstructorRegistry* g4pctorFactory =
G4PhysicsConstructorRegistry::Instance();
g4pctorFactory->PrintAvailablePhysicsConstructors();
}
}
}
// main() function
//
int main(int argc, char** argv) {
// Error in argument numbers
//
if (argc > 11) {
PrintUsageError::UsageError();
return 1;
}
// Convert arguments in G4string and G4int
//
G4String macro;
G4String session;
G4String physListName;
int nThreads = 0;
for (G4int i = 1; i < argc; i = i + 2) {
if (G4String(argv[i]) == "-m")
macro = argv[i + 1];
else if (G4String(argv[i]) == "-u")
session = argv[i + 1];
else if (G4String(argv[i]) == "-pl")
physListName = argv[i + 1];
#ifdef G4MULTITHREADED
else if (G4String(argv[i]) == "-t") {
nThreads = G4UIcommand::ConvertToInt(argv[i + 1]);
}
#endif
else {
PrintUsageError::UsageError();
return 1;
}
}
#ifdef G4MULTITHREADED
G4RunManager* runManager = G4RunManagerFactory::CreateRunManager(G4RunManagerType::Default, nThreads);
#else
G4RunManager* runManager = G4RunManagerFactory::CreateRunManager(G4RunManagerType::Serial);
#endif
G4Random::setTheEngine(new CLHEP::MTwistEngine());
// Detect interactive mode (if no macro provided) and define UI session
//
G4UIExecutive* ui = nullptr;
if (!macro.size()) { // if macro card is none
ui = new G4UIExecutive(argc, argv, session);
}
g4alt::G4PhysListFactory factory;
G4VModularPhysicsList* physList = nullptr;
factory.SetDefaultReferencePhysList("FTFP_BERT");
G4PhysListRegistry* plreg = G4PhysListRegistry::Instance();
plreg->AddPhysicsExtension("OPTICAL","G4OpticalPhysics");
plreg->AddPhysicsExtension("STEPLIMIT","G4StepLimiterPhysics");
if ( physListName.size() ) {
if ( G4VisExecutive::Verbosity() > 0 ) {
G4cout << "extensibleFactory: explicitly using '"
<< physListName << "'" << G4endl;
}
physList = factory.GetReferencePhysList(physListName);
} else {
if ( G4VisExecutive::Verbosity() > 0 ) {
G4cout << "extensibleFactory: no -pl flag;"
<< " using ReferencePhysList() (FTFP_BERT)" << G4endl;
}
physList = factory.ReferencePhysList();
}
if ( ! physList ) {
G4cerr << "extensibleFactory: PhysicsList '"
<< physListName
<< "' was not available in g4alt::PhysListFactory." << G4endl;
PrintAvailable(G4VisExecutive::Verbosity());
// if we can't get what the user asked for...
// don't go on to use something else, that's confusing
G4ExceptionDescription ED;
ED << "The factory for the physicslist ["
<< physListName
<< "] does not exist!"
<< G4endl;
G4Exception("Bucatini", "Buactini", FatalException, ED);
exit(42);
}
G4FastSimulationPhysics* fastSimPhysics = new G4FastSimulationPhysics();
fastSimPhysics->ActivateFastSimulation("opticalphoton");
physList->RegisterPhysics(fastSimPhysics);
G4OpticalParameters::Instance()->SetProcessActivation("Cerenkov", true);
G4OpticalParameters::Instance()->SetProcessActivation("Scintillation", true);
G4OpticalParameters::Instance()->SetProcessActivation("OpAbsorption", true);
G4OpticalParameters::Instance()->SetProcessActivation("OpRayleigh", false);
G4OpticalParameters::Instance()->SetProcessActivation("OpMieHG", false);
G4OpticalParameters::Instance()->SetProcessActivation("OpWLS", false);
G4OpticalParameters::Instance()->SetProcessActivation("OpWLS2", false);
//G4OpticalParameters::Instance()->SetCerenkovStackPhotons(false);
//G4OpticalParameters::Instance()->SetScintStackPhotons(false);
G4OpticalParameters::Instance()->SetScintTrackInfo(false);
G4OpticalParameters::Instance()->SetScintTrackSecondariesFirst(false); // only relevant if we actually stack and trace the optical photons
G4OpticalParameters::Instance()->SetCerenkovTrackSecondariesFirst(false); // only relevant if we actually stack and trace the optical photons
G4OpticalParameters::Instance()->SetCerenkovMaxPhotonsPerStep(100);
G4OpticalParameters::Instance()->SetCerenkovMaxBetaChange(10.0);
G4OpticalParameters::Instance()->Dump();
physList->DumpList();
// Set mandatory initialization classes
runManager->SetUserInitialization(new BucatiniDetectorConstruction());
runManager->SetUserInitialization(physList);
runManager->SetUserInitialization(new BucatiniActionInitialization());
// Initialize visualization
auto visManager = new G4VisExecutive("Quiet");
visManager->Initialize();
// Get the pointer to the User Interface manager
auto UImanager = G4UImanager::GetUIpointer();
// Process macro or start UI session
//
if (macro.size()) { // macro card mode
G4String command = "/control/execute ";
UImanager->ApplyCommand(command + macro);
} else { // start UI session
UImanager->ApplyCommand("/control/execute Bucatini_init_vis.mac");
if (ui->IsGUI()) {
UImanager->ApplyCommand("/control/execute Bucatini_gui.mac");
}
ui->SessionStart();
delete ui;
}
// Program termination (user actions deleted by run manager)
delete visManager;
delete runManager;
}
//**************************************************
| 32.694581
| 142
| 0.706645
|
EdoPro98
|
3260f431fd17186a0934bb7500142b1a27bef192
| 1,472
|
cpp
|
C++
|
test/Core/ListTest.cpp
|
anisimovsergey/gluino_test
|
7de141362cafb244841b13b7b86c17d00f550fba
|
[
"MIT"
] | 5
|
2017-10-07T06:46:23.000Z
|
2018-12-10T07:14:47.000Z
|
test/Core/ListTest.cpp
|
anisimovsergey/gluino_test
|
7de141362cafb244841b13b7b86c17d00f550fba
|
[
"MIT"
] | 8
|
2017-01-07T15:01:32.000Z
|
2017-07-16T20:18:10.000Z
|
test/Core/ListTest.cpp
|
anisimovsergey/gluino_test
|
7de141362cafb244841b13b7b86c17d00f550fba
|
[
"MIT"
] | 4
|
2017-01-07T14:58:00.000Z
|
2019-10-30T09:38:53.000Z
|
#include "Utils/Testing.hpp"
#include "Core/List.hpp"
#include "Core/Memory.hpp"
using namespace Core;
namespace {
class Content : public Core::IEntity {
TYPE_INFO(Content, Core::IEntity, "content")
public:
explicit Content(int i):i(i) {}
int i;
};
class ContentList : public Core::List<Content> {
TYPE_INFO(ContentList, Core::List<Content>, "contentList")
};
}
TEST_CASE("can add IEntity", "[List]") {
ContentList list;
list.addEntity(Content(1));
list.addEntity(Content(10));
int acc = 0;
auto res = list.forEachEntity([&](const IEntity& element) {
acc += static_cast<const Content&>(element).i;
return Status::OK;
});
REQUIRE(acc == 11);
REQUIRE(res.getCode() == StatusCode::OK);
}
TEST_CASE("can add Content", "[List]") {
ContentList list;
list.add(Content(1));
list.add(Content(10));
int acc = 0;
auto res = list.forEach([&](const Content& element) {
acc += element.i;
return Status::OK;
});
REQUIRE(acc == 11);
REQUIRE(res.getCode() == StatusCode::OK);
}
TEST_CASE("can abort forEach", "[List]") {
ContentList list;
list.add(Content(1));
list.add(Content(10));
list.add(Content(100));
int acc = 0;
auto res = list.forEach([&](const Content& element) {
if (element.i > 10)
return Status(StatusCode::NotFound, "not found");
acc += element.i;
return Status::OK;
});
REQUIRE(acc == 11);
REQUIRE(res.getCode() == StatusCode::NotFound);
}
| 20.444444
| 62
| 0.629076
|
anisimovsergey
|
3263c76c159ab76eaf8c303bfdfb9de5f1a8fbb5
| 1,444
|
hpp
|
C++
|
cpp/include/manager/robinhood_bot.hpp
|
algo-trading-kjsce/trading
|
29a245a16512fd5803168064b45021cd508e7de0
|
[
"MIT"
] | 2
|
2020-11-08T06:11:35.000Z
|
2021-09-18T01:44:45.000Z
|
cpp/include/manager/robinhood_bot.hpp
|
algo-trading-kjsce/trading
|
29a245a16512fd5803168064b45021cd508e7de0
|
[
"MIT"
] | null | null | null |
cpp/include/manager/robinhood_bot.hpp
|
algo-trading-kjsce/trading
|
29a245a16512fd5803168064b45021cd508e7de0
|
[
"MIT"
] | 1
|
2021-06-13T02:36:25.000Z
|
2021-06-13T02:36:25.000Z
|
/**
* @file robinhood_bot.hpp
* @author ashwinn76
* @brief
* @version 0.1
* @date 2021-02-12
*
* @copyright Copyright (c) 2021
*
*/
#pragma once
#include "stock_data.hpp"
#include "helper/py_object.hpp"
namespace trading
{
class robinhood_bot
{
private:
python::py_object m_bot{}; // Robinhood Bot
python::py_object m_historyFunc{}; // Function to get history of prices
python::py_object m_last_price_func{}; // Function to get latest price
public:
/**
* @brief Construct a new robinhood bot object
*
*/
robinhood_bot();
/**
* @brief Get the historical prices for a stock/currency
*
* @param i_symbol Symbol to find info
* @return csv_data Final historical result
*/
csv_data get_historical_prices( const std::string& i_symbol );
/**
* @brief Get the latest price for a stock/currency
*
* @param i_symbol Symbol to find info
* @return candle_s Candle for latest price
*/
candle_s get_latest_price( const std::string& i_symbol );
/**
* @brief Buy a ticker
*
* @param i_ticker incoming ticker
* @return number of shares and price per share bought
*/
std::pair<double, double> buy( const std::string& i_ticker );
/**
* @brief sell a ticker
*
* @param i_ticker incoming ticker
* @return sale price of ticker
*/
double sell( const std::string& i_ticker );
};
}
| 21.552239
| 76
| 0.631579
|
algo-trading-kjsce
|
32660093b2de2e07949a75a10b18c4a94b8dbb74
| 4,106
|
hpp
|
C++
|
include/item.hpp
|
hunter-land/humble-user-interface
|
2a6f9bf7f6c31e51061aa45fc1d0aa04e21b19e4
|
[
"Apache-2.0"
] | null | null | null |
include/item.hpp
|
hunter-land/humble-user-interface
|
2a6f9bf7f6c31e51061aa45fc1d0aa04e21b19e4
|
[
"Apache-2.0"
] | null | null | null |
include/item.hpp
|
hunter-land/humble-user-interface
|
2a6f9bf7f6c31e51061aa45fc1d0aa04e21b19e4
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include "./element.hpp"
#include "./itemHolder.hpp"
extern "C" {
#include <SDL2/SDL.h>
}
#include <vector>
namespace lui {
/**
* \brief A draggable item which can be placed inside itemHolders
*
* \note Item template type must match the itemHolder's template type for the item to be held.
*/
template<typename T>
class item : public element {
protected:
SDL_Texture *m_texture = nullptr; //!<The texture of the item
bool m_beingMoved = false; //!<Is this item currently being moved by the user
public:
SDL_Rect *srcrect = nullptr; //!<Rectangle of the texture to draw
itemHolder<T> *m_holder = nullptr; //!<The itemHolder to which we are assigned \warning This item should never be written to.
T value; //!<Value, or ID, of this item
/**
* \brief Construct item with a texture and a value
*
* \param *texture The texture of the item.
* \param val The value to assign to the item.
*/
item(SDL_Texture *texture, T val = T()) {
value = val;
}
/**
* \brief Construct item with a texture, position, size, angle, and value
*
* \param *texture The texture of the item.
* \param dstrect The rectangle to draw the item in.
* \param angle The angle the item will be at.
* \param flip The flip the item will have.
* \param val The value to assign to the item.
*/
item(SDL_Texture *texture, const SDL_FRect dstrect, const double angle = 0, const SDL_RendererFlip flip = SDL_FLIP_NONE, T val = T()) {
setDstrect(dstrect);
setAngle(angle);
setTexture(texture);
value = val;
}
/**
* \brief Deconstruct item
*/
~item() {}
void render(SDL_Renderer *renderer) {
SDL_RenderCopyExF(renderer, m_texture, srcrect, &m_dstrect, m_angle, &(zeroFPoint), m_flip);
}
void userLogic(std::vector<SDL_Event> &events, SDL_Renderer *renderer) {
element::userLogic(events, renderer);
for (SDL_Event &e : events) {
if (m_hasFocus) {
switch (e.type) {
case SDL_MOUSEMOTION:
if (m_beingMoved) {
m_dstrect.x += e.motion.xrel;
m_dstrect.y += e.motion.yrel;
}
break;
case SDL_MOUSEBUTTONDOWN:
if (e.button.button == SDL_BUTTON_LEFT) {
//Start dragging item.
pickup();
}
break;
case SDL_MOUSEBUTTONUP:
if (e.button.button == SDL_BUTTON_LEFT) {
//Release item
release();
}
break;
}
}
}
}
void resetUserLogic() {
element::resetUserLogic();
release();
}
using element::loopLogic;
using element::resetLoopLogic;
using element::bind;
using element::unbind;
using element::setSet;
using element::setFocus;
void onFocusUpdated() {
if (!m_hasFocus && m_beingMoved) {
release();
}
}
using element::setDstrect;
using element::getDstrect;
using element::setAngle;
using element::getAngle;
/**
* \brief Sets the item's texture
*
* \param *texture The texture for the item to use
*/
void setTexture(SDL_Texture *texture) {
m_texture = texture;
}
/**
* \brief Gets the item's texture
*
* \returns The texture of the item
*/
SDL_Texture* getTexture() {
return m_texture;
}
/**
* \brief Release/drop the item
*/
void release() {
m_beingMoved = false;
//Check if we were released on an itemHolder
if (m_parentSet != nullptr) {
std::array<element*, 2> focused = m_parentSet->getFocusedElements();
itemHolder<T>* focusedSub = dynamic_cast<itemHolder<T>*>(focused[1]);
if (focused[0] == this && focusedSub != nullptr) {
focusedSub->setChild(this);
}
}
}
/**
* \brief Pickup the item and attach it to the user's mouse
*/
void pickup() {
m_beingMoved = true;
//Check if we are being taken from an itemHolder
if (m_holder != nullptr) {
m_holder->setChild((item<T>*)nullptr);
m_holder = nullptr;
m_callEventFunction(Event::ValueChanged);
}
}
using element::pointInElement;
};
};
| 26.836601
| 138
| 0.619338
|
hunter-land
|
3268d43a8df22768303d546e28afa48c87c0a62f
| 1,221
|
hpp
|
C++
|
include/common/color_utils.hpp
|
riscygeek/AntSimulator
|
b35d1b0e0a3601ec326eb2839fb7551672d036af
|
[
"MIT"
] | null | null | null |
include/common/color_utils.hpp
|
riscygeek/AntSimulator
|
b35d1b0e0a3601ec326eb2839fb7551672d036af
|
[
"MIT"
] | null | null | null |
include/common/color_utils.hpp
|
riscygeek/AntSimulator
|
b35d1b0e0a3601ec326eb2839fb7551672d036af
|
[
"MIT"
] | null | null | null |
#pragma once
#include <SFML/Graphics.hpp>
#include "common/math.hpp"
#include "common/number_generator.hpp"
struct ColorUtils
{
template<typename T>
static sf::Color createColor(T r, T g, T b)
{
return sf::Color{ std::min(uint8_t{255}, std::max(uint8_t{0}, to<uint8_t>(r))),
std::min(uint8_t{255}, std::max(uint8_t{0}, to<uint8_t>(g))),
std::min(uint8_t{255}, std::max(uint8_t{0}, to<uint8_t>(b))) };
}
static sf::Color getRainbow(float t)
{
const float r = sin(t);
const float g = sin(t + 0.33f * 2.0f * Math::PI);
const float b = sin(t + 0.66f * 2.0f * Math::PI);
return createColor(255 * r * r, 255 * g * g, 255 * b * b);
}
static sf::Color getRandomColor()
{
return createColor(RNGf::getUnder(255.0f), RNGf::getUnder(255.0f), RNGf::getUnder(255.0f));
}
static sf::Color getDesaturated(sf::Color color, float ratio)
{
const float l = 0.3f * color.r + 0.6f * color.g + 0.1f * color.b;
float new_r = color.r + ratio * (l - color.r);
float new_g = color.g + ratio * (l - color.g);
float new_b = color.b + ratio * (l - color.b);
return createColor(new_r, new_g, new_b);
}
};
| 30.525
| 99
| 0.581491
|
riscygeek
|
326a25b67e681e27ee9bc177f2a0f2babbb38cc9
| 4,041
|
hpp
|
C++
|
include/desola/profiling/ExpressionGraph.hpp
|
FrancisRussell/desola
|
a469428466e4849c7c0e2009a0c50b89184cae01
|
[
"Apache-2.0"
] | 2
|
2021-12-17T10:46:20.000Z
|
2021-12-18T11:53:50.000Z
|
include/desola/profiling/ExpressionGraph.hpp
|
FrancisRussell/desola
|
a469428466e4849c7c0e2009a0c50b89184cae01
|
[
"Apache-2.0"
] | null | null | null |
include/desola/profiling/ExpressionGraph.hpp
|
FrancisRussell/desola
|
a469428466e4849c7c0e2009a0c50b89184cae01
|
[
"Apache-2.0"
] | null | null | null |
/****************************************************************************/
/* Copyright 2005-2006, Francis Russell */
/* */
/* Licensed under the Apache License, Version 2.0 (the License); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an AS IS BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* */
/****************************************************************************/
#ifndef DESOLA_PROFILING_EXPRESSION_GRAPH_HPP
#define DESOLA_PROFILING_EXPRESSION_GRAPH_HPP
#include "Desola_profiling_fwd.hpp"
#include <boost/ptr_container/ptr_vector.hpp>
#include <cstddef>
#include <functional>
#include <map>
#include <algorithm>
#include <cassert>
namespace desola
{
namespace detail
{
template<typename T_element>
class PExpressionGraph
{
private:
PExpressionGraph(const PExpressionGraph&);
PExpressionGraph& operator=(const PExpressionGraph&);
boost::ptr_vector< PExpressionNode<T_element> > exprVector;
mutable bool isHashCached;
mutable std::size_t cachedHash;
template<typename VisitorType>
class ApplyVisitor : public std::unary_function< void, PExpressionNode<T_element> >
{
private:
VisitorType& visitor;
public:
ApplyVisitor(VisitorType& v) : visitor(v)
{
}
inline void operator()(PExpressionNode<T_element>& node) const
{
node.accept(visitor);
}
};
public:
PExpressionGraph(ExpressionGraph<T_element>& expressionGraph) : isHashCached(false)
{
PExpressionNodeGenerator<T_element> generator(*this);
expressionGraph.accept(generator);
}
inline std::size_t nodeCount() const
{
return exprVector.size();
}
void addNode(PExpressionNode<T_element>* const node)
{
exprVector.push_back(node);
}
PExpressionNode<T_element>& nodeAt(const std::size_t index)
{
return exprVector[index];
}
void accept(PExpressionNodeVisitor<T_element>& visitor)
{
std::for_each(exprVector.begin(), exprVector.end(), ApplyVisitor< PExpressionNodeVisitor<T_element> >(visitor));
}
bool operator==(const PExpressionGraph& right) const
{
if(exprVector.size() != right.exprVector.size())
{
return false;
}
else
{
std::map<const PExpressionNode<T_element>*, const PExpressionNode<T_element>*> mappings;
for(std::size_t index = 0; index<exprVector.size(); ++index)
{
mappings[&exprVector[index]] = &right.exprVector[index];
}
PEqualityCheckingVisitor<T_element> checker(mappings);
const_cast<PExpressionGraph<T_element>&>(*this).accept(checker);
return checker.isEqual();
}
}
friend std::size_t hash_value(const PExpressionGraph<T_element>& graph)
{
if(!graph.isHashCached)
{
graph.isHashCached = true;
std::map<const PExpressionNode<T_element>*, int> nodeNumberings;
for(std::size_t index=0; index<graph.exprVector.size(); ++index)
{
nodeNumberings[&graph.exprVector[index]] = index;
}
PHashingVisitor<T_element> hasher(nodeNumberings);
const_cast<PExpressionGraph<T_element>&>(graph).accept(hasher);
graph.cachedHash = hasher.getHash();
}
return graph.cachedHash;
}
};
}
}
#endif
| 29.49635
| 116
| 0.592923
|
FrancisRussell
|
326a8bfdcdc201c13317a91c2fbb7621c50878c7
| 5,309
|
cpp
|
C++
|
src/cvm/defaults.cpp
|
thomas-pendragon/dablang
|
f8e1e0835138b6dc6a675da231e176ca20b1347a
|
[
"MIT"
] | 2
|
2017-06-02T02:55:36.000Z
|
2017-06-02T22:15:46.000Z
|
src/cvm/defaults.cpp
|
thomas-pendragon/dablang
|
f8e1e0835138b6dc6a675da231e176ca20b1347a
|
[
"MIT"
] | 1
|
2020-06-19T15:58:33.000Z
|
2020-06-19T15:58:33.000Z
|
src/cvm/defaults.cpp
|
thomas-pendragon/dablang
|
f8e1e0835138b6dc6a675da231e176ca20b1347a
|
[
"MIT"
] | 1
|
2017-06-02T22:17:52.000Z
|
2017-06-02T22:17:52.000Z
|
#include "cvm.h"
#ifndef DAB_PLATFORM_WINDOWS
#include <dlfcn.h>
#endif
#define STR2(s) #s
#define STR(s) STR2(s)
#ifdef __linux__
#define DAB_LIBC_NAME "libc.so.6" // LINUX
#else
#define DAB_LIBC_NAME "libc.dylib" // APPLE
#endif
DabValue DabVM::merge_arrays(const DabValue &arg0, const DabValue &arg1)
{
auto & a0 = arg0.array();
auto & a1 = arg1.array();
DabValue array_class = classes[CLASS_ARRAY];
DabValue value = array_class.create_instance();
auto & array = value.array();
array.resize(a0.size() + a1.size());
fprintf(stderr, "vm: merge %d and %d items into new %d-sized array\n", (int)a0.size(),
(int)a1.size(), (int)array.size());
size_t i = 0;
for (auto &item : a0)
{
array[i++] = item;
}
for (auto &item : a1)
{
array[i++] = item;
}
return value;
}
dab_function_reg_t import_external_function(void *symbol, const DabFunctionReflection &reflection)
{
return [symbol, &reflection](DabValue, std::vector<DabValue> args) {
const auto &arg_klasses = reflection.arg_klasses;
const auto ret_klass = reflection.ret_klass;
assert(args.size() == arg_klasses.size());
if (false)
{
}
#include "ffi_signatures.h"
else
{
fprintf(stderr, "vm: unsupported signature\n");
exit(1);
}
};
}
void DabVM::define_defaults()
{
fprintf(stderr, "vm: define defaults\n");
define_default_classes();
fprintf(stderr, "vm: define default functions\n");
auto make_import_function = [this](const char *name) {
return [this, name](DabValue, std::vector<DabValue> args) {
#ifndef DAB_PLATFORM_WINDOWS
assert(args.size() <= 2);
std::string libc_name;
if (args.size() == 2)
{
auto _libc_name = args[1];
libc_name = _libc_name.string();
}
auto method = args[0];
assert(method.class_index() == CLASS_METHOD);
auto method_name = method.string();
if (args.size() == 1)
{
libc_name = method_name;
}
fprintf(stderr, "vm: readjust '%s' to libc function '%s'\n", method_name.c_str(),
libc_name.c_str());
auto handle = dlopen(name, RTLD_LAZY);
if (!handle)
{
fprintf(stderr, "vm: dlopen error: %s", dlerror());
exit(1);
}
if (options.verbose)
{
fprintf(stderr, "vm: dlopen handle: %p\n", handle);
}
auto symbol = dlsym(handle, libc_name.c_str());
if (!symbol)
{
fprintf(stderr, "vm: dlsym error: %s", dlerror());
exit(1);
}
if (options.verbose)
{
fprintf(stderr, "vm: dlsym handle: %p\n", symbol);
}
auto func_index = get_or_create_symbol_index(method_name);
auto &function = functions[func_index];
function.regular = false;
function.address = -1;
function.extra_reg = import_external_function(symbol, function.reflection);
return DabValue(nullptr);
#else
(void)args;
if (true)
{
throw DabRuntimeError("function import not supported on windows yet");
}
return DabValue(nullptr);
#endif
};
};
{
DabFunction fun;
fun.name = "__import_libc";
fun.regular = false;
fun.extra_reg = make_import_function(DAB_LIBC_NAME);
auto func_index = get_or_create_symbol_index("__import_libc");
functions[func_index] = fun;
}
{
DabFunction fun;
fun.name = "__import_sdl";
fun.regular = false;
fun.extra_reg = make_import_function("/usr/local/lib/libSDL2.dylib");
auto func_index = get_or_create_symbol_index("__import_sdl");
functions[func_index] = fun;
}
{
DabFunction fun;
fun.name = "__import_pq";
fun.regular = false;
fun.extra_reg = make_import_function("/usr/local/lib/libpq.dylib");
auto func_index = get_or_create_symbol_index("__import_pq");
functions[func_index] = fun;
}
{
DabFunction fun;
fun.name = "||";
fun.regular = false;
fun.extra_reg = [](DabValue, std::vector<DabValue> args) {
assert(args.size() == 2);
auto arg0 = args[0];
auto arg1 = args[1];
return arg0.truthy() ? arg0 : arg1;
};
auto func_index = get_or_create_symbol_index("||");
functions[func_index] = fun;
}
{
DabFunction fun;
fun.name = "&&";
fun.regular = false;
fun.extra_reg = [](DabValue, std::vector<DabValue> args) {
assert(args.size() == 2);
auto arg0 = args[0];
auto arg1 = args[1];
return arg0.truthy() ? arg1 : arg0;
};
auto func_index = get_or_create_symbol_index("&&");
functions[func_index] = fun;
}
}
| 27.225641
| 98
| 0.531362
|
thomas-pendragon
|
326f8f201022daa2b16f257b0f344d04cfa2080d
| 6,668
|
cpp
|
C++
|
Gui/DataView/DirectConditionGenerator.cpp
|
WenjieXu/ogs
|
0cd1b72ec824833bf949a8bbce073c82158ee443
|
[
"BSD-4-Clause"
] | 1
|
2021-11-21T17:29:38.000Z
|
2021-11-21T17:29:38.000Z
|
Gui/DataView/DirectConditionGenerator.cpp
|
WenjieXu/ogs
|
0cd1b72ec824833bf949a8bbce073c82158ee443
|
[
"BSD-4-Clause"
] | null | null | null |
Gui/DataView/DirectConditionGenerator.cpp
|
WenjieXu/ogs
|
0cd1b72ec824833bf949a8bbce073c82158ee443
|
[
"BSD-4-Clause"
] | null | null | null |
/**
* \file
* \author Karsten Rink
* \date 2012-01-04
* \brief Implementation of the DirectConditionGenerator class.
*
* \copyright
* Copyright (c) 2013, OpenGeoSys Community (http://www.opengeosys.org)
* Distributed under a Modified BSD License.
* See accompanying file LICENSE.txt or
* http://www.opengeosys.org/project/license
*
*/
#include <fstream>
// ThirdParty/logog
#include "logog/include/logog.hpp"
#include "DirectConditionGenerator.h"
#include "Raster.h"
#include "MeshSurfaceExtraction.h"
#include "PointWithID.h"
#include "Mesh.h"
#include <cmath>
#include <limits>
const std::vector< std::pair<size_t,double> >& DirectConditionGenerator::directToSurfaceNodes(const MeshLib::Mesh &mesh, const std::string &filename)
{
if (_direct_values.empty())
{
GeoLib::Raster* raster(GeoLib::Raster::getRasterFromASCFile(filename));
if (! raster) {
ERR("Error in DirectConditionGenerator::directWithSurfaceIntegration() - could not load raster file.");
return _direct_values;
}
double origin_x(raster->getOrigin()[0]);
double origin_y(raster->getOrigin()[1]);
double delta(raster->getRasterPixelDistance());
double no_data(raster->getNoDataValue());
unsigned imgwidth(raster->getNCols()), imgheight(raster->getNRows());
double const*const img(raster->begin());
const double dir[3] = {0,0,1};
const std::vector<GeoLib::PointWithID*> surface_nodes(MeshLib::MeshSurfaceExtraction::getSurfaceNodes(mesh, dir) );
const size_t nNodes(surface_nodes.size());
_direct_values.reserve(nNodes);
for (size_t i=0; i<nNodes; i++)
{
const double* coords (surface_nodes[i]->getCoords());
if (coords[0]>=origin_x && coords[0]<(origin_x+(delta*imgwidth)) && coords[1]>=origin_y && coords[1]<(origin_y+(delta*imgheight)))
{
int cell_x = static_cast<int>(floor((coords[0] - origin_x)/delta));
int cell_y = static_cast<int>(floor((coords[1] - origin_y)/delta));
// if node outside of raster use raster boundary values
cell_x = (cell_x < 0) ? 0 : ((cell_x > static_cast<int>(imgwidth )) ? (imgwidth-1) : cell_x);
cell_y = (cell_y < 0) ? 0 : ((cell_y > static_cast<int>(imgheight)) ? (imgheight-1) : cell_y);
size_t index = cell_y*imgwidth+cell_x;
if (fabs(img[index] - no_data) > std::numeric_limits<float>::epsilon())
_direct_values.push_back( std::pair<size_t, double>(surface_nodes[i]->getID(),img[index]) );
}
}
delete raster;
}
else
ERR("Error in DirectConditionGenerator::directToSurfaceNodes() - Data vector contains outdated values.");
return _direct_values;
}
const std::vector< std::pair<size_t,double> >& DirectConditionGenerator::directWithSurfaceIntegration(MeshLib::Mesh &mesh, const std::string &filename, double scaling)
{
(void)mesh;
(void)filename;
(void)scaling;
/* TODO6
double no_data_value (-9999); // TODO: get this from asc-reader!
if (_direct_values.empty())
{
//mesh.MarkInterface_mHM_Hydro_3D(); // mark element faces on the surface
//----
const double dir[3] = {0,0,1};
MeshLib::Mesh* sfc_mesh (MeshLib::MeshSurfaceExtraction::getMeshSurface(mesh, dir));
std::vector<double> node_area_vec (sfc_mesh->getNNodes());
MeshLib::MeshSurfaceExtraction::getSurfaceAreaForNodes(sfc_mesh, node_area_vec);
//----
double origin_x(0), origin_y(0), delta(0);
size_t imgwidth(0), imgheight(0);
double node_val[8] = {0,0,0,0,0,0,0,0}; // maximum possible number of nodes per face (just in case ...)
FiniteElement::CElement* fem ( new FiniteElement::CElement(mesh.GetCoordinateFlag()) );
float* img = 0;
if (filename.substr(filename.length()-3,3).compare("asc") == 0)
img = VtkRaster::loadDataFromASC(filename, origin_x, origin_y, imgwidth, imgheight, delta);
else if (filename.substr(filename.length()-3,3).compare("grd") == 0)
img = VtkRaster::loadDataFromSurfer(filename, origin_x, origin_y, imgwidth, imgheight, delta);
if (img == 0)
{
std::cout << "Error in DirectConditionGenerator::directWithSurfaceIntegration() - could not load vtk raster." << std::endl;
return _direct_values;
}
const size_t nNodes(mesh.nod_vector.size());
std::vector<double> val(nNodes, 0.0);
for(size_t i = 0; i < nNodes; i++)
mesh.nod_vector[i]->SetMark(false);
// copied from CFEMesh::Precipitation2NeumannBC() by WW
size_t nFaces = mesh.face_vector.size();
for(size_t i=0; i<nFaces; i++)
{
MeshLib::CElem* elem = mesh.face_vector[i];
if (!elem->GetMark())
continue;
// if face is on the surface of the mesh
size_t nElemNodes = elem->GetNodesNumber(false);
for(size_t k=0; k<nElemNodes; k++)
node_val[k] = 0.0;
// get values from the raster for all nodes of the face
for(size_t k=0; k<nElemNodes; k++)
{
double const* const pnt_k (elem->GetNode(k)->getData());
int cell_x = static_cast<int>(floor((pnt_k[0] - origin_x) / delta));
int cell_y = static_cast<int>(floor((pnt_k[1] - origin_y) / delta));
// if node outside of raster use raster boundary values
cell_x = (cell_x < 0) ? 0 : ((static_cast<size_t>(cell_x) > imgwidth) ? (imgwidth-1) : cell_x);
cell_y = (cell_y < 0) ? 0 : ((static_cast<size_t>(cell_y) > imgheight) ? (imgheight-1) : cell_y);
node_val[k] = img[ 2 * (cell_y * imgwidth + cell_x) ];
if (fabs(node_val[k] - no_data_value) < std::numeric_limits<double>::epsilon())
node_val[k] = 0.;
}
// get area of the surface element face
elem->ComputeVolume();
// do the actual surface integration
fem->setOrder(mesh.getOrder() + 1);
fem->ConfigElement(elem);
fem->FaceIntegration(node_val);
// add up the integrated values (nodes get values added for all faces they are part of)
for(size_t k=0; k<elem->GetNodesNumber(false); k++)
{
MeshLib::CNode* node = elem->GetNode(k);
node->SetMark(true);
val[node->GetIndex()] += node_val[k];
}
}
_direct_values.reserve(nNodes);
for(size_t k=0; k<nNodes; k++)
{
if (!mesh.nod_vector[k]->GetMark())
continue;
// Assuming the unit of precipitation is mm/day
_direct_values.push_back( std::pair<size_t, double>(k, val[k] / scaling) );
}
}
else
std::cout << "Error in DirectConditionGenerator::directWithSurfaceIntegration() - Data vector contains outdated values..." << std::endl;
*/
return _direct_values;
}
int DirectConditionGenerator::writeToFile(const std::string &name) const
{
std::ofstream out( name.c_str(), std::ios::out );
if (out)
{
for (std::vector< std::pair<size_t,double> >::const_iterator it = _direct_values.begin(); it != _direct_values.end(); ++it)
out << it->first << "\t" << it->second << "\n";
out.close();
}
return 0;
}
| 34.194872
| 167
| 0.678464
|
WenjieXu
|
32732877e7abe53c30f32eda347d067269fe883d
| 6,733
|
cxx
|
C++
|
STEER/ESD/AliESDMuonCluster.cxx
|
AllaMaevskaya/AliRoot
|
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
|
[
"BSD-3-Clause"
] | 52
|
2016-12-11T13:04:01.000Z
|
2022-03-11T11:49:35.000Z
|
STEER/ESD/AliESDMuonCluster.cxx
|
AllaMaevskaya/AliRoot
|
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
|
[
"BSD-3-Clause"
] | 1,388
|
2016-11-01T10:27:36.000Z
|
2022-03-30T15:26:09.000Z
|
STEER/ESD/AliESDMuonCluster.cxx
|
AllaMaevskaya/AliRoot
|
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
|
[
"BSD-3-Clause"
] | 275
|
2016-06-21T20:24:05.000Z
|
2022-03-31T13:06:19.000Z
|
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
// $Id$
//-----------------------------------------------------------------------------
/// \class AliESDMuonCluster
///
/// Class to describe the MUON clusters in the Event Summary Data
///
/// \author Philippe Pillot, Subatech
//-----------------------------------------------------------------------------
#include "AliESDEvent.h"
#include "AliESDMuonCluster.h"
#include "AliESDMuonPad.h"
#include "AliLog.h"
#include <TClonesArray.h>
#include <Riostream.h>
using std::endl;
using std::cout;
/// \cond CLASSIMP
ClassImp(AliESDMuonCluster)
/// \endcond
//_____________________________________________________________________________
AliESDMuonCluster::AliESDMuonCluster()
: TObject(),
fCharge(0.),
fChi2(0.),
fPads(0x0),
fNPads(0),
fPadsId(0x0),
fLabel(-1)
{
/// default constructor
fXYZ[0] = fXYZ[1] = fXYZ[2] = 0.;
fErrXY[0] = fErrXY[1] = 0.;
}
//_____________________________________________________________________________
AliESDMuonCluster::AliESDMuonCluster (const AliESDMuonCluster& cluster)
: TObject(cluster),
fCharge(cluster.fCharge),
fChi2(cluster.fChi2),
fPads(0x0),
fNPads(cluster.fNPads),
fPadsId(0x0),
fLabel(cluster.fLabel)
{
/// Copy constructor
fXYZ[0] = cluster.fXYZ[0];
fXYZ[1] = cluster.fXYZ[1];
fXYZ[2] = cluster.fXYZ[2];
fErrXY[0] = cluster.fErrXY[0];
fErrXY[1] = cluster.fErrXY[1];
if (cluster.fPads) {
fPads = new TClonesArray("AliESDMuonPad",cluster.fPads->GetEntriesFast());
AliESDMuonPad *pad = (AliESDMuonPad*) cluster.fPads->First();
while (pad) {
new ((*fPads)[fPads->GetEntriesFast()]) AliESDMuonPad(*pad);
pad = (AliESDMuonPad*) cluster.fPads->After(pad);
}
}
if (cluster.fPadsId) fPadsId = new TArrayI(*(cluster.fPadsId));
}
//_____________________________________________________________________________
AliESDMuonCluster& AliESDMuonCluster::operator=(const AliESDMuonCluster& cluster)
{
/// Equal operator
if (this == &cluster) return *this;
TObject::operator=(cluster); // don't forget to invoke the base class' assignment operator
fXYZ[0] = cluster.fXYZ[0];
fXYZ[1] = cluster.fXYZ[1];
fXYZ[2] = cluster.fXYZ[2];
fErrXY[0] = cluster.fErrXY[0];
fErrXY[1] = cluster.fErrXY[1];
fCharge = cluster.fCharge;
fChi2 = cluster.fChi2;
fLabel = cluster.fLabel;
delete fPads;
if (cluster.fPads) {
fPads = new TClonesArray("AliESDMuonPad",cluster.fPads->GetEntriesFast());
AliESDMuonPad *pad = (AliESDMuonPad*) cluster.fPads->First();
while (pad) {
new ((*fPads)[fPads->GetEntriesFast()]) AliESDMuonPad(*pad);
pad = (AliESDMuonPad*) cluster.fPads->After(pad);
}
} else fPads = 0x0;
SetPadsId(cluster.fNPads, cluster.GetPadsId());
return *this;
}
//_____________________________________________________________________________
void AliESDMuonCluster::Copy(TObject &obj) const {
/// This overwrites the virtual TOBject::Copy()
/// to allow run time copying without casting
/// in AliESDEvent
if(this==&obj)return;
AliESDMuonCluster *robj = dynamic_cast<AliESDMuonCluster*>(&obj);
if(!robj)return; // not an AliESDMuonCluster
*robj = *this;
}
//__________________________________________________________________________
AliESDMuonCluster::~AliESDMuonCluster()
{
/// Destructor
delete fPads;
delete fPadsId;
}
//__________________________________________________________________________
void AliESDMuonCluster::Clear(Option_t* opt)
{
/// Clear arrays
if (opt && opt[0] == 'C') {
if (fPads) fPads->Clear("C");
} else {
delete fPads; fPads = 0x0;
}
delete fPadsId; fPadsId = 0x0;
fNPads = 0;
}
//_____________________________________________________________________________
void AliESDMuonCluster::AddPadId(UInt_t padId)
{
/// Add the given pad Id to the list associated to the cluster
if (!fPadsId) fPadsId = new TArrayI(10);
if (fPadsId->GetSize() <= fNPads) fPadsId->Set(fNPads+10);
fPadsId->AddAt(static_cast<Int_t>(padId), fNPads++);
}
//_____________________________________________________________________________
void AliESDMuonCluster::SetPadsId(Int_t nPads, const UInt_t *padsId)
{
/// Fill the list pads'Id associated to the cluster with the given list
if (nPads <= 0 || !padsId) {
delete fPadsId;
fPadsId = 0x0;
fNPads = 0;
return;
}
if (!fPadsId) fPadsId = new TArrayI(nPads, reinterpret_cast<const Int_t*>(padsId));
else fPadsId->Set(nPads, reinterpret_cast<const Int_t*>(padsId));
fNPads = nPads;
}
//_____________________________________________________________________________
void AliESDMuonCluster::MovePadsToESD(AliESDEvent &esd)
{
/// move the pads to the new ESD structure
if (!fPads) return;
for (Int_t i = 0; i < fPads->GetEntriesFast(); i++) {
AliESDMuonPad *pad = static_cast<AliESDMuonPad*>(fPads->UncheckedAt(i));
AliESDMuonPad *newPad = esd.NewMuonPad();
*newPad = *pad;
AddPadId(newPad->GetUniqueID());
}
delete fPads;
fPads = 0x0;
}
//_____________________________________________________________________________
void AliESDMuonCluster::Print(Option_t */*option*/) const
{
/// print cluster content
UInt_t cId = GetUniqueID();
cout<<Form("clusterID=%u (ch=%d, det=%d, index=%d)",
cId,GetChamberId(),GetDetElemId(),GetClusterIndex())<<endl;
cout<<Form(" position=(%5.2f, %5.2f, %5.2f), sigma=(%5.2f, %5.2f, 0.0)",
GetX(),GetY(),GetZ(),GetErrX(),GetErrY())<<endl;
cout<<Form(" charge=%5.2f, chi2=%5.2f, MClabel=%d", GetCharge(), GetChi2(), GetLabel())<<endl;
if (PadsStored()) {
cout<<" pad infos:"<<endl;
for (Int_t iPad=0; iPad<GetNPads(); iPad++) cout<<" "<<GetPadId(iPad)<<endl;
}
}
| 31.316279
| 97
| 0.65023
|
AllaMaevskaya
|
3277ee831ccf791ce03e8d6d2b7ade4965d08192
| 2,544
|
cpp
|
C++
|
VisualStudio2013/WinSPP/WinSPP/WinSPPFrm.cpp
|
ma-laforge/WinSPP
|
7499a85d9872a2429c87aaa7d67806f2816c7407
|
[
"MIT"
] | null | null | null |
VisualStudio2013/WinSPP/WinSPP/WinSPPFrm.cpp
|
ma-laforge/WinSPP
|
7499a85d9872a2429c87aaa7d67806f2816c7407
|
[
"MIT"
] | null | null | null |
VisualStudio2013/WinSPP/WinSPP/WinSPPFrm.cpp
|
ma-laforge/WinSPP
|
7499a85d9872a2429c87aaa7d67806f2816c7407
|
[
"MIT"
] | null | null | null |
#include <windows.h>
#include "WinSPPFrm.h"
#include <msclr/marshal_cppstd.h>
namespace WinSPP {
//In-elegant refresh all function to update control state:
void WinSPPFrm::UpdateControlState() {
tbFileName->Enabled = rbFromFile->Checked;
} //UpdateControlState
void WinSPPFrm::UpdateMetafile(bool displayErrors) {
using namespace Runtime::InteropServices;
using namespace GDIExt;
bool compensateSObug = chkSOComp->Checked;
std::string fileName = msclr::interop::marshal_as<std::string>(tbFileName->Text);
if (plot) { delete plot; plot = 0; }
try {
plot = new SParamPlots::Plot(compensateSObug);
if (rbEmptySmith->Checked)
plot->CreateEmptySmith();
else if (rbEmptyPolar->Checked)
plot->CreateEmptyPolar();
else
plot->Open(fileName);
} catch (std::exception &e) {
if (plot) { delete plot; plot = 0; }
RefreshPreview();
if (displayErrors) {
System::String ^msg = gcnew System::String(e.what());
MessageBox::Show(msg, "ERROR", MessageBoxButtons::OK);
}
}
} //UpdateMetafile
void WinSPPFrm::RefreshPreview() {
Drawing::Rectangle rect = pnlPreview->ClientRectangle;
int maxdim = min(rect.Width, rect.Height);
if (maxdim > 0) {
pbPreview->SetBounds((rect.Width - maxdim) / 2, (rect.Height - maxdim) / 2, maxdim, maxdim);
}
try {
using namespace Drawing;
using Drawing::Pen;
using Drawing::Rectangle;
using Drawing::SolidBrush;
Rectangle rect = pbPreview->ClientRectangle;
SolidBrush ^brush = gcnew SolidBrush(Color::White);
Bitmap ^bmp = gcnew Bitmap(rect.Width, rect.Height);
Graphics ^g = Graphics::FromImage(bmp);
//Use a white background:
g->FillRectangle(brush, rect);
if (plot) {
HDC hdc = static_cast<HDC>(g->GetHdc().ToPointer());
plot->Draw(hdc, GDIExt::Rect(pbPreview->Width, pbPreview->Height));
g->ReleaseHdc();
}
pbPreview->Image = bmp;
} catch (...) {}
} //RefreshPreview
void WinSPPFrm::SaveMetafile() {
try {
System::String ^msg;
std::string fileName = msclr::interop::marshal_as<std::string>(tbFileName->Text);
fileName += ".emf";
if (!plot) throw(std::runtime_error("Nothing to save."));
if (rbEmptySmith->Checked)
fileName = "Smith.emf";
else if (rbEmptyPolar->Checked)
fileName = "Polar.emf";
plot->Save(fileName);
msg = gcnew System::String(fileName.c_str());
MessageBox::Show(msg, "Saved to file:", MessageBoxButtons::OK);
} catch (std::exception &e) {
System::String ^msg = gcnew System::String(e.what());
MessageBox::Show(msg, "ERROR", MessageBoxButtons::OK);
}
} //SaveMetafile
} //namespace WinSPP
| 28.909091
| 94
| 0.693396
|
ma-laforge
|
32792a931f60d8ebaf5e45311ac7a032bfcb33cc
| 776
|
hpp
|
C++
|
includes/Entity.hpp
|
LightCollective/OneLight
|
523678cacdc027efe3d4afa5d2558ad85b739d7f
|
[
"MIT"
] | null | null | null |
includes/Entity.hpp
|
LightCollective/OneLight
|
523678cacdc027efe3d4afa5d2558ad85b739d7f
|
[
"MIT"
] | null | null | null |
includes/Entity.hpp
|
LightCollective/OneLight
|
523678cacdc027efe3d4afa5d2558ad85b739d7f
|
[
"MIT"
] | null | null | null |
#ifndef ONELIGHT_ENTITY_H
#define ONELIGHT_ENTITY_H
#include "FluxSprite.hpp"
#include "FluxSpriteBatch.hpp"
class Entity
{
public:
Entity();
virtual ~Entity();
Flux::Vector2 getPosition();
virtual void setPosition(const Flux::Vector2 &position);
std::shared_ptr<Flux::Sprite> getSprite();
Flux::Vector2 getVelocity();
void setVelocity(const Flux::Vector2 &velocity);
float getSpeed();
void setSpeed(const float speed);
virtual void update();
Flux::Rectangle2D getAABB();
protected:
std::shared_ptr<Flux::Sprite> sprite;
std::shared_ptr<Flux::SpriteBatch> sb;
Flux::Vector2 velocity;
Flux::Rectangle2D aabb;
float speed;
};
#endif
| 21.555556
| 64
| 0.628866
|
LightCollective
|
327a33491b966234533663c3aa20ceefa3cf84c4
| 2,980
|
cpp
|
C++
|
markup/mainwindow.cpp
|
rlbisbe/markup
|
03b8d706e9fc45586b54470bea9d324ab016020a
|
[
"MIT"
] | null | null | null |
markup/mainwindow.cpp
|
rlbisbe/markup
|
03b8d706e9fc45586b54470bea9d324ab016020a
|
[
"MIT"
] | null | null | null |
markup/mainwindow.cpp
|
rlbisbe/markup
|
03b8d706e9fc45586b54470bea9d324ab016020a
|
[
"MIT"
] | null | null | null |
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "markdownparser.h"
#include "document.h"
#include "autosaveddocument.h"
#include "wordcounter.h"
#include <QFileDialog>
#include <QTextStream>
#include <QSettings>
#include <QShortcut>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(openFile()));
connect(ui->actionNew, SIGNAL(triggered()), this, SLOT(newFile()));
connect(ui->actionSave_file, SIGNAL(triggered()), this, SLOT(saveFile()));
connect(ui->actionToggle_preview, SIGNAL(triggered()), this, SLOT(togglePreview()));
connect(ui->editor, SIGNAL(textChanged()), this, SLOT(refreshRenderer()));
QCoreApplication::setOrganizationName("Rlbisbe");
QCoreApplication::setOrganizationDomain("rlbisbe.net");
QCoreApplication::setApplicationName("MarkUp");
this->updatePreview();
}
void MainWindow::reloadBuffer(){
if(m_settings.contains("currentFile")){
openFile(m_settings.value("currentFile").toString());
}
}
void MainWindow::newFile(){
m_settings.remove("currentFile");
this->m_document = new AutosavedDocument();
ui->editor->setPlainText(m_document->getContent());
}
void MainWindow::openFile(){
//Get the new file name
QString fileName = QFileDialog::getOpenFileName(this,
tr("Open File"), nullptr, tr("Text files (*.md)"));
openFile(fileName);
}
void MainWindow::openFile(QString fileName){
this->m_document = new AutosavedDocument(fileName);
if(m_document->getContent() != nullptr){
ui->editor->setPlainText(m_document->getContent());
m_settings.setValue("currentFile", fileName);
this->updateWindowTitle();
}
}
void MainWindow::refreshRenderer(){
m_document->setContent(ui->editor->toPlainText());
QString htmlContent = MarkdownParser().convertToHtml(m_document->getContent());
ui->preview->setText(htmlContent);
this->updateWindowTitle();
WordCounter* wordCounter = new WordCounter();
ui->statusBar->showMessage(QString::number(wordCounter->count(m_document->getContent())) + " words");
}
void MainWindow::saveFile(){
if(this->m_document->getPath() == nullptr){
this->m_document->setPath(QFileDialog::getSaveFileName(this,
tr("Save File"), nullptr, tr("Text files (*.md)")));
}
this->m_document->save();
this->updateWindowTitle();
}
void MainWindow::togglePreview(){
m_settings.setValue("previewEnabled", !m_settings.value("previewEnabled", false).toBool());
this->updatePreview();
}
void MainWindow::updatePreview(){
bool previewEnabled = m_settings.value("previewEnabled", false).toBool();
ui->preview->setVisible(previewEnabled);
}
void MainWindow::updateWindowTitle(){
setWindowTitle(this->m_document->getPathWithChanges() +" - " + "MarkUp text editor");
}
MainWindow::~MainWindow()
{
delete ui;
}
| 27.33945
| 105
| 0.692953
|
rlbisbe
|
3280832dbbd4ecaa3f1434e9f96c7f9d5e0917c1
| 7,720
|
cpp
|
C++
|
src/main.cpp
|
moonshadow565/fuckingmanifestdownloader
|
b362508c424567e76e74239bfed0c7fddfbbf17d
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
moonshadow565/fuckingmanifestdownloader
|
b362508c424567e76e74239bfed0c7fddfbbf17d
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
moonshadow565/fuckingmanifestdownloader
|
b362508c424567e76e74239bfed0c7fddfbbf17d
|
[
"MIT"
] | null | null | null |
#include "manifest.hpp"
#include "file.hpp"
#include "error.hpp"
#include "cli.hpp"
#include "download.hpp"
#include <iostream>
#include <fstream>
#include <set>
using namespace rman;
struct Main {
CLI cli = {};
FileList manifest = {};
std::optional<FileList> upgrade = {};
std::unique_ptr<HttpClient> client = {};
void parse_args(int argc, char** argv) {
cli.parse(argc, argv);
}
void parse_manifest() {
rman_trace("Manifest file: %s", cli.manifest.c_str());
manifest = FileList::read(read_file(cli.manifest));
manifest.filter_langs(cli.langs);
manifest.filter_path(cli.path);
manifest.sanitize();
}
void parse_upgrade() {
if (!cli.upgrade.empty()) {
rman_trace("Upgrade from manifest file: %s", cli.upgrade.c_str());
upgrade = FileList::read(read_file(cli.upgrade));
upgrade->filter_langs(cli.langs);
upgrade->filter_path(cli.path);
upgrade->sanitize();
manifest.remove_uptodate(*upgrade);
}
}
void process() {
switch(cli.action) {
case Action::List:
action_list();
break;
case Action::ListBundles:
action_list_bundles();
break;
case Action::ListChunks:
action_list_chunks();
break;
case Action::Json:
action_json();
break;
case Action::Download:
action_download();
break;
}
}
void action_list() noexcept {
for(auto& file: manifest.files) {
if (cli.exist && file.remove_exist(cli.output)) {
continue;
}
if (cli.verify && file.remove_verified(cli.output)) {
continue;
}
std::cout << file.to_csv() << std::endl;
}
}
void action_list_bundles() noexcept {
auto visited = std::set<BundleID>{};
for (auto& file: manifest.files) {
if (cli.exist && file.remove_exist(cli.output)) {
continue;
}
if (cli.verify && file.remove_verified(cli.output)) {
continue;
}
for (auto const& chunk: file.chunks) {
auto const id = chunk.bundle_id;
if (visited.find(id) != visited.end()) {
continue;
}
visited.insert(id);
std::cout << cli.download.prefix << "/bundles/" << to_hex(chunk.bundle_id) << ".bundle" << std::endl;
}
}
for (auto const& id: manifest.unreferenced) {
if (visited.find(id) != visited.end()) {
continue;
}
visited.insert(id);
std::cout << cli.download.prefix << "/bundles/" << to_hex(id) << ".bundle" << std::endl;
}
}
void action_list_chunks() noexcept {
auto visited = std::set<std::pair<BundleID, ChunkID>>{};
for (auto& file: manifest.files) {
if (cli.exist && file.remove_exist(cli.output)) {
continue;
}
if (cli.verify && file.remove_verified(cli.output)) {
continue;
}
for (auto const& chunk: file.chunks) {
auto const id = std::make_pair(chunk.bundle_id, chunk.id);
if (visited.find(id) != visited.end()) {
continue;
}
visited.insert(id);
std::cout << to_hex(chunk.bundle_id) << '\t'
<< to_hex(chunk.id) << '\t'
<< to_hex(chunk.compressed_offset, 8) << '\t'
<< to_hex(chunk.compressed_size, 8) << '\t'
<< to_hex(chunk.uncompressed_size, 8) << std::endl;;
}
}
}
void action_json() noexcept {
std::cout << '[' << std::endl;
bool need_separator = false;
for(auto& file: manifest.files) {
if (cli.exist && file.remove_exist(cli.output)) {
continue;
}
if (cli.verify && file.remove_verified(cli.output)) {
continue;
}
if (!need_separator) {
need_separator = true;
std::cout << file.to_json(2) << std::endl;
} else {
std::cout << ',' << file.to_json(2) << std::endl;
}
}
std::cout << ']' << std::endl;
}
void action_download() {
client = std::make_unique<HttpClient>(cli.download);
for (auto& file: manifest.files) {
if (cli.exist && file.remove_exist(cli.output)) {
std::cout << "SKIP: " << file.path << std::endl;
continue;
}
if (cli.verify && file.remove_verified(cli.output)) {
std::cout << "OK: " << file.path << std::endl;
continue;
}
std::cout << "START: " << file.path << std::endl;
download_file(file);
}
}
void download_file(FileInfo& file) {
std::unique_ptr<std::ofstream> outfile = {};
if (!cli.nowrite) {
outfile = std::make_unique<std::ofstream>(file.create_file(cli.output));
}
if (!cli.source_cache.empty()) {
if (file.remove_cached(outfile.get(), cli.source_cache)) {
std::cout << "OK: " << file.path << std::endl;
return;
}
}
auto bundles = BundleDownloadList::from_file_info(file, cli.download);
client->set_outfile(outfile.get());
size_t total = bundles.unfinished.size();
for (uint32_t tried = 0; !bundles.unfinished.empty() && tried <= cli.download.retry; tried++) {
std::cout << '\r'
<< "Try: " << tried << ' '
<< "Bundles: " << bundles.good.size()
<< '/' << total << std::flush;
bundles.queued = std::move(bundles.unfinished);
for(;;) {
client->push(bundles);
client->perform();
client->pop(bundles);
std::cout << '\r'
<< "Try: " << tried << ' '
<< "Bundles: " << bundles.good.size()
<< '/' << total << std::flush;
if (client->finished() && bundles.queued.empty()) {
break;
}
client->poll(100);
}
}
std::cout << ' ' << (bundles.unfinished.empty() ? "OK!" : "ERROR!") << std::endl;
}
static std::vector<char> read_file(std::string const& filename) {
std::ifstream file(filename, std::ios::binary);
rman_assert(file.good());
auto start = file.tellg();
file.seekg(0, std::ios::end);
auto end = file.tellg();
file.seekg(start, std::ios::beg);
auto size = end - start;
rman_assert(size > 0 && size <= INT32_MAX);
std::vector<char> data;
data.resize((size_t)size);
file.read(data.data(), size);
return data;
}
};
int main(int argc, char ** argv) {
auto main = Main{};
try {
main.parse_args(argc, argv);
main.parse_manifest();
main.parse_upgrade();
main.process();
} catch (std::exception const& e) {
std::cerr << e.what() << std::endl;
for(auto const& error: error_stack()) {
std::cerr << error << std::endl;
}
error_stack().clear();
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| 33.565217
| 117
| 0.479793
|
moonshadow565
|
32845211cfd38ea90ce0f84eb9f9d322d94569b4
| 187
|
hpp
|
C++
|
projects/codility/niobium2019/include/Niobium.hpp
|
antaljanosbenjamin/miscellaneous
|
56d2f0030d1d8ff0dd6dd077c3d1ec981f6c2747
|
[
"MIT"
] | 2
|
2021-06-24T21:46:56.000Z
|
2021-09-24T07:51:04.000Z
|
projects/codility/niobium2019/include/Niobium.hpp
|
antaljanosbenjamin/miscellaneous
|
56d2f0030d1d8ff0dd6dd077c3d1ec981f6c2747
|
[
"MIT"
] | null | null | null |
projects/codility/niobium2019/include/Niobium.hpp
|
antaljanosbenjamin/miscellaneous
|
56d2f0030d1d8ff0dd6dd077c3d1ec981f6c2747
|
[
"MIT"
] | null | null | null |
#pragma once
#include <vector>
namespace Niobium {
// https://app.codility.com/programmers/task/flipping_matrix/
int solution(std::vector<std::vector<int>> &A);
} // namespace Niobium
| 18.7
| 61
| 0.73262
|
antaljanosbenjamin
|
3289f377ad108943861e878e6b115b570172d5f8
| 5,022
|
cpp
|
C++
|
gui/shared/importers/image_importer.cpp
|
sadisutikku/engine_libs
|
b9d8aea6218e043162850c092fd32eb930120e15
|
[
"MIT"
] | null | null | null |
gui/shared/importers/image_importer.cpp
|
sadisutikku/engine_libs
|
b9d8aea6218e043162850c092fd32eb930120e15
|
[
"MIT"
] | null | null | null |
gui/shared/importers/image_importer.cpp
|
sadisutikku/engine_libs
|
b9d8aea6218e043162850c092fd32eb930120e15
|
[
"MIT"
] | null | null | null |
//////////////////////////////////////////////////////////////////////
//! MIT License
//! Copyright (c) 2022 sadisutikku
//! Part of https://github.com/sadisutikku/engine_libs.git
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
//! Includes
//////////////////////////////////////////////////////////////////////
#include "gui/shared/importers/image_importer.h"
#include "gui/platforms/graphics/RHI/windows/d3d11/texture2d_d3d11.h"
#include "gui/shared/graphics/renderer/renderer.h"
#include "gui/shared/graphics/storage/render_storage.h"
#include <fstream>
#include <vector>
#define STBI_NO_PSD
#define STBI_NO_TGA
#define STBI_NO_HDR
#define STBI_NO_PIC
#define STBI_NO_PNM
#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_STATIC
#define STBI_NO_STDIO
//#define STBI_MALLOC(sz) sicore::MEMORY::allocate(sz)
//#define STBI_REALLOC(p,newsz) sicore::MEMORY::reallocate(p,newsz)
//#define STBI_FREE(p) sicore::MEMORY::free(p)
//#define STBI_REALLOC_SIZED(p,oldsz,newsz) sicore::MEMORY::reallocate(p,newsz); SICORE_UNUSED(oldsz)
#include <gui/thirdparty/stb/stb_image.h>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#define STB_IMAGE_WRITE_STATIC
#define STBI_WRITE_NO_STDIO
//#define STBIW_MALLOC(sz) sicore::MEMORY::allocate(sz)
//#define STBIW_REALLOC(p,newsz) sicore::MEMORY::reallocate(p,newsz)
//#define STBIW_FREE(p) sicore::MEMORY::free(p)
#include <gui/thirdparty/stb/stb_image_write.h>
#define STB_IMAGE_RESIZE_IMPLEMENTATION
#define STB_IMAGE_RESIZE_STATIC
// There is scope here to use the c (context) parameter to reuse temp buffers
//#define STBIR_MALLOC(sz,c) ((void)(c), sicore::MEMORY::allocate(sz))
//#define STBIR_FREE(p,c) ((void)(c), sicore::MEMORY::free(p))
#include <gui/thirdparty/stb/stb_image_resize.h>
namespace
{
struct CALLBACK_USER_DATA
{
std::vector<char>& data;
uint32_t position{};
bool is_eof{};
};
inline gui::RHI_Format get_rhi_format( const uint32_t bytes_per_channel, const uint32_t channel_count )
{
const uint32_t bits_per_channel = bytes_per_channel * 8;
if ( channel_count == 1 )
{
if ( bits_per_channel == 8 ) return gui::RHI_Format_R8_Unorm;
}
else if ( channel_count == 2 )
{
if ( bits_per_channel == 8 ) return gui::RHI_Format_R8G8_Unorm;
}
else if ( channel_count == 3 )
{
if ( bits_per_channel == 32 ) return gui::RHI_Format_R32G32B32A32_Float;
}
else if ( channel_count == 4 )
{
if ( bits_per_channel == 8 ) return gui::RHI_Format_R8G8B8A8_Unorm;
if ( bits_per_channel == 16 ) return gui::RHI_Format_R16G16B16A16_Float;
if ( bits_per_channel == 32 ) return gui::RHI_Format_R32G32B32A32_Float;
}
ASSERT_FAILED( "Could not deduce format" );
return gui::RHI_Format_Undefined;
}
}
namespace gui
{
int stream_read_callback( void *user, char *data, int size )
{
CALLBACK_USER_DATA* user_data = static_cast<CALLBACK_USER_DATA*>(user);
memcpy( data, static_cast<const void*>(&user_data->data[user_data->position]), size );
user_data->position += size;
return size;
}
void stream_skip_callback( void *user, int size )
{
CALLBACK_USER_DATA* user_data = static_cast<CALLBACK_USER_DATA*>(user);
user_data->position += size;
}
int stream_eof_callback( void *user )
{
const CALLBACK_USER_DATA* user_data = static_cast<CALLBACK_USER_DATA*>(user);
return user_data->is_eof;
}
TEXTURE2D_BASE* IMAGE_IMPORTER::load_from_file( const std::string& filepath )
{
if ( auto existing_texture = RENDER_STORAGE::get_singleton()->get_texture( filepath ); existing_texture )
{
return existing_texture;
}
std::ifstream file_for_read( filepath, std::ios::binary );
// Stop eating new lines in binary mode
file_for_read.unsetf( std::ios::skipws );
// get its size:
std::streampos file_size;
file_for_read.seekg( 0, std::ios::end );
file_size = file_for_read.tellg();
file_for_read.seekg( 0, std::ios::beg );
std::vector<char> vec;
vec.reserve( file_size );
std::copy( std::istream_iterator<char>( file_for_read ),
std::istream_iterator<char>(),
std::back_inserter( vec ) );
stbi_io_callbacks callbacks{ stream_read_callback, stream_skip_callback, stream_eof_callback };
CALLBACK_USER_DATA user_data{ vec };
int32_t width{};
int32_t height{};
int32_t channels{};
if ( stbi_uc* ptr = stbi_load_from_callbacks( &callbacks, &user_data, &width, &height, &channels, STBI_rgb_alpha ) )
{
const int32_t num_bytes{ width * height * channels };
auto byte_data{ reinterpret_cast<std::byte*>(ptr) };
std::vector<std::byte> image_data{ byte_data, byte_data + num_bytes };
const RHI_Format image_format = get_rhi_format( 1, channels );
auto texture = RENDERER::get_singleton()->create_texture2d( width, height, image_format, RHI_Texture_Sampled, image_data );
RENDER_STORAGE::get_singleton()->cache_texture( filepath, texture );
return texture;
}
else
{
return nullptr;
}
}
}
| 30.436364
| 126
| 0.686181
|
sadisutikku
|
3295b0730366a18035aa155b35d551cb60075ea1
| 1,962
|
cpp
|
C++
|
Problems/geeksforgeeks/first-repeating-element/main.cpp
|
grand87/timus
|
8edcae276ab74b68fff18da3722460f492534a8a
|
[
"MIT"
] | null | null | null |
Problems/geeksforgeeks/first-repeating-element/main.cpp
|
grand87/timus
|
8edcae276ab74b68fff18da3722460f492534a8a
|
[
"MIT"
] | 1
|
2019-05-09T19:17:00.000Z
|
2019-05-09T19:17:00.000Z
|
Problems/geeksforgeeks/first-repeating-element/main.cpp
|
grand87/timus
|
8edcae276ab74b68fff18da3722460f492534a8a
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <map>
using namespace std;
const int MAX_VAL = 1000100;
int countApp[MAX_VAL + 1];
int arr[MAX_VAL + 1];
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "rt", stdin);
#endif
int t;
cin >> t;
for (int i = 0; i < t; i++) {
map<int, int> positions;
int n;
cin >> n;
for (int j = 0; j < n; j++) {
cin >> arr[j];
if (positions.find(arr[j]) == positions.end()) {
positions[arr[j]] = j;
countApp[arr[j]] = 1;
}
else
countApp[arr[j]]++;
}
int lowestPos = n;
for (int j = 0; j < n; j++) {
if (countApp[arr[j]] > 1) {
//it means value `originalValue` appeared more then 2 times starting at position
if (positions[arr[j]] < lowestPos)
lowestPos = positions[arr[j]];
}
}
/*
int j = 0;
for (; j < n; j++) {
const int originalValue = arr[j] % MAX_VAL;
if (arr[originalValue] >= MAX_VAL) {
countApp[originalValue]++;
} else {
pos[originalValue] = j;
countApp[originalValue] = 1;
arr[originalValue] += MAX_VAL;
}
}
// need to find element which has 2 or more in the pos with lowest index
int lowestPos = n;
for (j = 0; j < n; j++) {
const int originalValue = arr[j] % MAX_VAL;
if (countApp[originalValue] >= 2) {
//it means value `originalValue` appeared more then 2 times starting at position
if (pos[originalValue] < lowestPos)
lowestPos = pos[originalValue];
}
}
*/
if (lowestPos == n) {
cout << -1 << endl;
}
else
cout << lowestPos + 1 << endl;
}
return 0;
}
| 26.876712
| 96
| 0.453619
|
grand87
|
3299c337d5c45106d83004e7bb91ae6c4f89d1e3
| 32,774
|
cc
|
C++
|
farmhash_golden_test.cc
|
dietmarkuehl/hashing-demo
|
006f61c4221c2119c893fcfda8c505c08ed5b006
|
[
"Apache-2.0"
] | 35
|
2015-03-26T03:38:41.000Z
|
2022-01-03T04:32:53.000Z
|
farmhash_golden_test.cc
|
dietmarkuehl/hashing-demo
|
006f61c4221c2119c893fcfda8c505c08ed5b006
|
[
"Apache-2.0"
] | null | null | null |
farmhash_golden_test.cc
|
dietmarkuehl/hashing-demo
|
006f61c4221c2119c893fcfda8c505c08ed5b006
|
[
"Apache-2.0"
] | 16
|
2015-03-26T02:53:23.000Z
|
2021-07-12T12:31:07.000Z
|
// Copyright 2015 Google Inc. 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.
// Golden tests of farmhash, based on tests in original FarmHash source.
#include <cassert>
#include <iostream>
#include "farmhash.h"
#include "std.h"
namespace farmhashna {
uint64_t HashLen16(uint64_t u, uint64_t v) {
static constexpr uint64_t kMul = 0x9ddfea08eb382d69ULL;
uint64_t a = (u ^ v) * kMul;
a ^= (a >> 47);
uint64_t b = (v ^ a) * kMul;
b ^= (b >> 47);
b *= kMul;
return b;
}
// Adapt our API to the one the test fixture expects
uint64_t Hash64(const char* str, size_t len) {
hashing::farmhash::state_type state;
return static_cast<size_t>(
hash_combine_range(hashing::farmhash(&state), str, str + len));
}
uint64_t Hash64WithSeeds(const char *s, size_t len,
uint64_t seed0, uint64_t seed1) {
return HashLen16(Hash64(s, len) - seed0, seed1);
}
uint64_t Hash64WithSeed(const char *s, size_t len,
uint64_t seed) {
static constexpr uint64_t k2 = 0x9ae16a3b2f90404fULL;
return Hash64WithSeeds(s, len, k2, seed);
}
} // namespace farmhashna
using std::cout;
using std::cerr;
using std::endl;
using std::hex;
constexpr int kDataSize = 1 << 20;
static const int kTestSize = 300;
char data[kDataSize];
int errors = 0;
template <typename T> constexpr bool IsNonZero(T x) {
return x != 0;
}
// Initialize data to pseudorandom values.
void Setup() {
static constexpr uint64_t k0 = 0xc3a5c85c97cb3127ULL;
uint64_t a = 9;
uint64_t b = 777;
for (int i = 0; i < kDataSize; i++) {
a += b;
b += a;
a = (a ^ (a >> 41)) * k0;
b = (b ^ (b >> 41)) * k0 + i;
uint8_t u = b >> 37;
memcpy(data + i, &u, 1); // uint8_t -> char
}
}
uint32_t CreateSeed(int offset, int salt) {
static constexpr uint32_t c1 = 0xcc9e2d51;
uint32_t h = static_cast<uint32_t>(salt & 0xffffffff);
h = h * c1;
h ^= (h >> 17);
h = h * c1;
h ^= (h >> 17);
h = h * c1;
h ^= (h >> 17);
h += static_cast<uint32_t>(offset & 0xffffffff);
h = h * c1;
h ^= (h >> 17);
h = h * c1;
h ^= (h >> 17);
h = h * c1;
h ^= (h >> 17);
return h;
}
#undef SEED
#undef SEED1
#undef SEED0
#define SEED CreateSeed(offset, -1)
#define SEED0 CreateSeed(offset, 0)
#define SEED1 CreateSeed(offset, 1)
uint32_t expected[] = {
1140953930u, 861465670u,
3277735313u, 2681724312u,
2598464059u, 797982799u,
890626835u, 800175912u,
2603993599u, 921001710u,
1410420968u, 2134990486u,
3283896453u, 1867689945u,
2914424215u, 2244477846u,
255297188u, 2992121793u,
1110588164u, 4186314283u,
161451183u, 3943596029u,
4019337850u, 452431531u,
283198166u, 2741341286u,
3379021470u, 2557197665u,
299850021u, 2532580744u,
452473466u, 1706958772u,
1298374911u, 3099673830u,
2199864459u, 3696623795u,
236935126u, 2976578695u,
4055299123u, 3281581178u,
1053458494u, 1882212500u,
2305012065u, 2169731866u,
3456121707u, 275903667u,
458884671u, 3033004529u,
3058973506u, 2379411653u,
1898235244u, 1402319660u,
2700149065u, 2699376854u,
147814787u, 720739346u,
2433714046u, 4222949502u,
4220361840u, 1712034059u,
3425469811u, 3690733394u,
4148372108u, 1330324210u,
594028478u, 2921867846u,
1635026870u, 192883107u,
780716741u, 1728752234u,
3280331829u, 326029180u,
3969463346u, 1436364519u,
393215742u, 3349570000u,
3824583307u, 1612122221u,
2859809759u, 3808705738u,
1379537552u, 1646032583u,
2233466664u, 1432476832u,
4023053163u, 2650381482u,
2052294713u, 3552092450u,
1628777059u, 1499109081u,
3476440786u, 3829307897u,
2960536756u, 1554038301u,
1145519619u, 3190844552u,
2902102606u, 3600725550u,
237495366u, 540224401u,
65721842u, 489963606u,
1448662590u, 397635823u,
1596489240u, 1562872448u,
1790705123u, 2128624475u,
180854224u, 2604346966u,
1435705557u, 1262831810u,
155445229u, 1672724608u,
1669465176u, 1341975128u,
663607706u, 2077310004u,
3610042449u, 1911523866u,
1043692997u, 1454396064u,
2563776023u, 294527927u,
1099072299u, 1389770549u,
703505868u, 678706990u,
2952353448u, 2026137563u,
3603803785u, 629449419u,
1933894405u, 3043213226u,
226132789u, 2489287368u,
1552847036u, 645684964u,
3828089804u, 3632594520u,
187883449u, 230403464u,
3151491850u, 3272648435u,
3729087873u, 1303930448u,
2002861219u, 165370827u,
916494250u, 1230085527u,
3103338579u, 3064290191u,
3807265751u, 3628174014u,
231181488u, 851743255u,
2295806711u, 1781190011u,
2988893883u, 1554380634u,
1142264800u, 3667013118u,
1968445277u, 315203929u,
2638023604u, 2290487377u,
732137533u, 1909203251u,
440398219u, 1891630171u,
1380301172u, 1498556724u,
4072067757u, 4165088768u,
4204318635u, 441430649u,
3931792696u, 197618179u,
956300927u, 914413116u,
3010839769u, 2837339569u,
2148126371u, 1913303225u,
3074915312u, 3117299654u,
4139181436u, 2993479124u,
3178848746u, 1357272220u,
1438494951u, 507436733u,
667183474u, 2084369203u,
3854939912u, 1413396341u,
126024219u, 146044391u,
1016656857u, 3022024459u,
3254014218u, 429095991u,
165589978u, 1578546616u,
985653208u, 1718653828u,
623071693u, 366414107u,
249776086u, 1207522198u,
3047342438u, 2991127487u,
3120876698u, 1684583131u,
46987739u, 1157614300u,
863214540u, 1087193030u,
199124911u, 520792961u,
3614377032u, 586863115u,
3331828431u, 1013201099u,
1716848157u, 4033596884u,
1164298657u, 4140791139u,
1146169032u, 1434258493u,
3824360466u, 3242407770u,
3725511003u, 232064808u,
872586426u, 762243036u,
2736953692u, 816692935u,
512845449u, 3748861010u,
2266795890u, 3781899767u,
4290630595u, 517646945u,
22638523u, 648000590u,
959214578u, 558910384u,
1283799121u, 3047062993u,
1024246061u, 4027776454u,
3544509313u, 622325861u,
834785312u, 382936554u,
411505255u, 1973395102u,
1825135056u, 2725923798u,
580988377u, 2826990641u,
3474970689u, 1029055034u,
812546227u, 2506885666u,
2584372201u, 1758123094u,
589567754u, 325737734u,
345313518u, 2022370576u,
3886113119u, 3338548567u,
257578986u, 3698087965u,
1776047957u, 1771384107u,
3604937815u, 3198590202u,
2305332220u, 191910725u,
4232136669u, 427759438u,
4244322689u, 542201663u,
3315355162u, 2135941665u,
556609672u, 45845311u,
1175961330u, 3948351189u,
23075771u, 3252374102u,
1634635545u, 4151937410u,
713127376u, 1467786451u,
663013031u, 3444053918u,
2638154051u, 810082938u,
3077742128u, 1062268187u,
2115441882u, 4081398201u,
3735739145u, 2794294783u,
2335576331u, 2560479831u,
1379288194u, 4225182569u,
2442302747u, 3948961926u,
3958366652u, 3067277639u,
3667516477u, 1709989541u,
1516711748u, 2339636583u,
4188504038u, 59581167u,
2725013602u, 3639843023u,
2658147000u, 2643979752u,
3758739543u, 4189944477u,
2470483982u, 877580602u,
2995362413u, 118817200u,
3252925478u, 2062343506u,
3981838403u, 3762572073u,
1231633714u, 4168280671u,
2931588131u, 3284356565u,
1129162571u, 732225574u,
4173605289u, 1407328702u,
1677744031u, 3532596884u,
3232041815u, 1652884780u,
2256541290u, 3459463480u,
3740979556u, 259034107u,
2227121257u, 1426140634u,
3606709555u, 3424793077u,
315836068u, 3200749877u,
1386256573u, 24035717u,
2982018998u, 1811050648u,
234531934u, 1115203611u,
1598686658u, 3146815575u,
1603559457u, 323296368u,
2632963283u, 1778459926u,
739944537u, 579625482u,
3486330348u, 492621815u,
1231665285u, 2457048126u,
3903349120u, 389846205u,
3355404249u, 3275550588u,
1052645068u, 862072556u,
2834153464u, 1481069623u,
2657392572u, 4279236653u,
1688445808u, 701920051u,
3740748788u, 3388062747u,
1873358321u, 2152785640u,
883382081u, 1005815394u,
1020177209u, 734239551u,
2371453141u, 100326520u,
3488500412u, 1279682138u,
2610427744u, 49703572u,
3026361211u, 605900428u,
302392721u, 2509302188u,
1416453607u, 2815915291u,
1862819968u, 519710058u,
2450888314u, 4017598378u,
937074653u, 3035635454u,
1590230729u, 3268013438u,
2710029305u, 12886044u,
3711259084u, 2627383582u,
3895772404u, 648534979u,
260307902u, 855990313u,
3669691805u, 263366740u,
2938543471u, 414331688u,
3080542944u, 3405007814u,
3565059103u, 1190977418u,
390836981u, 1606450012u,
2649808239u, 2514169310u,
2747519432u, 4129538640u,
1721522849u, 492099164u,
792990594u, 3625507637u,
2271095827u, 2993032712u,
2302363854u, 4013112951u,
1111617969u, 2183845740u,
795918276u, 1116991810u,
3110898804u, 3963062126u,
2737064702u, 462795667u,
937372240u, 1343017609u,
1091041189u, 2790555455u,
277024217u, 25485284u,
1166522068u, 1623631848u,
241727183u, 2836158787u,
3112996740u, 573836428u,
2721658101u, 1937681565u,
4175169209u, 3190765433u,
1970000788u, 1668258120u,
114616703u, 954762543u,
199237753u, 4094644498u,
2522281978u, 732086117u,
1756889687u, 2936126607u,
2437031370u, 4103143808u,
3883389541u, 3171090854u,
2483004780u, 1927385370u,
2360538162u, 2740855009u,
4241185118u, 1492209542u,
1672737098u, 2148675559u,
1789864670u, 2434313103u,
2319172611u, 2760941207u,
2636210123u, 1338083267u,
1128080590u, 822806371u,
1199583556u, 314727461u,
1335160250u, 2084630531u,
1156261526u, 316766066u,
112090465u, 3129033323u,
2746885618u, 636616055u,
2582210744u, 1721064910u,
3468394263u, 470463518u,
2076016059u, 408721884u,
2121041886u, 378460278u,
1915948002u, 357324860u,
2301682622u, 2691859523u,
1869756364u, 2429314418u,
2193146527u, 1185564327u,
2614088922u, 1975527044u,
919067651u, 2855948894u,
3662539576u, 1943802836u,
3529473373u, 1490330107u,
366036094u, 3384241033u,
4276268604u, 448403661u,
4271796078u, 1910401882u,
3077107698u, 299427366u,
2035665349u, 3201262636u,
3738454258u, 2554452696u,
3588997135u, 3363895827u,
1267505995u, 1852004679u,
2237827073u, 2803250686u,
3468044908u, 2143572850u,
1728158656u, 1022551180u,
1996680960u, 839529273u,
2400647871u, 2201096054u,
3606433628u, 2597259793u,
3544595875u, 3909443124u,
819278607u, 3447346709u,
806136613u, 2711436388u,
3656063205u, 837475154u,
694525336u, 4070212073u,
4011303412u, 1068395209u,
438095290u, 484603494u,
2673730227u, 737767009u,
642310823u, 3914002299u,
308425103u, 268427550u,
1334387085u, 4069797497u,
4280783219u, 2914011058u,
4243643405u, 2849988118u,
2504230175u, 1817156623u,
2804200483u, 3406991497u,
2948254999u, 2102063419u,
1071272117u, 514889942u,
571972433u, 1246595599u,
1735616066u, 1539151988u,
1230831543u, 277987182u,
4269526481u, 991511607u,
95237878u, 2005032160u,
1291113144u, 626619670u,
3560835907u, 164940926u,
1433635018u, 116647396u,
3039097112u, 2868163232u,
1141645918u, 1764165478u,
881378302u, 2159170082u,
2953647681u, 1011320066u,
184856151u, 1723308975u,
336034862u, 2017579106u,
1476681709u, 147523618u,
3896252223u, 2264728166u,
944743644u, 1694443528u,
2690700128u, 1947321519u,
735478508u, 4058183171u,
260177668u, 505662155u,
2391691262u, 1920739747u,
3216960415u, 1898176786u,
3722741628u, 1511077569u,
449636564u, 983350414u,
2580237367u, 2055059789u,
1103819072u, 2089123665u,
3873755579u, 2718467458u,
3124338704u, 3204250304u,
2475035432u, 1120017626u,
3873758287u, 1982999824u,
2950794582u, 780634378u,
2842141483u, 4029205195u,
1656892865u, 3330993377u,
80890710u, 1953796601u,
3873078673u, 136118734u,
2317676604u, 4199091610u,
1864448181u, 3063437608u,
1699452298u, 1403506686u,
1513069466u, 2348491299u,
4273657745u, 4055855649u,
1805475756u, 2562064338u,
973124563u, 4197091358u,
172861513u, 2858726767u,
4271866024u, 3071338162u,
3590386266u, 2328277259u,
1096050703u, 1189614342u,
459509140u, 771592405u,
817999971u, 3740825152u,
520400189u, 1941874618u,
185232757u, 4032960199u,
3928245258u, 3527721294u,
1301118856u, 752188080u,
3512945009u, 308584855u,
2105373972u, 752872278u,
3823368815u, 3760952096u,
4250142168u, 2565680167u,
3646354146u, 1259957455u,
1085857127u, 3471066607u,
38924274u, 3770488806u,
1083869477u, 3312508103u,
71956383u, 3738784936u,
3099963860u, 1255084262u,
4286969992u, 3621849251u,
1190908967u, 1831557743u,
2363435042u, 54945052u,
4059585566u, 4023974274u,
1788578453u, 3442180039u,
2534883189u, 2432427547u,
3909757989u, 731996369u,
4168347425u, 1356028512u,
2741583197u, 1280920000u,
312887059u, 3259015297u,
3946278527u, 4135481831u,
1281043691u, 1121403845u,
3312292477u, 1819941269u,
1741932545u, 3293015483u,
2127558730u, 713121337u,
2635469238u, 486003418u,
4015067527u, 2976737859u,
2108187161u, 927011680u,
1970188338u, 4177613234u,
1799789551u, 2118505126u,
4134691985u, 1958963937u,
1929210029u, 2555835851u,
2768832862u, 910892050u,
2567532373u, 4075249328u,
86689814u, 3726640307u,
1392137718u, 1240000030u,
4104757832u, 3026358429u,
313797689u, 1435798509u,
3101500919u, 1241665335u,
3573008472u, 3615577014u,
3767659003u, 3134294021u,
4063565523u, 2296824134u,
1541946015u, 3087190425u,
2693152531u, 2199672572u,
2123763822u, 1034244398u,
857839960u, 2515339233u,
2228007483u, 1628096047u,
2116502287u, 2502657424u,
2809830736u, 460237542u,
450205998u, 3646921704u,
3818199357u, 1808504491u,
1950698961u, 2069753399u,
3657033172u, 3734547671u,
4067859590u, 3292597295u,
1106466069u, 356742959u,
2469567432u, 3495418823u,
183440071u, 3248055817u,
3662626864u, 1750561299u,
3926138664u, 4088592524u,
567122118u, 3810297651u,
992181339u, 3384018814u,
3272124369u, 3177596743u,
320086295u, 2316548367u,
100741310u, 451656820u,
4086604273u, 3759628395u,
2553391092u, 1745659881u,
3650357479u, 2390172694u,
330172533u, 767377322u,
526742034u, 4102497288u,
2088767754u, 164402616u,
2482632320u, 2352347393u,
1873658044u, 3861555476u,
2751052984u, 1767810825u,
20037241u, 545143220u,
2594532522u, 472304191u,
3441135892u, 3323383489u,
258785117u, 2977745165u,
2781737565u, 2963590112u,
2756998822u, 207428029u,
2581558559u, 3824717027u,
1258619503u, 3472047571u,
2648427775u, 2360400900u,
2393763818u, 2332399088u,
3932701729u, 884421165u,
1396468647u, 1377764574u,
4061795938u, 1559119087u,
3343596838u, 3604258095u,
1435134775u, 1099809675u,
908163739u, 1418405656u,
368446627u, 3741651161u,
3374512975u, 3542220540u,
3244772570u, 200009340u,
3198975081u, 2521038253u,
4081637863u, 337070226u,
3235259030u, 3897262827u,
736956644u, 641040550u,
644850146u, 1306761320u,
4219448634u, 193750500u,
3293278106u, 1383997679u,
1242645122u, 4109252858u,
450747727u, 3716617561u,
362725793u, 2252520167u,
3377483696u, 1788337208u,
8130777u, 3226734120u,
759239140u, 1012411364u,
1658628529u, 2911512007u,
1002580201u, 1681898320u,
3039016929u, 4294520281u,
367022558u, 3071359622u,
3205848570u, 152989999u,
3839042136u, 2357687350u,
4273132307u, 3898950547u,
1176841812u, 1314157485u,
75443951u, 1027027239u,
1858986613u, 2040551642u,
36574105u, 2603059541u,
3456147251u, 2137668425u,
4077477194u, 3565689036u,
491832241u, 363703593u,
2579177168u, 3589545214u,
265993036u, 1864569342u,
4149035573u, 3189253455u,
1072259310u, 3153745937u,
923017956u, 490608221u,
855846773u, 845706553u,
1018226240u, 1604548872u,
3833372385u, 3287246572u,
2757959551u, 2452872151u,
1553870564u, 1713154780u,
2649450292u, 500120236u,
84251717u, 661869670u,
1444911517u, 2489716881u,
2810524030u, 1561519055u,
3884088359u, 2509890699u,
4247155916u, 1005636939u,
3224066062u, 2774151984u,
2035978240u, 2514910366u,
1478837908u, 3144450144u,
2107011431u, 96459446u,
3587732908u, 2389230590u,
3287635953u, 250533792u,
1235983679u, 4237425634u,
3704645833u, 3882376657u,
2976369049u, 1187061987u,
276949224u, 4100839753u,
1698347543u, 1629662314u,
1556151829u, 3784939568u,
427484362u, 4246879223u,
3155311770u, 4285163791u,
1693376813u, 124492786u,
1858777639u, 3476334357u,
1941442701u, 1121980173u,
3485932087u, 820852908u,
358032121u, 2511026735u,
1873607283u, 2556067450u,
2248275536u, 1528632094u,
1535473864u, 556796152u,
1499201704u, 1472623890u,
1526518503u, 3692729434u,
1476438092u, 2913077464u,
335109599u, 2167614601u,
4121131078u, 3158127917u,
3051522276u, 4046477658u,
2857717851u, 1863977403u,
1341023343u, 692059110u,
1802040304u, 990407433u,
3285847572u, 319814144u,
561105582u, 1540183799u,
4052924496u, 2926590471u,
2244539806u, 439121871u,
3317903224u, 3178387550u,
4265214507u, 82077489u,
1978918971u, 4279668976u,
128732476u, 2853224222u,
464407878u, 4190838199u,
997819001u, 3250520802u,
2330081301u, 4095846095u,
733509243u, 1583801700u,
722314527u, 3552883023u,
1403784280u, 432327540u,
1877837196u, 3912423882u,
505219998u, 696031431u,
908238873u, 4189387259u,
8759461u, 2540185277u,
3385159748u, 381355877u,
2519951681u, 1679786240u,
2019419351u, 4051584612u,
1933923923u, 3768201861u,
1670133081u, 3454981037u,
700836153u, 1675560450u,
371560700u, 338262316u,
847351840u, 2222395828u,
3130433948u, 405251683u,
3037574880u, 184098830u,
453340528u, 1385561439u,
2224044848u, 4071581802u,
1431235296u, 5570097u,
570114376u, 2287305551u,
2272418128u, 803575837u,
3943113491u, 414959787u,
708083137u, 2452657767u,
4019147902u, 3841480082u,
3791794715u, 2965956183u,
2763690963u, 2350937598u,
3424361375u, 779434428u,
1274947212u, 686105485u,
3426668051u, 3692865672u,
3057021940u, 2285701422u,
349809124u, 1379278508u,
3623750518u, 215970497u,
1783152480u, 823305654u,
216118434u, 1787189830u,
3692048450u, 2272612521u,
3032187389u, 4159715581u,
1388133148u, 1611772864u,
2544383526u, 552925303u,
3420960112u, 3198900547u,
3503230228u, 2603352423u,
2318375898u, 4064071435u,
3006227299u, 4194096960u,
1283392422u, 1510460996u,
174272138u, 3671038966u,
1775955687u, 1719108984u,
1763892006u, 1385029063u,
4083790740u, 406757708u,
684087286u, 531310503u,
3329923157u, 3492083607u,
1059031410u, 3037314475u,
3105682208u, 3382290593u,
2292208503u, 426380557u,
97373678u, 3842309471u,
777173623u, 3241407531u,
303065016u, 1477104583u,
4234905200u, 2512514774u,
2649684057u, 1397502982u,
1802596032u, 3973022223u,
2543566442u, 3139578968u,
3193669211u, 811750340u,
4013496209u, 567361887u,
4169410406u, 3622282782u,
3403136990u, 2540585554u,
895210040u, 3862229802u,
1145435213u, 4146963980u,
784952939u, 943914610u,
573034522u, 464420660u,
2356867109u, 3054347639u,
3985088434u, 1911188923u,
583391304u, 176468511u,
2990150068u, 2338031599u,
519948041u, 3181425568u,
496106033u, 4110294665u,
2736756930u, 1196757691u,
1089679033u, 240953857u,
3399092928u, 4040779538u,
2843673626u, 240495962u,
3017658263u, 3828377737u,
4243717901u, 2448373688u,
2759616657u, 2246245780u,
308018483u, 4262383425u,
2731780771u, 328023017u,
2884443148u, 841480070u,
3188015819u, 4051263539u,
2298178908u, 2944209234u,
1372958390u, 4164532914u,
4074952232u, 1683612329u,
2155036654u, 1872815858u,
2041174279u, 2368092311u,
206775997u, 2283918569u,
645945606u, 115406202u,
4206471368u, 3923500892u,
2217060665u, 350160869u,
706531239u, 2824302286u,
509981657u, 1469342315u,
140980u, 1891558063u,
164887091u, 3094962711u,
3437115622u, 13327420u,
422986366u, 330624974u,
3630863408u, 2425505046u,
824008515u, 3543885677u,
918718096u, 376390582u,
3224043675u, 3724791476u,
1837192976u, 2968738516u,
3424344721u, 3187805406u,
1550978788u, 1743089918u,
4251270061u, 645016762u,
3855037968u, 1928519266u,
1373803416u, 2289007286u,
1889218686u, 1610271373u,
3059200728u, 2108753646u,
582042641u, 812347242u,
3188172418u, 191994904u,
1343511943u, 2247006571u,
463291708u, 2697254095u,
1534175504u, 1106275740u,
622521957u, 917121602u,
4095777215u, 3955972648u,
3852234638u, 2845309942u,
3299763344u, 2864033668u,
2554947496u, 799569078u,
2551629074u, 1102873346u,
2661022773u, 2006922227u,
2900438444u, 1448194126u,
1321567432u, 1983773590u,
1237256330u, 3449066284u,
1691553115u, 3274671549u,
4271625619u, 2741371614u,
3285899651u, 786322314u,
1586632825u, 564385522u,
2530557509u, 2974240289u,
1244759631u, 3263135197u,
3592389776u, 3570296884u,
2749873561u, 521432811u,
987586766u, 3206261120u,
1327840078u, 4078716491u,
1753812954u, 976892272u,
1827135136u, 1781944746u,
1328622957u, 1015377974u,
3439601008u, 2209584557u,
2482286699u, 1109175923u,
874877499u, 2036083451u,
483570344u, 1091877599u,
4190721328u, 1129462471u,
640035849u, 1867372700u,
920761165u, 3273688770u,
1623777358u, 3389003793u,
3241132743u, 2734783008u,
696674661u, 2502161880u,
1646071378u, 1164309901u,
350411888u, 1978005963u,
2253937037u, 7371540u,
989577914u, 3626554867u,
3214796883u, 531343826u,
398899695u, 1145247203u,
1516846461u, 3656006011u,
529303412u, 3318455811u,
3062828129u, 1696355359u,
3698796465u, 3155218919u,
1457595996u, 3191404246u,
1395609912u, 2917345728u,
1237411891u, 1854985978u,
1091884675u, 3504488111u,
3109924189u, 1628881950u,
3939149151u, 878608872u,
778235395u, 1052990614u,
903730231u, 2069566979u,
2437686324u, 3163786257u,
2257884264u, 2123173186u,
939764916u, 2933010098u,
1235300371u, 1256485167u,
1950274665u, 2180372319u,
2648400302u, 122035049u,
1883344352u, 2083771672u,
3712110541u, 321199441u,
1896357377u, 508560958u,
3066325351u, 2770847216u,
3177982504u, 296902736u,
1486926688u, 456842861u,
601221482u, 3992583643u,
2794121515u, 1533934172u,
1706465470u, 4281971893u,
2557027816u, 900741486u,
227175484u, 550595824u,
690918144u, 2825943628u,
90375300u, 300318232u,
1985329734u, 1440763373u,
3670603707u, 2533900859u,
3253901179u, 542270815u,
3677388841u, 307706478u,
2570910669u, 3320103693u,
1273768482u, 1216399252u,
1652924805u, 1043647584u,
1120323676u, 639941430u,
325675502u, 3652676161u,
4241680335u, 1545838362u,
1991398008u, 4100211814u,
1097584090u, 3262252593u,
2254324292u, 1765019121u,
4060211241u, 2315856188u,
3704419305u, 411263051u,
238929055u, 3540688404u,
3094544537u, 3250435765u,
3460621305u, 1967599860u,
2016157366u, 847389916u,
1659615591u, 4020453639u,
901109753u, 2682611693u,
1661364280u, 177155177u,
3210561911u, 3802058181u,
797089608u, 3286110054u,
2110358240u, 1353279028u,
2479975820u, 471725410u,
2219863904u, 3623364733u,
3167128228u, 1052188336u,
3656587111u, 721788662u,
3061255808u, 1615375832u,
924941453u, 2547780700u,
3328169224u, 1310964134u,
2701956286u, 4145497671u,
1421461094u, 1221397398u,
1589183618u, 1492533854u,
449740816u, 2686506989u,
3035198924u, 1682886232u,
2529760244u, 3342031659u,
1235084019u, 2151665147u,
2315686577u, 3282027660u,
1140138691u, 2754346599u,
2091754612u, 1178454681u,
4226896579u, 2942520471u,
2122168506u, 3751680858u,
3213794286u, 2601416506u,
4142747914u, 3951404257u,
4243249649u, 748595836u,
4004834921u, 238887261u,
1927321047u, 2217148444u,
205977665u, 1885975275u,
186020771u, 2367569534u,
2941662631u, 2608559272u,
3342096731u, 741809437u,
1962659444u, 3539886328u,
3036596491u, 2282550094u,
2366462727u, 2748286642u,
2144472852u, 1390394371u,
1257385924u, 2205425874u,
2119055686u, 46865323u,
3597555910u, 3188438773u,
2372320753u, 3641116924u,
3116286108u, 2680722658u,
3371014971u, 2058751609u,
2966943726u, 2345078707u,
2330535244u, 4013841927u,
1169588594u, 857915866u,
1875260989u, 3175831309u,
3193475664u, 1955181430u,
923161569u, 4068653043u,
776445899u, 954196929u,
61509556u, 4248237857u,
3808667664u, 581227317u,
2893240187u, 4159497403u,
4212264930u, 3973886195u,
2077539039u, 851579036u,
2957587591u, 772351886u,
1173659554u, 946748363u,
2794103714u, 2094375930u,
4234750213u, 3671645488u,
2614250782u, 2620465358u,
3122317317u, 2365436865u,
3393973390u, 523513960u,
3645735309u, 2766686992u,
2023960931u, 2312244996u,
1875932218u, 3253711056u,
3622416881u, 3274929205u,
612094988u, 1555465129u,
2114270406u, 3553762793u,
1832633644u, 1087551556u,
3306195841u, 1702313921u,
3675066046u, 1735998785u,
1690923980u, 1482649756u,
1171351291u, 2043136409u,
1962596992u, 461214626u,
3278253346u, 1392428048u,
3744621107u, 1028502697u,
3991171462u, 1014064003u,
3642345425u, 3186995039u,
6114625u, 3359104346u,
414856965u, 2814387514u,
3583605071u, 2497896367u,
1024572712u, 1927582962u,
2892797583u, 845302635u,
328548052u, 1523379748u,
3392622118u, 1347167673u,
1012316581u, 37767602u,
2647726017u, 1070326065u,
2075035198u, 4202817168u,
2502924707u, 2612406822u,
2187115553u, 1180137213u,
701024148u, 1481965992u,
3223787553u, 2083541843u,
203230202u, 3876887380u,
1334816273u, 2870251538u,
2186205850u, 3985213979u,
333533378u, 806507642u,
1010064531u, 713520765u,
3084131515u, 2637421459u,
1703168933u, 1517562266u,
4089081247u, 3231042924u,
3079916123u, 3154574447u,
2253948262u, 1725190035u,
2452539325u, 1343734533u,
213706059u, 2519409656u,
108055211u, 2916327746u,
587001593u, 1917607088u,
4202913084u, 926304016u,
469255411u, 4042080256u,
3498936874u, 246692543u,
495780578u, 438717281u,
2259272650u, 4011324645u,
2836854664u, 2317249321u,
946828752u, 1280403658u,
1905648354u, 2034241661u,
774652981u, 1285694082u,
2200307766u, 2158671727u,
1135162148u, 232040752u,
397012087u, 1717527689u,
1720414106u, 918797022u,
2580119304u, 3568069742u,
2904461070u, 3893453420u,
973817938u, 667499332u,
3785870412u, 2088861715u,
1565179401u, 600903026u,
591806775u, 3512242245u,
997964515u, 2339605347u,
1134342772u, 3234226304u,
4084179455u, 302315791u,
2445626811u, 2590372496u,
345572299u, 2274770442u,
3600587867u, 3706939009u,
1430507980u, 2656330434u,
1079209397u, 2122849632u,
1423705223u, 3826321888u,
3683385276u, 1057038163u,
1242840526u, 3987000643u,
2398253089u, 1538190921u,
1295898647u, 3570196893u,
3065138774u, 3111336863u,
2524949549u, 4203895425u,
3025864372u, 968800353u,
1023721001u, 3763083325u,
526350786u, 635552097u,
2308118370u, 2166472723u,
2196937373u, 2643841788u,
3040011470u, 4010301879u,
2782379560u, 3474682856u,
4201389782u, 4223278891u,
1457302296u, 2251842132u,
1090062008u, 3188219189u,
292733931u, 1424229089u,
1590782640u, 1365212370u,
3975957073u, 3982969588u,
2927147928u, 1048291071u,
2766680094u, 884908196u,
35237839u, 2221180633u,
2490333812u, 4098360768u,
4029081103u, 3490831871u,
2392516272u, 3455379186u,
3948800722u, 335456628u,
2105117968u, 4181629008u,
1044201772u, 3335754111u,
540133451u, 3313113759u,
3786107905u, 2627207327u,
3540337875u, 3473113388u,
3430536378u, 2514123129u,
2124531276u, 3872633376u,
3272957388u, 3501994650u,
2418881542u, 487365389u,
3877672368u, 1512866656u,
3486531087u, 2102955203u,
1136054817u, 3004241477u,
1549075351u, 1302002008u,
3936430045u, 2258587644u,
4109233936u, 3679809321u,
3467083076u, 2484463221u,
1594979755u, 529218470u,
3527024461u, 1147434678u,
106799023u, 1823161970u,
1704656738u, 1675883700u,
3308746763u, 1875093248u,
1352868568u, 1898561846u,
2508994984u, 3177750780u,
4217929592u, 400784472u,
80090315u, 3564414786u,
3841585648u, 3379293868u,
160353261u, 2413172925u,
2378499279u, 673436726u,
1505702418u, 1330977363u,
1853298225u, 3201741245u,
2135714208u, 4069554166u,
3715612384u, 3692488887u,
3680311316u, 4274382900u,
914186796u, 2264886523u,
3869634032u, 1254199592u,
1131020455u, 194781179u,
429923922u, 2763792336u,
2052895198u, 3997373194u,
3440090658u, 2165746386u,
1575500242u, 3463310191u,
2064974716u, 3779513671u,
3106421434u, 880320527u,
3281914119u, 286569042u,
3909096631u, 122359727u,
1429837716u, 252230074u,
4111461225u, 762273136u,
93658514u, 2766407143u,
3623657004u, 3869801679u,
3925695921u, 2390397316u,
2499025338u, 2741806539u,
2507199021u, 1659221866u,
361292116u, 4048761557u,
3797133396u, 1517903247u,
3121647246u, 3884308578u,
1697201500u, 1558800262u,
4150812360u, 3161302278u,
2610217849u, 641564641u,
183814518u, 2075245419u,
611996508u, 2223461433u,
329123979u, 121860586u,
860985829u, 1137889144u,
4018949439u, 2904348960u,
947795261u, 1992594155u,
4255427501u, 2281583851u,
2892637604u, 1478186924u,
3050771207u, 2767035539u,
373510582u, 1963520320u,
3763848370u, 3756817798u,
627269409u, 1806905031u,
1814444610u, 3646665053u,
1822693920u, 278515794u,
584050483u, 4142579188u,
2149745808u, 3193071606u,
1179706341u, 2693495182u,
3259749808u, 644172091u,
880509048u, 3340630542u,
3365160815u, 2384445068u,
3053081915u, 2840648309u,
1986990122u, 1084703471u,
2370410550u, 1627743573u,
2244943480u, 4057483496u,
2611595995u, 2470013639u,
4024732359u, 3987190386u,
873421687u, 2447660175u,
3226583022u, 767655877u,
2528024413u, 1962070688u,
1233635843u, 2163464207u,
659054446u, 854207134u,
258410943u, 4197831420u,
2515400215u, 3100476924u,
1961549594u, 2219491151u,
3997658851u, 163850514u,
470325051u, 2598261204u,
3052145580u, 59836528u,
1376188597u, 966733415u,
850667549u, 3622479237u,
1083731990u, 1525777459u,
4005126532u, 1428155540u,
2781907007u, 943739431u,
1493961005u, 2839096988u,
2000057832u, 1941829603u,
1901484772u, 939810041u,
3377407371u, 3090115837u,
3310840540u, 2068409688u,
3261383939u, 2212130277u,
2594774045u, 2912652418u,
4179816101u, 3534504531u,
3349254805u, 2796552902u,
1385421283u, 4259908631u,
3714780837u, 3070073945u,
3372846298u, 3835884044u,
3047965714u, 3009018735u,
744091167u, 1861124263u,
2764936304u, 1338171648u,
4222019554u, 1395200692u,
1371426007u, 3338031581u,
2525665319u, 4196233786u,
2332743921u, 1474702008u,
2274266301u, 4255175517u,
2290169528u, 1793910997u,
2188254024u, 354202001u,
3864458796u, 4280290498u,
1554419340u, 1733094688u,
2010552302u, 1561807039u,
664313606u, 2548990879u,
1084699349u, 3233936866u,
973895284u, 2386881969u,
1831995860u, 2961465052u,
1428704144u, 3269904970u,
231648253u, 2602483763u,
4125013173u, 3319187387u,
3347011944u, 1892898231u,
4019114049u, 868879116u,
4085937045u, 2378411019u,
1072588531u, 3547435717u,
2208070766u, 1069899078u,
3142980597u, 2337088907u,
1593338562u, 919414554u,
688077849u, 3625708135u,
1472447348u, 1947711896u,
3953006207u, 877438080u,
845995820u, 3150361443u,
3053496713u, 2484577841u,
224271045u, 2914958001u,
2682612949u, 806655563u,
2436224507u, 1907729235u,
2920583824u, 1251814062u,
2070814520u, 4034325578u,
497847539u, 2714317144u,
385182008u, 640855184u,
1327075087u, 1062468773u,
1757405994u, 1374270191u,
4263183176u, 3041193150u,
1037871524u, 3633173991u,
4231821821u, 2830131945u,
3505072908u, 2830570613u,
4195208715u, 575398021u,
3992840257u, 3691788221u,
1949847968u, 2999344380u,
3183782163u, 3723754342u,
759716128u, 3284107364u,
1714496583u, 15918244u,
820509475u, 2553936299u,
2201876606u, 4237151697u,
2605688266u, 3253705097u,
1008333207u, 712158730u,
1722280252u, 1933868287u,
4152736859u, 2097020806u,
584426382u, 2836501956u,
2522777566u, 1996172430u,
2122199776u, 1069285218u,
1474209360u, 690831894u,
107482532u, 3695525410u,
670591796u, 768977505u,
2412057331u, 3647886687u,
3110327607u, 1072658422u,
379861934u, 1557579480u,
4124127129u, 2271365865u,
3880613089u, 739218494u,
547346027u, 388559045u,
3147335977u, 176230425u,
3094853730u, 2554321205u,
1495176194u, 4093461535u,
3521297827u, 4108148413u,
1913727929u, 1177947623u,
1911655402u, 1053371241u,
3265708874u, 1266515850u,
1045540427u, 3194420196u,
3717104621u, 1144474110u,
1464392345u, 52070157u,
4144237690u, 3350490823u,
4166253320u, 2747410691u,
};
// Return false only if offset is -1 and a spot check of 3 hashes all yield 0.
bool Test(int offset, int len = 0) {
#undef Check
#undef IsAlive
#define Check(x) do { \
const uint32_t actual = (x), e = expected[index++]; \
bool ok = actual == e; \
if (!ok) { \
cerr << "expected " << hex << e << " but got " << actual << endl; \
++errors; \
} \
assert(ok); \
} while (0)
#define IsAlive(x) do { alive += IsNonZero(x); } while (0)
// After the following line is where the uses of "Check" and such will go.
static int index = 0;
if (offset == -1) { int alive = 0; { uint64_t h = farmhashna::Hash64WithSeeds(data, len++, SEED0, SEED1); IsAlive(h >> 32); IsAlive((h << 32) >> 32); } { uint64_t h = farmhashna::Hash64WithSeed(data, len++, SEED); IsAlive(h >> 32); IsAlive((h << 32) >> 32); } { uint64_t h = farmhashna::Hash64(data, len++); IsAlive(h >> 32); IsAlive((h << 32) >> 32); } len -= 3; return alive > 0; }
{ uint64_t h = farmhashna::Hash64WithSeeds(data + offset, len, SEED0, SEED1); Check(h >> 32); Check((h << 32) >> 32); }
{ uint64_t h = farmhashna::Hash64WithSeed(data + offset, len, SEED); Check(h >> 32); Check((h << 32) >> 32); }
{ uint64_t h = farmhashna::Hash64(data + offset, len); Check(h >> 32); Check((h << 32) >> 32); }
return true;
#undef Check
#undef IsAlive
}
int RunTest() {
Setup();
int i = 0;
cout << "Running farmhashnaTest";
if (!Test(-1)) {
cout << "... Unavailable\n";
return errors;
}
// Good. The function is attempting to hash, so run the full test.
int errors_prior_to_test = errors;
for ( ; i < kTestSize - 1; i++) {
Test(i * i, i);
}
for ( ; i < kDataSize; i += i / 7) {
Test(0, i);
}
Test(0, kDataSize);
cout << (errors == errors_prior_to_test ? "... OK\n" : "... Failed\n");
return errors;
}
#undef SEED
#undef SEED1
#undef SEED0
int main(int argc, char* argv[]) {
return RunTest();
}
| 26.052464
| 383
| 0.801947
|
dietmarkuehl
|
3299c5a5c960b8e0e3a203a2fd5acd556c37ff53
| 18,489
|
cpp
|
C++
|
src/configator.cpp
|
MickaelBlet/Configator
|
e5679106d9946885e88b18430562ea4a6b47dbd4
|
[
"MIT"
] | null | null | null |
src/configator.cpp
|
MickaelBlet/Configator
|
e5679106d9946885e88b18430562ea4a6b47dbd4
|
[
"MIT"
] | null | null | null |
src/configator.cpp
|
MickaelBlet/Configator
|
e5679106d9946885e88b18430562ea4a6b47dbd4
|
[
"MIT"
] | 1
|
2020-07-14T02:26:16.000Z
|
2020-07-14T02:26:16.000Z
|
/**
* configator.cpp
*
* Licensed under the MIT License <http://opensource.org/licenses/MIT>.
* Copyright (c) 2020 BLET Mickaël.
*
* 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 <list>
#include "configator.hpp"
namespace mblet {
Configator::Configator():
_mapConfig(Configator::Map()),
_filename(std::string()),
_isRead(false) {
return ;
}
Configator::Configator(const char* filename):
_mapConfig(Configator::Map()),
_filename(std::string()),
_isRead(false) {
readFile(filename);
return ;
}
Configator::Configator(const Configator& src):
_mapConfig(src._mapConfig),
_filename(src._filename),
_isRead(src._isRead) {
return ;
}
Configator::~Configator() {
return ;
}
Configator& Configator::operator=(const Configator& rhs) {
_mapConfig = rhs._mapConfig;
_filename = rhs._filename;
_isRead = rhs._isRead;
return *this;
}
const Configator::Map& Configator::operator[](std::size_t index) const {
return _mapConfig[index];
}
const Configator::Map& Configator::operator[](const std::string& str) const {
return _mapConfig[str];
}
bool Configator::readFile(const char* filename) {
_mapConfig.clear();
_filename = "";
_isRead = false;
std::ifstream fileStream(filename); // open file
if (fileStream.is_open()) {
_filename = filename;
_isRead = true;
readStream(fileStream); // parse file
fileStream.close();
}
return _isRead;
}
void Configator::setConfig(const Configator::Map& mapConfig) {
_mapConfig.clear();
_mapConfig = mapConfig;
}
const Configator::Map& Configator::getConfig() const {
return _mapConfig;
}
const std::string& Configator::getFilename() const {
return _filename;
}
bool Configator::isRead() const {
return _isRead;
}
// =============================================================================
// dump
static void s_printCommentDump(std::ostream& oss, const std::string& str) {
if (!str.empty()) {
oss << " ; " << str;
}
}
static void s_printDump(std::ostream& oss, const std::string& str) {
unsigned int i;
for (i = 0; i < str.size(); ++i) {
if (str[i] == ' ' || str[i] == '"' || str[i] == '#' || str[i] == ';' || str[i] == '\\' || str[i] == '['
|| str[i] == ']') {
break;
}
}
if (i < str.size()) {
oss << '"';
for (i = 0; i < str.size(); ++i) {
if (str[i] == '"' || str[i] == '\\') {
oss << '\\' << str[i];
}
else {
oss << str[i];
}
}
oss << '"';
}
else {
oss << str;
}
}
static void s_sectionCommentDump(std::ostream& oss, const std::string& str) {
if (!str.empty()) {
oss << "; ";
unsigned int i;
for (i = 0; i < str.size(); ++i) {
oss << str[i];
if (str[i] == '\n') {
oss << "; ";
}
}
oss << '\n';
}
}
static void s_sectionDump(std::ostream& oss, const std::string& str, std::size_t sectionIndex) {
oss << std::string(sectionIndex + 1, '[');
s_printDump(oss, str);
oss << std::string(sectionIndex + 1, ']');
}
static void s_recurseDump(std::ostream& oss, const Configator::Map& map, std::size_t sectionIndex = 0) {
Configator::Map::const_iterator itSection;
for (itSection = map.begin(); itSection != map.end(); ++itSection) {
if (itSection->second.size() > 0) {
if (!itSection->second.value.empty()) {
s_printDump(oss, itSection->first);
oss << " = ";
s_printDump(oss, itSection->second.value);
oss << '\n';
}
s_sectionDump(oss, itSection->first, sectionIndex);
oss << '\n';
s_sectionCommentDump(oss, itSection->second.comment);
s_recurseDump(oss, itSection->second, sectionIndex + 1);
}
else {
s_printDump(oss, itSection->first);
oss << " = ";
s_printDump(oss, itSection->second.value);
s_printCommentDump(oss, itSection->second.comment);
oss << '\n';
}
}
}
std::ostream& Configator::dump(std::ostream& oss) const {
s_recurseDump(oss, _mapConfig);
return oss;
}
// =============================================================================
// parse
/**
* @brief check if character is comment
*
* @param c
* @return true : c is comment character
* @return false : c is not comment character
*/
static bool s_isComment(const char& c) {
if (c == ';' || c == '#') {
return true;
}
else {
return false;
}
}
/**
* @brief move index to character after spaces
*
* @param str
* @param index
*/
static void s_stringJumpSpace(const std::string& str, std::size_t& index) {
while (::isspace(str[index])) {
++index;
}
}
/**
* @brief detect if line is empty or comment
*
* @param line
* @return true : line is empty or comment
* @return false : line is not empty or comment
*/
static bool s_emptyOrComment(const std::string& line, std::string* retComment) {
std::size_t start;
std::size_t end;
std::size_t i = 0;
s_stringJumpSpace(line, i);
if (line[i] != '\0' && !s_isComment(line[i])) {
return false;
}
++i; // jump character ';' or '#'
s_stringJumpSpace(line, i);
start = i;
while (line[i] != '\0') {
++i;
}
--i; // revert jump '\0'
while (i > 0 && isspace(line[i])) {
--i;
}
++i; // last character
end = i;
*retComment = line.substr(start, end - start);
return true;
}
/**
* @brief parse section name
*
* @param line
* @param retSection
* @param retComment
* @return true
* @return false
*/
static bool s_parseSections(std::string line, std::list<std::string>* retSection, std::string* retComment) {
char quote;
std::size_t start;
std::size_t end;
std::size_t last;
std::size_t level = 0;
std::size_t i = 0;
s_stringJumpSpace(line, i);
// if not begin section
if (line[i] != '[') {
return false;
}
while (line[i] == '[') {
++i; // jump character '['
++level;
s_stringJumpSpace(line, i);
if (line[i] == '[') {
return false;
}
// start section name
if (line[i] == '\"' || line[i] == '\'') {
// get quote character
quote = line[i];
++i; // jump quote
start = i;
// search end quote
while (line[i] != quote) {
if (line[i] == '\\' && (line[i + 1] == quote || line[i + 1] == '\\')) {
line.erase(i, 1);
}
if (line[i] == '\0') {
return false;
}
++i;
}
end = i;
++i; // jump quote
s_stringJumpSpace(line, i);
}
else {
start = i;
while (line[i] != ']') {
if (line[i] == '\0') {
return false;
}
++i;
}
last = i;
--i; // revert jump ']'
while (i > 0 && isspace(line[i])) {
--i;
}
++i; // last character
end = i;
i = last;
}
if (line[i] != ']') {
return false;
}
++i; // jump ]
if (level == 1) {
retSection->clear();
}
retSection->push_back(line.substr(start, end - start));
s_stringJumpSpace(line, i);
}
if (line[i] != '\0' && !s_isComment(line[i])) {
retSection->pop_back();
return false;
}
if (s_isComment(line[i])) {
++i; // jump character ';' or '#'
s_stringJumpSpace(line, i);
start = i;
while (line[i] != '\0') {
++i;
}
--i; // revert jump '\0'
while (i > 0 && isspace(line[i])) {
--i;
}
++i; // last character
end = i;
*retComment = line.substr(start, end - start);
}
return true;
}
/**
* @brief parse section name
*
* @param line
* @param retSection
* @param retComment
* @return true
* @return false
*/
static bool s_parseSectionLevel(std::string line, std::list<std::string>* retSection, std::string* retComment) {
char quote;
std::size_t start;
std::size_t end;
std::size_t last;
std::size_t level = 0;
std::size_t saveLevel = 0;
std::size_t i = 0;
s_stringJumpSpace(line, i);
// if not begin section
if (line[i] != '[') {
return false;
}
while (line[i] == '[') {
++i; // jump character '['
++level;
s_stringJumpSpace(line, i);
}
// start section name
if (line[i] == '\"' || line[i] == '\'') {
// get quote character
quote = line[i];
++i; // jump quote
start = i;
// search end quote
while (line[i] != quote) {
if (line[i] == '\\' && (line[i + 1] == quote || line[i + 1] == '\\')) {
line.erase(i, 1);
}
if (line[i] == '\0') {
return false;
}
++i;
}
end = i;
++i; // jump quote
s_stringJumpSpace(line, i);
}
else {
start = i;
while (line[i] != ']') {
if (line[i] == '\0') {
return false;
}
++i;
}
last = i;
--i; // revert jump ']'
while (i > 0 && isspace(line[i])) {
--i;
}
++i; // last character
end = i;
i = last;
}
saveLevel = level;
while (line[i] == ']') {
++i; // jump character ']'
--level;
s_stringJumpSpace(line, i);
}
if (level != 0) {
return false;
}
--saveLevel;
while (retSection->size() > saveLevel) {
retSection->pop_back();
}
if (saveLevel == retSection->size()) {
retSection->push_back(line.substr(start, end - start));
}
else {
return false;
}
s_stringJumpSpace(line, i);
if (line[i] != '\0' && !s_isComment(line[i])) {
return false;
}
if (s_isComment(line[i])) {
++i; // jump character ';' or '#'
s_stringJumpSpace(line, i);
start = i;
while (line[i] != '\0') {
++i;
}
--i; // revert jump '\0'
while (i > 0 && isspace(line[i])) {
--i;
}
++i; // last character
end = i;
*retComment = line.substr(start, end - start);
}
return true;
}
/**
* @brief parse key
*
* @param line
* @param retKey
* @param retValue
* @param retComment
* @return true
* @return false
*/
static bool s_parseKey(std::string line, std::list<std::string>* retKey, std::string* retValue,
std::string* retComment) {
char quote;
std::size_t start;
std::size_t end;
std::size_t last;
std::size_t i = 0;
s_stringJumpSpace(line, i);
if (line[i] == '=') {
return false; // not key element
}
// start key name
if (line[i] == '\"' || line[i] == '\'') {
// get quote character
quote = line[i];
++i; // jump quote
start = i;
// search end quote
while (line[i] != quote) {
if (line[i] == '\\' && (line[i + 1] == quote || line[i + 1] == '\\')) {
line.erase(i, 1);
}
if (line[i] == '\0') {
return false;
}
++i;
}
end = i;
++i; // jump quote
s_stringJumpSpace(line, i);
if (line[i] != '=' && line[i] != '[') {
return false; // not valid key
}
}
else {
start = i;
while (line[i] != '=' && line[i] != '[') {
if (line[i] == '\0') {
return false;
}
++i;
}
last = i;
--i; // revert jump '=' or '['
while (i > 0 && isspace(line[i])) {
--i;
}
++i; // last character
end = i;
i = last;
}
retKey->push_back(line.substr(start, end - start));
// check table key
while (line[i] == '[') {
++i; // jump '['
s_stringJumpSpace(line, i);
// start key name
if (line[i] == '\"' || line[i] == '\'') {
// get quote character
quote = line[i];
++i; // jump quote
start = i;
// search end quote
while (line[i] != quote) {
if (line[i] == '\\' && (line[i + 1] == quote || line[i + 1] == '\\')) {
line.erase(i, 1);
}
if (line[i] == '\0') {
return false;
}
++i;
}
end = i;
++i; // jump quote
s_stringJumpSpace(line, i);
if (line[i] != ']') {
return false; // not valid key
}
}
else {
start = i;
while (line[i] != ']') {
if (line[i] == '\0') {
return false;
}
++i;
}
last = i;
--i; // revert jump '=' or '['
while (i > 0 && isspace(line[i])) {
--i;
}
++i; // last character
end = i;
i = last;
}
++i; // jump ']'
s_stringJumpSpace(line, i);
retKey->push_back(line.substr(start, end - start));
}
s_stringJumpSpace(line, i);
if (line[i] != '=') {
return false;
}
++i; // jump '='
s_stringJumpSpace(line, i);
// start value
if (line[i] == '\"' || line[i] == '\'') {
// get quote character
quote = line[i];
++i; // jump quote
start = i;
// search end quote
while (line[i] != quote) {
if (line[i] == '\\' && (line[i + 1] == quote || line[i + 1] == '\\')) {
line.erase(i, 1);
}
if (line[i] == '\0') {
return false;
}
++i;
}
end = i;
++i; // jump quote
s_stringJumpSpace(line, i);
if (line[i] != '\0' && !s_isComment(line[i])) {
return false; // not valid value
}
}
else {
start = i;
while (line[i] != '\0' && !s_isComment(line[i])) {
++i;
}
last = i;
--i; // revert jump '\0' or ';' or '#'
while (i > 0 && isspace(line[i])) {
--i;
}
++i; // last character
end = i;
i = last;
}
*retValue = line.substr(start, end - start);
if (s_isComment(line[i])) {
++i; // jump character ';' or '#'
s_stringJumpSpace(line, i);
start = i;
while (line[i] != '\0') {
++i;
}
--i; // revert jump '\0'
while (i > 0 && isspace(line[i])) {
--i;
}
++i; // last character
end = i;
*retComment = line.substr(start, end - start);
}
return true;
}
/**
* @brief get map of section
*
* @param map
* @param sections
* @return Configator::Map&
*/
static Configator::Map& s_section(Configator::Map& map, const std::list<std::string>& sections) {
std::list<std::string>::const_iterator itSection;
Configator::Map* pMap = ↦
for (itSection = sections.begin(); itSection != sections.end(); ++itSection) {
pMap = &((*pMap)[*itSection]);
}
return *pMap;
}
void Configator::readStream(std::istream& stream) {
std::string line("");
std::list<std::string> sections;
sections.push_back("");
while (std::getline(stream, line)) {
std::list<std::string> keys;
std::string comment = "";
std::string value = "";
if (s_emptyOrComment(line, &comment)) {
Configator::Map& map = s_section(_mapConfig, sections);
if (!map.comment.empty()) {
map.comment.append("\n");
}
map.comment.append(comment);
}
else if (s_parseSections(line, §ions, &comment)) {
Configator::Map& map = s_section(_mapConfig, sections);
map.comment = comment;
}
else if (s_parseSectionLevel(line, §ions, &comment)) {
Configator::Map& map = s_section(_mapConfig, sections);
map.comment = comment;
}
else if (s_parseKey(line, &keys, &value, &comment)) {
Configator::Map& map = s_section(_mapConfig, sections);
Configator::Map* tmpMap = &(map);
std::list<std::string>::iterator it;
for (it = keys.begin(); it != keys.end() ; ++it) {
if (it->empty()) {
std::ostringstream oss("");
oss << tmpMap->size();
tmpMap = &((*tmpMap)[oss.str()]);
}
else {
tmpMap = &((*tmpMap)[*it]);
}
}
*tmpMap = value;
tmpMap->comment = comment;
}
}
}
}
| 26.679654
| 112
| 0.467683
|
MickaelBlet
|
329fe9fec81dd232d8f5d189629999932344b660
| 12,190
|
cpp
|
C++
|
src/select/tcpsocket_impl.cpp
|
tempbottle/zsummerX
|
b5a6b306329d6877cb53c1f30b586a2363c7682a
|
[
"MIT"
] | 1
|
2021-07-14T01:42:21.000Z
|
2021-07-14T01:42:21.000Z
|
src/select/tcpsocket_impl.cpp
|
tempbottle/zsummerX
|
b5a6b306329d6877cb53c1f30b586a2363c7682a
|
[
"MIT"
] | null | null | null |
src/select/tcpsocket_impl.cpp
|
tempbottle/zsummerX
|
b5a6b306329d6877cb53c1f30b586a2363c7682a
|
[
"MIT"
] | 1
|
2021-07-14T01:42:25.000Z
|
2021-07-14T01:42:25.000Z
|
/*
* zsummerX License
* -----------
*
* zsummerX is licensed under the terms of the MIT license reproduced below.
* This means that zsummerX is free software and can be used for both academic
* and commercial purposes at absolutely no cost.
*
*
* ===============================================================================
*
* Copyright (C) 2010-2015 YaweiZhang <yawei.zhang@foxmail.com>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* ===============================================================================
*
* (end of COPYRIGHT)
*/
#include <zsummerX/select/tcpsocket_impl.h>
using namespace zsummer::network;
TcpSocket::TcpSocket()
{
g_appEnvironment.addCreatedSocketCount();
_register._type = tagRegister::REG_TCP_SOCKET;
}
TcpSocket::~TcpSocket()
{
g_appEnvironment.addClosedSocketCount();
if (_onRecvHandler || _onSendHandler || _onConnectHandler)
{
LCT("TcpSocket::~TcpSocket[this0x" << this << "] Handler status error. " << logSection());
}
if (_register._fd != InvalideFD)
{
closesocket(_register._fd);
_register._fd = InvalideFD;
}
}
std::string TcpSocket::logSection()
{
std::stringstream os;
os << ";; Status: summer.user_count()=" << _summer.use_count() << ", remoteIP=" << _remoteIP << ", remotePort=" << _remotePort
<< ", _onConnectHandler = " << (bool)_onConnectHandler
<< ", _onRecvHandler = " << (bool)_onRecvHandler << ", _pRecvBuf=" << (void*)_pRecvBuf << ", _iRecvLen=" << _iRecvLen
<< ", _onSendHandler = " << (bool)_onSendHandler << ", _pSendBuf=" << (void*)_pSendBuf << ", _iSendLen=" << _iSendLen
<< "; _register=" << _register;
return os.str();
}
bool TcpSocket::initialize(const EventLoopPtr & summer)
{
_summer = summer;
if (_register._linkstat != LS_UNINITIALIZE)
{
if (!_summer->registerEvent(0, _register))
{
LCE("TcpSocket::initialize[this0x" << this << "] socket already used or not initilize." << logSection());
return false;
}
_register._linkstat = LS_ESTABLISHED;
}
else
{
if (_register._fd != -1)
{
LCE("TcpSocket::doConnect[this0x" << this << "] fd aready used!" << logSection());
return false;
}
_register._fd = socket(AF_INET, SOCK_STREAM, 0);
if (_register._fd == -1)
{
LCE("TcpSocket::doConnect[this0x" << this << "] fd create failed!" << logSection());
return false;
}
setNonBlock(_register._fd);
setNoDelay(_register._fd);
_register._linkstat = LS_WAITLINK;
}
return true;
}
bool TcpSocket::attachSocket(SOCKET s, const std::string& remoteIP, unsigned short remotePort)
{
_register._fd = s;
_remoteIP = remoteIP;
_remotePort = remotePort;
_register._linkstat = LS_WAITLINK;
return true;
}
bool TcpSocket::doConnect(const std::string & remoteIP, unsigned short remotePort, _OnConnectHandler && handler)
{
if (!_summer)
{
LCE("TcpSocket::doConnect[this0x" << this << "] summer not bind!" << logSection());
return false;
}
if (_register._linkstat != LS_WAITLINK)
{
LCE("TcpSocket::doConnect[this0x" << this << "] _linkstat not LS_WAITLINK!" << logSection());
return false;
}
_register._wt = true;
_remoteIP = remoteIP;
_remotePort = remotePort;
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(_remoteIP.c_str());
addr.sin_port = htons(_remotePort);
int ret = connect(_register._fd, (sockaddr *) &addr, sizeof(addr));
#ifndef WIN32
if (ret != 0 && errno != EINPROGRESS)
#else
if (ret != 0 && WSAGetLastError() != WSAEWOULDBLOCK)
#endif
{
LCT("TcpSocket::doConnect[this0x" << this << "] ::connect error. " << OSTREAM_GET_LASTERROR << logSection());
closesocket(_register._fd);
_register._fd = InvalideFD;
return false;
}
_register._tcpSocketConnectPtr = shared_from_this();
if (!_summer->registerEvent(0, _register))
{
LCE("TcpSocket::doConnect[this0x" << this << "] registerEvent Error" << logSection());
closesocket(_register._fd);
_register._fd = InvalideFD;
_register._tcpSocketConnectPtr.reset();
return false;
}
_onConnectHandler = std::move(handler);
return true;
}
bool TcpSocket::doSend(char * buf, unsigned int len, _OnSendHandler && handler)
{
if (_register._linkstat != LS_ESTABLISHED)
{
LCT("TcpSocket::doSend[this0x" << this << "] _linkstat not REG_ESTABLISHED_TCP!" << logSection());
return false;
}
if (!_summer)
{
LCE("TcpSocket::doSend[this0x" << this << "] _summer not bind!" << logSection());
return false;
}
if (len == 0)
{
LCE("TcpSocket::doSend[this0x" << this << "] argument err! len ==0" << logSection());
return false;
}
if (_pSendBuf != NULL || _iSendLen != 0)
{
LCE("TcpSocket::doSend[this0x" << this << "] _pSendBuf =" << (void *) _pSendBuf << " _iSendLen =" << _iSendLen<< logSection());
return false;
}
if (_onSendHandler)
{
LCE("TcpSocket::doSend[this0x" << this << "] _onSendHandler == TRUE" << logSection());
return false;
}
_pSendBuf = buf;
_iSendLen = len;
_register._wt = true;
_register._tcpSocketSendPtr = shared_from_this();
if (!_summer->registerEvent(1, _register))
{
LCT("TcpSocket::doSend[this0x" << this << "] registerEvent Error" << logSection());
_pSendBuf = nullptr;
_iSendLen = 0;
_register._tcpSocketSendPtr.reset();
doClose();
return false;
}
_onSendHandler = std::move(handler);
return true;
}
bool TcpSocket::doRecv(char * buf, unsigned int len, _OnRecvHandler && handler)
{
if (_register._linkstat != LS_ESTABLISHED)
{
LCT("TcpSocket::doRecv[this0x" << this << "] type not REG_ESTABLISHED_TCP!" << logSection());
return false;
}
if (!_summer)
{
LCE("TcpSocket::doRecv[this0x" << this << "] _summer not bind!" << logSection());
return false;
}
if (len == 0 )
{
LCE("TcpSocket::doRecv[this0x" << this << "] argument err !!! len==0" << logSection());
return false;
}
if (_pRecvBuf != NULL || _iRecvLen != 0)
{
LCE("TcpSocket::doRecv[this0x" << this << "] (_pRecvBuf != NULL || _iRecvLen != 0) == TRUE" << logSection());
return false;
}
if (_onRecvHandler)
{
LCE("TcpSocket::doRecv[this0x" << this << "] (_onRecvHandler) == TRUE" << logSection());
return false;
}
_pRecvBuf = buf;
_iRecvLen = len;
_register._rd = true;
_register._tcpSocketRecvPtr = shared_from_this();
if (!_summer->registerEvent(1, _register))
{
LCT("TcpSocket::doRecv[this0x" << this << "] registerEvent Error" << logSection());
_pRecvBuf = nullptr;
_iRecvLen = 0;
_register._tcpSocketRecvPtr.reset();
return false;
}
_onRecvHandler = std::move(handler);
return true;
}
void TcpSocket::onSelectMessage(bool rd, bool wt, bool err)
{
unsigned char linkstat = _register._linkstat;
NetErrorCode ec = NEC_ERROR;
if (!_onRecvHandler && !_onSendHandler && !_onConnectHandler)
{
LCE("TcpSocket::onSelectMessage[this0x" << this << "] unknown error. " << OSTREAM_GET_LASTERROR << logSection());
return ;
}
if (linkstat == LS_WAITLINK)
{
std::shared_ptr<TcpSocket> guad(std::move(_register._tcpSocketConnectPtr));
_OnConnectHandler onConnect(std::move(_onConnectHandler));
int errCode = 0;
socklen_t len = sizeof(int);
if (err || getsockopt(_register._fd, SOL_SOCKET, SO_ERROR, (char*)&errCode, &len) != 0 || errCode != 0)
{
LOGT("onConnect False. " << OSTREAM_GET_LASTERROR);
_register._linkstat = LS_WAITLINK;
_summer->registerEvent(2, _register);
onConnect(NEC_ERROR);
return;
}
else
{
_register._wt = 0;
_summer->registerEvent(1, _register);
_register._linkstat = LS_ESTABLISHED;
onConnect(NEC_SUCCESS);
return;
}
return ;
}
if (rd && _onRecvHandler)
{
std::shared_ptr<TcpSocket> guad(std::move(_register._tcpSocketRecvPtr));
int ret = recv(_register._fd, _pRecvBuf, _iRecvLen, 0);
_register._rd = false;
if (!_summer->registerEvent(1, _register))
{
LCF("TcpSocket::onSelectMessage[this0x" << this << "] connect true & EPOLLMod error. " << OSTREAM_GET_LASTERROR << logSection());
}
if (ret == 0 || (ret == -1 && !IS_WOULDBLOCK))
{
ec = NEC_ERROR;
_register._linkstat = LS_CLOSED;
if (rd && _onRecvHandler)
{
_OnRecvHandler onRecv(std::move(_onRecvHandler));
onRecv(ec, 0);
}
if (!_onSendHandler && !_onRecvHandler)
{
if (!_summer->registerEvent(2, _register))
{
LCW("TcpSocket::onSelectMessage[this0x" << this << "] connect true & EPOLL DEL error. " << OSTREAM_GET_LASTERROR << logSection());
}
}
return ;
}
else if (ret != -1)
{
_OnRecvHandler onRecv(std::move(_onRecvHandler));
_pRecvBuf = NULL;
_iRecvLen = 0;
onRecv(NEC_SUCCESS,ret);
}
return;
}
else if (wt && _onSendHandler)
{
std::shared_ptr<TcpSocket> guad(std::move(_register._tcpSocketSendPtr));
int ret = send(_register._fd, _pSendBuf, _iSendLen, 0);
_register._wt = false;
if (!_summer->registerEvent(1, _register))
{
LCF("TcpSocket::onSelectMessage[this0x" << this << "] connect true & EPOLLMod error. " << OSTREAM_GET_LASTERROR << logSection());
}
if ((ret == -1 && !IS_WOULDBLOCK) || _register._linkstat == LS_CLOSED)
{
ec = NEC_ERROR;
_register._linkstat = LS_CLOSED;
_onSendHandler = nullptr;
if (!_onSendHandler && !_onRecvHandler)
{
if (!_summer->registerEvent(2, _register))
{
LCW("TcpSocket::onSelectMessage[this0x" << this << "] connect true & EPOLL DEL error. " << OSTREAM_GET_LASTERROR << logSection());
}
}
return ;
}
else if (ret != -1)
{
_OnSendHandler onSend(std::move(_onSendHandler));
_pSendBuf = NULL;
_iSendLen = 0;
onSend(NEC_SUCCESS, ret);
}
}
return ;
}
bool TcpSocket::doClose()
{
if (_register._fd != InvalideFD)
{
shutdown(_register._fd, SHUT_RDWR);
}
return true;
}
| 30.860759
| 151
| 0.579655
|
tempbottle
|
32a0a7fba84f4162d3de29e78fc6b8c5121fc1a1
| 5,967
|
cpp
|
C++
|
src/isodata/isodata.cpp
|
wmotte/toolkid
|
2a8f82e1492c9efccde9a4935ce3019df1c68cde
|
[
"MIT"
] | null | null | null |
src/isodata/isodata.cpp
|
wmotte/toolkid
|
2a8f82e1492c9efccde9a4935ce3019df1c68cde
|
[
"MIT"
] | null | null | null |
src/isodata/isodata.cpp
|
wmotte/toolkid
|
2a8f82e1492c9efccde9a4935ce3019df1c68cde
|
[
"MIT"
] | null | null | null |
#include "tkdCmdParser.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImage.h"
#include "itkTimeProbe.h"
#include "IsoDataImage.cpp"
/**
* ISODATA.
*/
class IsoData {
protected:
// Split function; return true if we should split...
bool split( IsoDataImage& img, double STDV, unsigned int minPointsPerCluster ) {
bool split = false;
//STEP 7:
img.calculateSTDVector();
//STEP 8:
img.calculateVmax();
// STEP 9:
// the vector to_split will contain integers that
// represent the cluster numbers that need to be split.
std::vector< unsigned int > to_split = img.shouldSplit( STDV, minPointsPerCluster );
if ( to_split.size() != 0 ) {
img.split( to_split );
split = true;
}
return split;
}
// Merge...
void merge( IsoDataImage& img, double LUMP, int MAXPAIR ) {
// STEP 11:
std::vector< IsoDataImage::PairDistanceNode > centerDistances = img.computeCenterDistances();
// STEP 12:
std::vector< IsoDataImage::PairDistanceNode > to_lump = img.findLumpCandidates( centerDistances, LUMP, MAXPAIR );
// STEP 13:
if ( to_lump.size() != 0 ) {
img.lump( to_lump );
}
}
// ************************************************************************************************
public:
/**
* Run.
*/
void run( const std::vector< std::string >& inputs, const std::string& output,
const std::string& mask, unsigned int NUMCLUS, unsigned int SAMPRM,
unsigned int MAXITER, double STDV, double LUMP, int MAXPAIR, bool normalize ) {
itk::TimeProbe probe;
probe.Start();
// initialize raw data...
IsoDataImage img = IsoDataImage( inputs, output, mask, normalize );
// STEP 1: arbitrarily choose k and init clusters...
img.initClusters( NUMCLUS );
for ( unsigned int i = 0; i < MAXITER; i++ ) {
std::cout << "Iter: " << i << std::endl;
// STEP 2: assign each point to the clostest cluster center...
img.assignPointsToClosestClusterCenter();
// STEP 3: discard clusters with less than min. samples per cluster...
// If any clusters were deleted, then go back to STEP 2...
if ( img.discardSmallClusters( SAMPRM ) ) {
continue;
}
// STEP 4: update each remaining cluster center...
img.updateClusters();
// STEP 5: compute the average distance of points in clusters from
// their corresponding cluster center...
// also compute overall average distance...
img.computeAverageDistance();
img.computeOverallAverageDistance();
// STEP 6:
if ( i == MAXITER ) {
LUMP = 0.0;
// goto STEP 9:
merge( img, LUMP, MAXPAIR );
} else if ( ( i % 2 == 0 ) || ( img.getNumCenters() >= 2 * NUMCLUS ) ) {
// goto STEP 9:
merge( img, LUMP, MAXPAIR );
} else if ( img.getNumCenters() <= ( NUMCLUS / 2 ) ) {
// goto STEP 7:
// if we are in last iteration and split is performed, we need to rerun from STEP 2 again
// as cluster centers need to be updated before final run...
if ( ( split( img, STDV, SAMPRM ) ) && ( i == MAXITER ) ) {
i--;
}
}
}
img.writeOutput( output );
probe.Stop();
std::cout << "Total runtime: " << probe.GetMeanTime() << " s." << std::endl;
}
};
/**
* Main.
*/
int main( int argc, char * argv[] ) {
// arguments...
std::vector< std::string > inputs;
std::string output;
std::string mask;
int numberOfClusters = 10; // kinit
int minNumberOfClusterPoints = 30; // nmin 1/5 average kluster size -> nmin = n/5 kinit.
int maxNumberOfIter = 20; // Imax default 20
double maxStdev = 0.1; // STDV default 2 * sigma
double minRequiredDistance = 0.001; // Lmin default 0.001
int maxPair = 4; // MAXPAIR
bool normalize = false; // normalize input images...
tkd::CmdParser parser( argv[0], "Isodata" );
parser.AddArgument( inputs, "inputs" ) -> AddAlias( "i" ) -> SetInput( "<strings>" ) -> SetDescription( "Input images" ) -> SetRequired(
true ) -> SetMinMax( 1, 10000 );
parser.AddArgument( output, "output" ) -> AddAlias( "o" ) -> SetInput( "<string>" ) -> SetDescription( "Output cluster image file" ) -> SetRequired(
true ) -> SetMinMax( 1, 1 );
parser.AddArgument( mask, "mask" ) -> AddAlias( "m" ) -> SetInput( "<string>" ) -> SetDescription( "Mask image" ) -> SetRequired(
false ) -> SetMinMax( 0, 1 );
parser.AddArgument( numberOfClusters, "clusters" ) -> AddAlias( "c" ) -> SetInput( "<int>" ) -> SetDescription(
"Initial number of clusters (NUMCLUS)" ) -> SetMinMax( 1, 1 );
parser.AddArgument( minNumberOfClusterPoints, "min-clusters" ) -> AddAlias( "m" ) -> SetInput( "<int>" ) -> SetDescription(
"Minimum number of points that can form a cluster (SAMPRM)" ) -> SetMinMax( 1, 1 );
parser.AddArgument( maxNumberOfIter, "max-itererations" ) -> AddAlias( "it" ) -> SetInput( "<int>" ) -> SetDescription(
"Maximum number of iterations (MAXITER)" ) -> SetMinMax( 1, 1 );
parser.AddArgument( maxStdev, "standard-deviation" ) -> AddAlias( "s" ) -> SetInput( "<double>" ) -> SetDescription(
"Maximum standard deviation of points from their cluster center along each axis (STDV)" ) -> SetMinMax( 1, 1 );
parser.AddArgument( minRequiredDistance, "min-distance" ) -> AddAlias( "d" ) -> SetInput( "<double>" ) -> SetDescription(
" Minimum required distance between two cluster centers (LUMP)" ) -> SetMinMax( 1, 1 );
parser.AddArgument( maxPair, "max-pairs" ) -> AddAlias( "p" ) -> SetInput( "<int>" ) -> SetDescription(
"Maximum number of cluster pairs that can be merged per iteration (MAXPAIR)" ) -> SetMinMax( 1, 1 );
parser.AddArgument( normalize, "normalize" ) -> AddAlias( "n" ) -> SetInput( "<bool>" ) -> SetDescription(
"Normalize input images before clustering (default: false)" );
if ( !parser.Parse( argc, argv ) ) {
parser.PrintUsage( std::cout );
return EXIT_FAILURE;
}
IsoData isoData = IsoData();
isoData.run( inputs, output, mask, numberOfClusters, minNumberOfClusterPoints, maxNumberOfIter, maxStdev, minRequiredDistance, maxPair, normalize );
}
| 33.335196
| 149
| 0.64002
|
wmotte
|
32a2a7171e1f335a70241b41cb2874d2ec40de69
| 457
|
hpp
|
C++
|
v3/include/AsyncWatchResponse.hpp
|
chijinxina/etcd-cpp-api
|
70946a5d4eff340a821096d247031d083fd0148e
|
[
"BSD-3-Clause"
] | null | null | null |
v3/include/AsyncWatchResponse.hpp
|
chijinxina/etcd-cpp-api
|
70946a5d4eff340a821096d247031d083fd0148e
|
[
"BSD-3-Clause"
] | null | null | null |
v3/include/AsyncWatchResponse.hpp
|
chijinxina/etcd-cpp-api
|
70946a5d4eff340a821096d247031d083fd0148e
|
[
"BSD-3-Clause"
] | 1
|
2021-07-13T07:19:37.000Z
|
2021-07-13T07:19:37.000Z
|
#ifndef __ASYNC_WATCH_HPP__
#define __ASYNC_WATCH_HPP__
#include <grpc++/grpc++.h>
#include "proto/rpc.grpc.pb.h"
#include "proto/rpc.pb.h"
#include "v3/include/V3Response.hpp"
using etcdserverpb::WatchRequest;
using etcdserverpb::WatchResponse;
using etcdserverpb::KV;
namespace etcdv3
{
class AsyncWatchResponse : public etcdv3::V3Response
{
public:
AsyncWatchResponse(){};
void ParseResponse(WatchResponse& resp);
};
}
#endif
| 17.576923
| 54
| 0.73523
|
chijinxina
|
32a41e70dacf34144ee21b788e81882f3e67b773
| 224
|
cpp
|
C++
|
Aaaah/main.cpp
|
KalawelaLo/Kattis
|
cbe2cc742f9902f5d325deb04fd39208774070c5
|
[
"Unlicense"
] | null | null | null |
Aaaah/main.cpp
|
KalawelaLo/Kattis
|
cbe2cc742f9902f5d325deb04fd39208774070c5
|
[
"Unlicense"
] | null | null | null |
Aaaah/main.cpp
|
KalawelaLo/Kattis
|
cbe2cc742f9902f5d325deb04fd39208774070c5
|
[
"Unlicense"
] | null | null | null |
#include <iostream>
#include <string>
using namespace std;
int main() {
string pat, doc;
cin>> pat >> doc;
if(pat.size() >= doc.size() ){
cout << "go\n";}
else{
cout << "no\n";}
return 0;}
| 20.363636
| 34
| 0.508929
|
KalawelaLo
|
32ab54505766855b05cb8df09bf8afb467aafed8
| 3,726
|
cpp
|
C++
|
ert/ertlibc/syscall.cpp
|
thomasten/edgelessrt
|
2b42deefdaaa75dbc6568ff4f8152b6ae74862bf
|
[
"MIT"
] | null | null | null |
ert/ertlibc/syscall.cpp
|
thomasten/edgelessrt
|
2b42deefdaaa75dbc6568ff4f8152b6ae74862bf
|
[
"MIT"
] | null | null | null |
ert/ertlibc/syscall.cpp
|
thomasten/edgelessrt
|
2b42deefdaaa75dbc6568ff4f8152b6ae74862bf
|
[
"MIT"
] | null | null | null |
// Copyright (c) Edgeless Systems GmbH.
// Licensed under the MIT License.
#include "syscall.h"
#include <openenclave/internal/malloc.h>
#include <openenclave/internal/trace.h>
#include <sys/syscall.h>
#include <cerrno>
#include <clocale>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <stdexcept>
#include <system_error>
#include "ertthread.h"
#include "locale.h"
#include "syscalls.h"
using namespace std;
using namespace ert;
long ert_syscall(long n, long x1, long x2, long x3, long, long, long)
{
try
{
switch (n)
{
case SYS_sched_yield:
__builtin_ia32_pause();
return 0;
case SYS_clock_gettime:
return sc::clock_gettime(
static_cast<int>(x1), reinterpret_cast<timespec*>(x2));
case SYS_gettid:
return ert_thread_self()->tid;
case SYS_exit_group:
sc::exit_group(static_cast<int>(x1));
return 0;
case SYS_getrandom:
return sc::getrandom(
reinterpret_cast<void*>(x1), // buf
static_cast<size_t>(x2), // buflen
static_cast<unsigned int>(x3) // flags
);
case SYS_sched_getaffinity:
return sc::sched_getaffinity(
static_cast<pid_t>(x1),
static_cast<size_t>(x2),
reinterpret_cast<cpu_set_t*>(x3));
case SYS_mprotect:
case SYS_madvise:
case SYS_mlock:
case SYS_munlock:
case SYS_mlockall:
case SYS_munlockall:
case SYS_mlock2:
// These can all be noops.
return 0;
case SYS_rt_sigaction:
sc::rt_sigaction(
static_cast<int>(x1), // signum
reinterpret_cast<k_sigaction*>(x2), // act
reinterpret_cast<k_sigaction*>(x3)); // oldact
return 0;
case SYS_rt_sigprocmask:
return 0; // Not supported. Silently ignore and return success.
case SYS_sigaltstack:
sc::sigaltstack(
reinterpret_cast<stack_t*>(x1),
reinterpret_cast<stack_t*>(x2));
return 0;
}
}
catch (const system_error& e)
{
OE_TRACE_ERROR("%s", e.what());
return -e.code().value();
}
catch (const runtime_error& e)
{
OE_TRACE_ERROR("%s", e.what());
}
catch (const exception& e)
{
OE_TRACE_FATAL("%s", e.what());
abort();
}
return -ENOSYS;
}
// This function is defined in this source file to guarantee that it overrides
// the weak symbol in ert/libc/locale.c.
extern "C" locale_t __newlocale(int mask, const char* locale, locale_t loc)
{
if (!(mask > 0 && !loc && locale && strcmp(locale, "C") == 0))
return newlocale(mask, locale, loc);
// Caller may be stdc++. We must return a struct that satisfies glibc
// internals (see glibc/locale/global-locale.c). The following struct is
// also compatible with musl.
static const __locale_struct c_locale{
{}, reinterpret_cast<const unsigned short*>(nl_C_LC_CTYPE_class + 128)};
return const_cast<locale_t>(&c_locale);
}
// The debug malloc check runs on enclave termination and prints errors for heap
// memory that has not been freed. As some global objects in (std)c++ use heap
// memory and don't free it by design, we cannot use this feature.
static int _init = [] {
oe_disable_debug_malloc_check = true;
return 0;
}();
| 31.310924
| 80
| 0.567901
|
thomasten
|
32abb8fe555c12e7c93a94570e29a92f8d04d5ac
| 30,229
|
hh
|
C++
|
sdl2/openblock/external/libSDL2pp/SDL2pp/Font.hh
|
pdpdds/SDLGameProgramming
|
3af68e2133296f3e7bc3d7454d9301141bca2d5a
|
[
"BSD-2-Clause"
] | null | null | null |
sdl2/openblock/external/libSDL2pp/SDL2pp/Font.hh
|
pdpdds/SDLGameProgramming
|
3af68e2133296f3e7bc3d7454d9301141bca2d5a
|
[
"BSD-2-Clause"
] | null | null | null |
sdl2/openblock/external/libSDL2pp/SDL2pp/Font.hh
|
pdpdds/SDLGameProgramming
|
3af68e2133296f3e7bc3d7454d9301141bca2d5a
|
[
"BSD-2-Clause"
] | null | null | null |
/*
libSDL2pp - C++11 bindings/wrapper for SDL2
Copyright (C) 2014-2015 Dmitry Marakasov <amdmi3@amdmi3.ru>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifndef SDL2PP_FONT_HH
#define SDL2PP_FONT_HH
#include <string>
#include <SDL2/SDL_ttf.h>
#include <SDL2pp/Optional.hh>
#include <SDL2pp/Point.hh>
#include <SDL2pp/Surface.hh>
#include <SDL2pp/Export.hh>
namespace SDL2pp {
class RWops;
////////////////////////////////////////////////////////////
/// \brief Holder of a loaded font
///
/// \ingroup ttf
///
/// \headerfile SDL2pp/Font.hh
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC56
///
////////////////////////////////////////////////////////////
class SDL2PP_EXPORT Font {
private:
TTF_Font* font_; ///< Managed TTF_Font object
public:
///@{
/// \name Construction and destruction
////////////////////////////////////////////////////////////
/// \brief Construct from existing TTF_Font structure
///
/// \param[in] font Existing TTF_Font to manage
///
////////////////////////////////////////////////////////////
Font(TTF_Font* font);
////////////////////////////////////////////////////////////
/// \brief Loads font from .ttf or .fon file
///
/// \param[in] file Pointer File name to load font from
/// \param[in] ptsize %Point size (based on 72DPI) to load font as. This basically translates to pixel height
/// \param[in] index Choose a font face from a file containing multiple font faces. The first face is always index 0
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC14
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC16
///
////////////////////////////////////////////////////////////
Font(const std::string& file, int ptsize, long index = 0);
////////////////////////////////////////////////////////////
/// \brief Loads font with RWops
///
/// \param[in] rwops RWops to load font from
/// \param[in] ptsize %Point size (based on 72DPI) to load font as. This basically translates to pixel height
/// \param[in] index Choose a font face from a file containing multiple font faces. The first face is always index 0
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC15
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC17
///
////////////////////////////////////////////////////////////
Font(RWops& rwops, int ptsize, long index = 0);
////////////////////////////////////////////////////////////
/// \brief Destructor
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC18
///
////////////////////////////////////////////////////////////
virtual ~Font();
///@}
///@{
/// \name Copy and move
////////////////////////////////////////////////////////////
/// \brief Move constructor
///
/// \param[in] other SDL2pp::Font object to move data from
///
////////////////////////////////////////////////////////////
Font(Font&& other) noexcept;
////////////////////////////////////////////////////////////
/// \brief Move assignment
///
/// \param[in] other SDL2pp::Font object to move data from
///
/// \returns Reference to self
///
////////////////////////////////////////////////////////////
Font& operator=(Font&& other) noexcept;
////////////////////////////////////////////////////////////
/// \brief Deleted copy constructor
///
/// This class is not copyable
///
////////////////////////////////////////////////////////////
Font(const Font&) = delete;
////////////////////////////////////////////////////////////
/// \brief Deleted assignment operator
///
/// This class is not copyable
///
////////////////////////////////////////////////////////////
Font& operator=(const Font&) = delete;
///@}
///@{
/// \name Compatibility with legacy SDL code
////////////////////////////////////////////////////////////
/// \brief Get pointer to managed TTF_Font structure
///
/// \returns Pointer to managed TTF_Font structure
///
////////////////////////////////////////////////////////////
TTF_Font* Get() const;
///@{
/// \name Attributes: font style
////////////////////////////////////////////////////////////
/// \brief Get the rendering style of the loaded font
///
/// \returns The style as a bitmask composed of the following masks:
/// TTF_STYLE_BOLD, TTF_STYLE_ITALIC, TTF_STYLE_UNDERLINE,
/// TTF_STYLE_STRIKETHROUGH. If no style is set then
/// TTF_STYLE_NORMAL is returned
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC21
///
////////////////////////////////////////////////////////////
int GetStyle() const;
////////////////////////////////////////////////////////////
/// \brief Set the rendering style of the loaded font
///
/// \param[in] style The style as a bitmask composed of the following masks:
/// TTF_STYLE_BOLD, TTF_STYLE_ITALIC, TTF_STYLE_UNDERLINE,
/// TTF_STYLE_STRIKETHROUGH. If no style is desired then use
/// TTF_STYLE_NORMAL, which is the default.
///
/// \note This will flush the internal cache of previously rendered
/// glyphs, even if there is no change in style, so it may be best
/// to check the current style by using GetStyle() first
///
/// \note TTF_STYLE_UNDERLINE may cause surfaces created by TTF_RenderGlyph_*
/// functions to be extended vertically, downward only, to encompass the
/// underline if the original glyph metrics didn't allow for the underline
/// to be drawn below. This does not change the math used to place a glyph
/// using glyph metrics.
/// On the other hand TTF_STYLE_STRIKETHROUGH doesn't extend the glyph,
/// since this would invalidate the metrics used to position the glyph
/// when blitting, because they would likely be extended vertically upward.
/// There is perhaps a workaround, but it would require programs to be
/// smarter about glyph blitting math than they are currently designed for.
/// Still, sometimes the underline or strikethrough may be outside of the
/// generated surface, and thus not visible when blitted to the screen.
/// In this case, you should probably turn off these styles and draw your
/// own strikethroughs and underlines.
///
/// \returns Reference to self
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC22
///
////////////////////////////////////////////////////////////
Font& SetStyle(int style = TTF_STYLE_NORMAL);
////////////////////////////////////////////////////////////
/// \brief Get the current outline size of the loaded font
///
/// \returns The size of the outline currently set on the font, in pixels
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC23
///
////////////////////////////////////////////////////////////
int GetOutline() const;
////////////////////////////////////////////////////////////
/// \brief Set the outline pixel width of the loaded font
///
/// \param[in] outline The size of outline desired, in pixels.
/// Use 0 (zero) to turn off outlining.
///
/// \note This will flush the internal cache of previously rendered
/// glyphs, even if there is no change in outline size, so it may be best
/// to check the current outline size by using GetOutline() first
///
/// \returns Reference to self
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC24
///
////////////////////////////////////////////////////////////
Font& SetOutline(int outline = 0);
///@}
///@{
/// \name Attributes: font settings
////////////////////////////////////////////////////////////
/// \brief Get the current hinting setting of the loaded font
///
/// \returns The hinting type matching one of the following defined values:
/// TTF_HINTING_NORMAL, TTF_HINTING_LIGHT, TTF_HINTING_MONO,
/// TTF_HINTING_NONE. If no hinting is set then TTF_HINTING_NORMAL is returned
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC25
///
////////////////////////////////////////////////////////////
int GetHinting() const;
////////////////////////////////////////////////////////////
/// \brief Set the hinting of the loaded font
///
/// \param[in] hinting The hinting setting desired, which is one of:
/// TTF_HINTING_NORMAL, TTF_HINTING_LIGHT, TTF_HINTING_MONO,
/// TTF_HINTING_NONE. The default is TTF_HINTING_NORMAL
///
/// You should experiment with this setting if you know which font
/// you are using beforehand, especially when using smaller sized
/// fonts. If the user is selecting a font, you may wish to let them
/// select the hinting mode for that font as well
///
/// \note This will flush the internal cache of previously rendered
/// glyphs, even if there is no change in hinting, so it may be best
/// to check the current hinting by using GetHinting() first
///
/// \returns Reference to self
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC26
///
////////////////////////////////////////////////////////////
Font& SetHinting(int hinting = TTF_HINTING_NORMAL);
////////////////////////////////////////////////////////////
/// \brief Get the current kerning setting of the loaded font
///
/// \returns False if kerning is disabled. True when enabled.
/// The default for a newly loaded font is true, enabled
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC27
///
////////////////////////////////////////////////////////////
bool GetKerning() const;
////////////////////////////////////////////////////////////
/// \brief Set whether to use kerning when rendering the loaded font
///
/// \param[in] allowed False to disable kerning, true to enable kerning.
/// The default is true, enabled
///
/// Set whether to use kerning when rendering the loaded font.
/// This has no effect on individual glyphs, but rather when
/// rendering whole strings of characters, at least a word at
/// a time. Perhaps the only time to disable this is when kerning
/// is not working for a specific font, resulting in overlapping
/// glyphs or abnormal spacing within words.
///
/// \returns Reference to self
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC28
///
////////////////////////////////////////////////////////////
Font& SetKerning(bool allowed = true);
///@}
///@{
/// \name Attributes: font metrics
////////////////////////////////////////////////////////////
/// \brief Get the maximum pixel height of all glyphs of the loaded font
///
/// \returns The maximum pixel height of all glyphs in the font
///
/// You may use this height for rendering text as close together
/// vertically as possible, though adding at least one pixel height
/// to it will space it so they can't touch. Remember that SDL_ttf
/// doesn't handle multiline printing, so you are responsible for
/// line spacing, see the GetLineSkip() as well.
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC29
///
////////////////////////////////////////////////////////////
int GetHeight() const;
////////////////////////////////////////////////////////////
/// \brief Get the maximum pixel ascent of all glyphs of the loaded font
///
/// \returns The maximum pixel ascent of all glyphs in the font
///
/// This can also be interpreted as the distance from the top of
/// the font to the baseline. It could be used when drawing an
/// individual glyph relative to a top point, by combining it
/// with the glyph's maxy metric to resolve the top of the
/// rectangle used when blitting the glyph on the screen.
///
/// \code{.cpp}
/// rect.y = top + Font.GetAscent() - glyph_metric.maxy;
/// \endcode
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC30
///
////////////////////////////////////////////////////////////
int GetAscent() const;
////////////////////////////////////////////////////////////
/// \brief Get the maximum pixel descent of all glyphs of the loaded font
///
/// \returns The maximum pixel height of all glyphs in the font
///
/// This can also be interpreted as the distance from the
/// baseline to the bottom of the font.
/// It could be used when drawing an individual glyph relative
/// to a bottom point, by combining it with the glyph's maxy
/// metric to resolve the top of the rectangle used when blitting
/// the glyph on the screen.
///
/// \code{.cpp}
/// rect.y = bottom - TTF_FontDescent(font) - glyph_metric.maxy;
/// \endcode
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC31
///
////////////////////////////////////////////////////////////
int GetDescent() const;
////////////////////////////////////////////////////////////
/// \brief Get the recommended pixel height of a rendered line of text of the loaded font
///
/// \returns The maximum pixel height of all glyphs in the font
///
/// This is usually larger than the GetHeight() of the font
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC32
///
////////////////////////////////////////////////////////////
int GetLineSkip() const;
///@}
///@{
/// \name Attributes: face attributes
////////////////////////////////////////////////////////////
/// \brief Get the number of faces ("sub-fonts") available in the loaded font
///
/// \returns The number of faces in the font
///
/// This is a count of the number of specific fonts (based on size
/// and style and other typographical features perhaps) contained
/// in the font itself. It seems to be a useless fact to know,
/// since it can't be applied in any other SDL_ttf functions.
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC33
///
////////////////////////////////////////////////////////////
long GetNumFaces() const;
////////////////////////////////////////////////////////////
/// \brief Test if the current font face of the loaded font is a fixed width font
///
/// \returns True if font is a fixed width font. False if not a fixed width font
///
/// Fixed width fonts are monospace, meaning every character
/// that exists in the font is the same width, thus you can
/// assume that a rendered string's width is going to be the
/// result of a simple calculation:
///
/// \code{.cpp}
/// glyph_width * string_length
/// \endcode
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC34
///
////////////////////////////////////////////////////////////
bool IsFixedWidth() const;
////////////////////////////////////////////////////////////
/// \brief Get the current font face family name from the loaded font
///
/// \returns The current family name of of the face of the font, or NullOpt perhaps
///
/// This function may return NullOpt, in which case the information is not available.
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC35
///
////////////////////////////////////////////////////////////
Optional<std::string> GetFamilyName() const;
////////////////////////////////////////////////////////////
/// \brief Get the current font face style name from the loaded font
///
/// \returns The current style name of of the face of the font, or NullOpt perhaps
///
/// This function may return NullOpt, in which case the information is not available
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC36
///
////////////////////////////////////////////////////////////
Optional<std::string> GetStyleName() const;
///@}
///@{
/// \name Attributes: glyphs
////////////////////////////////////////////////////////////
/// \brief Get the status of the availability of the glyph from the loaded font
///
/// \param[in] ch Unicode character to test glyph availability of
///
/// \returns The index of the glyph for ch in font, or 0 for an undefined character code
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC37
///
////////////////////////////////////////////////////////////
int IsGlyphProvided(Uint16 ch) const;
////////////////////////////////////////////////////////////
/// \brief Get glyph metrics of the UNICODE char
///
/// \param[in] ch UNICODE char to get the glyph metrics for
/// \param[out] minx Variable to store the returned minimum X offset into
/// \param[out] maxx Variable to store the returned maximum X offset into
/// \param[out] miny Variable to store the returned minimum Y offset into
/// \param[out] maxy Variable to store the returned maximum Y offset into
/// \param[out] advance Variable to store the returned advance offset into
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC38
/// \see http://freetype.sourceforge.net/freetype2/docs/tutorial/step2.html
///
////////////////////////////////////////////////////////////
void GetGlyphMetrics(Uint16 ch, int& minx, int& maxx, int& miny, int& maxy, int& advance) const;
////////////////////////////////////////////////////////////
/// \brief Get rect part of glyph metrics of the UNICODE char
///
/// \param[in] ch UNICODE char to get the glyph metrics for
///
/// \returns Rect representing glyph offset info
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC38
/// \see http://freetype.sourceforge.net/freetype2/docs/tutorial/step2.html
///
////////////////////////////////////////////////////////////
Rect GetGlyphRect(Uint16 ch) const;
////////////////////////////////////////////////////////////
/// \brief Get advance part of glyph metrics of the UNICODE char
///
/// \param[in] ch UNICODE char to get the glyph metrics for
///
/// \returns Advance offset into
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC38
/// \see http://freetype.sourceforge.net/freetype2/docs/tutorial/step2.html
///
////////////////////////////////////////////////////////////
int GetGlyphAdvance(Uint16 ch) const;
///@}
///@{
/// \name Attributes: text metrics
////////////////////////////////////////////////////////////
/// \brief Calculate the resulting surface size of the LATIN1 encoded text rendered using font
///
/// \param[in] text String to size up
///
/// \returns Point representing dimensions of the rendered text
///
/// \throws SDL2pp::Exception
///
/// No actual rendering is done, however correct kerning is done
/// to get the actual width. The height returned in h is the same
/// as you can get using GetHeight()
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC39
///
////////////////////////////////////////////////////////////
Point GetSizeText(const std::string& text) const;
////////////////////////////////////////////////////////////
/// \brief Calculate the resulting surface size of the UTF8 encoded text rendered using font
///
/// \param[in] text UTF8 encoded string to size up
///
/// \returns Point representing dimensions of the rendered text
///
/// \throws SDL2pp::Exception
///
/// No actual rendering is done, however correct kerning is done
/// to get the actual width. The height returned in h is the same
/// as you can get using GetHeight()
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC40
///
////////////////////////////////////////////////////////////
Point GetSizeUTF8(const std::string& text) const;
////////////////////////////////////////////////////////////
/// \brief Calculate the resulting surface size of the UNICODE encoded text rendered using font
///
/// \param[in] text UNICODE null terminated string to size up
///
/// \returns Point representing dimensions of the rendered text
///
/// \throws SDL2pp::Exception
///
/// No actual rendering is done, however correct kerning is done
/// to get the actual width. The height returned in h is the same
/// as you can get using GetHeight()
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC41
///
////////////////////////////////////////////////////////////
Point GetSizeUNICODE(const Uint16* text) const;
////////////////////////////////////////////////////////////
/// \brief Calculate the resulting surface size of the UNICODE encoded text rendered using font
///
/// \param[in] text UNICODE null terminated string to size up
///
/// \returns Point representing dimensions of the rendered text
///
/// \throws SDL2pp::Exception
///
/// No actual rendering is done, however correct kerning is done
/// to get the actual width. The height returned in h is the same
/// as you can get using GetHeight()
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC41
///
////////////////////////////////////////////////////////////
Point GetSizeUNICODE(const std::u16string& text) const;
///@}
///@{
/// \name Rendering: solid
////////////////////////////////////////////////////////////
/// \brief Render LATIN1 text using solid mode
///
/// \param[in] text LATIN1 string to render
/// \param[in] fg Color to render the text in
///
/// \returns Surface containing rendered text
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC43
///
////////////////////////////////////////////////////////////
Surface RenderText_Solid(const std::string& text, SDL_Color fg);
////////////////////////////////////////////////////////////
/// \brief Render UTF8 text using solid mode
///
/// \param[in] text UTF8 string to render
/// \param[in] fg Color to render the text in
///
/// \returns Surface containing rendered text
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC44
///
////////////////////////////////////////////////////////////
Surface RenderUTF8_Solid(const std::string& text, SDL_Color fg);
////////////////////////////////////////////////////////////
/// \brief Render UNICODE encoded text using solid mode
///
/// \param[in] text UNICODE encoded string to render
/// \param[in] fg Color to render the text in
///
/// \returns Surface containing rendered text
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC45
///
////////////////////////////////////////////////////////////
Surface RenderUNICODE_Solid(const Uint16* text, SDL_Color fg);
////////////////////////////////////////////////////////////
/// \brief Render UNICODE encoded text using solid mode
///
/// \param[in] text UNICODE encoded string to render
/// \param[in] fg Color to render the text in
///
/// \returns Surface containing rendered text
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC45
///
////////////////////////////////////////////////////////////
Surface RenderUNICODE_Solid(const std::u16string& text, SDL_Color fg);
////////////////////////////////////////////////////////////
/// \brief Render the glyph for UNICODE character using solid mode
///
/// \param[in] ch UNICODE character to render
/// \param[in] fg Color to render the glyph in
///
/// \returns Surface containing rendered text
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC46
///
////////////////////////////////////////////////////////////
Surface RenderGlyph_Solid(Uint16 ch, SDL_Color fg);
///@}
///@{
/// \name Rendering: shaded
////////////////////////////////////////////////////////////
/// \brief Render LATIN1 text using shaded mode
///
/// \param[in] text LATIN1 string to render
/// \param[in] fg Color to render the text in
/// \param[in] bg Color to render the background box in
///
/// \returns Surface containing rendered text
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC47
///
////////////////////////////////////////////////////////////
Surface RenderText_Shaded(const std::string& text, SDL_Color fg, SDL_Color bg);
////////////////////////////////////////////////////////////
/// \brief Render UTF8 text using shaded mode
///
/// \param[in] text UTF8 string to render
/// \param[in] fg Color to render the text in
/// \param[in] bg Color to render the background box in
///
/// \returns Surface containing rendered text
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC48
///
////////////////////////////////////////////////////////////
Surface RenderUTF8_Shaded(const std::string& text, SDL_Color fg, SDL_Color bg);
////////////////////////////////////////////////////////////
/// \brief Render UNICODE encoded text using shaded mode
///
/// \param[in] text UNICODE encoded string to render
/// \param[in] fg Color to render the text in
/// \param[in] bg Color to render the background box in
///
/// \returns Surface containing rendered text
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC49
///
////////////////////////////////////////////////////////////
Surface RenderUNICODE_Shaded(const Uint16* text, SDL_Color fg, SDL_Color bg);
////////////////////////////////////////////////////////////
/// \brief Render UNICODE encoded text using shaded mode
///
/// \param[in] text UNICODE encoded string to render
/// \param[in] fg Color to render the text in
/// \param[in] bg Color to render the background box in
///
/// \returns Surface containing rendered text
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC49
///
////////////////////////////////////////////////////////////
Surface RenderUNICODE_Shaded(const std::u16string& text, SDL_Color fg, SDL_Color bg);
////////////////////////////////////////////////////////////
/// \brief Render the glyph for UNICODE character using shaded mode
///
/// \param[in] ch UNICODE character to render
/// \param[in] fg Color to render the glyph in
/// \param[in] bg Color to render the background box in
///
/// \returns Surface containing rendered text
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC50
///
////////////////////////////////////////////////////////////
Surface RenderGlyph_Shaded(Uint16 ch, SDL_Color fg, SDL_Color bg);
///@}
///@{
/// \name Rendering: blended
////////////////////////////////////////////////////////////
/// \brief Render LATIN1 text using blended mode
///
/// \param[in] text LATIN1 string to render
/// \param[in] fg Color to render the text in
///
/// \returns Surface containing rendered text
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC51
///
////////////////////////////////////////////////////////////
Surface RenderText_Blended(const std::string& text, SDL_Color fg);
////////////////////////////////////////////////////////////
/// \brief Render UTF8 text using blended mode
///
/// \param[in] text UTF8 string to render
/// \param[in] fg Color to render the text in
///
/// \returns Surface containing rendered text
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC52
///
////////////////////////////////////////////////////////////
Surface RenderUTF8_Blended(const std::string& text, SDL_Color fg);
////////////////////////////////////////////////////////////
/// \brief Render UNICODE encoded text using blended mode
///
/// \param[in] text UNICODE encoded string to render
/// \param[in] fg Color to render the text in
///
/// \returns Surface containing rendered text
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC53
///
////////////////////////////////////////////////////////////
Surface RenderUNICODE_Blended(const Uint16* text, SDL_Color fg);
////////////////////////////////////////////////////////////
/// \brief Render UNICODE encoded text using blended mode
///
/// \param[in] text UNICODE encoded string to render
/// \param[in] fg Color to render the text in
///
/// \returns Surface containing rendered text
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC53
///
////////////////////////////////////////////////////////////
Surface RenderUNICODE_Blended(const std::u16string& text, SDL_Color fg);
////////////////////////////////////////////////////////////
/// \brief Render the glyph for UNICODE character using blended mode
///
/// \param[in] ch UNICODE character to render
/// \param[in] fg Color to render the glyph in
///
/// \returns Surface containing rendered text
///
/// \throws SDL2pp::Exception
///
/// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC54
///
////////////////////////////////////////////////////////////
Surface RenderGlyph_Blended(Uint16 ch, SDL_Color fg);
///@}
};
}
#endif
| 36.289316
| 117
| 0.553012
|
pdpdds
|
32ad881ee3d62285faa1035437facfee4bb8c9c5
| 4,859
|
cpp
|
C++
|
vislib/src/sys/Event.cpp
|
xge/megamol
|
1e298dd3d8b153d7468ed446f6b2ed3ac49f0d5b
|
[
"BSD-3-Clause"
] | 49
|
2017-08-23T13:24:24.000Z
|
2022-03-16T09:10:58.000Z
|
vislib/src/sys/Event.cpp
|
xge/megamol
|
1e298dd3d8b153d7468ed446f6b2ed3ac49f0d5b
|
[
"BSD-3-Clause"
] | 200
|
2018-07-20T15:18:26.000Z
|
2022-03-31T11:01:44.000Z
|
vislib/src/sys/Event.cpp
|
xge/megamol
|
1e298dd3d8b153d7468ed446f6b2ed3ac49f0d5b
|
[
"BSD-3-Clause"
] | 31
|
2017-07-31T16:19:29.000Z
|
2022-02-14T23:41:03.000Z
|
/*
* Event.cpp
*
* Copyright (C) 2006 - 2007 by Universitaet Stuttgart (VIS).
* Alle Rechte vorbehalten.
*/
#include "vislib/sys/Event.h"
#ifndef _WIN32
#include <climits>
#endif /* !_WIN32 */
#include "vislib/IllegalParamException.h"
#include "vislib/Trace.h"
#include "vislib/UnsupportedOperationException.h"
#include "vislib/assert.h"
#include "vislib/sys/SystemException.h"
#include "vislib/sys/error.h"
/*
* vislib::sys::Event::TIMEOUT_INFINITE
*/
#ifdef _WIN32
const DWORD vislib::sys::Event::TIMEOUT_INFINITE = INFINITE;
#else /* _WIN32 */
const DWORD vislib::sys::Event::TIMEOUT_INFINITE = UINT_MAX;
#endif /* _WIN32 */
/*
* vislib::sys::Event::Event
*/
vislib::sys::Event::Event(const bool isManualReset, const bool isInitiallySignaled)
#ifndef _WIN32
: isManualReset(isManualReset)
, semaphore(isInitiallySignaled ? 1 : 0, 1)
#endif /* _WIN32 */
{
#ifdef _WIN32
this->handle = ::CreateEventA(NULL, isManualReset ? TRUE : FALSE, isInitiallySignaled ? TRUE : FALSE, NULL);
ASSERT(this->handle != NULL);
#endif /* _WIN32 */
}
/*
* vislib::sys::Event::Event
*/
vislib::sys::Event::Event(const char* name, const bool isManualReset, const bool isInitiallySignaled, bool* outIsNew)
#ifndef _WIN32
: isManualReset(isManualReset)
, semaphore(name, isInitiallySignaled ? 1 : 0, 1, outIsNew)
#endif /* _WIN32 */
{
#ifdef _WIN32
if (outIsNew != NULL) {
*outIsNew = false;
}
/* Try to open existing event first. */
if ((this->handle = ::OpenEventA(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, name)) == NULL) {
this->handle = ::CreateEventA(NULL, isManualReset ? TRUE : FALSE, isInitiallySignaled ? TRUE : FALSE, name);
if (outIsNew != NULL) {
*outIsNew = true;
}
}
ASSERT(this->handle != NULL);
#endif /* _WIN32 */
}
/*
* vislib::sys::Event::Event
*/
vislib::sys::Event::Event(const wchar_t* name, const bool isManualReset, const bool isInitiallySignaled, bool* outIsNew)
#ifndef _WIN32
: isManualReset(isManualReset)
, semaphore(name, isInitiallySignaled ? 1 : 0, 1, outIsNew)
#endif /* _WIN32 */
{
#ifdef _WIN32
if (outIsNew != NULL) {
*outIsNew = false;
}
/* Try to open existing event first. */
if ((this->handle = ::OpenEventW(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, name)) == NULL) {
this->handle = ::CreateEventW(NULL, isManualReset ? TRUE : FALSE, isInitiallySignaled ? TRUE : FALSE, name);
if (outIsNew != NULL) {
*outIsNew = true;
}
}
ASSERT(this->handle != NULL);
#endif /* _WIN32 */
}
/*
* vislib::sys::Event::~Event
*/
vislib::sys::Event::~Event(void) {
#ifdef _WIN32
::CloseHandle(this->handle);
#else /* _WIN32 */
/* Nothing to do. */
#endif /* _WIN32 */
}
/*
* vislib::sys::Event::Reset
*/
void vislib::sys::Event::Reset(void) {
#ifdef _WIN32
if (!::ResetEvent(this->handle)) {
throw SystemException(__FILE__, __LINE__);
}
#else /* _WIN32 */
VLTRACE(vislib::Trace::LEVEL_VL_VERBOSE, "Event::Reset\n");
this->semaphore.TryLock();
ASSERT(!this->semaphore.TryLock());
#endif /* _WIN32 */
}
/*
* vislib::sys::Event::Set
*/
void vislib::sys::Event::Set(void) {
#ifdef _WIN32
if (!::SetEvent(this->handle)) {
throw SystemException(__FILE__, __LINE__);
}
#else /* _WIN32 */
VLTRACE(vislib::Trace::LEVEL_VL_VERBOSE, "Event::Set\n");
this->semaphore.TryLock();
this->semaphore.Unlock();
#endif /* _WIN32 */
}
/*
* vislib::sys::Event::Wait
*/
bool vislib::sys::Event::Wait(const DWORD timeout) {
#ifdef _WIN32
switch (::WaitForSingleObject(this->handle, timeout)) {
case WAIT_OBJECT_0:
/* falls through. */
case WAIT_ABANDONED:
return true;
/* Unreachable. */
case WAIT_TIMEOUT:
return false;
/* Unreachable. */
default:
throw SystemException(__FILE__, __LINE__);
/* Unreachable. */
}
#else /* _WIN32 */
VLTRACE(vislib::Trace::LEVEL_VL_VERBOSE, "Event::Wait\n");
bool retval = false;
if (timeout == TIMEOUT_INFINITE) {
this->semaphore.Lock();
retval = true;
} else {
retval = this->semaphore.TryLock(timeout);
}
if (retval && this->isManualReset) {
VLTRACE(vislib::Trace::LEVEL_VL_VERBOSE, "Event::Wait signal again\n");
this->semaphore.Unlock();
}
return retval;
#endif /* _WIN32 */
}
/*
* vislib::sys::Event::Event
*/
vislib::sys::Event::Event(const Event& rhs) {
throw UnsupportedOperationException("vislib::sys::Event::Event", __FILE__, __LINE__);
}
/*
* vislib::sys::Event::operator =
*/
vislib::sys::Event& vislib::sys::Event::operator=(const Event& rhs) {
if (this != &rhs) {
throw IllegalParamException("rhs", __FILE__, __LINE__);
}
return *this;
}
| 22.705607
| 120
| 0.626878
|
xge
|
32af2514e1ead7564365cb478f275cf7c2ea948a
| 2,664
|
hpp
|
C++
|
src/FclEx.DataStructuresCpp/Iterator.hpp
|
huoshan12345/FxUtility.DataStructures
|
cdad625154407c381ec0b5d1003cc7eabc37e829
|
[
"MIT"
] | 1
|
2017-04-30T21:12:55.000Z
|
2017-04-30T21:12:55.000Z
|
src/FclEx.DataStructuresCpp/Iterator.hpp
|
huoshan12345/FxUtility.DataStructures
|
cdad625154407c381ec0b5d1003cc7eabc37e829
|
[
"MIT"
] | null | null | null |
src/FclEx.DataStructuresCpp/Iterator.hpp
|
huoshan12345/FxUtility.DataStructures
|
cdad625154407c381ec0b5d1003cc7eabc37e829
|
[
"MIT"
] | 1
|
2018-10-04T23:54:26.000Z
|
2018-10-04T23:54:26.000Z
|
#pragma once
#include <iterator>
namespace FclEx
{
namespace Node
{
using namespace std;
template <class Node, class IteratorType>
class Iterator : public iterator<forward_iterator_tag,
typename Node::value_type,
typename Node::difference_type,
typename Node::pointer,
typename Node::reference>
{
public:
typedef Node node_type;
typedef typename node_type::BaseNode BaseNode;
typedef typename BaseNode::allocator_type allocator_type;
typedef typename BaseNode::difference_type difference_type;
typedef typename BaseNode::reference reference;
typedef typename BaseNode::const_reference const_reference;
typedef typename BaseNode::pointer pointer;
typedef typename BaseNode::const_pointer const_pointer;
typedef IteratorType self_type;
explicit Iterator(node_type *node) :_pNode(node) { }
virtual ~Iterator() { }
virtual self_type &operator++() = 0;
virtual self_type operator++(int) = 0;
reference operator*()
{
return _pNode->Item;
}
pointer operator->()
{
return &_pNode->Item;
}
bool operator==(const self_type &other) const
{
return _pNode == other._pNode;
}
bool operator!=(const self_type &other) const
{
return !operator==(other);
}
protected:
node_type *_pNode;
};
template <class Node, class IteratorType>
class ConstIterator : public iterator<forward_iterator_tag,
typename Node::value_type,
typename Node::difference_type,
typename Node::const_pointer,
typename Node::const_reference>
{
public:
typedef Node node_type;
typedef typename node_type::BaseNode BaseNode;
typedef typename BaseNode::allocator_type allocator_type;
typedef typename BaseNode::difference_type difference_type;
typedef typename BaseNode::reference reference;
typedef typename BaseNode::const_reference const_reference;
typedef typename BaseNode::pointer pointer;
typedef typename BaseNode::const_pointer const_pointer;
typedef IteratorType self_type;
explicit ConstIterator(const node_type *node) :_pNode(node) { }
virtual ~ConstIterator() { }
virtual self_type &operator++() const = 0;
virtual self_type operator++(int) const = 0;
const_reference operator*() const
{
return _pNode->Item;
}
const_pointer operator->() const
{
return &_pNode->Item;
}
bool operator==(const self_type &other) const
{
return _pNode == other._pNode;
}
bool operator!=(const self_type &other) const
{
return !operator==(other);
}
protected:
node_type *_pNode;
};
}
}
| 23.368421
| 66
| 0.693318
|
huoshan12345
|
32b8be4744f527e8ea9b3c385237a08e8bfb3967
| 1,140
|
hpp
|
C++
|
qtswarmtv/seasonepisodewidget.hpp
|
annejan/swarmtv
|
847d82114d1ee2338d37be314a222e386849aad1
|
[
"Unlicense"
] | 1
|
2019-07-10T10:33:23.000Z
|
2019-07-10T10:33:23.000Z
|
qtswarmtv/seasonepisodewidget.hpp
|
annejan/swarmtv
|
847d82114d1ee2338d37be314a222e386849aad1
|
[
"Unlicense"
] | null | null | null |
qtswarmtv/seasonepisodewidget.hpp
|
annejan/swarmtv
|
847d82114d1ee2338d37be314a222e386849aad1
|
[
"Unlicense"
] | null | null | null |
#ifndef SEASONEPISODEWIDGET_HPP
#define SEASONEPISODEWIDGET_HPP
#include <QDialog>
extern "C" {
#include <tvdb.h>
}
#include <QTreeWidget>
#include <taskqueue.hpp>
class episodeInfoWidget;
namespace Ui {
class seasonEpisodeWidget;
}
class seasonEpisodeWidget : public QDialog
{
Q_OBJECT
public:
explicit seasonEpisodeWidget(QWidget *parent = 0);
~seasonEpisodeWidget();
void setSeriesTitle(QString &name);
void setSeriesId(int id);
void setrieveEpisodeData();
void fillListView(tvdb_list_front_t *);
void retrieveEpisodeData();
public slots:
// GUI signals
void itemExpanded(QTreeWidgetItem *item);
void itemDoubleClicked(QTreeWidgetItem *item, int column);
// Task signals
void seriesResults(tvdb_buffer_t *series_xml);
void seriesFailed();
private:
void addTask(episodeInfoWidget *widget);
QTreeWidgetItem *addSeasonEntry(int seasonNum);
void addEpisodeEntry(QTreeWidgetItem *season, tvdb_series_info_t *s);
Ui::seasonEpisodeWidget *ui;
QString seriesName;
int seriesId;
taskQueue tc;
htvdb_t tvdb;
};
#endif // SEASONEPISODEWIDGET_HPP
| 21.923077
| 73
| 0.735088
|
annejan
|
32c1d7608b90688b8218d44771897257de20408b
| 950
|
cpp
|
C++
|
module-os/test/performance-monitor.cpp
|
buk7456/MuditaOS
|
06ef1e131b27b0f397cc615c96d51bede7050423
|
[
"BSL-1.0"
] | 369
|
2021-11-10T09:20:29.000Z
|
2022-03-30T06:36:58.000Z
|
module-os/test/performance-monitor.cpp
|
buk7456/MuditaOS
|
06ef1e131b27b0f397cc615c96d51bede7050423
|
[
"BSL-1.0"
] | 149
|
2021-11-10T08:38:35.000Z
|
2022-03-31T23:01:52.000Z
|
module-os/test/performance-monitor.cpp
|
buk7456/MuditaOS
|
06ef1e131b27b0f397cc615c96d51bede7050423
|
[
"BSL-1.0"
] | 41
|
2021-11-10T08:30:37.000Z
|
2022-03-29T08:12:46.000Z
|
#include <limits>
#define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
#include "prof.h"
TEST_CASE("prof api test")
{
struct prof_pool_init_data init{0};
prof_pool_init(init);
auto pp = prof_pool_get_data();
REQUIRE(pp.size == 0);
prof_pool_deinit();
}
TEST_CASE("overflow")
{
struct prof_pool_init_data init
{
0
};
prof_pool_init(init);
prof_pool_data_set(0,-1);
REQUIRE(prof_pool_overflow() == 1);
prof_pool_deinit();
}
TEST_CASE("prof api sum")
{
struct prof_pool_init_data init{1};
prof_pool_init(init);
auto pp = prof_pool_get_data();
REQUIRE(pp.size == 1);
const auto switches = 10;
const auto ts = 10;
for (auto i =0; i < switches ; ++i)
{
prof_pool_data_set(0,ts);
}
task_prof_data mem[1];
prof_pool_flush(mem, 1);
REQUIRE(mem->switches == switches);
REQUIRE(mem->exec_time == switches*ts);
prof_pool_deinit();
}
| 19
| 43
| 0.634737
|
buk7456
|
32c3cfe9fde5934fbf1e7fe0fb4d14f8c78085aa
| 595
|
hpp
|
C++
|
paper/config.hpp
|
williamstarkro/paper
|
13266b83b3922fc146cba1eecedac5a9addf6f2a
|
[
"BSD-2-Clause"
] | null | null | null |
paper/config.hpp
|
williamstarkro/paper
|
13266b83b3922fc146cba1eecedac5a9addf6f2a
|
[
"BSD-2-Clause"
] | null | null | null |
paper/config.hpp
|
williamstarkro/paper
|
13266b83b3922fc146cba1eecedac5a9addf6f2a
|
[
"BSD-2-Clause"
] | null | null | null |
#pragma once
#include <chrono>
#include <cstddef>
namespace paper
{
// Network variants with different genesis blocks and network parameters
enum class paper_networks
{
// Low work parameters, publicly known genesis key, test IP ports
paper_test_network,
// Normal work parameters, secret beta genesis key, beta IP ports
paper_beta_network,
// Normal work parameters, secret live key, live IP ports
paper_live_network
};
paper::paper_networks const paper_network = paper_networks::ACTIVE_NETWORK;
std::chrono::milliseconds const transaction_timeout = std::chrono::milliseconds (1000);
}
| 28.333333
| 87
| 0.789916
|
williamstarkro
|
32c420a5625bb5fe7b614a2677917e7e88ea0cb8
| 1,504
|
cpp
|
C++
|
src/MetaAuthoringTool/VRCAT.Wrapper/MRigidMeshComponent.cpp
|
phs008/PrismSolution
|
ea2452ef98bdd18216f3947dd0cb5483e2e2a079
|
[
"MIT"
] | null | null | null |
src/MetaAuthoringTool/VRCAT.Wrapper/MRigidMeshComponent.cpp
|
phs008/PrismSolution
|
ea2452ef98bdd18216f3947dd0cb5483e2e2a079
|
[
"MIT"
] | null | null | null |
src/MetaAuthoringTool/VRCAT.Wrapper/MRigidMeshComponent.cpp
|
phs008/PrismSolution
|
ea2452ef98bdd18216f3947dd0cb5483e2e2a079
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#include "MRigidMeshComponent.h"
#include <Resource/ResourcePath.h>
namespace MVRWrapper
{
MRigidMeshComponent::MRigidMeshComponent()
:MContainerComponent(ComponentEnum::RigidMesh)
{
_pRigidMesh = this->GetNative();
this->setMesh();
}
MRigidMeshComponent::MRigidMeshComponent(Code3::Component::ContainerComponent* _containerComponent)
:MContainerComponent(_containerComponent)
{
_pRigidMesh = this->GetNative();
this->setMesh();
}
Code3::Scene::RigidMesh* MRigidMeshComponent::GetNative()
{
return MContainerComponent::GetNative<Code3::Scene::RigidMesh>();
}
void MRigidMeshComponent::setMaterial(System::String^ matFile)
{
InternString path = MarshalHelper::StringToNativeString(matFile);
Code3::FileIO::Path p;
p.SetAbsolutePath(path);
if (p.MakeRelativePath(&Code3::Resource::GetResourcePath().ResourceFolder))
{
_pRigidMesh->PropRigidMesh.Material.Value = p;
_pRigidMesh->PropRigidMesh.Apply();
//_pRigidMesh->PropRigidMesh.MeshDraw.ResBuffer.Instance->ResMaterial.Instance->SaveToFile(p);
/*_pRigidMesh->PropRigidMesh.MeshDraw.ResBuffer.Instance->ResMaterial.Instance->SaveToFile(
_pRigidMesh->PropRigidMesh.MeshDraw.ResBuffer.Instance->ResMaterial.Instance->SourceFile);*/
}
//_pRigidMesh->PropRigidMesh.Apply();
}
void MRigidMeshComponent::setMesh()
{
_pRigidMesh->PropRigidMesh.Mesh.Value.SetRelativePath(Code3::BasicType::InternString("program"), "<sphere>1.0x30x30");
_pRigidMesh->PropRigidMesh.Apply();
}
}
| 32.695652
| 120
| 0.767952
|
phs008
|
32ca60aa7761e1341b0036ffae7c4dcf4c6f845d
| 1,224
|
cpp
|
C++
|
Engine/Source/Runtime/Renderer/Components/Buffers.cpp
|
1992please/NullEngine
|
8f5f124e9718b8d6627992bb309cf0f0d106d07a
|
[
"Apache-2.0"
] | null | null | null |
Engine/Source/Runtime/Renderer/Components/Buffers.cpp
|
1992please/NullEngine
|
8f5f124e9718b8d6627992bb309cf0f0d106d07a
|
[
"Apache-2.0"
] | null | null | null |
Engine/Source/Runtime/Renderer/Components/Buffers.cpp
|
1992please/NullEngine
|
8f5f124e9718b8d6627992bb309cf0f0d106d07a
|
[
"Apache-2.0"
] | null | null | null |
#include "NullPCH.h"
#include "Buffers.h"
#include "Platform/OpenGL/OpenGLBuffers.h"
#include "Renderer/Components/RendererAPI.h"
IVertexBuffer* IVertexBuffer::Create(float* InVertices, uint32 InSize)
{
switch (IRendererAPI::GetAPI())
{
case IRendererAPI::Type_None: NE_CHECK_F(false, "None Renderer API is not implemented yet."); return nullptr;
case IRendererAPI::Type_OpenGL: return new FOpenGLVertexBuffer(InVertices, InSize);
}
NE_CHECK_F(false, "Unknown Renderer API!!");
return nullptr;
}
IVertexBuffer* IVertexBuffer::Create(uint32 InSize)
{
switch (IRendererAPI::GetAPI())
{
case IRendererAPI::Type_None: NE_CHECK_F(false, "None Renderer API is not implemented yet."); return nullptr;
case IRendererAPI::Type_OpenGL: return new FOpenGLVertexBuffer(InSize);
}
NE_CHECK_F(false, "Unknown Renderer API!!");
return nullptr;
}
IIndexBuffer* IIndexBuffer::Create(uint32* InIndices, uint32 InCount)
{
switch (IRendererAPI::GetAPI())
{
case IRendererAPI::Type_None: NE_CHECK_F(false, "None Renderer API is not implemented yet."); return nullptr;
case IRendererAPI::Type_OpenGL: return new FOpenGLIndexBuffer(InIndices, InCount);
}
NE_CHECK_F(false, "Unknown Renderer API!!");
return nullptr;
}
| 33.081081
| 111
| 0.764706
|
1992please
|
32ce8492fa335e90ecf599e30210a90e42ff8f14
| 877
|
cpp
|
C++
|
src/TestInput.cpp
|
dublet/KARR
|
4b14090b34dab4d8be4e28814cb4d58cd34639ac
|
[
"BSD-3-Clause"
] | null | null | null |
src/TestInput.cpp
|
dublet/KARR
|
4b14090b34dab4d8be4e28814cb4d58cd34639ac
|
[
"BSD-3-Clause"
] | null | null | null |
src/TestInput.cpp
|
dublet/KARR
|
4b14090b34dab4d8be4e28814cb4d58cd34639ac
|
[
"BSD-3-Clause"
] | null | null | null |
#include "TestInput.h"
#include <thread>
#include <time.h>
#include "Status.h"
#include "CarDefinition.h"
using namespace KARR;
void generateTestData() {
Status &s = Status::instance();
struct timespec sleepTime;
sleepTime.tv_sec = 0;
sleepTime.tv_nsec = 20 * 1000 * 1000;
int rpmDirection = 1;
int speedDirection = 1;
for (;;) {
if (s.getRpm() >= StaticCarDefinition::revs.max)
rpmDirection = -1;
if (s.getRpm() == StaticCarDefinition::revs.min)
rpmDirection = 1;
if (s.getSpeed() >= StaticCarDefinition::speed.max)
speedDirection = -1;
if (s.getSpeed() == StaticCarDefinition::speed.min)
speedDirection = 1;
s.setRpm(s.getRpm() + rpmDirection);
s.setSpeed(s.getSpeed() + speedDirection);
nanosleep(&sleepTime, NULL);
}
}
void TestInput::run() {
std::thread tt(generateTestData);
tt.detach();
}
| 19.488889
| 52
| 0.651083
|
dublet
|
77f78d34dea4f79dffd4b2dbf25953ac52db750d
| 7,085
|
cpp
|
C++
|
Source/ModuleTrails.cpp
|
JellyBitStudios/JellyBitEngine
|
4b975a50bb1934dfdbdf72e0c96c53a713e6cfa4
|
[
"MIT"
] | 10
|
2019-02-05T07:57:21.000Z
|
2021-10-17T13:44:31.000Z
|
Source/ModuleTrails.cpp
|
JellyBitStudios/JellyBitEngine
|
4b975a50bb1934dfdbdf72e0c96c53a713e6cfa4
|
[
"MIT"
] | 178
|
2019-02-26T17:29:08.000Z
|
2019-06-05T10:55:42.000Z
|
Source/ModuleTrails.cpp
|
JellyBitStudios/JellyBitEngine
|
4b975a50bb1934dfdbdf72e0c96c53a713e6cfa4
|
[
"MIT"
] | 2
|
2020-02-27T18:57:27.000Z
|
2020-05-28T01:19:59.000Z
|
#include "ModuleTrails.h"
#include "ModuleTimeManager.h"
#include "ModuleInput.h"
#include "ModuleResourceManager.h"
#include "ModuleRenderer3D.h"
#include "ModuleInternalResHandler.h"
#include "ResourceMaterial.h"
#include "ResourceShaderObject.h"
#include "ResourceShaderProgram.h"
#include "ResourceMesh.h"
#include "Optick/include/optick.h"
#include <algorithm>
#include "MathGeoLib/include/Math/float4x4.h"
#include "Application.h"
#include "DebugDrawer.h"
#include "ComponentTransform.h"
#include "GLCache.h"
#include "glew/include/GL/glew.h"
ModuleTrails::ModuleTrails(bool start_enabled) : Module(start_enabled)
{}
ModuleTrails::~ModuleTrails()
{
trails.clear();
}
update_status ModuleTrails::PostUpdate()
{
#ifndef GAMEMODE
OPTICK_CATEGORY("ModuleTrails_PostUpdate", Optick::Category::VFX);
#endif // !GAMEMODE
for (std::list<ComponentTrail*>::iterator trail = trails.begin(); trail != trails.end(); ++trail)
{
(*trail)->Update();
}
return UPDATE_CONTINUE;
}
void ModuleTrails::Draw()
{
#ifndef GAMEMODE
OPTICK_CATEGORY("ModuleTrails_Draw", Optick::Category::VFX);
#endif // !GAMEMODE
for (std::list<ComponentTrail*>::iterator trail = trails.begin(); trail != trails.end(); ++trail)
{
if (!(*trail)->trailVertex.empty())
{
if ((*trail)->materialRes == 0) continue;
std::list<TrailNode*>::iterator begin = (*trail)->trailVertex.begin();
TrailNode* end = (*trail)->trailVertex.back();
float i = 0.0f;
float size = (*trail)->trailVertex.size() + 1;
for (std::list<TrailNode*>::iterator curr = (*trail)->trailVertex.begin(); curr != (*trail)->trailVertex.end(); ++curr)
{
i++;
std::list<TrailNode*>::iterator next = curr;
++next;
if (next != (*trail)->trailVertex.end())
{
ResourceMaterial* resourceMaterial = (ResourceMaterial*)App->res->GetResource((*trail)->materialRes);
uint shaderUuid = resourceMaterial->GetShaderUuid();
ResourceShaderProgram* resourceShaderProgram = (ResourceShaderProgram*)App->res->GetResource(shaderUuid);
GLuint shaderProgram = resourceShaderProgram->shaderProgram;
App->glCache->SwitchShader(shaderProgram);
math::float4x4 model_matrix = math::float4x4::identity;// particle matrix
model_matrix = model_matrix.Transposed();
math::float4x4 mvp_matrix = model_matrix * App->renderer3D->viewProj_matrix;
math::float4x4 normal_matrix = model_matrix;
normal_matrix.Inverse();
normal_matrix.Transpose();
uint location = glGetUniformLocation(shaderProgram, "model_matrix");
glUniformMatrix4fv(location, 1, GL_FALSE, model_matrix.ptr());
location = glGetUniformLocation(shaderProgram, "mvp_matrix");
glUniformMatrix4fv(location, 1, GL_FALSE, mvp_matrix.ptr());
location = glGetUniformLocation(shaderProgram, "normal_matrix");
glUniformMatrix3fv(location, 1, GL_FALSE, normal_matrix.Float3x3Part().ptr());
float currUV = (float(i) / size);
float nextUV = (float(i + 1) / size);
math::float3 originHigh = (*curr)->originHigh;
math::float3 originLow = (*curr)->originLow;
math::float3 destinationHigh = (*next)->originHigh;
math::float3 destinationLow = (*next)->originLow;
if ((*trail)->orient)
RearrangeVertex(trail, curr, next, currUV, nextUV, originHigh, originLow, destinationHigh, destinationLow);
location = glGetUniformLocation(shaderProgram, "currUV"); // cUV
glUniform1f(location, currUV);
location = glGetUniformLocation(shaderProgram, "nextUV"); // cUV
glUniform1f(location, nextUV);
location = glGetUniformLocation(shaderProgram, "realColor"); // Color
glUniform4f(location, (*trail)->color.x, (*trail)->color.y, (*trail)->color.z, (*trail)->color.w);
location = glGetUniformLocation(shaderProgram, "vertex1"); // Current High
glUniform3f(location, originHigh.x, originHigh.y, originHigh.z);
location = glGetUniformLocation(shaderProgram, "vertex2"); // Current Low
glUniform3f(location, originLow.x, originLow.y, originLow.z);
location = glGetUniformLocation(shaderProgram, "vertex3"); // Next High
glUniform3f(location, destinationHigh.x, destinationHigh.y, destinationHigh.z);
location = glGetUniformLocation(shaderProgram, "vertex4"); // Next Low
glUniform3f(location, destinationLow.x, destinationLow.y, destinationLow.z);
// Unknown uniforms
uint textureUnit = 0;
std::vector<Uniform> uniforms = resourceMaterial->GetUniforms();
for (uint i = 0; i < uniforms.size(); ++i)
{
Uniform uniform = uniforms[i];
if (strcmp(uniform.common.name, "material.albedo") == 0 || strcmp(uniform.common.name, "material.specular") == 0)
{
if (textureUnit < App->renderer3D->GetMaxTextureUnits())
{
glActiveTexture(GL_TEXTURE0 + textureUnit);
glBindTexture(GL_TEXTURE_2D, uniform.sampler2DU.value.id);
glUniform1i(uniform.common.location, textureUnit);
++textureUnit;
}
}
}
ResourceMesh* plane = (ResourceMesh*)App->res->GetResource(App->resHandler->plane);
glBindVertexArray(plane->GetVAO());
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, plane->GetIBO());
glDrawElements(GL_TRIANGLES, plane->GetIndicesCount(), GL_UNSIGNED_INT, NULL);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
}
// TODO: THIS IS USELESS I THINK
glEnd();
glPopMatrix();
}
}
}
void ModuleTrails::RearrangeVertex(std::list<ComponentTrail *>::iterator &trail, std::list<TrailNode *>::iterator &curr, std::list<TrailNode *>::iterator &next, float &currUV, float &nextUV, math::float3 &originHigh, math::float3 &originLow, math::float3 &destinationHigh, math::float3 &destinationLow)
{
// Rearrange vertex
float origin = 0;
float dest = 0;
GetOriginAndDest(trail, origin, curr, dest, next);
if (origin < dest)
{
float tmp = currUV;
currUV = nextUV;
nextUV = tmp;
math::float3 tmph = originHigh;
math::float3 tmpl = originLow;
originHigh = destinationHigh;
originLow = destinationLow;
destinationHigh = tmph;
destinationLow = tmpl;
}
}
void ModuleTrails::GetOriginAndDest(std::list<ComponentTrail *>::iterator &trail, float &origin, std::list<TrailNode *>::iterator &curr, float &dest, std::list<TrailNode *>::iterator &next)
{
switch ((*trail)->vector)
{
case X:
origin = (*curr)->originHigh.x;
dest = (*next)->originHigh.x;
break;
case Y:
// This is not right
origin = (*curr)->originHigh.x;
dest = (*next)->originHigh.x;
break;
case Z:
dest = (*curr)->originHigh.z;
origin = (*next)->originHigh.z;
break;
default:
break;
}
}
void ModuleTrails::DebugDraw() const
{
// Todo
}
void ModuleTrails::OnSystemEvent(System_Event event)
{
switch (event.type)
{
case System_Event_Type::Play:
case System_Event_Type::LoadFinished:
// Todo
break;
case System_Event_Type::Stop:
// Todo
break;
}
}
void ModuleTrails::RemoveTrail(ComponentTrail* trail)
{
trails.remove(trail);
}
| 29.894515
| 302
| 0.692449
|
JellyBitStudios
|
77f9ee909641a70f1d118cd6b3981bf2d3afbb95
| 821
|
cpp
|
C++
|
src/main.cpp
|
Maou-Shimazu/Operation-Cpp
|
17398c92b7e64bcabe0d597efc8b01cd724e692b
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
Maou-Shimazu/Operation-Cpp
|
17398c92b7e64bcabe0d597efc8b01cd724e692b
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
Maou-Shimazu/Operation-Cpp
|
17398c92b7e64bcabe0d597efc8b01cd724e692b
|
[
"MIT"
] | null | null | null |
#include <fstream>
#include <iostream>
#include <src/format.cc>
#include <fmt/core.h>
#include <parse_args.h>
#include "../include/prompts.hpp"
#include "loopTerminal.cpp"
#include "../include/argCheck.hpp"
using namespace arguments;
// todo: impliment directory check for program run in directory
void welcomeInfo(){}
int main(int argc, char *argv[]) {
ParseArgs parse = ParseArgs(argc, argv);
if (parse.ParseSelf()){
std::cout << prompt::welcome << std::endl;
prompt::loopInformation();
}
TerminalHandler terminal;
if (parse.DefaultParse("watch")) {
std::cout << "Welcome to watch mode! You can type 'help' to get an overview of the commands you can use here." << std::endl;
terminal.WatchMode();
}
if (parse.DefaultParse("help")) {
fmt::print(prompt::help);
}
return 0;
}
| 24.147059
| 128
| 0.677223
|
Maou-Shimazu
|
77faa89d81a4b36dab95fe24f37377da962077a4
| 297
|
cpp
|
C++
|
Porblems/bear_and_big_brother.cpp
|
ashish-ad/CPP-STL-Practice-and-Cp
|
ca8a112096ad96ed1abccddc9e99b1ead5cf522b
|
[
"Unlicense"
] | null | null | null |
Porblems/bear_and_big_brother.cpp
|
ashish-ad/CPP-STL-Practice-and-Cp
|
ca8a112096ad96ed1abccddc9e99b1ead5cf522b
|
[
"Unlicense"
] | null | null | null |
Porblems/bear_and_big_brother.cpp
|
ashish-ad/CPP-STL-Practice-and-Cp
|
ca8a112096ad96ed1abccddc9e99b1ead5cf522b
|
[
"Unlicense"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
int main(){
int limak,bob;
cin>>limak>>bob;
int i=1;
while(1){
limak=limak*3;
bob=bob*2;
if (limak>bob){
cout<<i<<endl;
break;
}
else{
i++;
}
}
}
| 14.85
| 26
| 0.40404
|
ashish-ad
|
77feeab069b3c47765e14808dc6d98b57875f0db
| 4,277
|
cpp
|
C++
|
AtCoder/typical90/029 - Long Bricks/main.cpp
|
t-mochizuki/cpp-study
|
df0409c2e82d154332cb2424c7810370aa9822f9
|
[
"MIT"
] | 1
|
2020-05-24T02:27:05.000Z
|
2020-05-24T02:27:05.000Z
|
AtCoder/typical90/029 - Long Bricks/main.cpp
|
t-mochizuki/cpp-study
|
df0409c2e82d154332cb2424c7810370aa9822f9
|
[
"MIT"
] | null | null | null |
AtCoder/typical90/029 - Long Bricks/main.cpp
|
t-mochizuki/cpp-study
|
df0409c2e82d154332cb2424c7810370aa9822f9
|
[
"MIT"
] | null | null | null |
// g++ -std=c++14 -DDEV=1 main.cpp
#include <stdio.h>
#include <cassert>
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <map>
using std::cin;
using std::cout;
using std::endl;
using std::terminate;
using std::vector;
using std::max;
using std::sort;
using std::map;
using std::make_pair;
// キーワード: 「座標圧縮」で効率化
//
// キーワード: 区間に対する処理は「セグメント木」
#define rep(i, a, n) for (int i = (a); i < (n); ++i)
#define bit(n, k) ((n >> k) & 1)
const long VALUE = 0;
class RangeUpdateQuery {
private:
int M = 1;
int N;
vector<long> value, lazy;
int parent(int i) {
return (i - 1) / 2;
}
int left(int i) {
return 2 * i + 1;
}
int right(int i) {
return 2 * i + 2;
}
void eval(int i) {
if (lazy[i] == VALUE) return ;
if (i < M - 1) {
lazy[left(i)] = lazy[i];
lazy[right(i)] = lazy[i];
}
value[i] = lazy[i];
lazy[i] = VALUE;
}
long find(int lhs, int rhs, int i, int L, int R) {
assert(i < N);
assert(i >= 0);
eval(i);
int ret = VALUE;
if (rhs <= L || R <= lhs) {
ret = VALUE;
} else if (lhs <= L && R <= rhs) {
ret = value[i];
} else {
long lv = find(lhs, rhs, left(i), L, (L + R) / 2);
long rv = find(lhs, rhs, right(i), (L + R) / 2, R);
ret = max(lv, rv);
}
return ret;
}
void update(long x, int lhs, int rhs, int i, int L, int R) {
assert(i < N);
assert(i >= 0);
eval(i);
if (rhs <= L || R <= lhs) {
} else if (lhs <= L && R <= rhs) {
lazy[i] = x;
eval(i);
} else {
update(x, lhs, rhs, left(i), L, (L + R) / 2);
update(x, lhs, rhs, right(i), (L + R) / 2, R);
value[i] = max(value[left(i)], value[right(i)]);
}
}
public:
RangeUpdateQuery(int len) {
while (M < len) {
M *= 2;
}
N = 2 * M - 1;
value.assign(N, VALUE);
lazy.assign(N, VALUE);
}
long find(int lhs, int rhs) {
int root = 0; // 葉の数はM、区間は[0, M)
return find(lhs, rhs, root, 0, M);
}
void update(long x, int lhs, int rhs) {
int root = 0; // 葉の数はM、区間は[0, M)
return update(x, lhs, rhs, root, 0, M);
}
};
class Problem {
private:
int W, N;
vector<int> L, R;
map<int, int> zip;
public:
Problem() {
cin >> W >> N;
assert(2 <= W);
assert(W <= 500000);
assert(1 <= N);
assert(N <= 250000);
L.resize(N);
R.resize(N);
rep(i, 0, N) {
cin >> L[i] >> R[i];
assert(1 <= L[i]);
assert(W >= L[i]);
assert(1 <= R[i]);
assert(W >= R[i]);
assert(L[i] <= R[i]);
}
rep(i, 0, N) {
if (zip.find(L[i]) == zip.end()) {
zip.insert(make_pair(L[i], 1));
}
if (zip.find(R[i]) == zip.end()) {
zip.insert(make_pair(R[i], 1));
}
}
int num = 1;
for (auto it = zip.begin(); it != zip.end(); ++it) {
it->second = num;
num++;
}
}
void fullSearch() {
vector<int> height;
height.assign(W+1, 0);
rep(i, 0, N) {
int maximum = 0;
rep(j, zip[L[i]], zip[R[i]]+1) {
maximum = max(height[j], maximum);
}
maximum++;
cout << maximum << endl;
rep(j, zip[L[i]], zip[R[i]]+1) height[j] = maximum;
}
}
void solve() {
vector<int> height;
height.assign(W+1, 0);
RangeUpdateQuery tree(zip.size()+5);
rep(i, 0, N) {
long x = tree.find(zip[L[i]], zip[R[i]]+1);
x++;
cout << x << endl;
tree.update(x, zip[L[i]], zip[R[i]]+1);
}
}
};
int main() {
#ifdef DEV
std::ifstream in("input");
cin.rdbuf(in.rdbuf());
int t; cin >> t;
for (int x = 1; x <= t; ++x) {
Problem p;
p.solve();
}
#else
Problem p;
p.solve();
#endif
return 0;
}
| 19.619266
| 64
| 0.416647
|
t-mochizuki
|
77fef9ca7e9b463b12918ccca0581b7399ccd45d
| 1,077
|
hpp
|
C++
|
camera/DumpProfile.hpp
|
flexibity-team/boost-tools
|
a6c67eacf7374136f9903680308334fc3408ba91
|
[
"MIT"
] | null | null | null |
camera/DumpProfile.hpp
|
flexibity-team/boost-tools
|
a6c67eacf7374136f9903680308334fc3408ba91
|
[
"MIT"
] | null | null | null |
camera/DumpProfile.hpp
|
flexibity-team/boost-tools
|
a6c67eacf7374136f9903680308334fc3408ba91
|
[
"MIT"
] | 2
|
2019-12-26T13:54:29.000Z
|
2020-10-31T10:19:13.000Z
|
#ifndef DUMBPROFILE_H_
#define DUMBPROFILE_H_
#include <sys/time.h>
#include <stdint.h>
#include <string.h>
#define DPROFILE dumb_profile dprf = dumb_profile(__FUNCTION__, __LINE__); dprf.start();
struct dumb_profile{
struct timeval start_;
struct timeval end_;
const char* fname_;
const uint32_t lnum_;
dumb_profile(const char* fname, const uint32_t lnum): start_(), end_(), fname_(fname), lnum_(lnum){
//start();
}
~dumb_profile(){
stop();
}
void start(){
gettimeofday(&start_, 0);
}
void stop(){
print();
memset(&start_, 0, sizeof(start_));
memset(&end_, 0, sizeof(end_));
}
int64_t started(){
return timeval_to_ms(start_);
}
int64_t timeval_to_ms(struct timeval& tv){
return (tv.tv_sec * 1000000) + tv.tv_usec;
}
void print(){
gettimeofday(&end_, 0);
//uint32_t now_ms = end_.;
int32_t delta = ((end_.tv_sec - start_.tv_sec) * 1000000) + end_.tv_usec - start_.tv_usec;
// printf("profile: %s:%d: now:%03li:04%li elapsed:%d us\n", fname_, lnum_, end_.tv_sec, end_.tv_usec / 1000 , delta);
}
};
#endif //DUMBPROFILE_H_
| 19.944444
| 119
| 0.679666
|
flexibity-team
|
ae033e4d44777869c7554d7e250a1ce42554f400
| 47,761
|
cpp
|
C++
|
source/D2Common/src/DataTbls/SequenceTbls.cpp
|
raumuongluoc/D2MOO
|
169de1bd24151cda4c654ef0f8027896a14552ec
|
[
"MIT"
] | 1
|
2022-03-20T12:12:15.000Z
|
2022-03-20T12:12:15.000Z
|
source/D2Common/src/DataTbls/SequenceTbls.cpp
|
raumuongluoc/D2MOO
|
169de1bd24151cda4c654ef0f8027896a14552ec
|
[
"MIT"
] | null | null | null |
source/D2Common/src/DataTbls/SequenceTbls.cpp
|
raumuongluoc/D2MOO
|
169de1bd24151cda4c654ef0f8027896a14552ec
|
[
"MIT"
] | 1
|
2022-03-20T12:12:18.000Z
|
2022-03-20T12:12:18.000Z
|
#include <D2DataTbls.h>
#include <DataTbls/SequenceTbls.h>
#include <D2BitManip.h>
#include <Units/Units.h>
#include <D2Skills.h>
#include <D2Composit.h>
//D2Common.0x6FDDE6A8
D2MonSeqTxt gPlayerSequenceHandToHand1[13] =
{
{ 0, PLRMODE_ATTACK1, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDE6F8
D2MonSeqTxt gPlayerSequenceHandToHand2[14] =
{
{ 0, PLRMODE_ATTACK1, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDE750
D2MonSeqTxt gPlayerSequenceJab_BOW[18] =
{
{ 0, PLRMODE_ATTACK1, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_PLAY_SOUND },
{ 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 6, 0, MONSEQ_EVENT_PLAY_SOUND },
{ 0, PLRMODE_ATTACK2, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 9, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 6, 0, MONSEQ_EVENT_PLAY_SOUND },
{ 0, PLRMODE_ATTACK2, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 9, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK2, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 13, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDE7C0
D2MonSeqTxt gPlayerSequenceJab_1HS[21] =
{
{ 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_PLAY_SOUND },
{ 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 15, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 6, 0, MONSEQ_EVENT_PLAY_SOUND },
{ 0, PLRMODE_ATTACK2, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 10, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 15, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 6, 0, MONSEQ_EVENT_PLAY_SOUND },
{ 0, PLRMODE_ATTACK2, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 10, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK2, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 15, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDE840
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceJab =
{
gPlayerSequenceHandToHand1, 13, 13,
gPlayerSequenceJab_BOW, 18, 18,
gPlayerSequenceJab_1HS, 21, 21,
};
//D2Common.0x6FDDE8E8
D2MonSeqTxt gPlayerSequenceSacrifice_1HT[7] =
{
{ 0, PLRMODE_ATTACK2, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 7, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK2, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 13, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDE914
D2MonSeqTxt gPlayerSequenceSacrifice_STF[8] =
{
{ 0, PLRMODE_ATTACK1, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 15, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDE948
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceSacrifice =
{
gPlayerSequenceHandToHand2, 14, 14,
0, 0, 0,
0, 0, 0,
gPlayerSequenceSacrifice_1HT, 7, 7,
gPlayerSequenceSacrifice_STF, 8, 8,
};
//D2Common.0x6FDDE9F0
D2MonSeqTxt gPlayerSequenceChastise_1HT[16] =
{
{ 0, PLRMODE_SPECIAL1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 7, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK2, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 13, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDEA50
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceChastise =
{
gPlayerSequenceHandToHand2, 14, 14,
0, 0, 0,
0, 0, 0,
gPlayerSequenceChastise_1HT, 16, 16,
};
//D2Common.0x6FDDEAF8
D2MonSeqTxt gPlayerSequenceCharge[15] =
{
{ 0, PLRMODE_RUN, 0, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_RUN, 1, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_RUN, 2, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_RUN, 3, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_RUN, 4, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_RUN, 5, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_RUN, 6, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_RUN, 7, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 5, 0, MONSEQ_EVENT_PLAY_SOUND },
{ 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDEB58
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceCharge =
{
gPlayerSequenceCharge, 15, 15,
gPlayerSequenceCharge, 15, 15,
gPlayerSequenceCharge, 15, 15,
gPlayerSequenceCharge, 15, 15,
gPlayerSequenceCharge, 15, 15,
0, 0, 0,
0, 0, 0,
gPlayerSequenceCharge, 15, 15,
};
//D2Common.0x6FDDEC00
D2MonSeqTxt gPlayerSequenceDefiance_1HT[6] =
{
{ 0, PLRMODE_ATTACK2, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 7, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK2, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 12, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDEC28
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceDefiance =
{
gPlayerSequenceHandToHand2, 14, 14,
0, 0, 0,
0, 0, 0,
gPlayerSequenceDefiance_1HT, 6, 6,
};
//D2Common.0x6FDDECD0
D2MonSeqTxt gPlayerSequenceInferno[15] =
{
{ 0, PLRMODE_CAST, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_CAST, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 13, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDED30
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceInferno =
{
gPlayerSequenceInferno, 15, 15,
gPlayerSequenceInferno, 15, 15,
gPlayerSequenceInferno, 15, 15,
gPlayerSequenceInferno, 15, 15,
gPlayerSequenceInferno, 15, 15,
gPlayerSequenceInferno, 15, 15,
gPlayerSequenceInferno, 15, 15,
gPlayerSequenceInferno, 15, 15,
gPlayerSequenceInferno, 15, 15,
gPlayerSequenceInferno, 15, 15,
gPlayerSequenceInferno, 15, 15,
gPlayerSequenceInferno, 15, 15,
gPlayerSequenceInferno, 15, 15,
gPlayerSequenceInferno, 15, 15,
};
//D2Common.0x6FDDEDD8
D2MonSeqTxt gPlayerSequenceStrafe_2HS[13] =
{
{ 0, PLRMODE_ATTACK1, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDEE28
D2MonSeqTxt gPlayerSequenceStrafe_2HT[20] =
{
{ 0, PLRMODE_ATTACK1, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 14, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 15, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 16, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 17, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 18, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 19, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDEEA0
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceStrafe =
{
gPlayerSequenceHandToHand1, 13, 13,
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0,
gPlayerSequenceStrafe_2HS, 13, 13,
gPlayerSequenceStrafe_2HT, 20, 20,
};
//D2Common.0x6FDDEF48
D2MonSeqTxt gPlayerSequenceImpale_BOW[21] =
{
{ 0, PLRMODE_ATTACK1, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 14, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDEFC8
D2MonSeqTxt gPlayerSequenceImpale_1HS[24] =
{
{ 0, PLRMODE_ATTACK1, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 14, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 15, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 16, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 17, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDF058
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceImpale =
{
gPlayerSequenceHandToHand1, 13, 13,
gPlayerSequenceImpale_BOW, 21, 21,
gPlayerSequenceImpale_1HS, 24, 24,
};
//D2Common.0x6FDDF100
D2MonSeqTxt gPlayerSequenceFend_BOW[16] =
{
{ 0, PLRMODE_ATTACK1, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 12, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 14, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDF160
D2MonSeqTxt gPlayerSequenceFend_1HS[16] =
{
{ 0, PLRMODE_ATTACK1, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 14, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 14, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 15, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 16, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 17, 0, MONSEQ_EVENT_NONE },
{ 0, 0, 0, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDF1C0
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceFend =
{
gPlayerSequenceHandToHand1, 13, 13,
gPlayerSequenceFend_BOW, 16, 16,
gPlayerSequenceFend_1HS, 16, 16,
};
//D2Common.0x6FDDF268
D2MonSeqTxt gPlayerSequenceWhirlwind[8] =
{
{ 0, PLRMODE_ATTACK1, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 3, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_MELEE_ATTACK },
};
//D2Common.0x6FDDF298
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceWhirlwind =
{
gPlayerSequenceWhirlwind, 8, 8,
gPlayerSequenceWhirlwind, 8, 8,
gPlayerSequenceWhirlwind, 8, 8,
gPlayerSequenceWhirlwind, 8, 8,
gPlayerSequenceWhirlwind, 8, 8,
0, 0, 0,
0, 0, 0,
gPlayerSequenceWhirlwind, 8, 8,
gPlayerSequenceWhirlwind, 8, 8,
gPlayerSequenceWhirlwind, 8, 8,
gPlayerSequenceWhirlwind, 8, 8,
gPlayerSequenceWhirlwind, 8, 8,
gPlayerSequenceWhirlwind, 8, 8,
gPlayerSequenceWhirlwind, 8, 8,
};
//D2Common.0x6FDDF340
D2MonSeqTxt gPlayerSequenceDoubleSwing[17] =
{
{ 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 14, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL3, 2, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL3, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL3, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL3, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL3, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL3, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL3, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL3, 11, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDF3A8
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceDoubleSwing =
{
gPlayerSequenceDoubleSwing, 17, 17,
gPlayerSequenceDoubleSwing, 17, 17,
gPlayerSequenceDoubleSwing, 17, 17,
gPlayerSequenceDoubleSwing, 17, 17,
gPlayerSequenceDoubleSwing, 17, 17,
gPlayerSequenceDoubleSwing, 17, 17,
gPlayerSequenceDoubleSwing, 17, 17,
gPlayerSequenceDoubleSwing, 17, 17,
gPlayerSequenceDoubleSwing, 17, 17,
gPlayerSequenceDoubleSwing, 17, 17,
gPlayerSequenceDoubleSwing, 17, 17,
gPlayerSequenceDoubleSwing, 17, 17,
gPlayerSequenceDoubleSwing, 17, 17,
gPlayerSequenceDoubleSwing, 17, 17,
};
//D2Common.0x6FDDF450
D2MonSeqTxt gPlayerSequenceLightning[19] =
{
{ 0, PLRMODE_CAST, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 13, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDF4C8
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceLightning =
{
gPlayerSequenceLightning, 19, 19,
gPlayerSequenceLightning, 19, 19,
gPlayerSequenceLightning, 19, 19,
gPlayerSequenceLightning, 19, 19,
gPlayerSequenceLightning, 19, 19,
gPlayerSequenceLightning, 19, 19,
gPlayerSequenceLightning, 19, 19,
gPlayerSequenceLightning, 19, 19,
gPlayerSequenceLightning, 19, 19,
gPlayerSequenceLightning, 19, 19,
gPlayerSequenceLightning, 19, 19,
gPlayerSequenceLightning, 19, 19,
gPlayerSequenceLightning, 19, 19,
gPlayerSequenceLightning, 19, 19,
};
//D2Common.0x6FDDF570
D2MonSeqTxt gPlayerSequenceLeap[15] =
{
{ 0, PLRMODE_SPECIAL1, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 5, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 11, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 14, 0, MONSEQ_EVENT_MELEE_ATTACK },
};
//D2Common.0x6FDDF5D0
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceLeap =
{
gPlayerSequenceLeap, 15, 15,
gPlayerSequenceLeap, 15, 15,
gPlayerSequenceLeap, 15, 15,
gPlayerSequenceLeap, 15, 15,
gPlayerSequenceLeap, 15, 15,
gPlayerSequenceLeap, 15, 15,
gPlayerSequenceLeap, 15, 15,
gPlayerSequenceLeap, 15, 15,
gPlayerSequenceLeap, 15, 15,
gPlayerSequenceLeap, 15, 15,
gPlayerSequenceLeap, 15, 15,
gPlayerSequenceLeap, 15, 15,
gPlayerSequenceLeap, 15, 15,
gPlayerSequenceLeap, 15, 15,
};
//D2Common.0x6FDDF678
D2MonSeqTxt gPlayerSequenceLeapAttack_HTH[22] =
{
{ 0, PLRMODE_SPECIAL1, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 5, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 11, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 14, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDF700
D2MonSeqTxt gPlayerSequenceLeapAttack_BOW_1HT[25] =
{
{ 0, PLRMODE_SPECIAL1, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 5, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 11, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 14, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 14, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 15, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDF798
D2MonSeqTxt gPlayerSequenceLeapAttack_1HS_XBW[28] =
{
{ 0, PLRMODE_SPECIAL1, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 5, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 11, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 14, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 14, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 15, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 16, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 17, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 18, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDF840
D2MonSeqTxt gPlayerSequenceLeapAttack_STF[27] =
{
{ 0, PLRMODE_SPECIAL1, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 5, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 11, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 14, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 14, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 15, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 16, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK1, 17, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDF8E8
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceLeapAttack =
{
gPlayerSequenceLeapAttack_HTH, 22, 22,
gPlayerSequenceLeapAttack_BOW_1HT, 25, 25,
gPlayerSequenceLeapAttack_1HS_XBW, 28, 28,
gPlayerSequenceLeapAttack_BOW_1HT, 25, 25,
gPlayerSequenceLeapAttack_STF, 27, 27,
0, 0, 0,
0, 0, 0,
gPlayerSequenceLeapAttack_1HS_XBW, 28, 28,
gPlayerSequenceLeapAttack_HTH, 22, 22,
gPlayerSequenceLeapAttack_HTH, 22, 22,
gPlayerSequenceLeapAttack_HTH, 22, 22,
gPlayerSequenceLeapAttack_HTH, 22, 22,
gPlayerSequenceLeapAttack_HTH, 22, 22,
gPlayerSequenceLeapAttack_HTH, 22, 22,
};
//D2Common.0x6FDDF990
D2MonSeqTxt gPlayerSequenceDoubleThrow[12] =
{
{ 0, PLRMODE_THROW, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_THROW, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_THROW, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_THROW, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_THROW, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_THROW, 8, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL3, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL3, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL3, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL3, 7, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL3, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL3, 10, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDF9D8
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceDoubleThrow =
{
gPlayerSequenceDoubleThrow, 12, 12,
gPlayerSequenceDoubleThrow, 12, 12,
gPlayerSequenceDoubleThrow, 12, 12,
gPlayerSequenceDoubleThrow, 12, 12,
gPlayerSequenceDoubleThrow, 12, 12,
gPlayerSequenceDoubleThrow, 12, 12,
gPlayerSequenceDoubleThrow, 12, 12,
gPlayerSequenceDoubleThrow, 12, 12,
gPlayerSequenceDoubleThrow, 12, 12,
gPlayerSequenceDoubleThrow, 12, 12,
gPlayerSequenceDoubleThrow, 12, 12,
gPlayerSequenceDoubleThrow, 12, 12,
gPlayerSequenceDoubleThrow, 12, 12,
gPlayerSequenceDoubleThrow, 12, 12,
};
//D2Common.0x6FDDFA80
D2MonSeqTxt gPlayerSequenceDragonClaw_HTH_HT1[12] =
{
{ 0, PLRMODE_ATTACK2, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 6, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_ATTACK2, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 11, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDFAC8
D2MonSeqTxt gPlayerSequenceDragonClaw_HT2[16] =
{
{ 0, PLRMODE_ATTACK2, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_ATTACK2, 6, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL4, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL4, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL4, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL4, 6, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL4, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL4, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL4, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL4, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL4, 11, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDFB28
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceDragonClaw =
{
gPlayerSequenceDragonClaw_HTH_HT1, 12, 12,
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0,
gPlayerSequenceDragonClaw_HTH_HT1, 12, 12,
gPlayerSequenceDragonClaw_HT2, 16, 16,
};
//D2Common.0x6FDDFBD0
D2MonSeqTxt gPlayerSequenceProjection[19] =
{
{ 0, PLRMODE_CAST, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 7, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_CAST, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 11, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_CAST, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 14, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 15, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 16, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 17, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 18, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, 0, 0, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDFC48
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceProjection =
{
gPlayerSequenceProjection, 19, 19,
gPlayerSequenceProjection, 19, 19,
gPlayerSequenceProjection, 19, 19,
gPlayerSequenceProjection, 19, 19,
gPlayerSequenceProjection, 19, 19,
gPlayerSequenceProjection, 19, 19,
gPlayerSequenceProjection, 19, 19,
gPlayerSequenceProjection, 19, 19,
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0,
gPlayerSequenceProjection, 19, 19,
gPlayerSequenceProjection, 19, 19,
};
//D2Common.0x6FDDFCF0
D2MonSeqTxt gPlayerSequenceDragonTalon[20] =
{
{ 0, PLRMODE_KICK, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 4, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_KICK, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 4, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_KICK, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 5, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_KICK, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 11, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDFD68
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceDragonTalon =
{
gPlayerSequenceDragonTalon, 20, 20,
gPlayerSequenceDragonTalon, 20, 20,
gPlayerSequenceDragonTalon, 20, 20,
gPlayerSequenceDragonTalon, 20, 20,
gPlayerSequenceDragonTalon, 20, 20,
gPlayerSequenceDragonTalon, 20, 20,
gPlayerSequenceDragonTalon, 20, 20,
gPlayerSequenceDragonTalon, 20, 20,
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0,
gPlayerSequenceDragonTalon, 20, 20,
gPlayerSequenceDragonTalon, 20, 20,
};
//D2Common.0x6FDDFE10
D2MonSeqTxt gPlayerSequenceArcticBlast[15] =
{
{ 0, PLRMODE_SPECIAL1, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 9, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 13, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDFE70
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceArcticBlast =
{
gPlayerSequenceArcticBlast, 15, 15,
gPlayerSequenceArcticBlast, 15, 15,
gPlayerSequenceArcticBlast, 15, 15,
gPlayerSequenceArcticBlast, 15, 15,
gPlayerSequenceArcticBlast, 15, 15,
gPlayerSequenceArcticBlast, 15, 15,
gPlayerSequenceArcticBlast, 15, 15,
gPlayerSequenceArcticBlast, 15, 15,
gPlayerSequenceArcticBlast, 15, 15,
gPlayerSequenceArcticBlast, 15, 15,
gPlayerSequenceArcticBlast, 15, 15,
gPlayerSequenceArcticBlast, 15, 15,
gPlayerSequenceArcticBlast, 15, 15,
gPlayerSequenceArcticBlast, 15, 15,
};
//D2Common.0x6FDDFF18
D2MonSeqTxt gPlayerSequenceDragonBreath[17] =
{
{ 0, PLRMODE_SPECIAL1, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 8, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 10, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL1, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 12, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 13, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 14, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDDFF80
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceDragonBreath =
{
gPlayerSequenceDragonBreath, 17, 17,
gPlayerSequenceDragonBreath, 17, 17,
gPlayerSequenceDragonBreath, 17, 17,
gPlayerSequenceDragonBreath, 17, 17,
gPlayerSequenceDragonBreath, 17, 17,
gPlayerSequenceDragonBreath, 17, 17,
gPlayerSequenceDragonBreath, 17, 17,
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0,
0, 0, 0,
gPlayerSequenceDragonBreath, 17, 17,
gPlayerSequenceDragonBreath, 17, 17,
};
//D2Common.0x6FDE0028
D2MonSeqTxt gPlayerSequenceDragonFlight[23] =
{
{ 0, PLRMODE_CAST, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_KICK, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 4, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_KICK, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_KICK, 12, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDE00B8
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceDragonFlight =
{
gPlayerSequenceDragonFlight, 23, 23,
gPlayerSequenceDragonFlight, 23, 23,
gPlayerSequenceDragonFlight, 23, 23,
gPlayerSequenceDragonFlight, 23, 23,
gPlayerSequenceDragonFlight, 23, 23,
gPlayerSequenceDragonFlight, 23, 23,
gPlayerSequenceDragonFlight, 23, 23,
gPlayerSequenceDragonFlight, 23, 23,
gPlayerSequenceDragonFlight, 23, 23,
gPlayerSequenceDragonFlight, 23, 23,
gPlayerSequenceDragonFlight, 23, 23,
gPlayerSequenceDragonFlight, 23, 23,
gPlayerSequenceDragonFlight, 23, 23,
gPlayerSequenceDragonFlight, 23, 23,
};
//D2Common.0x6FDE0160
D2MonSeqTxt gPlayerSequenceUnmorph[16] =
{
{ 0, PLRMODE_SPECIAL1, 15, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 14, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 10, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 2, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_SPECIAL1, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_SPECIAL1, 0, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDE01C0
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceUnmorph =
{
gPlayerSequenceUnmorph, 16, 16,
gPlayerSequenceUnmorph, 16, 16,
gPlayerSequenceUnmorph, 16, 16,
gPlayerSequenceUnmorph, 16, 16,
gPlayerSequenceUnmorph, 16, 16,
gPlayerSequenceUnmorph, 16, 16,
gPlayerSequenceUnmorph, 16, 16,
gPlayerSequenceUnmorph, 16, 16,
gPlayerSequenceUnmorph, 16, 16,
gPlayerSequenceUnmorph, 16, 16,
gPlayerSequenceUnmorph, 16, 16,
gPlayerSequenceUnmorph, 16, 16,
gPlayerSequenceUnmorph, 16, 16,
gPlayerSequenceUnmorph, 16, 16,
};
//D2Common.0x6FDE0268
D2MonSeqTxt gPlayerSequenceBladeFury[19] =
{
{ 0, PLRMODE_CAST, 0, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 1, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 2, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 3, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 4, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 5, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 6, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 7, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 8, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 10, 0, MONSEQ_EVENT_MELEE_ATTACK },
{ 0, PLRMODE_CAST, 11, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 12, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 13, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 14, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 15, 0, MONSEQ_EVENT_NONE },
{ 0, PLRMODE_CAST, 16, 0, MONSEQ_EVENT_NONE },
};
//D2Common.0x6FDE02E0
D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceBladeFury =
{
gPlayerSequenceBladeFury, 19, 19,
gPlayerSequenceBladeFury, 19, 19,
gPlayerSequenceBladeFury, 19, 19,
gPlayerSequenceBladeFury, 19, 19,
gPlayerSequenceBladeFury, 19, 19,
gPlayerSequenceBladeFury, 19, 19,
gPlayerSequenceBladeFury, 19, 19,
gPlayerSequenceBladeFury, 19, 19,
gPlayerSequenceBladeFury, 19, 19,
gPlayerSequenceBladeFury, 19, 19,
gPlayerSequenceBladeFury, 19, 19,
gPlayerSequenceBladeFury, 19, 19,
gPlayerSequenceBladeFury, 19, 19,
gPlayerSequenceBladeFury, 19, 19,
};
//D2Common.0x6FDE0388
D2PlayerWeaponSequencesStrc* gPlayerWeaponsSequenceTable[24] =
{
NULL,
&gPlayerWeaponsSequenceJab,
&gPlayerWeaponsSequenceSacrifice,
&gPlayerWeaponsSequenceChastise,
&gPlayerWeaponsSequenceCharge,
&gPlayerWeaponsSequenceDefiance,
&gPlayerWeaponsSequenceInferno,
&gPlayerWeaponsSequenceStrafe,
&gPlayerWeaponsSequenceImpale,
&gPlayerWeaponsSequenceFend,
&gPlayerWeaponsSequenceWhirlwind,
&gPlayerWeaponsSequenceDoubleSwing,
&gPlayerWeaponsSequenceLightning,
&gPlayerWeaponsSequenceLeap,
&gPlayerWeaponsSequenceLeapAttack,
&gPlayerWeaponsSequenceDoubleThrow,
&gPlayerWeaponsSequenceDragonClaw,
&gPlayerWeaponsSequenceProjection,
&gPlayerWeaponsSequenceArcticBlast,
&gPlayerWeaponsSequenceDragonTalon,
&gPlayerWeaponsSequenceDragonBreath,
&gPlayerWeaponsSequenceDragonFlight,
&gPlayerWeaponsSequenceUnmorph,
&gPlayerWeaponsSequenceBladeFury,
};
//D2Common.0x6FDE03E8
//Note: This should really just be an array since the indices are ordered anyway...
static const int gWeaponIndexToClassMap[14][2] =
{
{ 0, WEAPONCLASS_HTH },
{ 1, WEAPONCLASS_1HT },
{ 2, WEAPONCLASS_2HT },
{ 3, WEAPONCLASS_1HS },
{ 4, WEAPONCLASS_2HS },
{ 5, WEAPONCLASS_BOW },
{ 6, WEAPONCLASS_XBW },
{ 7, WEAPONCLASS_STF },
{ 8, WEAPONCLASS_1JS },
{ 9, WEAPONCLASS_1JT },
{ 10, WEAPONCLASS_1SS },
{ 11, WEAPONCLASS_1ST },
{ 12, WEAPONCLASS_HT1 },
{ 13, WEAPONCLASS_HT2 }
};
//D2Common.0x6FD727A0 (#10682)
D2MonSeqTxt* __stdcall DATATBLS_GetMonSeqTxtRecordFromUnit(D2UnitStrc* pUnit)
{
D2SeqRecordStrc* pSeqRecord = DATATBLS_GetSeqRecordFromUnit(pUnit);
if (pSeqRecord)
{
return pSeqRecord->pMonSeqTxtRecord;
}
return NULL;
}
//D2Common.0x6FD727C0
D2SeqRecordStrc* __fastcall DATATBLS_GetSeqRecordFromUnit(D2UnitStrc* pUnit)
{
if (D2SkillStrc* pSkill = UNITS_GetUsedSkill(pUnit))
{
int nSequenceNum = SKILLS_GetSeqNumFromSkill(pUnit, pSkill);
if (nSequenceNum > 0)
{
int nUnitType = UNIT_TYPES_COUNT;
if (pUnit)
{
nUnitType = pUnit->dwUnitType;
}
if (nUnitType == UNIT_PLAYER)
{
int nWeaponClass = WEAPONCLASS_HTH;
COMPOSIT_GetWeaponClassId(pUnit, pUnit->pInventory, &nWeaponClass, -1, TRUE);
int nWClassIndex = -1;
for (int i = 0; i < 14; i++)
{
if (nWeaponClass == gWeaponIndexToClassMap[i][1])
{
nWClassIndex = gWeaponIndexToClassMap[i][0];
break;
}
}
D2_ASSERT(nWClassIndex != -1);
return &gPlayerWeaponsSequenceTable[nSequenceNum]->weaponRecords[nWClassIndex];
}
else if (nUnitType == UNIT_MONSTER && DATATBLS_GetMonStatsTxtRecord(pUnit->dwClassId))
{
return DATATBLS_GetMonSeqTableRecord(nSequenceNum);
}
}
}
return NULL;
}
//D2Common.0x6FD728A0 (#10683)
int __stdcall DATATBLS_GetSeqFramePointsCount(D2UnitStrc* pUnit)
{
D2SeqRecordStrc* pSeqRecord = DATATBLS_GetSeqRecordFromUnit(pUnit);
if (pSeqRecord)
{
return (pSeqRecord->nSeqFramesCount << 8);
}
return 0;
}
//D2Common.0x6FD728C0 (#10684)
int __stdcall DATATBLS_GetSeqFrameCount(D2UnitStrc* pUnit)
{
D2SeqRecordStrc* pSeqRecord = DATATBLS_GetSeqRecordFromUnit(pUnit);
if (pSeqRecord)
{
return pSeqRecord->nFramesCount;
}
return 0;
}
//D2Common.0x6FD728E0 (#10685)
void __stdcall DATATBLS_ComputeSequenceAnimation(D2MonSeqTxt* pMonSeqTxt, int nTargetFramePoint, int nCurrentFramePoint, unsigned int* pMode, unsigned int* pFrame, int* pDirection, int* pEvent)
{
if (pMonSeqTxt)
{
const D2MonSeqTxt* pMonSeqTxtRecord = &pMonSeqTxt[nCurrentFramePoint >> 8];
*pMode = pMonSeqTxtRecord->nMode;
*pFrame = pMonSeqTxtRecord->nFrame;
*pDirection = pMonSeqTxtRecord->nDir;
if (nCurrentFramePoint == nTargetFramePoint)
{
*pEvent = pMonSeqTxtRecord->nEvent;
}
else // Retrieve the last event, note that it discard the intermediary events.
{
*pEvent = 0;
const int nNextFrame = (nCurrentFramePoint >> 8) + 1;
const int nTargetFrame = nTargetFramePoint >> 8;
for (int frameIdx = nNextFrame; frameIdx <= nTargetFrame; frameIdx++)
{
const D2MonSeqEvent nEvent = pMonSeqTxt[frameIdx].nEvent;
if (nEvent != MONSEQ_EVENT_NONE)
{
*pEvent = nEvent;
}
}
}
}
else
{
*pMode = 0;
*pFrame = 0;
*pDirection = 0;
*pEvent = MONSEQ_EVENT_NONE;
}
}
//D2Common.0x6FD72990 (#10686)
void __stdcall DATATBLS_GetSequenceEvent(D2MonSeqTxt* pMonSeqTxt, int nSeqFramePoint, int* pEvent)
{
if (pMonSeqTxt)
{
*pEvent = pMonSeqTxt[nSeqFramePoint >> 8].nEvent;
}
else
{
*pEvent = 0;
}
}
//D2Common.0x6FD6F050
void __fastcall DATATBLS_LoadMonSeqTxt(void* pMemPool)
{
D2BinFieldStrc pTbl[] =
{
{ "sequence", TXTFIELD_NAMETOINDEX, 0, 0, &sgptDataTables->pMonSeqLinker },
{ "mode", TXTFIELD_CODETOBYTE, 0, 2, &sgptDataTables->pMonModeLinker },
{ "frame", TXTFIELD_BYTE, 0, 3, NULL },
{ "dir", TXTFIELD_BYTE, 0, 4, NULL },
{ "event", TXTFIELD_BYTE, 0, 5, NULL },
{ "end", TXTFIELD_NONE, 0, 0, NULL },
};
sgptDataTables->pMonSeqLinker = (D2TxtLinkStrc*)FOG_AllocLinker(__FILE__, __LINE__);
sgptDataTables->pMonSeqTxt = (D2MonSeqTxt*)DATATBLS_CompileTxt(pMemPool, "monseq", pTbl, &sgptDataTables->nMonSeqTxtRecordCount, sizeof(D2MonSeqTxt));
if (sgptDataTables->nMonSeqTxtRecordCount > 0)
{
sgptDataTables->nMonSeqTableRecordCount = sgptDataTables->pMonSeqTxt[sgptDataTables->nMonSeqTxtRecordCount - 1].wSequence + 1;
sgptDataTables->pMonSeqTable = (D2SeqRecordStrc*)D2_CALLOC_SERVER(NULL, sizeof(D2SeqRecordStrc) * sgptDataTables->nMonSeqTableRecordCount);
for (int i = 0; i < sgptDataTables->nMonSeqTxtRecordCount; ++i)
{
int nSequence = sgptDataTables->pMonSeqTxt[i].wSequence;
if (!sgptDataTables->pMonSeqTable[nSequence].pMonSeqTxtRecord)
{
sgptDataTables->pMonSeqTable[nSequence].pMonSeqTxtRecord = &sgptDataTables->pMonSeqTxt[i];
}
++sgptDataTables->pMonSeqTable[nSequence].nSeqFramesCount;
++sgptDataTables->pMonSeqTable[nSequence].nFramesCount;
}
}
}
//D2Common.0x6FD6F200 (#11262)
D2SeqRecordStrc* __stdcall DATATBLS_GetMonSeqTableRecord(int nSequence)
{
if (nSequence >= 0 && nSequence < sgptDataTables->nMonSeqTableRecordCount)
{
return &sgptDataTables->pMonSeqTable[nSequence];
}
return NULL;
}
| 35.615958
| 193
| 0.731748
|
raumuongluoc
|
ae06620b4145aff4fd7b6004b47eeef88f43cf26
| 1,656
|
cpp
|
C++
|
src/coherence/component/net/extend/protocol/cache/AbstractKeySetRequest.cpp
|
chpatel3/coherence-cpp-extend-client
|
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
|
[
"UPL-1.0",
"Apache-2.0"
] | 6
|
2020-07-01T21:38:30.000Z
|
2021-11-03T01:35:11.000Z
|
src/coherence/component/net/extend/protocol/cache/AbstractKeySetRequest.cpp
|
chpatel3/coherence-cpp-extend-client
|
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
|
[
"UPL-1.0",
"Apache-2.0"
] | 1
|
2020-07-24T17:29:22.000Z
|
2020-07-24T18:29:04.000Z
|
src/coherence/component/net/extend/protocol/cache/AbstractKeySetRequest.cpp
|
chpatel3/coherence-cpp-extend-client
|
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
|
[
"UPL-1.0",
"Apache-2.0"
] | 6
|
2020-07-10T18:40:58.000Z
|
2022-02-18T01:23:40.000Z
|
/*
* Copyright (c) 2000, 2020, Oracle and/or its affiliates.
*
* Licensed under the Universal Permissive License v 1.0 as shown at
* http://oss.oracle.com/licenses/upl.
*/
#include "private/coherence/component/net/extend/protocol/cache/AbstractKeySetRequest.hpp"
#include "coherence/util/ArrayList.hpp" // REVIEW
COH_OPEN_NAMESPACE6(coherence,component,net,extend,protocol,cache)
using coherence::util::ArrayList;
// ----- constructors -------------------------------------------------------
AbstractKeySetRequest::AbstractKeySetRequest()
: f_vCol(self())
{
}
// ----- PortableObject interface -------------------------------------------
void AbstractKeySetRequest::readExternal(PofReader::Handle hIn)
{
AbstractPofRequest::readExternal(hIn);
setKeySet(hIn->readCollection(1, ArrayList::create()));
}
void AbstractKeySetRequest::writeExternal(PofWriter::Handle hOut) const
{
AbstractPofRequest::writeExternal(hOut);
hOut->writeCollection(1, getKeySet());
//release state
// m_vCol = NULL; // c++ optimization uses FinalView and thus can't be released
}
// ----- Describable interface ----------------------------------------------
String::View AbstractKeySetRequest::getDescription() const
{
return COH_TO_STRING(super::getDescription() << ", KeySet=" << getKeySet());
}
// ----- accessors ----------------------------------------------------------
Collection::View AbstractKeySetRequest::getKeySet() const
{
return f_vCol;
}
void AbstractKeySetRequest::setKeySet(Collection::View vCol)
{
initialize(f_vCol, vCol);
}
COH_CLOSE_NAMESPACE6
| 25.476923
| 90
| 0.61715
|
chpatel3
|
ae09b5ccdd4d276517f3989a7ce916f5813cb65a
| 74
|
cpp
|
C++
|
src/ace/ACE_wrappers/ACEXML/common/Attributes.cpp
|
wfnex/OpenBRAS
|
b8c2cd836ae85d5307f7f5ca87573b964342bb49
|
[
"BSD-3-Clause"
] | 8
|
2017-06-05T08:56:27.000Z
|
2020-04-08T16:50:11.000Z
|
src/ace/ACE_wrappers/ACEXML/common/Attributes.cpp
|
wfnex/OpenBRAS
|
b8c2cd836ae85d5307f7f5ca87573b964342bb49
|
[
"BSD-3-Clause"
] | null | null | null |
src/ace/ACE_wrappers/ACEXML/common/Attributes.cpp
|
wfnex/OpenBRAS
|
b8c2cd836ae85d5307f7f5ca87573b964342bb49
|
[
"BSD-3-Clause"
] | 17
|
2017-06-05T08:54:27.000Z
|
2021-08-29T14:19:12.000Z
|
#include "Attributes.h"
ACEXML_Attributes::~ACEXML_Attributes (void)
{
}
| 12.333333
| 44
| 0.756757
|
wfnex
|
ae0bd9b41366661e5c83824971bbd8235099a335
| 1,027
|
cpp
|
C++
|
extractor/Utils/DBCReader.cpp
|
avennstrom/NovusCore-Tools
|
03c2bd1ee8e6b865498b4d489ac962b0f168ad59
|
[
"MIT"
] | null | null | null |
extractor/Utils/DBCReader.cpp
|
avennstrom/NovusCore-Tools
|
03c2bd1ee8e6b865498b4d489ac962b0f168ad59
|
[
"MIT"
] | 2
|
2020-01-16T13:58:44.000Z
|
2020-07-01T11:37:00.000Z
|
extractor/Utils/DBCReader.cpp
|
avennstrom/NovusCore-Tools
|
03c2bd1ee8e6b865498b4d489ac962b0f168ad59
|
[
"MIT"
] | 5
|
2020-01-16T13:56:44.000Z
|
2021-12-20T22:16:08.000Z
|
#include "DBCReader.h"
/*
1 = Can't open file
2 = Invalid format
3 = Invalid data / string size read
*/
int DBCReader::Load(std::shared_ptr<Bytebuffer> buffer)
{
u32 header = 0;
buffer->GetU32(header);
// Check for WDBC header
if (header != NOVUSDBC_WDBC_TOKEN)
return 2;
try
{
buffer->GetU32(_rowCount);
buffer->GetU32(_fieldCount);
buffer->GetU32(_rowSize);
buffer->GetU32(_stringSize);
}
catch (std::exception)
{
return 2;
}
// Cleanup Memory if we've previously loaded DBC Files
if (_data)
{
delete[] _data;
}
u32 dataSize = _rowSize * _rowCount + _stringSize;
_data = new unsigned char[dataSize];
std::memset(_data, 0, dataSize);
_stringTable = _data + _rowSize * _rowCount;
if (!_data || !_stringTable)
return 3;
buffer->GetBytes(_data, dataSize);
return 0;
}
DBCReader::DBCRow DBCReader::GetRow(u32 id)
{
return DBCRow(*this, _data + id * _rowSize);
}
| 20.137255
| 58
| 0.6037
|
avennstrom
|
ae1126f4317e7224849ef4da6c39a7f628d6738e
| 523
|
cpp
|
C++
|
exercises/6/Seminar_02 - Introduction to classes/structures_unions_alignment/unions.cpp
|
triffon/oop-2019-20
|
db199631d59ddefdcc0c8eb3d689de0095618f92
|
[
"MIT"
] | 19
|
2020-02-21T16:46:50.000Z
|
2022-01-26T19:59:49.000Z
|
exercises/6/Seminar_02 - Introduction to classes/structures_unions_alignment/unions.cpp
|
triffon/oop-2019-20
|
db199631d59ddefdcc0c8eb3d689de0095618f92
|
[
"MIT"
] | 1
|
2020-03-14T08:09:45.000Z
|
2020-03-14T08:09:45.000Z
|
exercises/6/Seminar_02 - Introduction to classes/structures_unions_alignment/unions.cpp
|
triffon/oop-2019-20
|
db199631d59ddefdcc0c8eb3d689de0095618f92
|
[
"MIT"
] | 11
|
2020-02-23T12:29:58.000Z
|
2021-04-11T08:30:12.000Z
|
#include <iostream>
//Source: https://www.youtube.com/watch?v=6uqU9Y578n4
struct Vector2 {
float x, y;
};
struct Vector4 {
union {
struct {
float x, y, z, w;
};
struct {
Vector2 a, b;
};
};
};
void printVector2(const Vector2& vector) {
std::cout << "( " << vector.x << ", " << vector.y << " )" << std::endl;
}
int main() {
Vector4 vec = { 1.0f, 2.0f, 3.0f, 4.0f };
printVector2(vec.a);
std::cout << "----------------------" << std::endl;
vec.z = 500.0f;
printVector2(vec.b);
return 0;
}
| 14.527778
| 72
| 0.529637
|
triffon
|
ae1df20fd6c4d4f350682072ec4175a62b66a344
| 6,242
|
cc
|
C++
|
bwidgets/widgets/bwNumberSlider.cc
|
julianeisel/bWidgets
|
35695df104f77b35992013a5602adf2723ab1022
|
[
"MIT"
] | 72
|
2018-03-26T20:13:47.000Z
|
2022-03-08T15:59:55.000Z
|
bwidgets/widgets/bwNumberSlider.cc
|
julianeisel/bWidgets
|
35695df104f77b35992013a5602adf2723ab1022
|
[
"MIT"
] | 12
|
2018-03-30T12:54:15.000Z
|
2021-05-30T23:33:01.000Z
|
bwidgets/widgets/bwNumberSlider.cc
|
julianeisel/bWidgets
|
35695df104f77b35992013a5602adf2723ab1022
|
[
"MIT"
] | 10
|
2018-03-26T23:04:06.000Z
|
2021-11-17T21:04:27.000Z
|
#include <algorithm>
#include <cassert>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <sstream>
#include "bwEvent.h"
#include "bwPainter.h"
#include "bwStyle.h"
#include "bwNumberSlider.h"
namespace bWidgets {
bwNumberSlider::bwNumberSlider(std::optional<unsigned int> width_hint,
std::optional<unsigned int> height_hint)
: bwTextBox(width_hint, height_hint), precision(2)
{
}
auto bwNumberSlider::getTypeIdentifier() const -> std::string_view
{
return "bwNumberSlider";
}
void bwNumberSlider::draw(bwStyle& style)
{
bwPainter painter;
bwRectanglePixel inner_rect = rectangle;
const float radius = base_style.corner_radius * style.dpi_fac;
// Inner - "inside" of outline, so scale down
inner_rect.resize(-1);
painter.setContentMask(inner_rect);
painter.enableGradient(
bwGradient(base_style.backgroundColor(), base_style.shadeTop(), base_style.shadeBottom()));
painter.drawRoundbox(inner_rect, base_style.roundbox_corners, radius - 1.0f);
painter.active_drawtype = bwPainter::DrawType::FILLED;
// Text editing
if (is_text_editing) {
// Selection drawing
painter.setActiveColor(base_style.decorationColor());
painter.drawRectangle(selection_rectangle);
}
else {
drawValueIndicator(painter, style);
}
// Outline
painter.setActiveColor(base_style.borderColor());
painter.active_drawtype = bwPainter::DrawType::OUTLINE;
painter.drawRoundbox(rectangle, base_style.roundbox_corners, radius);
painter.setActiveColor(base_style.textColor());
if (!is_text_editing) {
painter.drawText(text, rectangle, base_style.text_alignment);
}
painter.drawText(valueToString(precision),
rectangle,
is_text_editing ? TextAlignment::LEFT : TextAlignment::RIGHT);
}
void bwNumberSlider::drawValueIndicator(bwPainter& painter, bwStyle& style) const
{
bwGradient gradient = bwGradient(base_style.decorationColor(),
// shadeTop/Bottom intentionally inverted
base_style.shadeBottom(),
base_style.shadeTop());
bwRectanglePixel indicator_offset_rect = rectangle;
bwRectanglePixel indicator_rect = rectangle;
unsigned int roundbox_corners = base_style.roundbox_corners;
const float radius = base_style.corner_radius * style.dpi_fac;
float right_side_radius = radius;
indicator_offset_rect.xmax = indicator_offset_rect.xmin + right_side_radius;
indicator_rect.xmin = indicator_offset_rect.xmax;
indicator_rect.xmax = indicator_rect.xmin + calcValueIndicatorWidth(style);
if (indicator_rect.xmax > (rectangle.xmax - right_side_radius)) {
right_side_radius *= (indicator_rect.xmax + right_side_radius - rectangle.xmax) /
right_side_radius;
}
else {
roundbox_corners &= ~(TOP_RIGHT | BOTTOM_RIGHT);
}
painter.enableGradient(gradient);
painter.drawRoundbox(
indicator_offset_rect, roundbox_corners & ~(TOP_RIGHT | BOTTOM_RIGHT), radius);
painter.drawRoundbox(
indicator_rect, roundbox_corners & ~(TOP_LEFT | BOTTOM_LEFT), right_side_radius);
}
auto bwNumberSlider::setValue(float _value) -> bwNumberSlider&
{
const int precision_fac = std::pow(10, precision);
const float unclamped_value = std::max(min, std::min(max, _value));
value = std::roundf(unclamped_value * precision_fac) / precision_fac;
return *this;
}
auto bwNumberSlider::getValue() const -> float
{
return value;
}
auto bwNumberSlider::setMinMax(float _min, float _max) -> bwNumberSlider&
{
min = _min;
max = _max;
return *this;
}
auto bwNumberSlider::valueToString(unsigned int precision) const -> std::string
{
std::stringstream string_stream;
string_stream << std::fixed << std::setprecision(precision) << value;
return string_stream.str();
}
auto bwNumberSlider::calcValueIndicatorWidth(bwStyle& style) const -> float
{
const float range = max - min;
const float radius = base_style.corner_radius * style.dpi_fac;
assert(max > min);
return ((value - min) * (rectangle.width() - radius)) / range;
}
// ------------------ Handling ------------------
class bwNumberSliderHandler : public bwTextBoxHandler {
public:
bwNumberSliderHandler(bwNumberSlider& numberslider);
~bwNumberSliderHandler() = default;
void onMousePress(bwMouseButtonEvent&) override;
void onMouseRelease(bwMouseButtonEvent&) override;
void onMouseClick(bwMouseButtonEvent&) override;
void onMouseDrag(bwMouseButtonDragEvent&) override;
private:
bwNumberSlider& numberslider;
// Initial value before starting to edit.
float initial_value;
};
bwNumberSliderHandler::bwNumberSliderHandler(bwNumberSlider& numberslider)
: bwTextBoxHandler(numberslider), numberslider(numberslider)
{
}
auto bwNumberSlider::createHandler() -> std::unique_ptr<bwScreenGraph::EventHandler>
{
return std::make_unique<bwNumberSliderHandler>(*this);
}
void bwNumberSliderHandler::onMousePress(bwMouseButtonEvent& event)
{
if (event.button == bwMouseButtonEvent::Button::LEFT) {
initial_value = numberslider.value;
numberslider.setState(bwWidget::State::SUNKEN);
event.swallow();
}
else if (event.button == bwMouseButtonEvent::Button::RIGHT) {
if (numberslider.is_text_editing) {
endTextEditing();
}
else if (is_dragging) {
numberslider.value = initial_value;
}
event.swallow();
}
}
void bwNumberSliderHandler::onMouseRelease(bwMouseButtonEvent& event)
{
if (is_dragging) {
numberslider.setState(bwWidget::State::NORMAL);
}
is_dragging = false;
event.swallow();
}
void bwNumberSliderHandler::onMouseClick(bwMouseButtonEvent& event)
{
if (event.button == bwMouseButtonEvent::Button::LEFT) {
startTextEditing();
}
event.swallow();
}
void bwNumberSliderHandler::onMouseDrag(bwMouseButtonDragEvent& event)
{
if (event.button == bwMouseButtonEvent::Button::LEFT) {
numberslider.setValue(initial_value +
(event.drag_distance.x / (float)numberslider.rectangle.width()));
if (numberslider.apply_functor) {
(*numberslider.apply_functor)();
}
is_dragging = true;
event.swallow();
}
}
} // namespace bWidgets
| 28.372727
| 97
| 0.716437
|
julianeisel
|
ae1f29f88c6f05e3560317369e6deaca5e2fb449
| 324
|
cpp
|
C++
|
Sirul_Retardat/Sirul_Retardat.cpp
|
EneRgYCZ/Problems
|
e8bf9aa4bba2b5ead25fc5ce482a36c861501f46
|
[
"MIT"
] | null | null | null |
Sirul_Retardat/Sirul_Retardat.cpp
|
EneRgYCZ/Problems
|
e8bf9aa4bba2b5ead25fc5ce482a36c861501f46
|
[
"MIT"
] | null | null | null |
Sirul_Retardat/Sirul_Retardat.cpp
|
EneRgYCZ/Problems
|
e8bf9aa4bba2b5ead25fc5ce482a36c861501f46
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int main ()
{
int n, x, y, z, v[10001];
cin >> n >> x >> y >> z;
v[1] = x;
v[2] = y;
v[3] = z;
for (int i = 4; i <= n; ++i)
{
v[i] = v[i - 1] + v[i - 2] - v[i - 3];
}
for (int i = n; i >= 1; --i)
{
cout << v[i] << " ";
}
}
| 17.052632
| 46
| 0.330247
|
EneRgYCZ
|
ae1fcacb9a1c8125da9eda8a38dbe2fb5d748bfa
| 95,361
|
cpp
|
C++
|
v3d_main/neuron_annotator/gui/NaMainWindow.cpp
|
hanchuan/vaa3d_external
|
d6381572dec4079705ac5d3e39c9556b50472403
|
[
"MIT"
] | null | null | null |
v3d_main/neuron_annotator/gui/NaMainWindow.cpp
|
hanchuan/vaa3d_external
|
d6381572dec4079705ac5d3e39c9556b50472403
|
[
"MIT"
] | null | null | null |
v3d_main/neuron_annotator/gui/NaMainWindow.cpp
|
hanchuan/vaa3d_external
|
d6381572dec4079705ac5d3e39c9556b50472403
|
[
"MIT"
] | null | null | null |
// Fix windows compile problem with windows.h being included too late.
// I wish it wasn't included at all...
#ifdef _MSC_VER
#define NOMINMAX //added by PHC, 2010-05-20 to overcome VC min max macro
#include <windows.h>
#endif
#include <QDir>
#include <QFileInfo>
#include <QDebug>
#include <iostream>
#include <cmath>
#include <cassert>
#include "NaMainWindow.h"
#include "Na3DWidget.h"
#include "ui_NaMainWindow.h"
#include "../../basic_c_fun/v3d_message.h"
#include "../../v3d/v3d_application.h"
#include "../DataFlowModel.h"
#include "../MultiColorImageStackNode.h"
#include "../NeuronAnnotatorResultNode.h"
#include "../TimebasedIdentifierGenerator.h"
#include "RendererNeuronAnnotator.h"
#include "GalleryButton.h"
#include "../../cell_counter/CellCounter3D.h"
#include "../NeuronSelector.h"
#include "FragmentGalleryWidget.h"
#include "AnnotationWidget.h"
#include "../utility/loadV3dFFMpeg.h"
#include "PreferencesDialog.h"
#include "../utility/FooDebug.h"
#include "../utility/url_tools.h"
#include <cstdlib> // getenv
using namespace std;
using namespace jfrc;
//////////////////
// NutateThread //
//////////////////
NutateThread::NutateThread(qreal cyclesPerSecond, QObject * parentObj /* = NULL */)
: QThread(parentObj)
, speed(cyclesPerSecond)
, interval(0.200) // update every 200 milliseconds
, currentAngle(0.0)
{
deltaAngle = 2.0 * 3.14159 * cyclesPerSecond * interval;
}
void NutateThread::run()
{
while(true) {
if (paused) {
msleep(500);
continue;
}
// qDebug() << "nutation angle = " << currentAngle;
rot = deltaNutation(currentAngle, deltaAngle);
emit nutate(rot);
currentAngle += deltaAngle;
while (currentAngle > 2.0 * 3.14159) currentAngle -= 2.0 * 3.14159;
msleep( (1000.0 * deltaAngle) / (2.0 * 3.14159 * speed) );
}
}
void NutateThread::pause() {paused = true;}
void NutateThread::unpause() {paused = false;}
//////////////////
// NaMainWindow //
//////////////////
inline const char * getConsolePort()
{
const char *port;
port = getenv("WORKSTATION_SERVICE_PORT");
if(NULL == port) port = "30001";
return port;
}
NaMainWindow::NaMainWindow(QWidget * parent, Qt::WindowFlags flags)
: QMainWindow(parent, flags)
, ui(new Ui::NaMainWindow)
, nutateThread(NULL)
, statusProgressBar(NULL)
, neuronSelector(this)
, undoStack(NULL)
, showAllNeuronsInEmptySpaceAction(NULL)
, hideAllAction(NULL)
, selectNoneAction(NULL)
, neuronContextMenu(NULL)
, viewerContextMenu(NULL)
, recentViewer(VIEWER_3D)
, dynamicRangeTool(NULL)
, isInCustomCutMode(false)
, bShowCrosshair(true) // default to on
, viewMode(VIEW_SINGLE_STACK)
, cutPlanner(NULL)
{
const char* port = getConsolePort();
qDebug() << "Using console port: " << port;
QString qport(port);
QString url = QString("http://localhost:%1/axis2/services/cds").arg(port);
consoleUrl = new char[url.length() + 1];
QByteArray ba = url.toUtf8();
strcpy(consoleUrl, ba.data());
qDebug() << "Using console URL: " << consoleUrl;
// Set up potential 3D stereo modes before creating QGLWidget.
#ifdef ENABLE_STEREO
QGLFormat glFormat = QGLFormat::defaultFormat();
glFormat.setStereo(true);
glFormat.setDoubleBuffer(true);
if (glFormat.stereo()) {
// qDebug() << "Attempting to set 3D stereo format";
}
else {
// qDebug() << "Failed to make stereo 3D default QGLFormat";
}
QGLFormat::setDefaultFormat(glFormat);
#endif
recentFileActions.fill(NULL, NaMainWindow::maxRecentFiles);
ui->setupUi(this);
setAcceptDrops(true);
// Z value comes from camera model
qRegisterMetaType<Vector3D>("Vector3D");
// hide neuron gallery until there are neurons to show
setViewMode(VIEW_SINGLE_STACK);
// ui->mipsFrame->setVisible(false);
// hide compartment map until it works correctly and is not so slow on Mac
ui->compartmentSelectGroupBox->hide();
dataFlowModel=0;
// TODO - neuronSelector should probably be a member of Na3DViewer, not of NaMainWindow
// neuronSelector = new NeuronSelector(this);
// Create stubs for recent file menu
for (int i = 0; i < maxRecentFiles; ++i) {
recentFileActions[i] = new OpenFileAction(this);
ui->menuOpen_Recent->addAction(recentFileActions[i]);
recentFileActions[i]->setVisible(false);
connect(recentFileActions[i], SIGNAL(openFileRequested(QString)),
this, SLOT(openFileOrUrl(QString)));
}
updateRecentFileActions();
// Create an area in the status bar for progress messages.
statusProgressMessage = new QLabel(NULL);
statusBar()->addWidget(statusProgressMessage);
statusProgressBar = new QProgressBar(NULL);
statusProgressBar->setValue(0);
statusProgressBar->setMinimum(0);
statusProgressBar->setMaximum(100);
statusBar()->addWidget(statusProgressBar);
statusProgressBar->hide();
statusProgressMessage->hide();
// hide progress bar for 3d viewer until it is needed
ui->widget_progress3d->hide();
// hide the File->Open 3D Image stack menu item
ui->menuFile->removeAction(ui->actionLoad_Tiff);
ui->menuFile->removeAction(ui->actionCell_Counter_3D_2ch_lsm);
// hide dev-version rotate-X movie maker, until it become more user-friendly
ui->menuExport->removeAction(ui->actionX_Rotation_Movie);
// hide fps option: it's for debugging
ui->menuView->removeAction(ui->actionMeasure_Frame_Rate);
// hide octree test item
ui->menuFile->removeAction(ui->actionOpen_Octree_Volume);
#ifdef USE_FFMPEG
ui->actionLoad_movie_as_texture->setVisible(true);
ui->actionLoad_fast_separation_result->setVisible(true);
#else
ui->actionLoad_movie_as_texture->setVisible(false);
ui->actionLoad_fast_separation_result->setVisible(false);
#endif
// visualize compartment map
//QDockWidget *dock = new QDockWidget(tr("Compartment Map"), this);
//dock->setWidget( ui->compartmentMapWidget);
qRegisterMetaType<QList<LabelSurf> >("QList<LabelSurf>");
ui->compartmentMapWidget->setComboBox(ui->compartmentMapComboBox);
connect(ui->compartmentMapComboBox, SIGNAL(currentIndexChanged(int)), ui->compartmentMapWidget, SLOT(switchCompartment(int)));
//connect(ui->compartmentMapWidget, SIGNAL(viscomp3dview(QList<LabelSurf>)), (Renderer_gl1*)(ui->v3dr_glwidget->getRenderer()), SLOT(setListLabelSurf(QList<LabelSurf>))); // vis compartments in Na3Dviewer
// Wire up MIP viewer
// Status bar message
connect(ui->naLargeMIPWidget, SIGNAL(statusMessage(const QString&)),
statusBar(), SLOT(showMessage(const QString&)));
connect(ui->naZStackWidget, SIGNAL(statusMessage(const QString&)),
statusBar(), SLOT(showMessage(const QString&)));
ui->progressWidgetMip->hide();
connect(ui->naLargeMIPWidget, SIGNAL(showProgress()),
ui->progressWidgetMip, SLOT(show()));
connect(ui->naLargeMIPWidget, SIGNAL(hideProgress()),
ui->progressWidgetMip, SLOT(hide()));
connect(ui->naLargeMIPWidget, SIGNAL(setProgressMax(int)),
ui->progressBarMip, SLOT(setMaximum(int)));
connect(ui->naLargeMIPWidget, SIGNAL(setProgress(int)),
ui->progressBarMip, SLOT(setValue(int)));
ui->progressWidgetZ->hide();
// ui->gammaWidget_Zstack->hide();
// Distinguish the two gamma sliders
ui->sharedGammaWidget->gamma_label->setText("N "); // "neurons"
ui->sharedGammaWidget->setToolTip(tr("Brightness/gamma of data"));
ui->referenceGammaWidget->gamma_label->setText("R "); // "reference"
ui->referenceGammaWidget->setToolTip(tr("Brightness/gamma of reference channel"));
ui->BoxSize_spinBox->setMinimum(NaZStackWidget::minHdrBoxSize);
// Wire up Z-stack / HDR viewer
connect(ui->HDR_checkBox, SIGNAL(toggled(bool)),
ui->naZStackWidget, SLOT(setHDRCheckState(bool)));
connect(ui->naZStackWidget, SIGNAL(changedHDRCheckState(bool)),
ui->HDR_checkBox, SLOT(setChecked(bool)));
connect(ui->HDRRed_pushButton, SIGNAL(clicked()),
ui->naZStackWidget, SLOT(setRedChannel()));
connect(ui->HDRGreen_pushButton, SIGNAL(clicked()),
ui->naZStackWidget, SLOT(setGreenChannel()));
connect(ui->HDRBlue_pushButton, SIGNAL(clicked()),
ui->naZStackWidget, SLOT(setBlueChannel()));
connect(ui->HDRNc82_pushButton, SIGNAL(clicked()),
ui->naZStackWidget, SLOT(setNc82Channel()));
connect(ui->naZStackWidget, SIGNAL(curColorChannelChanged(NaZStackWidget::Color)),
this, SLOT(onHdrChannelChanged(NaZStackWidget::Color)));
ui->naZStackWidget->setHDRCheckState(false);
connect(ui->ZSlice_horizontalScrollBar, SIGNAL(valueChanged(int)),
ui->naZStackWidget, SLOT(setCurrentZSlice(int)));
connect(ui->naZStackWidget, SIGNAL(curZsliceChanged(int)),
ui->ZSlice_horizontalScrollBar, SLOT(setValue(int)));
connect(ui->BoxSize_spinBox, SIGNAL(valueChanged(int)),
ui->naZStackWidget, SLOT(setHdrBoxSize(int)));
connect(ui->naZStackWidget, SIGNAL(hdrBoxSizeChanged(int)),
ui->BoxSize_spinBox, SLOT(setValue(int)));
// 3D viewer
connect(ui->rotationResetButton, SIGNAL(clicked()),
ui->v3dr_glwidget, SLOT(resetRotation()));
connect(ui->nutateButton, SIGNAL(toggled(bool)),
this, SLOT(setNutate(bool)));
connect(this, SIGNAL(nutatingChanged(bool)),
ui->nutateButton, SLOT(setChecked(bool)));
connect(ui->actionAnimate_3D_nutation, SIGNAL(toggled(bool)),
this, SLOT(setNutate(bool)));
connect(this, SIGNAL(nutatingChanged(bool)),
ui->actionAnimate_3D_nutation, SLOT(setChecked(bool)));
connect(ui->v3dr_glwidget, SIGNAL(signalTextureLoaded()),
this, SLOT(onDataLoadFinished()));
/* obsolete. now we toggle channels.
connect(ui->redToggleButton, SIGNAL(toggled(bool)),
ui->v3dr_glwidget, SLOT(setChannelR(bool)));
connect(ui->greenToggleButton, SIGNAL(toggled(bool)),
ui->v3dr_glwidget, SLOT(setChannelG(bool)));
connect(ui->blueToggleButton, SIGNAL(toggled(bool)),
ui->v3dr_glwidget, SLOT(setChannelB(bool)));
*/
// 3D rotation
// synchronize compartment map
connect(&sharedCameraModel, SIGNAL(rotationChanged(const Rotation3D&)),
ui->compartmentMapWidget, SLOT(setRotation(const Rotation3D&)));
// connect(&sharedCameraModel, SIGNAL(focusChanged(const Vector3D&)),
// ui->compartmentMapWidget, SLOT(setFocus(const Vector3D&)));
connect(&(ui->v3dr_glwidget->cameraModel), SIGNAL(rotationChanged(const Rotation3D&)),
this, SLOT(on3DViewerRotationChanged(const Rotation3D&)));
connect(ui->rotXWidget, SIGNAL(angleChanged(int)),
this, SLOT(update3DViewerXYZBodyRotation()));
connect(ui->rotYWidget, SIGNAL(angleChanged(int)),
this, SLOT(update3DViewerXYZBodyRotation()));
connect(ui->rotZWidget, SIGNAL(angleChanged(int)),
this, SLOT(update3DViewerXYZBodyRotation()));
connect(ui->v3dr_glwidget, SIGNAL(progressValueChanged(int)),
this, SLOT(set3DProgress(int)));
connect(ui->v3dr_glwidget, SIGNAL(progressComplete()),
this, SLOT(complete3DProgress()));
connect(ui->v3dr_glwidget, SIGNAL(progressMessageChanged(QString)),
this, SLOT(set3DProgressMessage(QString)));
connect(ui->v3dr_glwidget, SIGNAL(progressAborted(QString)),
this, SLOT(complete3DProgress()));
// 3D volume cut
connect(ui->v3dr_glwidget, SIGNAL(changeXCut0(int)), ui->XcminSlider, SLOT(setValue(int))); // x-cut
connect(ui->XcminSlider, SIGNAL(valueChanged(int)), ui->v3dr_glwidget, SLOT(setXCut0(int)));
connect(ui->v3dr_glwidget, SIGNAL(changeXCut1(int)), ui->XcmaxSlider, SLOT(setValue(int)));
connect(ui->XcmaxSlider, SIGNAL(valueChanged(int)), ui->v3dr_glwidget, SLOT(setXCut1(int)));
connect(ui->v3dr_glwidget, SIGNAL(changeYCut0(int)), ui->YcminSlider, SLOT(setValue(int))); // y-cut
connect(ui->YcminSlider, SIGNAL(valueChanged(int)), ui->v3dr_glwidget, SLOT(setYCut0(int)));
connect(ui->v3dr_glwidget, SIGNAL(changeYCut1(int)), ui->YcmaxSlider, SLOT(setValue(int)));
connect(ui->YcmaxSlider, SIGNAL(valueChanged(int)), ui->v3dr_glwidget, SLOT(setYCut1(int)));
connect(ui->v3dr_glwidget, SIGNAL(changeZCut0(int)), ui->ZcminSlider, SLOT(setValue(int))); // z-cut
connect(ui->ZcminSlider, SIGNAL(valueChanged(int)), ui->v3dr_glwidget, SLOT(setZCut0(int)));
connect(ui->v3dr_glwidget, SIGNAL(changeZCut1(int)), ui->ZcmaxSlider, SLOT(setValue(int)));
connect(ui->ZcmaxSlider, SIGNAL(valueChanged(int)), ui->v3dr_glwidget, SLOT(setZCut1(int)));
connect(ui->XCutCB, SIGNAL(stateChanged(int)), ui->v3dr_glwidget, SLOT(setXCutLock(int)));
connect(ui->YCutCB, SIGNAL(stateChanged(int)), ui->v3dr_glwidget, SLOT(setYCutLock(int)));
connect(ui->ZCutCB, SIGNAL(stateChanged(int)), ui->v3dr_glwidget, SLOT(setZCutLock(int)));
connect(ui->slabThicknessSlider, SIGNAL(valueChanged(int)),
ui->v3dr_glwidget, SLOT(setSlabThickness(int)));
connect(ui->slabPositionSlider, SIGNAL(valueChanged(int)),
ui->v3dr_glwidget, SLOT(setSlabPosition(int)));
connect(ui->v3dr_glwidget, SIGNAL(slabThicknessChanged(int)),
this, SLOT(onSlabThicknessChanged(int)));
// ui->slabThicknessSlider, SLOT(setValue(int)));
connect(ui->v3dr_glwidget, SIGNAL(slabPositionChanged(int)),
ui->slabPositionSlider, SLOT(setValue(int)));
connect(ui->freezeFrontBackButton, SIGNAL(clicked()),
ui->v3dr_glwidget, SLOT(clipSlab()));
// alpha blending
connect(ui->action3D_alpha_blending, SIGNAL(toggled(bool)),
ui->v3dr_glwidget, SLOT(setAlphaBlending(bool)));
connect(ui->v3dr_glwidget, SIGNAL(alphaBlendingChanged(bool)),
ui->action3D_alpha_blending, SLOT(setChecked(bool)));
// show axes
connect(ui->actionShow_Axes, SIGNAL(toggled(bool)),
ui->v3dr_glwidget, SLOT(setShowCornerAxes(bool)));
// Whether to use common zoom and focus in MIP, ZStack and 3D viewers
connect(ui->actionLink_viewers, SIGNAL(toggled(bool)),
this, SLOT(unifyCameras(bool)));
unifyCameras(true); // Start with cameras linked
connect(ui->resetViewButton, SIGNAL(clicked()),
this, SLOT(resetView()));
connect(ui->zoomWidget, SIGNAL(zoomValueChanged(qreal)),
&sharedCameraModel, SLOT(setScale(qreal)));
connect(&sharedCameraModel, SIGNAL(scaleChanged(qreal)),
ui->zoomWidget, SLOT(setZoomValue(qreal)));
connect(&sharedCameraModel, SIGNAL(scaleChanged(qreal)),
this, SLOT(updateViewers()));
// Colors
connect(ui->redToggleButton, SIGNAL(toggled(bool)),
this, SLOT(setChannelZeroVisibility(bool)));
connect(ui->greenToggleButton, SIGNAL(toggled(bool)),
this, SLOT(setChannelOneVisibility(bool)));
connect(ui->blueToggleButton, SIGNAL(toggled(bool)),
this, SLOT(setChannelTwoVisibility(bool)));
// Crosshair
connect(ui->actionShow_Crosshair, SIGNAL(toggled(bool)),
this, SLOT(setCrosshairVisibility(bool)));
connect(this, SIGNAL(crosshairVisibilityChanged(bool)),
ui->actionShow_Crosshair, SLOT(setChecked(bool)));
connect(this, SIGNAL(crosshairVisibilityChanged(bool)),
ui->naLargeMIPWidget, SLOT(showCrosshair(bool)));
connect(this, SIGNAL(crosshairVisibilityChanged(bool)),
ui->v3dr_glwidget, SLOT(showCrosshair(bool)));
connect(this, SIGNAL(crosshairVisibilityChanged(bool)),
ui->naZStackWidget, SLOT(showCrosshair(bool)));
retrieveCrosshairVisibilitySetting();
// Axes
// TODO I want a small set of axes that sits in the lower left corner. The gigantic axes are less useful.
// connect(ui->actionShow_Axes, SIGNAL(toggled(bool)),
// ui->v3dr_glwidget, SLOT(enableShowAxes(bool)));
// Clear status message when viewer changes
connect(ui->viewerStackedWidget, SIGNAL(currentChanged(int)),
this, SLOT(onViewerChanged(int)));
// Create "Undo" menu options
// TODO - figure out which of these variables to expose once we have a QUndoCommand to work with.
QUndoGroup * undoGroup = new QUndoGroup(this);
QAction * undoAction = undoGroup->createUndoAction(this);
undoAction->setShortcuts(QKeySequence::Undo);
QAction * redoAction = undoGroup->createRedoAction(this);
redoAction->setShortcuts(QKeySequence::Redo);
ui->menuEdit->insertAction(ui->menuEdit->actions().at(0), redoAction);
ui->menuEdit->insertAction(redoAction, undoAction);
// expose undoStack
undoStack = new QUndoStack(undoGroup);
undoGroup->setActiveStack(undoStack);
ui->v3dr_glwidget->setUndoStack(*undoStack);
// Connect sort buttons to gallery widget
connect(ui->gallerySortBySizeButton, SIGNAL(clicked()),
ui->fragmentGalleryWidget, SLOT(sortBySize()));
connect(ui->gallerySortByColorButton, SIGNAL(clicked()),
ui->fragmentGalleryWidget, SLOT(sortByColor()));
connect(ui->gallerySortByIndexButton, SIGNAL(clicked()),
ui->fragmentGalleryWidget, SLOT(sortByIndex()));
connect(ui->gallerySortByNameButton, SIGNAL(clicked()),
ui->fragmentGalleryWidget, SLOT(sortByName()));
// Allow cross-thread signals/slots that pass QList<int>
qRegisterMetaType< QList<int> >("QList<int>");
// Set up the annotation widget
ui->annotationFrame->setMainWindow(this);
ui->centralwidget->installEventFilter(ui->annotationFrame);
ui->annotationFrame->consoleConnect(3);
// NeuronSelector helper class for selecting neurons
connect(&neuronSelector, SIGNAL(neuronSelected(int)),
ui->annotationFrame, SLOT(selectNeuron(int)));
connect(ui->v3dr_glwidget, SIGNAL(neuronSelected(double,double,double)),
&neuronSelector, SLOT(updateSelectedPosition(double,double,double)));
connect(ui->actionDynamic_range, SIGNAL(triggered(bool)),
this, SLOT(showDynamicRangeTool()));
connect(ui->actionFull_Screen, SIGNAL(toggled(bool)),
this, SLOT(setFullScreen(bool)));
connect(this, SIGNAL(benchmarkTimerResetRequested()),
this, SLOT(resetBenchmarkTimer()));
connect(this, SIGNAL(benchmarkTimerPrintRequested(QString)),
this, SLOT(printBenchmarkTimer(QString)));
connect(ui->v3dr_glwidget, SIGNAL(benchmarkTimerPrintRequested(QString)),
this, SIGNAL(benchmarkTimerPrintRequested(QString)));
connect(ui->v3dr_glwidget, SIGNAL(benchmarkTimerResetRequested()),
this, SIGNAL(benchmarkTimerResetRequested()));
initializeContextMenus();
initializeStereo3DOptions();
connectCustomCut();
}
/* slot */
void NaMainWindow::onSlabThicknessChanged(int t)
{
// qDebug() << "NaMainWindow::onSlabThicknessChanged()" << t << __FILE__ << __LINE__;
if (t > ui->slabThicknessSlider->maximum()) {
ui->slabThicknessSlider->setMaximum(t);
ui->slabPositionSlider->setMaximum(t/2);
ui->slabPositionSlider->setMinimum(-t/2);
}
ui->slabThicknessSlider->setValue(t);
}
/* slot */
void NaMainWindow::resetBenchmarkTimer()
{
mainWindowStopWatch.restart();
}
/* slot */
void NaMainWindow::printBenchmarkTimer(QString message)
{
// qDebug() << "BENCHMARK" << message << "at" << mainWindowStopWatch.elapsed()/1000.0 << "seconds";
}
/* virtual */
void NaMainWindow::keyPressEvent(QKeyEvent *event)
{
// Press <ESC> to exit full screen mode
if (event->key() == Qt::Key_Escape)
{
// qDebug() << "escape pressed in main window";
exitFullScreen();
}
QMainWindow::keyPressEvent(event);
}
/* slot */
void NaMainWindow::setViewMode(ViewMode mode)
{
// if (mode == viewMode)
// return; // no change
viewMode = mode;
if (mode == VIEW_SINGLE_STACK) {
ui->mipsFrame->setVisible(false);
ui->annotationFrame->setVisible(true);
ui->referenceGammaWidget->setVisible(false);
// qDebug() << "Changing to single stack mode" << __FILE__ << __LINE__;
}
if (mode == VIEW_NEURON_SEPARATION) {
ui->mipsFrame->setVisible(true);
ui->annotationFrame->setVisible(true);
ui->referenceGammaWidget->setVisible(true);
// qDebug() << "Changing to separation result mode" << __FILE__ << __LINE__;
}
update();
}
/* slot */
void NaMainWindow::exitFullScreen()
{
if (! isFullScreen())
return;
if (viewMode == VIEW_NEURON_SEPARATION)
{
ui->mipsFrame->show();
}
ui->annotationFrame->show();
ui->viewerSelectorAndControlFrame->show();
statusBar()->show();
showNormal();
}
/* slot */
void NaMainWindow::setFullScreen(bool b)
{
if (isFullScreen() == b)
return;
if (b)
{
ui->annotationFrame->hide();
ui->mipsFrame->hide();
ui->viewerSelectorAndControlFrame->hide();
statusBar()->hide();
showFullScreen();
}
else
{
exitFullScreen();
}
}
QString NaMainWindow::getDataDirectoryPathWithDialog()
{
QString initialDialogPath = QDir::currentPath();
// Use previous annotation path as initial file browser location
QSettings settings(QSettings::UserScope, "HHMI", "Vaa3D");
QString previousAnnotationDirString = settings.value("NeuronAnnotatorPreviousAnnotationPath").toString();
if (! previousAnnotationDirString.isEmpty()) {
QDir previousAnnotationDir(previousAnnotationDirString);
if (previousAnnotationDir.exists() && previousAnnotationDir.isReadable())
{
initialDialogPath = previousAnnotationDir.path();
// qDebug() << "Annotation directory path = " << initialDialogPath;
}
}
QString dirName = QFileDialog::getExistingDirectory(
this,
"Select neuron separation directory",
initialDialogPath,
QFileDialog::ShowDirsOnly);
if (dirName.isEmpty())
return "";
QDir dir(dirName);
if (! dir.exists() )
{
QMessageBox::warning(this, tr("No such directory"),
QString("'%1'\n No such directory.\nIs the file share mounted?\nHas the directory moved?").arg(dirName));
return "";
}
// Remember parent directory to ease browsing next time
if (dir.cdUp()) {
if (dir.exists()) {
// qDebug() << "Saving annotation dir parent path " << parentDir.path();
settings.setValue("NeuronAnnotatorPreviousAnnotationPath", dir.path());
}
else {
// qDebug() << "Problem saving parent directory of " << dirName;
}
}
return dirName;
}
QString NaMainWindow::getStackPathWithDialog()
{
QString initialDialogPath = QDir::currentPath();
// Use previous annotation path as initial file browser location
QSettings settings(QSettings::UserScope, "HHMI", "Vaa3D");
QString previousAnnotationDirString = settings.value("NeuronAnnotatorPreviousAnnotationPath").toString();
if (! previousAnnotationDirString.isEmpty()) {
QDir previousAnnotationDir(previousAnnotationDirString);
if (previousAnnotationDir.exists() && previousAnnotationDir.isReadable())
{
initialDialogPath = previousAnnotationDir.path();
// qDebug() << "Annotation directory path = " << initialDialogPath;
}
}
QString fileName = QFileDialog::getOpenFileName(this,
"Select volume file",
initialDialogPath,
tr("Stacks (*.lsm *.tif *.tiff *.mp4 *.v3draw *.v3dpbd)"));
if (fileName.isEmpty()) // Silently do nothing when user presses Cancel. No error dialogs please!
return "";
QFile movieFile(fileName);
if (! movieFile.exists() )
{
QMessageBox::warning(this, tr("No such file"),
QString("'%1'\n No such file.\nIs the file share mounted?\nHas the directory moved?").arg(fileName));
return "";
}
// Remember parent directory to ease browsing next time
QDir parentDir = QFileInfo(movieFile).dir();
if (parentDir.exists()) {
// qDebug() << "Saving annotation dir parent path " << parentDir.path();
settings.setValue("NeuronAnnotatorPreviousAnnotationPath", parentDir.path());
}
else {
// qDebug() << "Problem saving parent directory of " << fileName;
}
return fileName;
}
/* slot */
void NaMainWindow::on_action1280x720_triggered() {
int w = ui->v3dr_glwidget->width();
int h = ui->v3dr_glwidget->height();
int dw = 1280 - w;
int dh = 720 - h;
resize(width() + dw, height() + dh);
}
/* slot */
void NaMainWindow::on_actionAdd_landmark_at_cursor_triggered() {
// qDebug() << "add landmark";
RendererNeuronAnnotator * rna = ui->v3dr_glwidget->getRendererNa();
if (rna != NULL) {
float radius = 20.0;
Vector3D focus = sharedCameraModel.focus();
// Shape comes from type not shape argument. whatever
// 0 - dodecahedron
// 1 - cube
ImageMarker landmark = ImageMarker(2, 0, focus.x(), rna->dim2 - focus.y(), rna->dim3 - focus.z(), radius);
// cycle colors red->green->blue
int c = viewerLandmarks3D.size() % 3;
if (c == 0)
landmark.color.i = 0xff5050ff;
else if (c == 1)
landmark.color.i = 0xff50ff50;
else if (c == 2)
landmark.color.i = 0xffff5050;
viewerLandmarks3D << landmark;
rna->sShowMarkers = true;
rna->markerSize = (int) radius;
rna->setLandmarks(viewerLandmarks3D);
rna->b_showMarkerLabel = false;
rna->b_showMarkerName = false;
// rna->updateLandmark(); // deletes markerList!
}
}
/* slot */
void NaMainWindow::on_actionAppend_key_frame_at_current_view_triggered() {
// qDebug() << "append frame";
KeyFrame newFrame(4.0);
newFrame.storeCameraSettings(sharedCameraModel);
newFrame.storeLandmarkVisibility(viewerLandmarks3D);
if (dataFlowModel != NULL)
{
DataColorModel::Reader reader(dataFlowModel->getDataColorModel());
newFrame.storeChannelColorModel(reader);
}
currentMovie.appendKeyFrame(newFrame);
}
/* slot */
void NaMainWindow::on_actionLoad_movie_as_texture_triggered()
{
#ifdef USE_FFMPEG
QString fileName = getStackPathWithDialog();
if (fileName.isEmpty()) return;
if (! dataFlowModel) return;
dataFlowModel->getFast3DTexture().loadFile(fileName);
#endif
}
void NaMainWindow::on_actionClear_landmarks_triggered() {
viewerLandmarks3D.clear();
RendererNeuronAnnotator * rna = ui->v3dr_glwidget->getRendererNa();
if (rna != NULL) {
rna->clearLandmarks();
}
}
void NaMainWindow::on_actionClear_movie_triggered() {
currentMovie.clear();
}
/* slot */
void NaMainWindow::on_actionMeasure_Frame_Rate_triggered()
{
cout << "Measuring frame rate..." << endl;
Rotation3D currentRotation = sharedCameraModel.rotation();
Rotation3D dRot;
const int numSteps = 30;
dRot.setRotationFromAngleAboutUnitVector(
2.0 * 3.14159 / numSteps,
UnitVector3D(0, 1, 0));
QElapsedTimer timer;
timer.start();
for (int deg = 0; deg < numSteps; ++deg)
{
// cout << "step " << deg << endl;
currentRotation = dRot * currentRotation;
sharedCameraModel.setRotation(currentRotation);
QCoreApplication::processEvents();
ui->v3dr_glwidget->updateGL();
QCoreApplication::processEvents();
}
qint64 msTime = timer.elapsed();
double meanFrameTime = msTime / (double)(numSteps);
double frameRate = 1000.0 / meanFrameTime;
cout << meanFrameTime << " ms per frame; " << frameRate << " frames per second" << endl;
// cout << timer.elapsed() << endl;
}
/* slot */
void NaMainWindow::on_actionOpen_Octree_Volume_triggered()
{
QString fileName = getStackPathWithDialog();
if (fileName.isEmpty())
return;
loadSingleStack(fileName, false);
// TODO - actually do something clever
}
/* slot */
void NaMainWindow::on_actionOpen_Single_Movie_Stack_triggered()
{
// qDebug() << "NaMainWindow::on_actionOpen_Single_Movie_Stack_triggered";
QString initialDialogPath = QDir::currentPath();
// Use previous annotation path as initial file browser location
QSettings settings(QSettings::UserScope, "HHMI", "Vaa3D");
QString previousAnnotationDirString = settings.value("NeuronAnnotatorPreviousAnnotationPath").toString();
if (! previousAnnotationDirString.isEmpty()) {
QDir previousAnnotationDir(previousAnnotationDirString);
if (previousAnnotationDir.exists() && previousAnnotationDir.isReadable())
{
initialDialogPath = previousAnnotationDir.path();
// qDebug() << "Annotation directory path = " << initialDialogPath;
}
}
QString fileName = QFileDialog::getOpenFileName(this,
"Select MPEG4 format volume data",
initialDialogPath);
// qDebug() << dirName;
// If user presses cancel, QFileDialog::getOpenFileName returns a null string
if (fileName.isEmpty()) // Silently do nothing when user presses Cancel. No error dialogs please!
return;
QFile movieFile(fileName);
if (! movieFile.exists() )
{
QMessageBox::warning(this, tr("No such file"),
QString("'%1'\n No such file.\nIs the file share mounted?\nHas the directory moved?").arg(fileName));
return;
}
// Remember parent directory to ease browsing next time
QDir parentDir = QFileInfo(movieFile).dir();
if (parentDir.exists()) {
// qDebug() << "Saving annotation dir parent path " << parentDir.path();
settings.setValue("NeuronAnnotatorPreviousAnnotationPath", parentDir.path());
}
else {
// qDebug() << "Problem saving parent directory of " << fileName;
}
loadSingleStack(fileName, false);
}
void NaMainWindow::on_actionPlay_movie_triggered() {
// qDebug() << "Play movie";
currentMovie.rewind();
QTime movieTimer;
movieTimer.start();
double movieElapsedTime = 0.0;
AnimationFrame frame;
bool bPlayRealTime = true;
while (currentMovie.hasMoreFrames()) {
frame = currentMovie.getNextFrame();
// Skip frames to catch up, if behind schedule
movieElapsedTime += currentMovie.secondsPerFrame;
if (bPlayRealTime && (movieElapsedTime < movieTimer.elapsed()/1000.0))
continue; // race to next frame
//
animateToFrame(frame);
}
// Alway finish in final frame.
if (bPlayRealTime)
animateToFrame(frame);
}
void NaMainWindow::animateToFrame(const AnimationFrame& frame) {
frame.retrieveCameraSettings(sharedCameraModel);
frame.retrieveLandmarkVisibility(viewerLandmarks3D);
RendererNeuronAnnotator * rna = ui->v3dr_glwidget->getRendererNa();
if (rna != NULL) {
rna->clearLandmarks();
rna->setLandmarks(viewerLandmarks3D);
rna->sShowMarkers = true;
}
// One channel visibility at a time
// Test for positive comparisons, to avoid NaN values
if (frame.channelZeroVisibility >= 0.5)
emit setChannelZeroVisibility(true);
else if (frame.channelZeroVisibility < 0.5)
emit setChannelZeroVisibility(false);
//
if (frame.channelOneVisibility >= 0.5)
emit setChannelOneVisibility(true);
else if (frame.channelOneVisibility < 0.5)
emit setChannelOneVisibility(false);
//
if (frame.channelTwoVisibility >= 0.5)
emit setChannelTwoVisibility(true);
else if (frame.channelTwoVisibility < 0.5)
emit setChannelTwoVisibility(false);
//
if (frame.channelThreeVisibility >= 0.5)
emit setChannelThreeVisibility(true);
else if (frame.channelThreeVisibility < 0.5)
emit setChannelThreeVisibility(false);
ui->v3dr_glwidget->update();
QApplication::processEvents();
}
void NaMainWindow::on_actionSave_movie_frames_triggered() {
// Get output folder
static QString startFolder;
QString sf;
if (! startFolder.isEmpty())
sf = startFolder;
QString folderName = QFileDialog::getExistingDirectory(this,
tr("Choose folder to store movie frame images"),
sf);
if (folderName.isEmpty())
return;
QDir folder(folderName);
if (! folder.exists()) {
QMessageBox::warning(this, "No such folder", "Folder " +folderName+ " does not exist");
return;
}
currentMovie.rewind();
double secondsElapsed = 0.0;
int frameIndex = 0;
int savedCount = 0;
while (currentMovie.hasMoreFrames()) {
animateToFrame(currentMovie.getNextFrame());
QImage grabbedFrame = ui->v3dr_glwidget->grabFrameBuffer(true); // true->with alpha
frameIndex += 1;
QString fileName;
fileName.sprintf("frame_%05d.png", frameIndex);
fileName = folder.absoluteFilePath(fileName);
qDebug() << fileName;
if (grabbedFrame.save(fileName)) {
savedCount += 1;
}
else {
// TODO - better error handling
qDebug() << "Failed to save frame" << fileName;
}
}
QMessageBox::information(this, "Finished saving frames", QString("Saved %1 frames").arg(savedCount));
// Remember this folder next time
startFolder = folderName;
}
void NaMainWindow::on_zThicknessDoubleSpinBox_valueChanged(double val) {
ui->v3dr_glwidget->setThickness(val);
}
static bool isFolder(QString path) {
if (path.isEmpty())
return false;
if (path.endsWith("/"))
return true;
if (QFileInfo(path).suffix().isEmpty())
return true;
return false;
}
void NaMainWindow::openFileOrUrl(QString name)
{
// qDebug() << "NaMainWindow::openFileOrUrl" << name << __FILE__ << __LINE__;
if (name.isEmpty())
return;
QUrl url(name);
if (! url.isValid())
url = QUrl::fromLocalFile(name);
bool isDir = true;
if (url.isValid() && (!url.isRelative()) && url.toLocalFile().isEmpty())
isDir = isFolder(url.path()); // non-file URL
else
isDir = QFileInfo(url.toLocalFile()).isDir(); // local file
if (isDir)
openMulticolorImageStack(url);
else
loadSingleStack(url);
}
/* slot */
void NaMainWindow::setCrosshairVisibility(bool b)
{
if (bShowCrosshair == b) return; // no change
bShowCrosshair = b;
QSettings settings(QSettings::UserScope, "HHMI", "Vaa3D");
settings.setValue("NaCrosshairVisibility", bShowCrosshair);
emit crosshairVisibilityChanged(bShowCrosshair);
}
void NaMainWindow::retrieveCrosshairVisibilitySetting()
{
QSettings settings(QSettings::UserScope, "HHMI", "Vaa3D");
bool bVisible = true; // default to "on"
QVariant val = settings.value("NaCrosshairVisibility");
if (! val.isNull())
bVisible = val.toBool();
setCrosshairVisibility(bVisible);
}
/////////////////////////////////////////////////////
// Drop volume files onto main window to view them //
/////////////////////////////////////////////////////
// Return file name if the dragged item can be usefully dropped into the NeuronAnnotator main window
QUrl checkDragEvent(QDropEvent* event)
{
QList<QUrl> urls;
if (event->mimeData()->hasUrls())
urls = event->mimeData()->urls();
// Maybe the user dragged a string with a filename or url
else if (event->mimeData()->hasText()) {
QString text = event->mimeData()->text();
QUrl url(text);
if (url.isValid() && ! url.isEmpty())
urls.append(url);
else {
if (QFileInfo(text).exists())
urls.append(QUrl::fromLocalFile(text));
}
}
if (urls.isEmpty())
return QUrl();
/* Switch to use URLs, not files Jan 2013
QString fileName = urls.first().toLocalFile();
if (fileName.isEmpty())
return "";
*/
QUrl url = urls.first();
if (url.isEmpty())
return QUrl();
QString urlPath = url.path();
if (url.host() == "")
url.setHost("localhost");
// check for recognized file extensions
QString fileExtension = QFileInfo(urlPath).suffix().toLower();
if (fileExtension == "lsm")
return url;
if (fileExtension.startsWith("tif")) // tif or tiff
return url;
if (fileExtension.startsWith("v3d")) // v3draw or v3dpdb
return url;
#ifdef USE_FFMPEG
if (fileExtension.startsWith("mp4")) // v3draw or v3dpdb
return url;
#endif
bool isDir = isFolder(url.path());
if (isDir)
return url; // neuron separation folder
return QUrl();
}
void NaMainWindow::dragEnterEvent(QDragEnterEvent * event)
{
QUrl url = checkDragEvent(event);
if (! url.isEmpty())
event->acceptProposedAction();
// qDebug() << "NaMainWindow::dragEnterEvent" << fileName << __FILE__ << __LINE__;
}
void NaMainWindow::dropEvent(QDropEvent * event)
{
QUrl url = checkDragEvent(event);
if (url.isEmpty()) return;
openFileOrUrl(url.toString());
}
void NaMainWindow::moveEvent ( QMoveEvent * event )
{
// qDebug() << "NaMainWindow::moveEvent()" << __FILE__ << __LINE__;
ui->v3dr_glwidget->updateScreenPosition();
QMainWindow::moveEvent(event);
}
void NaMainWindow::loadSingleStack(QUrl url)
{
// Default to NeuronAnnotator, not Vaa3D classic, when URL is given
loadSingleStack(url, false);
}
/* slot */
void NaMainWindow::loadSingleStack(QString fileName)
{
QUrl url = QUrl::fromLocalFile(fileName);
loadSingleStack(url, true); // default to classic mode
}
/* slot */
void NaMainWindow::loadSingleStack(QUrl url, bool useVaa3dClassic)
{
if (url.isEmpty())
return;
if (! url.isValid())
return;
mainWindowStopWatch.start();
if (useVaa3dClassic) {
// Open in Vaa3D classic mode
ui->actionV3DDefault->trigger(); // switch mode
QString fileName = url.toLocalFile();
if (! fileName.isEmpty())
emit defaultVaa3dFileLoadRequested(fileName);
else
emit defaultVaa3dUrlLoadRequested(url);
}
else
{
setViewMode(VIEW_SINGLE_STACK);
onDataLoadStarted();
createNewDataFlowModel();
VolumeTexture& volumeTexture = dataFlowModel->getVolumeTexture();
volumeTexture.queueVolumeData();
QString baseName = QFileInfo(url.path()).fileName();
setTitle(baseName);
emit singleStackLoadRequested(url);
addUrlToRecentFilesList(url);
}
}
///////////////////////////////////
// User clip planes in 3D viewer //
///////////////////////////////////
void NaMainWindow::connectCustomCut()
{
connect(ui->customCutButton, SIGNAL(pressed()),
this, SLOT(applyCustomCut()));
connect(ui->defineClipPlaneButton, SIGNAL(pressed()),
this, SLOT(toggleCustomCutMode()));
}
/* slot */
void NaMainWindow::applyCustomCut()
{
// assert(isInCustomCutMode);
ui->v3dr_glwidget->applyCustomCut();
if (isInCustomCutMode)
toggleCustomCutMode();
}
/* slot */
void NaMainWindow::applyCustomKeepPlane()
{
// qDebug() << "NaMainWindow::applyCustomKeepPlane()" << __FILE__ << __LINE__;
// assert(isInCustomCutMode);
ui->v3dr_glwidget->applyCustomKeepPlane();
if (isInCustomCutMode)
toggleCustomCutMode();
}
/* slot */
void NaMainWindow::setCustomCutMode(bool doCustom)
{
if (doCustom)
{
// Activate custom cut mode
ui->defineClipPlaneButton->setText(tr("Cancel"));
ui->customCutButton->setEnabled(true);
ui->v3dr_glwidget->setCustomCutMode();
}
else
{
// Turn off custom cut mode
ui->defineClipPlaneButton->setText(tr("Custom..."));
ui->customCutButton->setEnabled(false);
ui->v3dr_glwidget->cancelCustomCutMode();
}
isInCustomCutMode = doCustom;
}
/* slot */
void NaMainWindow::toggleCustomCutMode()
{
setCustomCutMode(!isInCustomCutMode);
}
/* slot */
void NaMainWindow::showDynamicRangeTool()
{
// qDebug() << "NaMainWindow::showDynamicRangeTool";
if (! dynamicRangeTool) {
dynamicRangeTool = new DynamicRangeTool(this);
if (dataFlowModel)
dynamicRangeTool->setColorModel(&dataFlowModel->getDataColorModel());
else
dynamicRangeTool->setColorModel(NULL);
}
dynamicRangeTool->show();
}
void NaMainWindow::onDataLoadStarted()
{
// Give strong indication to user that load is in progress
ui->viewerControlTabWidget->setEnabled(false);
ViewerIndex currentIndex = (ViewerIndex)ui->viewerStackedWidget->currentIndex();
if (currentIndex != VIEWER_WAIT_LOADING_SCREEN)
recentViewer = currentIndex;
ui->viewerStackedWidget->setCurrentIndex(VIEWER_WAIT_LOADING_SCREEN);
update();
}
void NaMainWindow::onDataLoadFinished()
{
if (undoStack)
undoStack->clear();
ui->viewerStackedWidget->setCurrentIndex(recentViewer);
ui->viewerControlTabWidget->setEnabled(true);
// qDebug() << "Data load took" << mainWindowStopWatch.elapsed()/1000.0 << "seconds";
update();
}
void NaMainWindow::initializeStereo3DOptions()
{
// Only check one stereo format at a time
QActionGroup* stereoModeGroup = new QActionGroup(this);
stereoModeGroup->setExclusive(true);
stereoModeGroup->addAction(ui->actionMono_Off);
stereoModeGroup->addAction(ui->actionLeft_eye_view);
stereoModeGroup->addAction(ui->actionRight_eye_view);
stereoModeGroup->addAction(ui->actionQuadro_120_Hz);
stereoModeGroup->addAction(ui->actionAnaglyph_Red_Cyan);
stereoModeGroup->addAction(ui->actionAnaglyph_Green_Magenta);
stereoModeGroup->addAction(ui->actionRow_Interleaved_Zalman);
stereoModeGroup->addAction(ui->actionChecker_Interleaved_3DTV);
stereoModeGroup->addAction(ui->actionColumn_Interleaved);
connect(ui->actionMono_Off, SIGNAL(toggled(bool)),
ui->v3dr_glwidget, SLOT(setStereoOff(bool)));
connect(ui->actionLeft_eye_view, SIGNAL(toggled(bool)),
ui->v3dr_glwidget, SLOT(setStereoLeftEye(bool)));
connect(ui->actionRight_eye_view, SIGNAL(toggled(bool)),
ui->v3dr_glwidget, SLOT(setStereoRightEye(bool)));
connect(ui->actionQuadro_120_Hz, SIGNAL(toggled(bool)),
ui->v3dr_glwidget, SLOT(setStereoQuadBuffered(bool)));
connect(ui->actionAnaglyph_Red_Cyan, SIGNAL(toggled(bool)),
ui->v3dr_glwidget, SLOT(setStereoAnaglyphRedCyan(bool)));
connect(ui->actionAnaglyph_Green_Magenta, SIGNAL(toggled(bool)),
ui->v3dr_glwidget, SLOT(setStereoAnaglyphGreenMagenta(bool)));
connect(ui->actionRow_Interleaved_Zalman, SIGNAL(toggled(bool)),
ui->v3dr_glwidget, SLOT(setStereoRowInterleaved(bool)));
connect(ui->actionChecker_Interleaved_3DTV, SIGNAL(toggled(bool)),
ui->v3dr_glwidget, SLOT(setStereoCheckerInterleaved(bool)));
connect(ui->actionColumn_Interleaved, SIGNAL(toggled(bool)),
ui->v3dr_glwidget, SLOT(setStereoColumnInterleaved(bool)));
connect(ui->v3dr_glwidget, SIGNAL(quadStereoSupported(bool)),
this, SLOT(supportQuadStereo(bool)));
}
/* slot */
void NaMainWindow::supportQuadStereo(bool b)
{
ui->actionQuadro_120_Hz->setEnabled(b);
if ( (!b) && ui->actionQuadro_120_Hz->isChecked() )
ui->actionMono_Off->setChecked(true);
}
void NaMainWindow::connectContextMenus(const NeuronSelectionModel& neuronSelectionModel)
{
connect(showAllNeuronsInEmptySpaceAction, SIGNAL(triggered()),
&neuronSelectionModel, SLOT(showAllNeuronsInEmptySpace()));
connect(selectNoneAction, SIGNAL(triggered()),
&neuronSelectionModel, SLOT(clearSelection()));
connect(hideAllAction, SIGNAL(triggered()),
&neuronSelectionModel, SLOT(showNothing()));
neuronContextMenu->connectActions(neuronSelectionModel);
}
void NaMainWindow::initializeContextMenus()
{
viewerContextMenu = new QMenu(this);
neuronContextMenu = new NeuronContextMenu(this);
// Some QActions were already made in Qt Designer
showAllNeuronsInEmptySpaceAction = ui->actionShow_all_neurons_in_empty_space;
hideAllAction = ui->actionClear_Hide_All;
selectNoneAction = ui->actionSelect_None;
//
viewerContextMenu->addAction(showAllNeuronsInEmptySpaceAction);
viewerContextMenu->addAction(hideAllAction);
viewerContextMenu->addAction(selectNoneAction);
//
neuronContextMenu->addSeparator();
neuronContextMenu->addAction(showAllNeuronsInEmptySpaceAction);
neuronContextMenu->addAction(hideAllAction);
neuronContextMenu->addAction(selectNoneAction);
//
ui->naLargeMIPWidget->setContextMenus(viewerContextMenu, neuronContextMenu);
ui->naZStackWidget->setContextMenus(viewerContextMenu, neuronContextMenu);
ui->v3dr_glwidget->setContextMenus(viewerContextMenu, neuronContextMenu);
}
/* slot */
void NaMainWindow::onHdrChannelChanged(NaZStackWidget::Color channel)
{
switch(channel)
{
// Due to exclusive group, checking one button unchecks the others.
case NaZStackWidget::COLOR_RED:
ui->HDRRed_pushButton->setChecked(true);
break;
case NaZStackWidget::COLOR_GREEN:
ui->HDRGreen_pushButton->setChecked(true);
break;
case NaZStackWidget::COLOR_BLUE:
ui->HDRBlue_pushButton->setChecked(true);
break;
case NaZStackWidget::COLOR_NC82:
ui->HDRNc82_pushButton->setChecked(true);
break;
}
}
/* slot */
void NaMainWindow::onColorModelChanged()
{
// For historical reasons, reference channel is denormalized into both NeuronSelectionModel and DataColorModel
bool bReferenceColorIsVisible;
bool bReferenceOverlayIsVisible;
{
DataColorModel::Reader colorReader(dataFlowModel->getDataColorModel());
if (dataFlowModel->getDataColorModel().readerIsStale(colorReader)) return;
ui->redToggleButton->setChecked(colorReader.getChannelVisibility(0));
ui->greenToggleButton->setChecked(colorReader.getChannelVisibility(1));
ui->blueToggleButton->setChecked(colorReader.getChannelVisibility(2));
// Gamma
ui->sharedGammaWidget->setGammaBrightness(colorReader.getSharedGamma());
const int refIndex = 3;
NaVolumeData::Reader volumeReader(dataFlowModel->getVolumeData());
if (volumeReader.hasReadLock() && volumeReader.hasReferenceImage())
ui->referenceGammaWidget->setGammaBrightness(colorReader.getChannelGamma(refIndex));
// Communicate reference channel changes between NeuronSelectionModel and DataColorModel
bReferenceColorIsVisible = colorReader.getChannelVisibility(refIndex);
NeuronSelectionModel::Reader selectionReader(dataFlowModel->getNeuronSelectionModel());
if (! selectionReader.hasReadLock()) return;
if (selectionReader.getMaskStatusList().size() < 1)
return; // selection model is not active, single stack being viewed?
bReferenceOverlayIsVisible = selectionReader.getOverlayStatusList()[DataFlowModel::REFERENCE_MIP_INDEX];
} // release read locks
// Communicate reference visibility change, if any, to NeuronSelectionModel
if (bReferenceColorIsVisible != bReferenceOverlayIsVisible)
dataFlowModel->getNeuronSelectionModel().updateOverlay(DataFlowModel::REFERENCE_MIP_INDEX, bReferenceColorIsVisible);
}
/* slot */
void NaMainWindow::onSelectionModelVisibilityChanged()
{
// For historical reasons, reference channel is denormalized into both NeuronSelectionModel and DataColorModel
bool bReferenceColorIsVisible;
bool bReferenceOverlayIsVisible;
{
DataColorModel::Reader colorReader(dataFlowModel->getDataColorModel());
if (dataFlowModel->getDataColorModel().readerIsStale(colorReader)) return;
bReferenceColorIsVisible = colorReader.getChannelVisibility(3);
NeuronSelectionModel::Reader selectionReader(dataFlowModel->getNeuronSelectionModel());
if (! selectionReader.hasReadLock()) return;
bReferenceOverlayIsVisible = selectionReader.getOverlayStatusList()[DataFlowModel::REFERENCE_MIP_INDEX];
}
if (bReferenceColorIsVisible != bReferenceOverlayIsVisible)
// TODO - this causes a fork of data color model
// dataFlowModel->getDataColorModel().setChannelVisibility(3, bReferenceOverlayIsVisible);
emit channelVisibilityChanged(3, bReferenceOverlayIsVisible);
}
/* slot */
void NaMainWindow::setChannelZeroVisibility(bool v)
{
// qDebug() << "NaMainWindow::setChannelZeroVisibility" << v;
emit channelVisibilityChanged(0, v);
}
/* slot */
void NaMainWindow::setChannelOneVisibility(bool v)
{
emit channelVisibilityChanged(1, v);
}
/* slot */
void NaMainWindow::setChannelTwoVisibility(bool v)
{
emit channelVisibilityChanged(2, v);
}
/* slot */
void NaMainWindow::setChannelThreeVisibility(bool v) // reference channel
{
// For reference channel, update both DataColorModel AND "overlay" of NeuronSelectionModel
if (dataFlowModel)
dataFlowModel->getNeuronSelectionModel().updateOverlay(DataFlowModel::REFERENCE_MIP_INDEX, v);
emit channelVisibilityChanged(3, v);
}
void NaMainWindow::onViewerChanged(int viewerIndex)
{
QString msg(" viewer selected.");
switch(viewerIndex) {
case VIEWER_MIP:
msg = "Maximum intensity projection" + msg;
break;
case VIEWER_ZSTACK:
msg = "Z-stack" + msg;
break;
case VIEWER_3D:
msg = "3D" + msg;
break;
default:
return; // wait window gets no message
break;
}
ui->statusbar->showMessage(msg);
}
void NaMainWindow::setRotation(Rotation3D r) {
sharedCameraModel.setRotation(r);
ui->v3dr_glwidget->update();
}
void NaMainWindow::setNutate(bool bDoNutate)
{
if (bDoNutate) {
// qDebug() << "nutate";
if (! nutateThread) {
nutateThread = new NutateThread(0.2, this);
qRegisterMetaType<Rotation3D>("Rotation3D");
connect(nutateThread, SIGNAL(nutate(const Rotation3D&)),
this, SLOT(nutate(const Rotation3D&)));
}
if (! nutateThread->isRunning())
nutateThread->start(QThread::IdlePriority);
if (nutateThread->isRunning() && nutateThread->isPaused()) {
nutateThread->unpause();
emit nutatingChanged(bDoNutate);
}
}
else {
// qDebug() << "stop nutating";
if (!nutateThread) return;
if (nutateThread->isRunning() && (!nutateThread->isPaused())) {
nutateThread->pause();
emit nutatingChanged(bDoNutate);
}
}
}
void NaMainWindow::nutate(const Rotation3D& R) {
// qDebug() << "nutate!";
// std::cout << R << std::endl;
CameraModel& cam = ui->v3dr_glwidget->cameraModel;
if (!ui->v3dr_glwidget->mouseIsDragging()) {
cam.setRotation(R * cam.rotation());
// TODO - use a signal here instead of processEvents
QCoreApplication::processEvents(); // keep responsive during nutation
ui->v3dr_glwidget->update();
}
}
void NaMainWindow::resetView()
{
// TODO - might not work if cameras are not linked
Vector3D newFocus = ui->v3dr_glwidget->getDefaultFocus();
// cerr << newFocus << __LINE__ << __FILE__;
sharedCameraModel.setFocus(newFocus);
sharedCameraModel.setRotation(Rotation3D()); // identity rotation
sharedCameraModel.setScale(1.0); // fit to window
ui->viewerStackedWidget->update(); // whichever viewer is shown
}
void NaMainWindow::updateViewers()
{
ui->naLargeMIPWidget->update();
ui->naZStackWidget->update();
ui->v3dr_glwidget->update();
}
void NaMainWindow::unifyCameras(bool bDoUnify)
{
// TODO - explicitly copy parameters from active displayed viewer
if (bDoUnify) {
ui->naLargeMIPWidget->synchronizeWithCameraModel(&sharedCameraModel);
ui->naZStackWidget->synchronizeWithCameraModel(&sharedCameraModel);
ui->v3dr_glwidget->synchronizeWithCameraModel(&sharedCameraModel);
// qDebug() << "unify cameras";
}
else {
ui->naLargeMIPWidget->decoupleCameraModel(&sharedCameraModel);
ui->naZStackWidget->decoupleCameraModel(&sharedCameraModel);
ui->v3dr_glwidget->decoupleCameraModel(&sharedCameraModel);
// qDebug() << "disband cameras";
}
}
void NaMainWindow::setZRange(int minZ, int maxZ) {
// qDebug() << "minZ = " << minZ << "; maxZ = " << maxZ;
QString text = QString("of %1").arg(maxZ);
// qDebug() << text;
ui->ZSliceTotal_label->setText(text);
ui->ZSlice_horizontalScrollBar->setMaximum(maxZ);
ui->ZSlice_spinBox->setMaximum(maxZ);
ui->ZSlice_horizontalScrollBar->setMinimum(minZ);
ui->ZSlice_spinBox->setMinimum(minZ);
}
void NaMainWindow::handleCoordinatedCloseEvent(QCloseEvent *e)
{
if (isVisible())
{
// Remember window size for next time.
// These settings affect both NaMainWindow and classic V3D MainWindows. So only use
// NaMainWindow settings if the NaMainWindow is visible.
// qDebug() << "Saving NaMainWindow size and position";
QSettings settings(QSettings::UserScope, "HHMI", "Vaa3D");
settings.setValue("pos", pos());
settings.setValue("size", size());
}
e->accept();
}
void NaMainWindow::closeEvent(QCloseEvent *e)
{
V3dApplication::handleCloseEvent(e);
}
void NaMainWindow::on_actionQuit_triggered() {
close();
}
void NaMainWindow::on_actionV3DDefault_triggered() {
V3dApplication::deactivateNaMainWindow();
V3dApplication::activateMainWindow();
}
void NaMainWindow::on_actionNeuronAnnotator_triggered() {
V3dApplication::activateNaMainWindow();
V3dApplication::deactivateMainWindow();
}
void NaMainWindow::setV3DDefaultModeCheck(bool checkState) {
QAction* ui_actionV3DDefault = this->findChild<QAction*>("actionV3DDefault");
ui_actionV3DDefault->setChecked(checkState);
}
void NaMainWindow::setNeuronAnnotatorModeCheck(bool checkState) {
QAction* ui_actionNeuronAnnotator = this->findChild<QAction*>("actionNeuronAnnotator");
ui_actionNeuronAnnotator->setChecked(checkState);
}
void NaMainWindow::on_actionOpen_microCT_Cut_Planner_triggered()
{
if (cutPlanner == NULL) {
cutPlanner = new CutPlanner(sharedCameraModel, *ui->v3dr_glwidget, this);
connect(cutPlanner, SIGNAL(rotationAdjusted(Rotation3D)),
this, SLOT(setRotation(Rotation3D)));
connect(cutPlanner, SIGNAL(clipPlaneRequested()),
this, SLOT(applyCustomCut()));
connect(cutPlanner, SIGNAL(keepPlaneRequested()),
this, SLOT(applyCustomKeepPlane()));
connect(cutPlanner, SIGNAL(cutGuideRequested(bool)),
this, SLOT(setCustomCutMode(bool)));
connect(cutPlanner, SIGNAL(compartmentNamingRequested()),
this, SLOT(labelNeuronsAsFlyBrainCompartments()));
}
setCustomCutMode(true);
cutPlanner->show();
}
void NaMainWindow::on_actionOpen_triggered()
{
QString dirName = getDataDirectoryPathWithDialog();
openMulticolorImageStack(dirName);
}
bool NaMainWindow::openMulticolorImageStack(QString dirName)
{
// qDebug() << "NaMainWindow::openMulticolorImageStack" << dirName << __FILE__ << __LINE__;
// string could be a folder name or a URL string
// Try for folder name
QDir imageDir(dirName);
if (imageDir.exists()) {
QUrl url = QUrl::fromLocalFile(imageDir.absolutePath());
return openMulticolorImageStack(url);
}
// Path is always a folder, so make it explicit
if (! dirName.endsWith("/"))
dirName = dirName + "/";
// That didn't work: try for a URL
QUrl url(dirName);
if (! url.isValid()) {
QMessageBox::warning(this, tr("No such directory or URL"),
QString("'%1'\n No such directory or URL.\nIs the file share mounted?\nHas the directory moved?").arg(dirName));
return false;
}
// qDebug() << url;
bool result = openMulticolorImageStack(url);
if (! result) {
QMessageBox::warning(this, tr("Error opening directory or URL"),
QString("'%1'\n Could not open directory or URL.\nIs the file share mounted?\nHas the directory moved?").arg(dirName));
}
return result;
}
bool NaMainWindow::openMulticolorImageStack(QUrl url)
{
// qDebug() << "NaMainWindow::openMulticolorImageStack" << url << __FILE__ << __LINE__;
mainWindowStopWatch.start();
// std::cout << "Selected directory=" << imageDir.absolutePath().toStdString() << endl;
emit benchmarkTimerResetRequested();
emit benchmarkTimerPrintRequested("openMulticolorImageStack called");
if (! tearDownOldDataFlowModel()) {
QMessageBox::warning(this, tr("Could not close previous Annotation Session"),
"Error saving previous session and/or clearing memory - please exit application");
return false;
}
// Try to avoid Dec 2013 crash
ui->v3dr_glwidget->clearImage();
createNewDataFlowModel();
// reset front/back clip slab
ui->v3dr_glwidget->resetSlabThickness();
emit initializeColorModelRequested();
VolumeTexture& volumeTexture = dataFlowModel->getVolumeTexture();
// Queue up the various volumes to load, using StageFileLoaders
// delegated to VolumeTexture (3D viewer) and NaVolumeTexture (all viewers)
onDataLoadStarted();
if (! volumeTexture.queueSeparationFolder(url))
{
onDataLoadFinished();
return false;
}
// Make sure 3D viewer is showing if fast loading is enabled
if(volumeTexture.hasFastVolumesQueued()) {
// Fast loading is only interesting if 3D viewer is selected.
// So show the 3D viewer
ui->viewerControlTabWidget->setCurrentIndex(2);
setViewMode(VIEW_SINGLE_STACK); // no gallery yet.
}
// MulticolorImageStackNode setup is required for loadLsmMetadata call to succeed.
MultiColorImageStackNode* multiColorImageStackNode =
new MultiColorImageStackNode(url.toString());
QUrl fileUrl = url;
QString path = fileUrl.path();
if (! path.endsWith("/"))
path = path + "/";
// These file names will be overridden by Staged loader
fileUrl.setPath(path + "ConsolidatedSignal");
multiColorImageStackNode->setPathToOriginalImageStackFile(fileUrl.toString());
fileUrl.setPath(path + "Reference");
multiColorImageStackNode->setPathToReferenceStackFile(fileUrl.toString());
fileUrl.setPath(path + "ConsolidatedLabel");
multiColorImageStackNode->setPathToMulticolorLabelMaskFile(fileUrl.toString());
dataFlowModel->setMultiColorImageStackNode(multiColorImageStackNode);
if (! dataFlowModel->getVolumeData().queueSeparationFolder(url)) {
onDataLoadFinished();
return false;
}
// Correct Z-thickness
dataFlowModel->loadLsmMetadata();
// Kick off loading sequence
emit stagedLoadRequested();
// volumeTexture.loadNextVolume();
addUrlToRecentFilesList(url);
return true;
}
bool NaMainWindow::loadSeparationDirectoryV1Pbd(QUrl imageInputDirectory)
{
onDataLoadStarted();
// Need to construct (temporary until backend implemented) MultiColorImageStackNode from this directory
// This code will be redone when the node/filestore is implemented.
QUrl originalImageStackFilePath =
appendPath(imageInputDirectory, MultiColorImageStackNode::IMAGE_STACK_BASE_FILENAME);
QUrl maskLabelFilePath =
appendPath(imageInputDirectory, MultiColorImageStackNode::IMAGE_MASK_BASE_FILENAME);
QUrl referenceStackFilePath =
appendPath(imageInputDirectory, MultiColorImageStackNode::IMAGE_REFERENCE_BASE_FILENAME);
// Create input nodes
MultiColorImageStackNode* multiColorImageStackNode = new MultiColorImageStackNode(imageInputDirectory);
multiColorImageStackNode->setPathToMulticolorLabelMaskFile(maskLabelFilePath);
multiColorImageStackNode->setPathToOriginalImageStackFile(originalImageStackFilePath);
multiColorImageStackNode->setPathToReferenceStackFile(referenceStackFilePath);
dataFlowModel->setMultiColorImageStackNode(multiColorImageStackNode);
// Create result node
long resultNodeId=TimebasedIdentifierGenerator::getSingleId();
NeuronAnnotatorResultNode* resultNode = new NeuronAnnotatorResultNode(resultNodeId);
if (!resultNode->ensureDirectoryExists()) {
QMessageBox::warning(this, tr("Could not create NeuronAnnotationResultNode"),
"Error creating directory="+resultNode->getDirectoryPath());
return false;
}
dataFlowModel->setNeuronAnnotatorResultNode(resultNode);
// Opposite of fast loading behavior
dataFlowModel->getVolumeData().doFlipY = true;
dataFlowModel->getVolumeData().bDoUpdateSignalTexture = true;
// fooDebug() << __FILE__ << __LINE__;
// Load session
setViewMode(VIEW_NEURON_SEPARATION);
if (! dataFlowModel->loadVolumeData()) return false;
// dataChanged() signal will be emitted if load succeeds
return true;
}
// Recent files list
void NaMainWindow::addDirToRecentFilesList(QDir imageDir)
{
QString fileName = imageDir.absolutePath();
addFileNameToRecentFilesList(QUrl::fromLocalFile(fileName).toString());
}
void NaMainWindow::addUrlToRecentFilesList(QUrl url)
{
addFileNameToRecentFilesList(url.toString());
}
void NaMainWindow::addFileNameToRecentFilesList(QString fileName)
{
// fooDebug() << fileName << __FILE__ << __LINE__;
if (fileName.isEmpty()) return;
QSettings settings(QSettings::UserScope, "HHMI", "Vaa3D");
QVariant filesVariant = settings.value("NeuronAnnotatorRecentFileList");
QStringList files = filesVariant.toStringList();
if ( (files.size() > 0) && (files[0] == fileName) )
return; // this dir is already the top entry as is
files.removeAll(fileName);
files.removeAll(QString());
files.prepend(fileName);
while (files.size() > maxRecentFiles)
files.removeLast();
settings.setValue("NeuronAnnotatorRecentFileList", files);
updateRecentFileActions();
}
void NaMainWindow::updateRecentFileActions()
{
QSettings settings(QSettings::UserScope, "HHMI", "Vaa3D");
QStringList files = settings.value("NeuronAnnotatorRecentFileList").toStringList();
ui->menuOpen_Recent->setEnabled(files.size() > 0);
for (int i = 0; i < maxRecentFiles; ++i)
{
if ( (i < files.size() && (! files[i].isEmpty())) ) { // active
recentFileActions[i]->setFileName(files[i]);
recentFileActions[i]->setVisible(true);
}
else { // inactive
recentFileActions[i]->setFileName(QString());
recentFileActions[i]->setVisible(false);
}
}
}
QString NaMainWindow::suggestedExportFilenameFromCurrentState(const NeuronSelectionModel::Reader& selectionReader)
{
MultiColorImageStackNode* multiColorImageStackNode=this->dataFlowModel->getMultiColorImageStackNode();
QStringList lsmFilePathsList=multiColorImageStackNode->getLsmFilePathList();
if (lsmFilePathsList.size()>0) {
// First get filename prefix
QString firstFilePath=lsmFilePathsList.at(0);
QStringList components=firstFilePath.split(QRegExp("/"));
QString name=components.at(components.size()-1);
QStringList extComponents=name.split(QRegExp("\\."));
QString filenamePrefix=extComponents.at(0);
// Next, add current state
if(selectionReader.getOverlayStatusList().at(DataFlowModel::REFERENCE_MIP_INDEX)) {
filenamePrefix.append("_R");
}
if (selectionReader.getOverlayStatusList().at(DataFlowModel::BACKGROUND_MIP_INDEX)) {
filenamePrefix.append("_B");
}
const QList<bool> neuronStatusList = selectionReader.getMaskStatusList();
int activeCount=0;
QString neuronStatusString;
for (int i=0;i<neuronStatusList.size();i++) {
if (neuronStatusList.at(i)) {
neuronStatusString.append("_");
QString number=QString("%1").arg(i);
neuronStatusString.append(number);
activeCount++;
}
}
if (activeCount==neuronStatusList.size()) {
filenamePrefix.append("_all");
} else if (activeCount<6) {
filenamePrefix.append(neuronStatusString);
} else {
filenamePrefix.append("_multiple");
}
return filenamePrefix;
} else {
return QString("");
}
}
void expressRegretsAboutVolumeWriting(QString message) {
QMessageBox::warning(NULL, "Volume export failed",
message);
}
void NaMainWindow::on_action3D_Volume_triggered()
{
if (! dataFlowModel) {
expressRegretsAboutVolumeWriting("No data available to save");
return;
}
QString suggestedFile;
{
NeuronSelectionModel::Reader selectionReader(dataFlowModel->getNeuronSelectionModel());
if (! selectionReader.hasReadLock()) {
expressRegretsAboutVolumeWriting("Could not access selection data");
return;
}
suggestedFile=suggestedExportFilenameFromCurrentState(selectionReader);
}
QString fileTypes = "*.v3dpbd *.v3draw *.tif";
#ifdef USE_FFMPEG
fileTypes += " *.mp4";
#endif
fileTypes = "3D Volumes ("+fileTypes+")";
QString filename = QFileDialog::getSaveFileName(
0,
QObject::tr("Save 3D Volume to a file"),
suggestedFile,
QObject::tr(fileTypes.toStdString().c_str()));
if (filename.isEmpty())
return; // user pressed "Cancel"
QFileInfo fi(filename);
if (fi.suffix().isEmpty())
filename = filename + ".v3dpbd";
fooDebug() << filename;
ExportFile *pExport = new ExportFile(
filename,
dataFlowModel->getVolumeData(),
dataFlowModel->getNeuronSelectionModel(),
dataFlowModel->getDataColorModel(),
sharedCameraModel);
connect(pExport, SIGNAL(finished()), pExport, SLOT(deleteLater()));
connect(pExport, SIGNAL(exportFinished(QString)),
this, SLOT(onExportFinished(QString)));
connect(pExport, SIGNAL(exportFailed(QString, QString)),
this, SLOT(onExportFinished(QString, QString)));
pExport->start();
}
/* slot */
void NaMainWindow::onExportFinished(QString fileName) {
QMessageBox::information(this, "Volume export succeeded",
"Saved file " + fileName);
}
/* slot */
void NaMainWindow::onExportFailed(QString fileName, QString message) {
QMessageBox::warning(this, "Volume export failed",
message + ": " + fileName);
}
void NaMainWindow::on_action2D_MIP_triggered() {
QString filename = QFileDialog::getSaveFileName(0, QObject::tr("Save 2D MIP to an .tif file"), ".", QObject::tr("2D MIP (*.tif)"));
if (!(filename.isEmpty())){
// bool saved = ui->naLargeMIPWidget->saveImage(filename); // REPLACING WITH 3D MIP USING ROTATION and CUT PLANES
ExportFile *pExport = new ExportFile(
filename,
dataFlowModel->getVolumeData(),
dataFlowModel->getNeuronSelectionModel(),
dataFlowModel->getDataColorModel(),
sharedCameraModel,
true /* is2D */);
connect(pExport, SIGNAL(finished()), pExport, SLOT(deleteLater()));
connect(pExport, SIGNAL(exportFinished(QString)),
this, SLOT(onExportFinished(QString)));
connect(pExport, SIGNAL(exportFailed(QString, QString)),
this, SLOT(onExportFinished(QString, QString)));
pExport->start();
}
}
void NaMainWindow::on_actionScreenShot_triggered() {
static QString dirname = ".";
QString filename = QFileDialog::getSaveFileName(
ui->v3dr_glwidget,
QObject::tr("Save 3D View to an image file"),
dirname,
QObject::tr("Images (*.tif *.png *.jpg *.ppm *.xpm)"));
if (filename.isEmpty())
return; // User cancelled
bool saved = ui->v3dr_glwidget->screenShot(filename);
if (saved) {
QMessageBox::information(ui->v3dr_glwidget,
"Successfully saved screen shot",
"Successfully saved screen shot to file " + filename);
// Remember this directory next time
// TODO - use QSettings for more persistent memory
dirname = filename;
}
else {
QMessageBox::critical(this,
"Failed to save screen shot",
"Failed to save screen shot to file " + filename
+ " \nDo you have write permission in that folder?"
+ " \nMaybe a different image format would work better?");
}
}
void NaMainWindow::on_actionPreferences_triggered()
{
PreferencesDialog dlg(this);
dlg.loadPreferences();
int result = dlg.exec();
if (result == QDialog::Accepted) {
dlg.savePreferences();
}
}
void NaMainWindow::on_actionX_Rotation_Movie_triggered()
{
QString fileName = QFileDialog::getSaveFileName(
this, tr("Save movie frame images"),
"",
tr("Images (*.png *.jpg *.ppm)"));
if (fileName.isEmpty())
return;
QFileInfo fi(fileName);
QDir dir = fi.absoluteDir();
QString base = fi.completeBaseName();
QString suffix = fi.suffix();
int frameCount = 540;
Rotation3D dRot;
dRot.setRotationFromAngleAboutUnitVector(
2.0 * 3.14159 / frameCount,
UnitVector3D(1, 0, 0));
Rotation3D currentRotation = sharedCameraModel.rotation();
ui->v3dr_glwidget->resize(1280, 720);
for (int f = 0; f < frameCount; ++f)
{
QString fnum = QString("_%1.").arg(f, 5, 10, QChar('0'));
QString fName = dir.absoluteFilePath(base + fnum + suffix);
fooDebug() << fName;
currentRotation = dRot * currentRotation;
sharedCameraModel.setRotation(currentRotation);
ui->v3dr_glwidget->repaint();
QCoreApplication::processEvents();
QImage frameImage = ui->v3dr_glwidget->grabFrameBuffer();
frameImage.save(fName, NULL, 95);
}
}
// June 27, 2012 modify to accept "NULL" during data flow replacement
void NaMainWindow::setDataFlowModel(DataFlowModel* dataFlowModelParam)
{
if (dataFlowModel == dataFlowModelParam)
return; // no change
if ( (dataFlowModelParam != NULL) // we are not currently tearing down
&& (dataFlowModel != NULL) ) // there is another different model in existence
{
qDebug() << "WARNING: setDataFlowModel() should not be tearing down old models" << __FILE__ << __LINE__;
tearDownOldDataFlowModel();
}
dataFlowModel = dataFlowModelParam;
ui->v3dr_glwidget->setDataFlowModel(dataFlowModel);
ui->naLargeMIPWidget->setDataFlowModel(dataFlowModel);
ui->naZStackWidget->setDataFlowModel(dataFlowModel);
ui->fragmentGalleryWidget->setDataFlowModel(dataFlowModel);
neuronSelector.setDataFlowModel(dataFlowModel);
// was in loadAnnotationSessionFromDirectory June 27, 2012
if (dynamicRangeTool) {
if (NULL == dataFlowModel)
dynamicRangeTool->setColorModel(NULL);
else
dynamicRangeTool->setColorModel(&dataFlowModel->getDataColorModel());
}
// No connecting if the model is NULL
if (NULL == dataFlowModel)
{
ui->naLargeMIPWidget->setMipMergedData(NULL);
return;
}
connect(this, SIGNAL(subsampleLabelPbdFileNamed(QUrl)),
&dataFlowModel->getVolumeTexture(), SLOT(setLabelPbdFileUrl(QUrl)));
connect(dataFlowModel, SIGNAL(benchmarkTimerPrintRequested(QString)),
this, SIGNAL(benchmarkTimerPrintRequested(QString)));
connect(dataFlowModel, SIGNAL(benchmarkTimerResetRequested()),
this, SIGNAL(benchmarkTimerResetRequested()));
// Connect mip viewer to data flow model
ui->naLargeMIPWidget->setMipMergedData(&dataFlowModel->getMipMergedData());
connectContextMenus(dataFlowModel->getNeuronSelectionModel());
connect(dataFlowModel, SIGNAL(scrollBarFocus(NeuronSelectionModel::NeuronIndex)),
ui->fragmentGalleryWidget, SLOT(scrollToFragment(NeuronSelectionModel::NeuronIndex)));
connect(&dataFlowModel->getVolumeData(), SIGNAL(channelsLoaded(int)),
this, SLOT(processUpdatedVolumeData()));
// Both mip images and selection model need to be in place to update gallery
connect(&dataFlowModel->getGalleryMipImages(), SIGNAL(dataChanged()),
this, SLOT(updateGalleries()));
connect(&dataFlowModel->getNeuronSelectionModel(), SIGNAL(initialized()),
this, SLOT(initializeGalleries()));
// Z value comes from camera model
connect(&sharedCameraModel, SIGNAL(focusChanged(Vector3D)),
&dataFlowModel->getZSliceColors(), SLOT(onCameraFocusChanged(Vector3D)));
connect(&dataFlowModel->getNeuronSelectionModel(), SIGNAL(selectionCleared()),
ui->annotationFrame, SLOT(deselectNeurons()));
connect(ui->annotationFrame, SIGNAL(neuronSelected(int)),
&dataFlowModel->getNeuronSelectionModel(), SLOT(selectExactlyOneNeuron(int)));
connect(ui->annotationFrame, SIGNAL(neuronsDeselected()),
&dataFlowModel->getNeuronSelectionModel(), SLOT(clearSelection()));
connect(this, SIGNAL(initializeSelectionModelRequested()),
&dataFlowModel->getNeuronSelectionModel(), SLOT(initializeSelectionModel()));
connect(&dataFlowModel->getNeuronSelectionModel(), SIGNAL(visibilityChanged()),
this, SLOT(onSelectionModelVisibilityChanged()));
// Progress if NaVolumeData file load
// TODO - this is a lot of connection boilerplate code. This should be abstracted into a single call or specialized ProgressManager class.
connect(&dataFlowModel->getVolumeData(), SIGNAL(progressMessageChanged(QString)),
this, SLOT(setProgressMessage(QString)));
connect(&dataFlowModel->getVolumeData(), SIGNAL(progressValueChanged(int)),
this, SLOT(setProgressValue(int)));
connect(&dataFlowModel->getVolumeData(), SIGNAL(progressCompleted()),
this, SLOT(completeProgress()));
connect(&dataFlowModel->getVolumeData(), SIGNAL(progressAborted(QString)),
this, SLOT(abortProgress(QString)));
// Loading single stack
connect(this, SIGNAL(singleStackLoadRequested(QUrl)),
&dataFlowModel->getVolumeData(), SLOT(loadChannels(QUrl)));
connect(&dataFlowModel->getVolumeData(), SIGNAL(channelsLoaded(int)),
this, SLOT(onDataLoadFinished()));
// Loading a series of separation result stacks
connect(this, SIGNAL(stagedLoadRequested()),
&dataFlowModel->getVolumeTexture(), SLOT(loadStagedVolumes()));
// Color toggling
connect(this, SIGNAL(channelVisibilityChanged(int,bool)),
&dataFlowModel->getDataColorModel(), SLOT(setChannelVisibility(int,bool)));
connect(ui->resetColorsButton, SIGNAL(clicked()),
&dataFlowModel->getDataColorModel(), SLOT(resetColors()));
connect(ui->sharedGammaWidget, SIGNAL(gammaBrightnessChanged(qreal)),
&dataFlowModel->getDataColorModel(), SLOT(setSharedGamma(qreal)));
connect(ui->referenceGammaWidget, SIGNAL(gammaBrightnessChanged(qreal)),
&dataFlowModel->getDataColorModel(), SLOT(setReferenceGamma(qreal)));
connect(&dataFlowModel->getDataColorModel(), SIGNAL(dataChanged()),
this, SLOT(onColorModelChanged()));
connect(ui->naZStackWidget, SIGNAL(hdrRangeChanged(int,qreal,qreal)),
&dataFlowModel->getDataColorModel(), SLOT(setChannelHdrRange(int,qreal,qreal)));
connect(this, SIGNAL(initializeColorModelRequested()),
&dataFlowModel->getDataColorModel(), SLOT(resetColors()));
}
bool NaMainWindow::tearDownOldDataFlowModel()
{
ui->v3dr_glwidget->clearImage();
if (NULL == dataFlowModel)
return true;
// TODO - orderly shut down of old data flow model
DataFlowModel* dfm = dataFlowModel; // save pointer
// TODO - make sure clients respect setting to null
// TODO - make sure this does not yet delete dataFlowModel
setDataFlowModel(NULL);
delete dfm;
return true;
}
bool NaMainWindow::createNewDataFlowModel()
{
if (NULL != dataFlowModel) {
bool result = tearDownOldDataFlowModel();
if (!result)
return false;
}
DataFlowModel* dfm = new DataFlowModel();
setDataFlowModel(dfm);
ui->v3dr_glwidget->invalidate();
ui->naZStackWidget->invalidate();
ui->naLargeMIPWidget->invalidate();
ui->v3dr_glwidget->clearImage();
ui->v3dr_glwidget->initializeDefaultTextures(); // <- this is how to reset the label texture
return true;
}
void NaMainWindow::setTitle(QString title) {
setWindowTitle(QString("%1 - V3D Neuron Annotator").arg(title));
}
/* slot */
void NaMainWindow::processUpdatedVolumeData() // activated by volumeData::dataChanged() signal
{
onDataLoadFinished();
// TODO -- install separate listeners for dataChanged() in the various display widgets
dataFlowModel->loadLsmMetadata();
int img_sc, img_sz, ref_sc;
{
NaVolumeData::Reader volumeReader(dataFlowModel->getVolumeData());
if (! volumeReader.hasReadLock()) return;
const Image4DProxy<My4DImage>& imgProxy = volumeReader.getOriginalImageProxy();
const Image4DProxy<My4DImage>& refProxy = volumeReader.getReferenceImageProxy();
img_sc = imgProxy.sc;
img_sz = imgProxy.sz;
ref_sc = refProxy.sc;
} // release read locks
setZRange(0, img_sz - 1);
// Ensure z-stack viewer gets enabled
dataFlowModel->getZSliceColors().onCameraFocusChanged(sharedCameraModel.focus());
// Start in middle of volume
// No, initial position should be set in 3D viewer
// ui->naZStackWidget->setCurrentZSlice(img_sz / 2 + 1);
// Need at least two colors for use of the color buttons to make sense
ui->HDRRed_pushButton->setEnabled(img_sc > 1);
ui->HDRGreen_pushButton->setEnabled(img_sc > 1);
ui->HDRBlue_pushButton->setEnabled(img_sc > 2);
ui->HDRNc82_pushButton->setEnabled(ref_sc > 0);
resetVolumeCutRange();
}
/* slot */
void NaMainWindow::resetVolumeCutRange()
{
int mx, my, mz;
mx = my = mz = 0;
// first try VolumeTexture to get dimensions
{
VolumeTexture::Reader textureReader(dataFlowModel->getVolumeTexture());
if (! dataFlowModel->getVolumeTexture().readerIsStale(textureReader))
{
Dimension size = textureReader.originalImageSize();
mx = (int)size.x() - 1;
my = (int)size.y() - 1;
mz = (int)size.z() - 1;
}
}
// if that fails, try VolumeData
if (mx <= 0)
{
NaVolumeData::Reader volumeReader(dataFlowModel->getVolumeData());
if (volumeReader.hasReadLock())
{
const Image4DProxy<My4DImage>& imgProxy = volumeReader.getOriginalImageProxy();
mx = imgProxy.sx - 1;
my = imgProxy.sy - 1;
mz = imgProxy.sz - 1;
}
}
if (mx <= 0)
return;
// volume cut update
ui->XcminSlider->setRange(0, mx);
ui->XcminSlider->setValue(0);
ui->XcmaxSlider->setRange(0, mx);
ui->XcmaxSlider->setValue(mx);
ui->YcminSlider->setRange(0, my);
ui->YcminSlider->setValue(0);
ui->YcmaxSlider->setRange(0, my);
ui->YcmaxSlider->setValue(my);
ui->ZcminSlider->setRange(0, my);
ui->ZcminSlider->setValue(0);
ui->ZcmaxSlider->setRange(0, my);
ui->ZcmaxSlider->setValue(my);
} // release lock
DataFlowModel* NaMainWindow::getDataFlowModel() const {
return dataFlowModel;
}
void NaMainWindow::initializeGalleries()
{
initializeOverlayGallery();
initializeNeuronGallery();
}
void NaMainWindow::updateGalleries()
{
updateOverlayGallery();
updateNeuronGallery();
// Show or hide galleries depending on data structures
// In particular, hide galleries when there is no reference, nor any neurons.
bool bShowGalleries = false;
if (NULL == dataFlowModel)
; // bShowGalleries = false;
else {
NaVolumeData::Reader volumeReader(dataFlowModel->getVolumeData());
if (volumeReader.hasReadLock()) {
if ( (volumeReader.getNumberOfNeurons() > 0)
|| (volumeReader.hasReferenceImage()) )
{
bShowGalleries = true;
}
}
}
// ui->mipsFrame->setVisible(bShowGalleries);
if (bShowGalleries)
setViewMode(VIEW_NEURON_SEPARATION);
}
void NaMainWindow::initializeOverlayGallery()
{
// qDebug() << "NaMainWindow::initializeOverlayGallery()" << __FILE__ << __LINE__;
// Create layout, only if needed.
QFrame* ui_maskFrame = this->findChild<QFrame*>("maskFrame");
if (! ui_maskFrame->layout()) {
ui_maskFrame->setLayout(new QHBoxLayout());
assert(ui_maskFrame->layout());
}
QLayout *managementLayout = ui_maskFrame->layout();
// Create new buttons, only if needed.
if (overlayGalleryButtonList.size() != 2) {
// Delete any old contents from the layout, such as previous thumbnails
QLayoutItem * item;
while ( ( item = managementLayout->takeAt(0)) != NULL )
{
delete item->widget();
delete item;
}
QImage initialImage(100, 140, QImage::Format_ARGB32);
initialImage.fill(Qt::gray);
GalleryButton* referenceButton = new GalleryButton(
initialImage,
"Reference",
DataFlowModel::REFERENCE_MIP_INDEX,
GalleryButton::OVERLAY_BUTTON);
managementLayout->addWidget(referenceButton);
overlayGalleryButtonList.append(referenceButton);
GalleryButton* backgroundButton = new GalleryButton(
initialImage,
"Background",
DataFlowModel::BACKGROUND_MIP_INDEX,
GalleryButton::OVERLAY_BUTTON);
managementLayout->addWidget(backgroundButton);
overlayGalleryButtonList.append(backgroundButton);
}
// Initialize signals whether the buttons were already there or not
for (int i = 0; i < 2; ++i)
{
overlayGalleryButtonList[i]->setNeuronSelectionModel(dataFlowModel->getNeuronSelectionModel());
}
updateOverlayGallery();
}
void NaMainWindow::updateOverlayGallery()
{
if (overlayGalleryButtonList.size() != 2) return; // not initialized
if (NULL == dataFlowModel) return;
{
NeuronSelectionModel::Reader selectionReader(dataFlowModel->getNeuronSelectionModel());
if (selectionReader.getOverlayStatusList().size() < 2) return;
if (selectionReader.hasReadLock())
{
for (int i = 0; i < 2; ++i)
overlayGalleryButtonList[i]->setChecked(selectionReader.getOverlayStatusList().at(i));
}
}
{
GalleryMipImages::Reader mipReader(dataFlowModel->getGalleryMipImages()); // acquire read lock
if (mipReader.hasReadLock() && (mipReader.getNumberOfOverlays() == 2))
{
for (int i = 0; i < 2; ++i)
overlayGalleryButtonList[i]->setThumbnailIcon(*mipReader.getOverlayMip(i));
}
}
for (int i = 0; i < 2; ++i)
overlayGalleryButtonList[i]->update();
}
void NaMainWindow::initializeNeuronGallery()
{
GalleryMipImages::Reader mipReader(dataFlowModel->getGalleryMipImages()); // acquire read lock
if (! mipReader.hasReadLock()) return;
NeuronSelectionModel::Reader selectionReader(dataFlowModel->getNeuronSelectionModel());
if (! selectionReader.hasReadLock()) return;
if (neuronGalleryButtonList.size() != mipReader.getNumberOfNeurons())
{
neuronGalleryButtonList.clear();
ui->fragmentGalleryWidget->clear(); // deletes buttons
// qDebug() << "Number of neuron masks = " << mipReader.getNumberOfNeurons();
for (int i = 0; i < mipReader.getNumberOfNeurons(); ++i)
{
GalleryButton* button = new GalleryButton(
*mipReader.getNeuronMip(i),
QString("Neuron fragment %1").arg(i),
i,
GalleryButton::NEURON_BUTTON);
button->setContextMenu(neuronContextMenu);
neuronGalleryButtonList.append(button);
ui->fragmentGalleryWidget->appendFragment(button);
}
// qDebug() << "createMaskGallery() end size=" << mipReader.getNumberOfNeurons();
}
// Update signals whether the buttons were already there or not
for (int i = 0; i < mipReader.getNumberOfNeurons(); ++i)
{
neuronGalleryButtonList[i]->setThumbnailIcon(*mipReader.getNeuronMip(i));
neuronGalleryButtonList[i]->setChecked(selectionReader.getMaskStatusList().at(i));
neuronGalleryButtonList[i]->update();
neuronGalleryButtonList[i]->setNeuronSelectionModel(
dataFlowModel->getNeuronSelectionModel());
}
ui->fragmentGalleryWidget->updateButtonsGeometry();
}
// For microCT mode
/* slot */
void NaMainWindow::labelNeuronsAsFlyBrainCompartments() {
// If a second renaming scheme is ever needed, refactor this to load names from an
// external data source.
QList<QString> compartmentNames;
compartmentNames << "FB (Fan-shaped Body)";
compartmentNames << "EB (Ellipsoid Body)";
compartmentNames << "SAD (Saddle)";
compartmentNames << "NO (Noduli)";
compartmentNames << "SOG (Suboesophageal Ganglion)";
compartmentNames << "PB (Protocerebral Bridge)";
compartmentNames << "CRE_R (Crepine)";
compartmentNames << "EPA_R (Epaulette)";
compartmentNames << "VES_R (Vesta)";
compartmentNames << "ATL_R (Antler)";
compartmentNames << "PLP_R (Posterior Lateral Protocerebrum)";
compartmentNames << "AVLP_R (Anterior Ventro-lateral protocerebrum)";
compartmentNames << "AL_R (Antennal Lobe)";
compartmentNames << "GOR_R (Gorget)";
compartmentNames << "SCL_R (Superior Clamp)";
compartmentNames << "FLA (Flange)";
compartmentNames << "ICL_R (Inferior Clamp)";
compartmentNames << "ME_R (Medulla)";
compartmentNames << "LOP_R (Lobula Plate)";
compartmentNames << "LO_R (Lobula)";
compartmentNames << "MB_R (Mushroom Body)";
compartmentNames << "PVLP_R (Posterior Ventro-lateral Protocerebrum)";
compartmentNames << "OTU_R (Optic Tubercle)";
compartmentNames << "WED_R (Wedge)";
compartmentNames << "SMP_R (Superior Medial Protocerebrum)";
compartmentNames << "LH_R (Lateral Horn)";
compartmentNames << "SLP_R (Superior Lateral Protocerebrum)";
compartmentNames << "LB_R (Lateral Bulb)";
compartmentNames << "SIP_R (Superior Intermediate Protocerebrum)";
compartmentNames << "IB_R (Inferior Bridge)";
compartmentNames << "IVLP_R (Inferior Ventro-lateral Protocerebrum)";
compartmentNames << "IPS_R (Inferior Posterior Slope)";
compartmentNames << "SPS_R (Superior Posterior Slope)";
compartmentNames << "LAL_R (Lateral Accessory Lobe)";
compartmentNames << "PRW (Prow)";
compartmentNames << "AME_R (Accessory Medulla)";
compartmentNames << "GA_R (Gall)";
compartmentNames << "CRE_L (Crepine)";
compartmentNames << "EPA_L (Epaulette)";
compartmentNames << "VES_L (Vesta)";
compartmentNames << "ATL_L (Antler)";
compartmentNames << "PLP_L (Posterior Lateral Protocerebrum)";
compartmentNames << "AVLP_L (Anterior Ventro-lateral protocerebrum)";
compartmentNames << "AL_L (Antennal Lobe)";
compartmentNames << "GOR_L (Gorget)";
compartmentNames << "SCL_L (Superior Clamp)";
compartmentNames << "ICL_L (Inferior Clamp)";
compartmentNames << "ME_L (Medulla)";
compartmentNames << "LOP_L (Lobula Plate)";
compartmentNames << "LO_L (Lobula)";
compartmentNames << "MB_L (Mushroom Body)";
compartmentNames << "PVLP_L (Posterior Ventro-lateral Protocerebrum)";
compartmentNames << "OTU_L (Optic Tubercle)";
compartmentNames << "WED_L (Wedge)";
compartmentNames << "SMP_L (Superior Medial Protocerebrum)";
compartmentNames << "LH_L (Lateral Horn)";
compartmentNames << "SLP_L (Superior Lateral Protocerebrum)";
compartmentNames << "LB_L (Lateral Bulb)";
compartmentNames << "SIP_L (Superior Intermediate Protocerebrum)";
compartmentNames << "IB_L (Inferior Bridge)";
compartmentNames << "IVLP_L (Inferior Ventro-lateral Protocerebrum)";
compartmentNames << "IPS_L (Inferior Posterior Slope)";
compartmentNames << "SPS_L (Superior Posterior Slope)";
compartmentNames << "LAL_L (Lateral Accessory Lobe)";
compartmentNames << "AME_L (Accessory Medulla)";
compartmentNames << "GA_L (Gall)";
compartmentNames << "AMMC_L (Antennal Mechanosensory and Motor Centre)";
compartmentNames << "AMMC_R (Antennal Mechanosensory and Motor Centre)";
for (int i = 0; i < neuronGalleryButtonList.size(); ++ i) {
if (i >= compartmentNames.size())
break;
neuronGalleryButtonList[i]->setLabelText(compartmentNames[i]);
}
ui->fragmentGalleryWidget->updateNameSortTable();
}
void NaMainWindow::updateNeuronGallery()
{
GalleryMipImages::Reader mipReader(dataFlowModel->getGalleryMipImages()); // acquire read lock
if (! mipReader.hasReadLock()) return;
NeuronSelectionModel::Reader selectionReader(dataFlowModel->getNeuronSelectionModel());
if (! selectionReader.hasReadLock()) return;
if (neuronGalleryButtonList.size() != mipReader.getNumberOfNeurons())
initializeNeuronGallery();
else {
for (int i = 0; i < mipReader.getNumberOfNeurons(); ++i)
{
neuronGalleryButtonList[i]->setThumbnailIcon(*mipReader.getNeuronMip(i));
neuronGalleryButtonList[i]->setChecked(selectionReader.getMaskStatusList().at(i));
neuronGalleryButtonList[i]->update();
}
ui->fragmentGalleryWidget->updateButtonsGeometry();
}
}
void NaMainWindow::on3DViewerRotationChanged(const Rotation3D& rot)
{
Vector3D angles = rot.convertBodyFixedXYZRotationToThreeAngles();
int rotX = Na3DWidget::radToDeg(angles.x());
int rotY = Na3DWidget::radToDeg(angles.y());
int rotZ = Na3DWidget::radToDeg(angles.z());
int oldRotX = ui->rotXWidget->spinBox->value();
int oldRotY = ui->rotYWidget->spinBox->value();
int oldRotZ = ui->rotZWidget->spinBox->value();
if (Na3DWidget::eulerAnglesAreEquivalent(rotX, rotY, rotZ, oldRotX, oldRotY, oldRotZ))
return;
// Block signals from individual rot widgets until we update them all
ui->rotXWidget->blockSignals(true);
ui->rotYWidget->blockSignals(true);
ui->rotZWidget->blockSignals(true);
ui->rotXWidget->setAngle(rotX);
ui->rotYWidget->setAngle(rotY);
ui->rotZWidget->setAngle(rotZ);
ui->rotXWidget->blockSignals(false);
ui->rotYWidget->blockSignals(false);
ui->rotZWidget->blockSignals(false);
}
void NaMainWindow::update3DViewerXYZBodyRotation()
{
int rotX = ui->rotXWidget->spinBox->value();
int rotY = ui->rotYWidget->spinBox->value();
int rotZ = ui->rotZWidget->spinBox->value();
// qDebug() << rotX << ", " << rotY << ", " << rotZ;
ui->v3dr_glwidget->setXYZBodyRotationInt(rotX, rotY, rotZ);
}
// update neuron selected status
void NaMainWindow::synchronizeGalleryButtonsToAnnotationSession(QString updateString)
{
NeuronSelectionModel::Reader selectionReader(
dataFlowModel->getNeuronSelectionModel());
if (! selectionReader.hasReadLock()) return;
// We are not using the update string in this case, which is from the modelUpdated() signal,
// because we are doing a total update.
int maskStatusListSize=selectionReader.getMaskStatusList().size();
int neuronGalleryButtonSize=neuronGalleryButtonList.size();
assert(neuronGalleryButtonSize == maskStatusListSize);
for (int i = 0; i < maskStatusListSize; i++) {
neuronGalleryButtonList.at(i)->setChecked(
selectionReader.neuronMaskIsChecked(i));
}
// Reference toggle
if (selectionReader.getOverlayStatusList().at(DataFlowModel::REFERENCE_MIP_INDEX)) {
overlayGalleryButtonList.at(DataFlowModel::REFERENCE_MIP_INDEX)->setChecked(true);
} else {
overlayGalleryButtonList.at(DataFlowModel::REFERENCE_MIP_INDEX)->setChecked(false);
}
// Background toggle
if (selectionReader.getOverlayStatusList().at(DataFlowModel::BACKGROUND_MIP_INDEX)) {
overlayGalleryButtonList.at(DataFlowModel::BACKGROUND_MIP_INDEX)->setChecked(true);
} else {
overlayGalleryButtonList.at(DataFlowModel::BACKGROUND_MIP_INDEX)->setChecked(false);
}
}
/* slot */
void NaMainWindow::setProgressValue(int progressValueParam)
{
if (progressValueParam >= 100) {
completeProgress();
return;
}
statusProgressBar->setValue(progressValueParam);
statusProgressBar->show();
}
/* slot */
void NaMainWindow::setProgressMessage(QString msg)
{
statusBar()->showMessage(""); // avoid overlap of temporary messages with progress message
statusProgressMessage->setText(msg);
statusProgressMessage->show();
}
/* slot */
void NaMainWindow::completeProgress()
{
statusProgressBar->hide();
statusProgressMessage->hide();
statusBar()->showMessage("", 500);
}
/* slot */
void NaMainWindow::abortProgress(QString msg)
{
statusProgressBar->hide();
statusProgressMessage->hide();
statusBar()->showMessage(msg, 1000);
}
static const bool use3DProgress = false;
void NaMainWindow::set3DProgress(int prog)
{
if (prog >= 100) {
complete3DProgress();
return;
}
if (use3DProgress) {
ui->progressBar3d->setValue(prog);
// ui->v3dr_glwidget->setResizeEnabled(false); // don't show ugly brief resize behavior
ui->widget_progress3d->show();
}
else
setProgressValue(prog);
}
void NaMainWindow::complete3DProgress()
{
if (use3DProgress) {
ui->widget_progress3d->hide();
// avoid jerky resize to accomodated progress widget
QCoreApplication::processEvents(); // flush pending resize events
ui->v3dr_glwidget->resizeEvent(NULL);
ui->v3dr_glwidget->setResizeEnabled(true);
//
ui->v3dr_glwidget->update();
}
else completeProgress();
}
void NaMainWindow::set3DProgressMessage(QString msg)
{
if (use3DProgress) {
ui->progressLabel3d->setText(msg);
ui->v3dr_glwidget->setResizeEnabled(false); // don't show ugly brief resize behavior
ui->widget_progress3d->show();
}
else
setProgressMessage(msg);
}
char* NaMainWindow::getConsoleURL()
{
return consoleUrl;
}
// NutateThread
| 37.425824
| 208
| 0.672696
|
hanchuan
|
ae223da69d12a8042f518d725fe23972111e156a
| 580
|
cpp
|
C++
|
contest/AOJ/0035.cpp
|
not522/Competitive-Programming
|
be4a7d25caf5acbb70783b12899474a56c34dedb
|
[
"Unlicense"
] | 7
|
2018-04-14T14:55:51.000Z
|
2022-01-31T10:49:49.000Z
|
contest/AOJ/0035.cpp
|
not522/Competitive-Programming
|
be4a7d25caf5acbb70783b12899474a56c34dedb
|
[
"Unlicense"
] | 5
|
2018-04-14T14:28:49.000Z
|
2019-05-11T02:22:10.000Z
|
contest/AOJ/0035.cpp
|
not522/Competitive-Programming
|
be4a7d25caf5acbb70783b12899474a56c34dedb
|
[
"Unlicense"
] | null | null | null |
#include "geometry/polygon.hpp"
#include "string.hpp"
int main() {
setBoolName("YES", "NO");
for (String line; line = in, !in.eof;) {
auto v = line.split(',').transform(cast<String, long double>());
Polygon polygon(4);
for (int i = 0; i < 4; ++i) {
polygon[i] = Point(v[2 * i], v[2 * i + 1]);
}
if (polygon.area() < 0) {
polygon.reverse();
}
auto is_convex = [](const Vector<Point> &corner) {
return ccw(Segment(corner[0], corner[1]), corner[2]) != RIGHT;
};
cout << polygon.getCorners().all_of(is_convex) << endl;
}
}
| 27.619048
| 68
| 0.555172
|
not522
|
ae264600552d13c8335eae879cf3250abfc1074d
| 5,203
|
cpp
|
C++
|
ass2/Ass2_3.cpp
|
krishna-akula/OSLab
|
09ea00eb9b346a2a51b39a0948d05b4f3b414342
|
[
"MIT"
] | null | null | null |
ass2/Ass2_3.cpp
|
krishna-akula/OSLab
|
09ea00eb9b346a2a51b39a0948d05b4f3b414342
|
[
"MIT"
] | null | null | null |
ass2/Ass2_3.cpp
|
krishna-akula/OSLab
|
09ea00eb9b346a2a51b39a0948d05b4f3b414342
|
[
"MIT"
] | null | null | null |
#include<unistd.h>
#include<stdlib.h>
#include<fcntl.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<sys/stat.h>
#include<string>
#include<cstring>
#include<sstream>
#include<vector>
#include<iostream>
using namespace std;
struct cmd_info{
int type;
string infilename,outfilename,filename;
string cmd;
string fcmd;
string path;
char *argv[1024];
int size;
cmd_info()
{
size=0;
}
};
void run_internal_cmd(cmd_info &rd)
{
int status=-1;
if(rd.fcmd=="mkdir")
{
status=mkdir((rd.path).c_str(),0777);
}
else if(rd.fcmd=="rm")
{
status=rmdir((rd.path).c_str());
}
else if(rd.fcmd=="cd")
{
char cwd[256];
getcwd(cwd,sizeof(cwd));
cout<<"Original directory:\t"<<cwd<<"\n";
status=chdir((rd.path).c_str());
getcwd(cwd,sizeof(cwd));
cout<<"Changed directory:\t"<<cwd<<"\n";
}
if(status==-1)
cout<<"enter correct command\n";
else
cout<<"command executed successfully\n";
}
void run_exec(cmd_info &rd)
{
pid_t id_child;
int cstatus=0;
pid_t c;
int in,out;
id_child=fork();
if(id_child==0)
{
if(rd.type==3)
{
in = open(rd.filename.c_str(), O_RDONLY);
dup2(in,0);
}
else if(rd.type==4)
{
out = open(rd.filename.c_str(), O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IRGRP | S_IWGRP | S_IWUSR);
dup2(out,1);
}
// execlp("/bin/sh",argc);
// if(rd.type==5)
// {
// //setpgid(0,0);
// fclose(stdin);
// }
// setpgid(0,0);
execvp((rd.cmd).c_str(),rd.argv);
cout<<"Child process could not do execlp.\n";//error if the child process is not executed
exit(2);
}
else if(id_child==-1)
{
//if forking is failed
cout<<"Fork failed\n";
}
else
{
if(rd.type==5)
waitpid(id_child,&cstatus,WNOHANG);
else
waitpid(id_child,&cstatus,0);
}
}
void get_tokens(cmd_info &rd,string command_line)
{
istringstream iss(command_line);
string word;
iss>>rd.cmd;
if((rd.cmd).size()>0){
rd.argv[rd.size]=new char[(rd.cmd).length()+1];
strcpy(rd.argv[rd.size],(rd.cmd).c_str());
rd.size++;
}
else rd.cmd=" ";
while(iss >> word) {
if(word==">" or word=="<")
{
iss>>rd.filename;
rd.type=word==">"?4:3;
break;
}
else if(word=="&")
{
break;
}
rd.argv[rd.size]=new char[word.length()+1];
strcpy(rd.argv[rd.size],word.c_str());
rd.size++;
}
if(rd.size==0)
{
rd.argv[0]=" ";
rd.size++;
}
rd.argv[rd.size]='\0';
}
void connect_cmds(int in,int out,cmd_info & rd,int last)
{
pid_t id_child;
pid_t c;
int cstatus;
id_child=fork();
if(id_child==0)
{
if(in!=0)
{
dup2(in,0);
close(in);
}
if(out!=1 and !last)
{
// close(in);
dup2(out,1);
close(out);
}
execvp((rd.cmd).c_str(),rd.argv);
cout<<" chld process could not be constructed\n";
exit(1);
}
else
{
c=wait(&cstatus);
close(in);
close(out);
return;
}
}
void run_pipe_cmds(vector<cmd_info> &rds)
{
int n=rds.size();
int pipes[n-1][2];
int in=0;
// pipe(pipes);
int stdo,stdi;
stdi=dup(0);
stdo=dup(1);
for(int i=0;i<n-1;i++)
{
pipe(pipes[i]);
}
for(int i=0;i<n;i++)
{
if(i==n-1)
{
connect_cmds(in,1,rds[i],1);
dup2(stdi,0);
dup2(stdo,1);
}
else
{
dup2(in,0);
connect_cmds(in,pipes[i][1],rds[i],0);
in = pipes[i][0];
}
}
}
int main()
{
cout<<"----------------------------------------------------------------------------------------------\n";
cout<<"select the option for excecution\n";
cout<<"1.\tInternal command\n";
cout<<"2:\tExternal command\n";
cout<<"3:\tExternal command by redirectting standard input\n";
cout<<"4:\tExternal command by redirectting standard output\n";
cout<<"5:\tExternal command in the background\n";
cout<<"6:\tExternal command by for pipelining execution\n";
cout<<"7:\tQuit the program\n";
while(1)
{
int choice;
pid_t par;
par=getpid();
cmd_info rd;
cout<<">option\t\t:";
cin>>choice;
cout<<"\n";
if(choice<1 or choice>=7)
break;
string command_line,word;
cin.ignore(256, '\n');
cout<<">command\t:";
getline(cin,command_line);
cout<<"\n";
rd.type=choice;
if(choice==1)
{
istringstream iss(command_line);
iss>>rd.fcmd;
iss>>rd.path;
run_internal_cmd(rd);
}
else if( (choice>=2 and choice <=4) or choice==5)
{
get_tokens(rd,command_line);
run_exec(rd);
}
else if(choice==6)
{
vector<string>pipe_cmds;
string delim="|";
size_t pos = 0;
string token;
while ((pos = command_line.find(delim)) != string::npos) {
token = command_line.substr(0, pos);
pipe_cmds.push_back(token);
command_line.erase(0, pos + delim.length());
}
if(command_line.size()!=0)
{
pipe_cmds.push_back(command_line);
}
vector< cmd_info >rds(pipe_cmds.size());
for(int i=0;i<pipe_cmds.size();i++)
{
rds[i].type=2;
get_tokens(rds[i],pipe_cmds[i]);
}
// cout<<rds.size()<<endl;
run_pipe_cmds(rds);
}
if(getpid()!=par)
{
exit(1);
}
}
}
| 17.171617
| 106
| 0.55641
|
krishna-akula
|
ae26a8066b1380a0d36c6e3d5e87ca7977f0762f
| 506
|
cpp
|
C++
|
6.ExceptionHandling/i-Assess/HallBookingBO.cpp
|
Concept-Team/e-box-UTA018
|
a6caf487c9f27a5ca30a00847ed49a163049f67e
|
[
"MIT"
] | 26
|
2021-03-17T03:15:22.000Z
|
2021-06-09T13:29:41.000Z
|
6.ExceptionHandling/i-Assess/HallBookingBO.cpp
|
Servatom/e-box-UTA018
|
a6caf487c9f27a5ca30a00847ed49a163049f67e
|
[
"MIT"
] | 6
|
2021-03-16T19:04:05.000Z
|
2021-06-03T13:41:04.000Z
|
6.ExceptionHandling/i-Assess/HallBookingBO.cpp
|
Concept-Team/e-box-UTA018
|
a6caf487c9f27a5ca30a00847ed49a163049f67e
|
[
"MIT"
] | 42
|
2021-03-17T03:16:22.000Z
|
2021-06-14T21:11:20.000Z
|
#include<iostream>
#include<list>
#include"HallBooking.cpp"
#include<iterator>
using namespace std;
class HallBookingBO{
public:
bool validateHallBooking(list<HallBooking> lst,HallBooking hallObj){
try{
for(HallBooking h: lst){
if(h.getHall()==hallObj.getHall()&&h.getDateOfBooking()==hallObj.getDateOfBooking()){
throw 1;
}
}
}catch(...){
return false;
}
return true;
}
};
| 24.095238
| 101
| 0.551383
|
Concept-Team
|
ae2a6ab82e3b1a653467db1256731298173dee6a
| 268
|
cpp
|
C++
|
LastHope Engine/Component.cpp
|
rohomedesrius/LastHopeEngine
|
5a73a0a3cf00fbcd2fa48f0ec1ce2c9bc1057bc0
|
[
"MIT"
] | 1
|
2018-10-03T14:01:40.000Z
|
2018-10-03T14:01:40.000Z
|
LastHope Engine/Component.cpp
|
rohomedesrius/LastHopeEngine
|
5a73a0a3cf00fbcd2fa48f0ec1ce2c9bc1057bc0
|
[
"MIT"
] | null | null | null |
LastHope Engine/Component.cpp
|
rohomedesrius/LastHopeEngine
|
5a73a0a3cf00fbcd2fa48f0ec1ce2c9bc1057bc0
|
[
"MIT"
] | null | null | null |
#include "Component.h"
GameObject* Component::GetGameObject() const
{
return game_object;
}
bool Component::IsActive() const
{
return active;
}
void Component::SetActive(bool value)
{
active = value;
}
ComponentType Component::GetType() const
{
return type;
}
| 12.181818
| 44
| 0.727612
|
rohomedesrius
|
ae2c515406c9ae9c65d4a3b150e08c2c989fafc9
| 2,598
|
hpp
|
C++
|
include/multi_sync_replayer.hpp
|
dabinkim-LGOM/lsc_planner
|
88dcb1de59bac810d1b1fd194fe2b8d24d1860c9
|
[
"MIT"
] | 9
|
2021-09-04T15:14:57.000Z
|
2022-03-29T04:34:13.000Z
|
include/multi_sync_replayer.hpp
|
dabinkim-LGOM/lsc_planner
|
88dcb1de59bac810d1b1fd194fe2b8d24d1860c9
|
[
"MIT"
] | null | null | null |
include/multi_sync_replayer.hpp
|
dabinkim-LGOM/lsc_planner
|
88dcb1de59bac810d1b1fd194fe2b8d24d1860c9
|
[
"MIT"
] | 4
|
2021-09-29T11:32:54.000Z
|
2022-03-06T05:24:33.000Z
|
#pragma once
#include <ros/ros.h>
#include <param.hpp>
#include <mission.hpp>
#include <obstacle_generator.hpp>
#include <visualization_msgs/MarkerArray.h>
#include <std_msgs/Float64.h>
#include <std_msgs/Float64MultiArray.h>
#include <util.hpp>
namespace DynamicPlanning {
class MultiSyncReplayer {
public:
MultiSyncReplayer(const ros::NodeHandle& _nh, Param _param, Mission _mission);
void initializeReplay();
void replay(double t);
void readCSVFile(const std::string& file_name);
void setOctomap(std::string file_name);
private:
ros::NodeHandle nh;
ros::Publisher pub_agent_trajectories;
ros::Publisher pub_obstacle_trajectories;
ros::Publisher pub_collision_model;
ros::Publisher pub_start_goal_points;
// ros::Publisher pub_safety_margin_to_agents;
// ros::Publisher pub_safety_margin_to_obstacles;
ros::Publisher pub_agent_velocities_x;
ros::Publisher pub_agent_velocities_y;
ros::Publisher pub_agent_velocities_z;
ros::Publisher pub_agent_accelerations_x;
ros::Publisher pub_agent_accelerations_y;
ros::Publisher pub_agent_accelerations_z;
ros::Publisher pub_agent_vel_limits;
ros::Publisher pub_agent_acc_limits;
ros::Publisher pub_world_boundary;
ros::Publisher pub_collision_alert;
Param param;
Mission mission;
std::shared_ptr<DynamicEDTOctomap> distmap_obj;
ObstacleGenerator obstacle_generator;
visualization_msgs::MarkerArray msg_agent_trajectories_replay;
visualization_msgs::MarkerArray msg_obstacle_trajectories_replay;
std::vector<std::vector<State>> agent_state_history;
std::vector<std::vector<State>> obstacle_state_history;
// std_msgs::Float64MultiArray safety_margin_to_agents_replay;
// std_msgs::Float64MultiArray safety_margin_to_obstacles_replay;
// std::vector<std::vector<double>> safety_margin_to_agents_history;
// std::vector<std::vector<double>> safety_margin_to_obstacles_history;
double timeStep, makeSpan;
void doReplay(double t);
void publish_agent_trajectories(double t);
void publish_obstacle_trajectories(double t);
void publish_collision_model();
void publish_start_goal_points();
// void publish_safety_margin(double t);
void publish_collision_alert();
void publish_agent_vel_acc(double t);
static std::vector<std::string> csv_read_row(std::istream& in, char delimiter);
};
}
| 33.307692
| 87
| 0.711316
|
dabinkim-LGOM
|
ae2d3ee25a6ac1b5bde055317dabe97eabc70e44
| 1,764
|
cpp
|
C++
|
CF R405/B.cpp
|
parthlathiya/Codeforces_Submissions
|
6c8f40dbeea31a3c3c7d37b799b78f6af4bbcf68
|
[
"MIT"
] | null | null | null |
CF R405/B.cpp
|
parthlathiya/Codeforces_Submissions
|
6c8f40dbeea31a3c3c7d37b799b78f6af4bbcf68
|
[
"MIT"
] | null | null | null |
CF R405/B.cpp
|
parthlathiya/Codeforces_Submissions
|
6c8f40dbeea31a3c3c7d37b799b78f6af4bbcf68
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
#define forall(i,a,b) for(int i=a;i<b;i++)
#define ll long long int
#define llu long long unsigned
#define vll vector<ll>
#define vllu vector<llu>
#define sll set<ll>
#define sllu set<llu>
#define pb push_back
#define mll map<ll,ll>
#define mllu map<llu,llu>
#define miN(a,b) ( (a) < (b) ? (a) : (b))
#define maX(a,b) ( (a) > (b) ? (a) : (b))
#define mod 1000000007
int main()
{
#ifndef ONLINE_JUDGE
freopen("B_in.txt","r",stdin);
#endif
int n,m;
cin>>n>>m;
int a[n][n];
forall(i,0,n)
forall(j,0,n)
a[i][j]=0;
forall(i,0,m)
{
ll p, q;
cin>>p>>q;
a[p-1][q-1]=1;
}
int c[n][n];
forall(i,0,n)
{
forall(j,0,n)
{
c[i][j]=0;
forall(k,0,n){
c[i][j]=c[i][j]+(a[i][k]*a[k][j]);
if(c[i][j]>0)
break;
}
}
}
int ans=1;
int i,j;
// for(i=0;i<n;++i)
// {
// for(j=0;j<n;++j)
// {
// cout<<a[i][j]<<" ";
// }
// cout<<"\n";
// }
// for(i=0;i<n;++i)
// {
// for(j=0;j<n;++j)
// {
// cout<<c[i][j]<<" ";
// }
// cout<<"\n";
// }
forall(i,0,n)
{
forall(j,0,n)
{
if(c[i][j]>0 && a[i][j]!=1)
{
ans=0;
break;
}
}
if(!ans)break;
}
if(ans)
cout<<"YES";
else
cout<<"NO";
return 0;
}
| 19.173913
| 61
| 0.3322
|
parthlathiya
|
ae2d8775f8329e8e9c17bff4ec195a3d69b6d59f
| 32,224
|
cpp
|
C++
|
DRE2008OS_plugins/DRE2008_OS_Callback.cpp
|
GreatCong/GUI_EC_PluginSrc
|
9194e67b76f3707f782f1fc17ba6e6dcb712c2a5
|
[
"MIT"
] | 1
|
2019-12-25T13:36:01.000Z
|
2019-12-25T13:36:01.000Z
|
DRE2008OS_plugins/DRE2008_OS_Callback.cpp
|
GreatCong/GUI_EC_PluginSrc
|
9194e67b76f3707f782f1fc17ba6e6dcb712c2a5
|
[
"MIT"
] | null | null | null |
DRE2008OS_plugins/DRE2008_OS_Callback.cpp
|
GreatCong/GUI_EC_PluginSrc
|
9194e67b76f3707f782f1fc17ba6e6dcb712c2a5
|
[
"MIT"
] | 1
|
2020-08-05T14:05:15.000Z
|
2020-08-05T14:05:15.000Z
|
#include "DRE2008_OS_Callback.h"
#include <QDebug>
//int slave_num = 1;
//int16_t Normal_AD_Input[8] = { 0,0,0,0,0,0,0,0 };
char file[500]; //需要保存数据的文件
DRE2008_OS_Callback::DRE2008_OS_Callback(QObject *parent) : QObject(parent),Ethercat_Callback()
{
m_isOS_Reset = false;//超采样初始化
m_isOS_Run = false;
pre_OverSampling_CycleCount = 0;
output_ptr = nullptr;
input_ptr = nullptr;
m_measure_Q = new QQueue<int16_t>();
m_OS_Channel = OS_CH1; //超采样通道设置
m_SamplingRate = 20; //采样率设置(最大40Khz)
m_AD_Channel = AD_CH1;
m_ErrState = Error_None;
memset(m_Normal_AD_Input,0,sizeof(m_Normal_AD_Input));
}
void DRE2008_OS_Callback::Master_AppLoop_callback()
{
static int reset_num = 0;
if(m_isOS_Run){
if(!m_isOS_Reset){//这里貌似是需要按顺序执行,稍后再改
//超采样设置
if(reset_num < 3){//先Reset,再进行其他操作
reset_num++;
// DRE2008_OS_Reset(slave_num); //DRE2008-OS复位(禁止超采样)
// pre_OverSampling_CycleCount = 0;
DRE2008_OS_Reset(output_ptr); //DRE2008-OS复位(禁止超采样)
pre_OverSampling_CycleCount = 0;
}
else{
DRE2008_OS_SamplingRateSet(output_ptr, m_SamplingRate); //设置采样率
DRE2008_OS_Enable(output_ptr, m_OS_Channel); //设置超采样通道并使能超采样
m_isOS_Reset = true;
reset_num = 0;
}
}
else{
DRE2008_OS_NormalInputRead(input_ptr, m_Normal_AD_Input); //普通模式数据采集
// qDebug() << Normal_AD_Input[0];
m_ErrState = DRE2008_OS_OverSamplingInputLog(input_ptr, m_OS_Channel, 0, file, m_AD_Channel); //超采样数据log
// if(m_ErrState != Error_None){
// qDebug() << m_ErrState;
// }
}
}
else{
pre_OverSampling_CycleCount = 0;
DRE2008_OS_SamplingRateSet(output_ptr, 50);
DRE2008_OS_Disable(output_ptr);
// printf("required %d data log complete!\n", num_of_samples);
// TestKillTimer(1);
}
}
void DRE2008_OS_Callback::Master_AppStart_callback()
{
// qDebug() << "Index1:" << this->Master_getSlaveChooseIndex();
output_ptr = (uint8_t *)(m_Master_addressBase + this->Master_getAddressList().at(this->Master_getSlaveChooseIndex()).outputs_offset);//这里需要根据扫描到的地址替换
input_ptr = (uint8_t *)(m_Master_addressBase + this->Master_getAddressList().at(this->Master_getSlaveChooseIndex()).inputs_offset);
m_isOS_Reset = false;//超采样初始化
pre_OverSampling_CycleCount = 0;//超采样获取中的参数
m_isOS_Run = false;
// initQueue(&my_ecQueue.my_ecQueue_ch1);
m_measure_Q->clear();
emit Master_RunStateChanged(true);
}
void DRE2008_OS_Callback::Master_AppStop_callback()
{
m_isOS_Reset = false;//超采样初始化
m_isOS_Run = false;
// clearQueue(&my_ecQueue.my_ecQueue_ch1);
m_measure_Q->clear();
emit Master_RunStateChanged(false);
}
void DRE2008_OS_Callback::Master_AppScan_callback()
{
emit Sig_MasterScanChanged();
}
void DRE2008_OS_Callback::Master_ReleaseAddress()
{
m_Master_addressBase = NULL;
output_ptr = NULL;
input_ptr = NULL;
}
int DRE2008_OS_Callback::Master_setAdressBase(char *address)
{
m_Master_addressBase = address;
return 0;
}
void DRE2008_OS_Callback::Set_OverSampling_run(bool isRun)
{
m_isOS_Run = isRun;
}
void DRE2008_OS_Callback::Set_OverSampling_Reset(bool isReset)
{
m_isOS_Reset = isReset;
}
const QString DRE2008_OS_Callback::ErrorState_ToString()
{
QString str;
switch(m_ErrState){
case Error_None:
str = "Error_None";
break;
case Error_NoFile:
str = "Error_NoFile";
break;
case Error_File_WriteOver:
str = "Error_File_WriteOver";
break;
case Error_TimeOut:
str = "Error_TimeOut";
break;
case Error_Channel_Invalid:
str = "Error_Channel_Invalid";
break;
default:
str = "ErrorCode:"+QString::number(m_ErrState);
break;
}
return str;
}
/* DRE2008 */
void DRE2008_OS_Callback::DRE2008_OS_Reset(uint8_t *data_OutPtr)
{
// int i = 0;
DRE2008_OS_SamplingRateSet(data_OutPtr, 50);
DRE2008_OS_Disable(data_OutPtr);
// while(i < 50)
// {
// ec_send_processdata();
// ec_receive_processdata(EC_TIMEOUTRET);
// osal_usleep(2000);
// i++;
// }
// printf("RESET OVER......\n");
// qDebug() << "RESET OVER......";
}
void DRE2008_OS_Callback::DRE2008_OS_SamplingRateSet(uint8_t *data_Outptr, int SamplingRate)
{
uint8_t *data_out;
// data_out = ec_slave[slave_num].outputs;
data_out = data_Outptr;
*data_out++ = SamplingRate & 0xFF;
*data_out++ = SamplingRate >> 8;
}
void DRE2008_OS_Callback::DRE2008_OS_Enable(uint8_t *data_Outptr, int channel)
{
uint8_t *data_out;
// data_out = ec_slave[slave_num].outputs;
data_out = data_Outptr;
*data_out++;
*data_out++;
*data_out++ = channel & 0xFF;
*data_out++ = channel >> 8;
}
void DRE2008_OS_Callback::DRE2008_OS_Disable(uint8_t *data_Outptr)
{
uint8_t *data_out;
int channel = OS_NONE;
// data_out = ec_slave[slave_num].outputs;
data_out = data_Outptr;
*data_out++;
*data_out++;
*data_out++ = channel & 0xFF;
*data_out++ = channel >> 8;
}
void DRE2008_OS_Callback::DRE2008_OS_NormalInputRead(uint8_t *data_Inptr, int16_t *NormalInput)
{
uint8_t *data_in;
int16_t temp1, temp2;
// data_in = ec_slave[slave_num].inputs;
data_in = data_Inptr;
temp1 = *data_in++;
temp2 = *data_in++;
NormalInput[0] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
NormalInput[1] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
NormalInput[2] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
NormalInput[3] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
NormalInput[4] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
NormalInput[5] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
NormalInput[6] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
NormalInput[7] = temp1 + (temp2 << 8);
}
void DRE2008_OS_Callback::DRE2008_OS_OverSamplingInputRead(uint8_t *data_Inptr, int32_t *CycleCount, int16_t *OverSamplingInput)
{
uint8_t *data_in;
int16_t temp1, temp2, temp3, temp4;
// data_in = ec_slave[slave_num].inputs;
data_in = data_Inptr;
*data_in++;
*data_in++;
*data_in++;
*data_in++;
*data_in++;
*data_in++;
*data_in++;
*data_in++;
*data_in++;
*data_in++;
*data_in++;
*data_in++;
*data_in++;
*data_in++;
*data_in++;
*data_in++;
*data_in++;
*data_in++;
temp1 = *data_in++;
temp2 = *data_in++;
temp3 = *data_in++;
temp4 = *data_in++;
*CycleCount = temp1 + (temp2 << 8) + (temp3 << 16) + (temp4 << 24);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[0] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[1] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[2] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[3] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[4] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[5] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[6] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[7] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[8] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[9] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[10] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[11] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[12] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[13] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[14] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[15] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[16] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[17] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[18] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[19] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[20] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[21] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[22] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[23] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[24] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[25] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[26] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[27] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[28] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[29] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[30] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[31] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[32] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[33] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[34] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[35] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[36] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[37] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[38] = temp1 + (temp2 << 8);
temp1 = *data_in++;
temp2 = *data_in++;
OverSamplingInput[39] = temp1 + (temp2 << 8);
}
int DRE2008_OS_Callback::DRE2008_OS_OverSamplingInputLog(uint8_t *data_Inptr, int channel, int num_of_samples, char *file, int dis_channel)
{
// FILE *fpWrite;
(void*)(&num_of_samples);
(void*)file;
int32_t OverSampling_CycleCount = 0;
int16_t OverSampling_AD_Input[40] = { 0 };
// static int32_t pre_OverSampling_CycleCount = 0;
int circlecount_error = 3;//当前周期读取到的circlrcount与上一周期的差值,理论为1,将该值设置大于1可提高容错率但会造成部分数据丢失
int ret = Error_None;
// int channelDis_temp = 0;
// channelDis_temp = dis_channel -1;//C语言数组从0开始,而参数是从1开始
int channelDis_temp = dis_channel;//dis_channel本身从0开始
DRE2008_OS_OverSamplingInputRead(data_Inptr, &OverSampling_CycleCount, OverSampling_AD_Input);//读取40个数据
switch (channel)
{
case OS_CH1://CH1超采样
{
if((OverSampling_CycleCount > pre_OverSampling_CycleCount) && ((OverSampling_CycleCount - pre_OverSampling_CycleCount) < circlecount_error + 1))
{
// printf("CycleCount: %d PreCycleCount: %d\n", OverSampling_CycleCount, pre_OverSampling_CycleCount);
pre_OverSampling_CycleCount = OverSampling_CycleCount;
// fpWrite = fopen(file, "a+");
// if (fpWrite == NULL)
// {
// return Error_NoFile;
// }
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 1, OverSampling_AD_Input[0]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 2, OverSampling_AD_Input[1]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 3, OverSampling_AD_Input[2]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 4, OverSampling_AD_Input[3]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 5, OverSampling_AD_Input[4]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 6, OverSampling_AD_Input[5]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 7, OverSampling_AD_Input[6]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 8, OverSampling_AD_Input[7]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 9, OverSampling_AD_Input[8]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 10, OverSampling_AD_Input[9]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 11, OverSampling_AD_Input[10]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 12, OverSampling_AD_Input[11]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 13, OverSampling_AD_Input[12]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 14, OverSampling_AD_Input[13]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 15, OverSampling_AD_Input[14]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 16, OverSampling_AD_Input[15]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 17, OverSampling_AD_Input[16]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 18, OverSampling_AD_Input[17]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 19, OverSampling_AD_Input[18]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 20, OverSampling_AD_Input[19]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 21, OverSampling_AD_Input[20]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 22, OverSampling_AD_Input[21]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 23, OverSampling_AD_Input[22]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 24, OverSampling_AD_Input[23]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 25, OverSampling_AD_Input[24]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 26, OverSampling_AD_Input[25]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 27, OverSampling_AD_Input[26]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 28, OverSampling_AD_Input[27]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 29, OverSampling_AD_Input[28]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 30, OverSampling_AD_Input[29]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 31, OverSampling_AD_Input[30]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 32, OverSampling_AD_Input[31]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 33, OverSampling_AD_Input[32]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 34, OverSampling_AD_Input[33]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 35, OverSampling_AD_Input[34]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 36, OverSampling_AD_Input[35]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 37, OverSampling_AD_Input[36]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 38, OverSampling_AD_Input[37]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 39, OverSampling_AD_Input[38]);
// fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 40, OverSampling_AD_Input[39]);
// fclose(fpWrite);
if(channelDis_temp < 1){
for(int index=0,loop_num = 0;loop_num < 40;index++,loop_num++){
m_measure_Q->enqueue(OverSampling_AD_Input[index]);
// enQueue(&my_ecQueue.my_ecQueue_ch1, OverSampling_AD_Input[index]);
// qDebug() << OverSampling_AD_Input[index];
// enQueue(&my_ecQueue.my_ecQueue_ch2, OverSampling_AD_Input[index]);
}
}
else {
ret = Error_Channel_Invalid;//通道不匹配
}
// if (((OverSampling_CycleCount - 1) * 40 + 40) >= num_of_samples)
// {
// pre_OverSampling_CycleCount = 0;
// DRE2008_OS_SamplingRateSet(slave_num, 50);
// DRE2008_OS_Disable(slave_num);
// printf("required %d data log complete!\n", num_of_samples);
// ret = Error_File_WriteOver;//表示满了
// }
}
else{
ret = Error_TimeOut;
}
break;
}
case OS_CH1_CH2://CH1-CH2超采样
{
if ((OverSampling_CycleCount > pre_OverSampling_CycleCount) && ((OverSampling_CycleCount - pre_OverSampling_CycleCount) < circlecount_error + 1))
{
// printf("CycleCount: %d PreCycleCount: %d\n", OverSampling_CycleCount, pre_OverSampling_CycleCount);
pre_OverSampling_CycleCount = OverSampling_CycleCount;
// fpWrite = fopen(file, "a+");
// if (fpWrite == NULL)
// {
// return Error_NoFile;
// }
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 1, OverSampling_AD_Input[0], OverSampling_AD_Input[20]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 2, OverSampling_AD_Input[1], OverSampling_AD_Input[21]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 3, OverSampling_AD_Input[2], OverSampling_AD_Input[22]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 4, OverSampling_AD_Input[3], OverSampling_AD_Input[23]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 5, OverSampling_AD_Input[4], OverSampling_AD_Input[24]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 6, OverSampling_AD_Input[5], OverSampling_AD_Input[25]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 7, OverSampling_AD_Input[6], OverSampling_AD_Input[26]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 8, OverSampling_AD_Input[7], OverSampling_AD_Input[27]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 9, OverSampling_AD_Input[8], OverSampling_AD_Input[28]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 10, OverSampling_AD_Input[9], OverSampling_AD_Input[29]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 11, OverSampling_AD_Input[10], OverSampling_AD_Input[30]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 12, OverSampling_AD_Input[11], OverSampling_AD_Input[31]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 13, OverSampling_AD_Input[12], OverSampling_AD_Input[32]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 14, OverSampling_AD_Input[13], OverSampling_AD_Input[33]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 15, OverSampling_AD_Input[14], OverSampling_AD_Input[34]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 16, OverSampling_AD_Input[15], OverSampling_AD_Input[35]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 17, OverSampling_AD_Input[16], OverSampling_AD_Input[36]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 18, OverSampling_AD_Input[17], OverSampling_AD_Input[37]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 19, OverSampling_AD_Input[18], OverSampling_AD_Input[38]);
// fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 20, OverSampling_AD_Input[19], OverSampling_AD_Input[39]);
// fclose(fpWrite);
// if (((OverSampling_CycleCount - 1) * 20 + 20) >= num_of_samples)
// {
// pre_OverSampling_CycleCount = 0;
// DRE2008_OS_SamplingRateSet(slave_num, 50);
// DRE2008_OS_Disable(slave_num);
// printf("required %d data log complete!\n", num_of_samples);
// ret = Error_File_WriteOver;
// }
if(channelDis_temp < 2){
for(int index = channelDis_temp*20,loop_num = 0;loop_num < 20;index++,loop_num++){
// enQueue(&my_ecQueue.my_ecQueue_ch1, OverSampling_AD_Input[index]);
m_measure_Q->enqueue(OverSampling_AD_Input[index]);
// enQueue(&my_ecQueue.my_ecQueue_ch2, OverSampling_AD_Input[index]);
}
}
else {
ret = Error_Channel_Invalid;
}
}
else{
ret = Error_TimeOut;
}
break;
}
case OS_CH1_CH4://CH1-CH4超采样
{
if ((OverSampling_CycleCount > pre_OverSampling_CycleCount) && ((OverSampling_CycleCount - pre_OverSampling_CycleCount) < circlecount_error + 1))
{
// printf("CycleCount: %d PreCycleCount: %d\n", OverSampling_CycleCount, pre_OverSampling_CycleCount);
pre_OverSampling_CycleCount = OverSampling_CycleCount;
// fpWrite = fopen(file, "a+");
// if (fpWrite == NULL)
// {
// return -1;
// }
// fprintf(fpWrite, "%d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 10 + 1, OverSampling_AD_Input[0], OverSampling_AD_Input[10], \
// OverSampling_AD_Input[20], OverSampling_AD_Input[30]);
// fprintf(fpWrite, "%d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 10 + 2, OverSampling_AD_Input[1], OverSampling_AD_Input[11], \
// OverSampling_AD_Input[21], OverSampling_AD_Input[31]);
// fprintf(fpWrite, "%d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 10 + 3, OverSampling_AD_Input[2], OverSampling_AD_Input[12], \
// OverSampling_AD_Input[22], OverSampling_AD_Input[32]);
// fprintf(fpWrite, "%d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 10 + 4, OverSampling_AD_Input[3], OverSampling_AD_Input[13], \
// OverSampling_AD_Input[23], OverSampling_AD_Input[33]);
// fprintf(fpWrite, "%d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 10 + 5, OverSampling_AD_Input[4], OverSampling_AD_Input[14], \
// OverSampling_AD_Input[24], OverSampling_AD_Input[34]);
// fprintf(fpWrite, "%d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 10 + 6, OverSampling_AD_Input[5], OverSampling_AD_Input[15], \
// OverSampling_AD_Input[25], OverSampling_AD_Input[35]);
// fprintf(fpWrite, "%d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 10 + 7, OverSampling_AD_Input[6], OverSampling_AD_Input[16], \
// OverSampling_AD_Input[26], OverSampling_AD_Input[36]);
// fprintf(fpWrite, "%d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 10 + 8, OverSampling_AD_Input[7], OverSampling_AD_Input[17], \
// OverSampling_AD_Input[27], OverSampling_AD_Input[37]);
// fprintf(fpWrite, "%d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 10 + 9, OverSampling_AD_Input[8], OverSampling_AD_Input[18], \
// OverSampling_AD_Input[28], OverSampling_AD_Input[38]);
// fprintf(fpWrite, "%d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 10 + 10, OverSampling_AD_Input[9], OverSampling_AD_Input[19], \
// OverSampling_AD_Input[29], OverSampling_AD_Input[39]);
// fclose(fpWrite);
if(channelDis_temp < 4){
for(int index = channelDis_temp*10,loop_num = 0;loop_num < 10;index++,loop_num++){
// enQueue(&my_ecQueue.my_ecQueue_ch1, OverSampling_AD_Input[index]);
m_measure_Q->enqueue(OverSampling_AD_Input[index]);
// enQueue(&my_ecQueue.my_ecQueue_ch2, OverSampling_AD_Input[index]);
}
}
else{
ret = Error_Channel_Invalid;
}
// if (((OverSampling_CycleCount - 1) * 10 + 10) >= num_of_samples)
// {
// pre_OverSampling_CycleCount = 0;
// DRE2008_OS_SamplingRateSet(slave_num, 50);
// DRE2008_OS_Disable(slave_num);
// printf("required %d data log complete!\n", num_of_samples);
// ret = Error_File_WriteOver;
// }
}
else{
ret = Error_TimeOut;
}
break;
}
case OS_CH1_CH8://CH1-CH8超采样
{
if ((OverSampling_CycleCount > pre_OverSampling_CycleCount) && ((OverSampling_CycleCount - pre_OverSampling_CycleCount) < circlecount_error + 1))
{
// printf("CycleCount: %d PreCycleCount: %d\n", OverSampling_CycleCount, pre_OverSampling_CycleCount);
pre_OverSampling_CycleCount = OverSampling_CycleCount;
// fpWrite = fopen(file, "a+");
// if (fpWrite == NULL)
// {
// return Error_NoFile;
// }
// fprintf(fpWrite, "%d %d %d %d %d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 5 + 1, OverSampling_AD_Input[0], OverSampling_AD_Input[5], \
// OverSampling_AD_Input[10], OverSampling_AD_Input[15], \
// OverSampling_AD_Input[20], OverSampling_AD_Input[25], \
// OverSampling_AD_Input[30], OverSampling_AD_Input[35]);
// fprintf(fpWrite, "%d %d %d %d %d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 5 + 2, OverSampling_AD_Input[1], OverSampling_AD_Input[6], \
// OverSampling_AD_Input[11], OverSampling_AD_Input[16], \
// OverSampling_AD_Input[21], OverSampling_AD_Input[26], \
// OverSampling_AD_Input[31], OverSampling_AD_Input[36]);
// fprintf(fpWrite, "%d %d %d %d %d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 5 + 3, OverSampling_AD_Input[2], OverSampling_AD_Input[7], \
// OverSampling_AD_Input[12], OverSampling_AD_Input[17], \
// OverSampling_AD_Input[22], OverSampling_AD_Input[27], \
// OverSampling_AD_Input[32], OverSampling_AD_Input[37]);
// fprintf(fpWrite, "%d %d %d %d %d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 5 + 4, OverSampling_AD_Input[3], OverSampling_AD_Input[8], \
// OverSampling_AD_Input[13], OverSampling_AD_Input[18], \
// OverSampling_AD_Input[23], OverSampling_AD_Input[28], \
// OverSampling_AD_Input[33], OverSampling_AD_Input[38]);
// fprintf(fpWrite, "%d %d %d %d %d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 5 + 5, OverSampling_AD_Input[4], OverSampling_AD_Input[9], \
// OverSampling_AD_Input[14], OverSampling_AD_Input[19], \
// OverSampling_AD_Input[24], OverSampling_AD_Input[29], \
// OverSampling_AD_Input[34], OverSampling_AD_Input[39]);
// fclose(fpWrite);
if(channelDis_temp < 8){
for(int index = channelDis_temp*5,loop_num = 0;loop_num < 5;index++,loop_num++){
// enQueue(&my_ecQueue.my_ecQueue_ch1, OverSampling_AD_Input[index]);
m_measure_Q->enqueue(OverSampling_AD_Input[index]);
// enQueue(&my_ecQueue.my_ecQueue_ch2, OverSampling_AD_Input[index]);
}
}
else{
ret = Error_Channel_Invalid;
}
// if (((OverSampling_CycleCount - 1) * 5 + 5) >= num_of_samples)
// {
// pre_OverSampling_CycleCount = 0;
// DRE2008_OS_SamplingRateSet(slave_num, 50);
// DRE2008_OS_Disable(slave_num);
// printf("The required %d data log complete!\n", num_of_samples);
// ret = Error_File_WriteOver;
// }
}
else{
ret = Error_TimeOut;
}
break;
}
default:
break;
}
return ret;
}
| 43.961801
| 172
| 0.543105
|
GreatCong
|
ae2d8c0a1f4465bf6b72f7b7cc39561f4ef0ad19
| 1,798
|
hpp
|
C++
|
include/np/ndarray/dynamic/NDArrayDynamicSortImpl.hpp
|
mgorshkov/np
|
75c7adff38e7260371135839b547d5340f3ca367
|
[
"MIT"
] | null | null | null |
include/np/ndarray/dynamic/NDArrayDynamicSortImpl.hpp
|
mgorshkov/np
|
75c7adff38e7260371135839b547d5340f3ca367
|
[
"MIT"
] | null | null | null |
include/np/ndarray/dynamic/NDArrayDynamicSortImpl.hpp
|
mgorshkov/np
|
75c7adff38e7260371135839b547d5340f3ca367
|
[
"MIT"
] | null | null | null |
/*
C++ numpy-like template-based array implementation
Copyright (c) 2022 Mikhail Gorshkov (mikhail.gorshkov@gmail.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#pragma once
#include <np/ndarray/dynamic/NDArrayDynamicDecl.hpp>
namespace np::ndarray::array_dynamic {
// Sort an array
template<typename DType, typename Storage>
inline void NDArrayDynamic<DType, Storage>::sort() {
m_ArrayImpl.sort();
auto shape = m_ArrayImpl.shape();
shape.flatten();
m_ArrayImpl.setShape(shape);
}
// Sort the elements of an array's axis
// TODO
// template<typename DType, typename Storage>
// template<std::size_t N>
// inline void NDArrayDynamic<DType, Storage>::sort(std::optional<Axis<N>> axis) {
// }
} // namespace np::ndarray::array_dynamic
| 36.693878
| 86
| 0.74861
|
mgorshkov
|
ae3120a1f2b602611be0945168db439e9cd8076f
| 35
|
cpp
|
C++
|
NotifyServer/SQLThreadConPool.cpp
|
lijialong1234/TeachNotice
|
27ec630d1a8e669bd30df406ea6618d8fbce8c3b
|
[
"MIT"
] | 2
|
2019-05-25T13:25:33.000Z
|
2019-06-03T06:48:24.000Z
|
NotifyServer/SQLThreadConPool.cpp
|
lijialong1234/TeachNotice
|
27ec630d1a8e669bd30df406ea6618d8fbce8c3b
|
[
"MIT"
] | null | null | null |
NotifyServer/SQLThreadConPool.cpp
|
lijialong1234/TeachNotice
|
27ec630d1a8e669bd30df406ea6618d8fbce8c3b
|
[
"MIT"
] | null | null | null |
#include "SQLThreadConPool.h"
| 8.75
| 30
| 0.685714
|
lijialong1234
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.