blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2 values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905 values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 10.4M | extension stringclasses 115 values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
25e6ae123ebad5f9886cabeff82dd1976f0b0245 | fa2643eb4d0d6daf1e588c0203ddab30cc174200 | /12865/12865.cc | 24f762aa6fff9bf23ae2b984d40e253c2421f8f8 | [] | no_license | 1cekrim/boj | 67a4bd2f5d5350c689ea67b35ec6c3984cab012f | 933f8c573156b3f5b4977f8d150f51df9e214a93 | refs/heads/master | 2020-09-04T23:31:02.076900 | 2020-03-05T13:01:57 | 2020-03-06T11:32:03 | 219,923,744 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 961 | cc | #include <algorithm>
#include <iostream>
#include <tuple>
#include <vector>
int solve(const std::vector<std::tuple<int, int>> data, int idx, int cap)
{
static std::vector<std::vector<int>> memo(idx + 1,
std::vector<int>(cap + 1, 0));
if (!(idx && cap))
{
return 0;
}
if (memo[idx][cap])
{
return memo[idx][cap];
}
auto [weight, value] = data[idx];
if (weight > cap)
{
return memo[idx][cap] = solve(data, idx - 1, cap);
}
return memo[idx][cap] =
std::max(solve(data, idx - 1, cap),
solve(data, idx - 1, cap - weight) + value);
}
int main()
{
int n, k;
std::cin >> n >> k;
std::vector<std::tuple<int, int>> data(n + 1);
for (int i = 1; i <= n; ++i)
{
int a, b;
std::cin >> a >> b;
data[i] = { a, b };
}
std::cout << solve(data, n, k) << '\n';
} | [
"1cekrim.dev@gmail.com"
] | 1cekrim.dev@gmail.com |
8d5580513ac092501f25a645be636aced14d3632 | a35b30a7c345a988e15d376a4ff5c389a6e8b23a | /boost/phoenix/object/detail/preprocessed/construct_eval_20.hpp | 2eeada87ad0ced741d2e06b1af2666ffce02ae84 | [] | no_license | huahang/thirdparty | 55d4cc1c8a34eff1805ba90fcbe6b99eb59a7f0b | 07a5d64111a55dda631b7e8d34878ca5e5de05ab | refs/heads/master | 2021-01-15T14:29:26.968553 | 2014-02-06T07:35:22 | 2014-02-06T07:35:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 98 | hpp | #include "thirdparty/boost_1_55_0/boost/phoenix/object/detail/preprocessed/construct_eval_20.hpp"
| [
"liuhuahang@xiaomi.com"
] | liuhuahang@xiaomi.com |
151c21804e384c395a77610c5832db38bc4f0c95 | 13caeaf7ba609ed47d6b1a400525c02dc9d577a0 | /asylo/platform/posix/io/epoll_test.cc | 4618a386624d9d3c342bb5e1354274c04911a935 | [
"Apache-2.0"
] | permissive | annasapek/asylo | 45d0463bc9d21c41b54b36027de8622766990499 | 8f9277bbd3bd6c46a8767fa339adcafba8f5c73d | refs/heads/master | 2020-04-01T03:29:19.291832 | 2018-10-12T19:24:28 | 2018-10-12T19:24:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,681 | cc | /*
*
* Copyright 2018 Asylo authors
*
* 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 <sys/epoll.h>
#include <unistd.h>
#include <chrono>
#include <thread>
#include <unordered_set>
#include "asylo/test/util/status_matchers.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
namespace asylo {
namespace {
constexpr const char *kTestString = "Will this go through the pipe?";
constexpr size_t kBufferSize = 1024;
constexpr size_t kNumPipes = 8;
constexpr int kRead = 0;
constexpr int kWrite = 1;
class EpollTest : public ::testing::Test {
protected:
Status WriteData(int fd, const char *str) {
ssize_t num_bytes_left = strlen(str);
while (num_bytes_left > 0) {
ssize_t num_bytes_written = write(fd, str, num_bytes_left);
if (num_bytes_written < 0) {
return Status(error::GoogleError::INTERNAL, "write() failed");
}
num_bytes_left -= num_bytes_written;
}
return Status::OkStatus();
}
Status ReadData(int fd, char *buf, size_t bytes_to_read) {
while (bytes_to_read > 0) {
int num_bytes_read = read(fd, buf, bytes_to_read);
if (num_bytes_read < 0) {
return Status(error::GoogleError::INTERNAL, "read() failed");
}
bytes_to_read -= num_bytes_read;
}
return Status::OkStatus();
}
void WriteToPipes(const std::vector<int> &write_fds, const char *str) {
for (int fd : write_fds) {
EXPECT_THAT(WriteData(fd, str), IsOk());
}
}
void RegisterFds(int epfd, int pipe_idx, int additional_flags = 0) {
for (size_t i = 0; i < kNumPipes; ++i) {
// Create the epoll event we want to add.
struct epoll_event ev;
ev.events = pipe_idx == 0 ? EPOLLIN : EPOLLOUT;
ev.events |= additional_flags;
ev.data.fd = fd_pairs_[i][pipe_idx];
ASSERT_NE(epoll_ctl(epfd, EPOLL_CTL_ADD, fd_pairs_[i][pipe_idx], &ev),
-1);
}
}
void InitializePipes() {
for (int i = 0; i < kNumPipes; ++i) {
ASSERT_EQ(pipe(fd_pairs_[i]), 0);
}
}
void ClosePipes() {
for (int i = 0; i < kNumPipes; ++i) {
close(fd_pairs_[i][0]);
close(fd_pairs_[i][1]);
}
}
// Verify that only the first kNumPipes/2 fds have registered read events.
void VerifyReadEvents(int epfd) {
struct epoll_event events[kNumPipes];
int num_events = epoll_wait(epfd, events, kNumPipes, -1);
ASSERT_NE(num_events, -1);
EXPECT_EQ(num_events, kNumPipes / 2);
std::unordered_set<int> read_fds;
for (int i = 0; i < num_events; ++i) {
// Make sure that the current fd hasn't been encountered before.
ASSERT_EQ(read_fds.find(events[i].data.fd), read_fds.end());
read_fds.insert(events[i].data.fd);
}
// Make sure that the first kNumPipes/2 read fds are in our set.
for (int i = 0; i < kNumPipes / 2; ++i) {
ASSERT_NE(read_fds.find(fd_pairs_[i][kRead]), read_fds.end());
}
// Makes sure the last kNumPipes/2 read fds are not in our set.
for (int i = kNumPipes / 2; i < kNumPipes; ++i) {
ASSERT_EQ(read_fds.find(fd_pairs_[i][kRead]), read_fds.end());
}
}
void BasicEpollTest(bool edge_triggered) {
InitializePipes();
int epfd = epoll_create(1);
ASSERT_NE(epfd, -1);
// Register all read ends from fd_pairs_ with this epoll instance.
int additional_flags = edge_triggered ? EPOLLET : 0;
RegisterFds(epfd, kRead, additional_flags);
std::vector<int> write_fds;
// Only write to the first kNumPipes/2.
for (int i = 0; i < kNumPipes / 2; ++i) {
write_fds.push_back(fd_pairs_[i][kWrite]);
}
WriteToPipes(write_fds, kTestString);
VerifyReadEvents(epfd);
ASSERT_EQ(close(epfd), 0);
ClosePipes();
}
void TimeoutTest(int sleep_dur, int timeout) {
InitializePipes();
int epfd = epoll_create(1);
ASSERT_NE(epfd, -1);
// Register all read ends from fd_pairs_ with this epoll instance.
RegisterFds(epfd, kRead);
std::vector<int> write_fds;
// Only write to the first kNumPipes/2.
for (int i = 0; i < kNumPipes / 2; ++i) {
write_fds.push_back(fd_pairs_[i][kWrite]);
}
std::thread writer([write_fds, sleep_dur, this]() {
std::this_thread::sleep_for(std::chrono::milliseconds(sleep_dur));
WriteToPipes(write_fds, kTestString);
});
struct epoll_event events[kNumPipes];
int num_events = epoll_wait(epfd, events, kNumPipes, timeout);
writer.join();
ASSERT_NE(num_events, -1);
if (timeout < sleep_dur) {
EXPECT_EQ(num_events, 0);
} else { // We must have registered at least one event.
EXPECT_GT(num_events, 0);
}
ClosePipes();
}
void LevelEdgeBehaviorTest(bool edge_triggered) {
size_t test_str_len = strlen(kTestString);
int fds[2];
ASSERT_EQ(pipe(fds), 0);
int epfd = epoll_create(1);
ASSERT_NE(epfd, -1);
struct epoll_event ev;
ev.events = EPOLLIN;
if (edge_triggered) ev.events |= EPOLLET;
ev.data.fd = fds[kRead];
ASSERT_NE(epoll_ctl(epfd, EPOLL_CTL_ADD, fds[kRead], &ev), -1);
EXPECT_THAT(WriteData(fds[kWrite], kTestString), IsOk());
struct epoll_event events[1];
int num_events = epoll_wait(epfd, events, 1, -1);
ASSERT_EQ(num_events, 1);
// Read half of the string.
char buf[kBufferSize];
EXPECT_THAT(ReadData(fds[kRead], buf, test_str_len / 2), IsOk());
num_events = epoll_wait(epfd, events, 1, 0);
if (edge_triggered) {
// There is no change in state, so we shouldn't receive a notification.
ASSERT_EQ(num_events, 0);
} else {
// There is data available to read, so we should receive a notification.
ASSERT_EQ(num_events, 1);
}
ASSERT_EQ(close(epfd), 0);
ASSERT_EQ(close(fds[kRead]), 0);
ASSERT_EQ(close(fds[kWrite]), 0);
}
int fd_pairs_[kNumPipes][2];
};
TEST_F(EpollTest, LevelTriggeredBasic) { BasicEpollTest(false); }
TEST_F(EpollTest, EdgeTriggeredBasic) { BasicEpollTest(true); }
TEST_F(EpollTest, EpollWaitTimeoutNotExceeded) { TimeoutTest(10, 2000); }
TEST_F(EpollTest, EpollWaitTimeoutExceeded) { TimeoutTest(500, 50); }
TEST_F(EpollTest, EpollCtlDel) {
InitializePipes();
int epfd = epoll_create(1);
ASSERT_NE(epfd, -1);
// Register all read ends from fd_pairs_ with this epoll instance.
RegisterFds(epfd, kRead);
// Deregister the second half of the fds using epoll_ctl
for (int i = kNumPipes / 2; i < kNumPipes; ++i) {
ASSERT_NE(epoll_ctl(epfd, EPOLL_CTL_DEL, fd_pairs_[i][kRead], nullptr), -1);
}
std::vector<int> write_fds;
// Write to all of the fds. Only the first half should register the events
for (int i = 0; i < kNumPipes; ++i) {
write_fds.push_back(fd_pairs_[i][kWrite]);
}
WriteToPipes(write_fds, kTestString);
VerifyReadEvents(epfd);
ASSERT_EQ(close(epfd), 0);
ClosePipes();
}
TEST_F(EpollTest, EpollCtlMod) {
InitializePipes();
int epfd = epoll_create(1);
ASSERT_NE(epfd, -1);
// Register all read ends from fd_pairs_ with this epoll instance.
RegisterFds(epfd, kRead);
// Have the second half check when the fd is available for writing, which it
// never should be;
for (int i = kNumPipes / 2; i < kNumPipes; ++i) {
struct epoll_event ev;
ev.events = EPOLLOUT;
ev.data.fd = fd_pairs_[i][kRead];
ASSERT_NE(epoll_ctl(epfd, EPOLL_CTL_MOD, fd_pairs_[i][kRead], &ev), -1);
}
std::vector<int> write_fds;
// Write to all of the fds. Only the first half should register the events.
for (int i = 0; i < kNumPipes; ++i) {
write_fds.push_back(fd_pairs_[i][kWrite]);
}
WriteToPipes(write_fds, kTestString);
VerifyReadEvents(epfd);
ASSERT_EQ(close(epfd), 0);
ClosePipes();
}
TEST_F(EpollTest, EpollCtlMix) {
InitializePipes();
int epfd = epoll_create(1);
ASSERT_NE(epfd, -1);
// Register all read ends from fd_pairs_ with this epoll instance.
RegisterFds(epfd, kRead);
// Deregister the second half of the fds using epoll_ctl DEL.
for (int i = kNumPipes / 2; i < kNumPipes; ++i) {
ASSERT_NE(epoll_ctl(epfd, EPOLL_CTL_DEL, fd_pairs_[i][kRead], nullptr), -1);
}
// Reregister the second half of the fds using epoll_ctl ADD.
for (int i = kNumPipes / 2; i < kNumPipes; ++i) {
struct epoll_event ev;
ev.events = EPOLLIN;
ev.data.fd = fd_pairs_[i][kRead];
ASSERT_NE(epoll_ctl(epfd, EPOLL_CTL_ADD, fd_pairs_[i][kRead], &ev), -1);
}
// Deregister the second half of the fds using epoll_ctl MOD by making epoll
// track these fds for write events.
for (int i = kNumPipes / 2; i < kNumPipes; ++i) {
struct epoll_event ev;
ev.events = EPOLLOUT;
ev.data.fd = fd_pairs_[i][kRead];
ASSERT_NE(epoll_ctl(epfd, EPOLL_CTL_MOD, fd_pairs_[i][kRead], &ev), -1);
}
std::vector<int> write_fds;
// Write to all of the fds. Only the first half should register the events.
for (int i = 0; i < kNumPipes; ++i) {
write_fds.push_back(fd_pairs_[i][kWrite]);
}
WriteToPipes(write_fds, kTestString);
VerifyReadEvents(epfd);
ASSERT_EQ(close(epfd), 0);
ClosePipes();
}
TEST_F(EpollTest, LevelTriggeredBehavior) { LevelEdgeBehaviorTest(false); }
TEST_F(EpollTest, EdgeTriggeredBehavior) { LevelEdgeBehaviorTest(true); }
} // namespace
} // namespace asylo
| [
"arminn@google.com"
] | arminn@google.com |
7833b6eed961498e106a84fd577230eec0a8b85e | ea401c3e792a50364fe11f7cea0f35f99e8f4bde | /released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/gui/ext/boost/bimap/container_adaptor/detail/non_unique_container_helper.hpp | 695704535ab53e7dc62a0975daccbed255e81301 | [
"BSD-2-Clause",
"MIT",
"BSL-1.0",
"GPL-1.0-or-later",
"LicenseRef-scancode-unknown-license-reference",
"GPL-2.0-only"
] | permissive | Vaa3D/vaa3d_tools | edb696aa3b9b59acaf83d6d27c6ae0a14bf75fe9 | e6974d5223ae70474efaa85e1253f5df1814fae8 | refs/heads/master | 2023-08-03T06:12:01.013752 | 2023-08-02T07:26:01 | 2023-08-02T07:26:01 | 50,527,925 | 107 | 86 | MIT | 2023-05-22T23:43:48 | 2016-01-27T18:19:17 | C++ | UTF-8 | C++ | false | false | 3,626 | hpp | // Boost.Bimap
//
// Copyright (c) 2006-2007 Matias Capeletto
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
/// \file container_adaptor/detail/non_unique_container_helper.hpp
/// \brief Details for non unique containers
#ifndef BOOST_BIMAP_CONTAINER_ADAPTOR_DETAIL_NON_UNIQUE_CONTAINER_HELPER_HPP
#define BOOST_BIMAP_CONTAINER_ADAPTOR_DETAIL_NON_UNIQUE_CONTAINER_HELPER_HPP
#if defined(_MSC_VER) && (_MSC_VER>=1200)
#pragma once
#endif
#include <boost/config.hpp>
/*****************************************************************************/
#define BOOST_BIMAP_NON_UNIQUE_CONTAINER_ADAPTOR_INSERT_FUNCTIONS \
\
template <class InputIterator> \
void insert(InputIterator iterBegin, InputIterator iterEnd) \
{ \
for( ; iterBegin != iterEnd ; ++iterBegin ) \
{ \
this->base().insert( \
this->template functor< \
BOOST_DEDUCED_TYPENAME base_::value_to_base>()( \
BOOST_DEDUCED_TYPENAME base_::value_type(*iterBegin)) ); \
} \
} \
\
BOOST_DEDUCED_TYPENAME base_::iterator insert( \
BOOST_DEDUCED_TYPENAME ::boost::call_traits< \
BOOST_DEDUCED_TYPENAME base_::value_type >::param_type x) \
{ \
return this->base().insert( this->template functor< \
BOOST_DEDUCED_TYPENAME base_:: \
value_to_base>()(x) ); \
} \
\
BOOST_DEDUCED_TYPENAME base_::iterator \
insert(BOOST_DEDUCED_TYPENAME base_::iterator pos, \
BOOST_DEDUCED_TYPENAME ::boost::call_traits< \
BOOST_DEDUCED_TYPENAME base_::value_type >::param_type x) \
{ \
return this->template functor< \
BOOST_DEDUCED_TYPENAME base_::iterator_from_base>()( \
this->base().insert(this->template functor< \
BOOST_DEDUCED_TYPENAME base_::iterator_to_base>()(pos), \
this->template functor< \
BOOST_DEDUCED_TYPENAME base_::value_to_base>()(x)) \
); \
}
/*****************************************************************************/
#endif // BOOST_BIMAP_CONTAINER_ADAPTOR_DETAIL_NON_UNIQUE_CONTAINER_HELPER_HPP
| [
"hanchuan.peng@gmail.com"
] | hanchuan.peng@gmail.com |
af8d8616b9bcd7831502511bf50d8b6f3bc6d166 | dbd4f40c16380778073a4e813283bc3d192c88a2 | /SenderMonitorDlg.h | db31a41685ecec97a596f236d79bd834b9fafe4b | [
"Apache-2.0"
] | permissive | lotharperr/p3t | 1a9db775d06ed091a0b11123447e9cbb44debc3f | 2f8d8f8196f6c2b2bbb75bb4325d1487c2429a1d | refs/heads/master | 2016-09-06T11:08:08.458252 | 2015-04-20T13:28:33 | 2015-04-20T13:28:33 | 34,257,136 | 0 | 0 | null | null | null | null | ISO-8859-2 | C++ | false | false | 2,476 | h | /***************************************************************************
* Copyright 2015 Lothar Perr
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
***************************************************************************/
#pragma once
#include "Sender.h"
#include "afxwin.h"
#include <string>
#include <mutex>
#include "afxlinkctrl.h"
#include "p3t.h"
class CSenderMonitorDlg : public CDialogEx
{
DECLARE_DYNAMIC(CSenderMonitorDlg)
private:
CString m_Param_Server;
int m_Param_Port;
int m_Param_PacketSize;
int m_Param_PacketsPerBlock;
int m_Param_BlockDelay;
ProtocolType m_Param_Protocol;
CBrush m_brush;
class CSender *m_Sender;
std::thread *m_SenderMonitorThread;
std::atomic<bool> m_StopFlag;
std::atomic<unsigned short> m_RefreshCount;
std::mutex m_StatusStringLock;
std::wstring m_StatusString;
std::wstring m_LastStatusString;
std::atomic<unsigned long long> m_SenderTotalPackets;
std::atomic<unsigned long long> m_SenderTotalBytes;
std::atomic<unsigned long long> m_SenderCurrentPacketsPerSecond;
std::atomic<unsigned long long> m_SenderCurrentBytesPerSecond;
std::atomic<bool> m_NewValue;
bool m_PauseStatus;
void MonitorSenderThreadProc();
void UpdateSenderValues();
void StartTest();
void StopTest();
public:
CSenderMonitorDlg(CWnd* pParent = NULL); // Standardkonstruktor
virtual ~CSenderMonitorDlg();
void RunTest(CString Server, int Port, int PacketSize, int PacketsPerBlock, int BlockDelay, ProtocolType Protocol);
// Dialogfelddaten
enum { IDD = IDD_SENDERMONITOR };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV-Unterstützung
DECLARE_MESSAGE_MAP()
public:
CEdit m_PacketCount;
CEdit m_BytesSent;
CEdit m_PacketsPerSecond;
CEdit m_BytesPerSecond;
CEdit m_SenderStatus;
virtual BOOL OnInitDialog();
afx_msg void OnTimer(UINT_PTR nIDEvent);
afx_msg void OnCancelDialog();
afx_msg void OnBnClickedPause();
CButton m_btnPause;
CEdit m_Receiver;
CEdit m_Settings;
};
| [
"lothar.perr@gmail.com"
] | lothar.perr@gmail.com |
226958b4cc91bfce4960c1c64978a0871342b700 | c0690fc8961d0ce47550eee82ccbd7edde030f1e | /source/armory/Projectile_Revolver.h | 5d5515bb305b67be7682201bde82eee72b7f496f | [] | no_license | ryansnelgrove/RavenProject | beab61afaff4fccbbca0b27af50035d81cff458a | 1fd8bc11ee843a6c6ec7a62c2fbc67e52185efbd | refs/heads/master | 2021-01-01T04:01:34.046553 | 2016-05-16T20:04:24 | 2016-05-16T20:04:24 | 56,002,266 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 269 | h | #ifndef REVBULLET_H
#define REVBULLET_H
#include "Raven_Projectile.h"
class Raven_Bot;
class RevBullet : public Raven_Projectile
{
private:
void TestForImpact();
public:
RevBullet(Raven_Bot* shooter, Vector2D target);
void Render();
void Update();
};
#endif | [
"snelgror@gmatc.matc.edu"
] | snelgror@gmatc.matc.edu |
6656ca5e956338bf7c189658a74ca130f08b07bd | 6385a177cc731c4f20061effb63dab73b84ba30b | /QtSkia/QtSkiaWidget/QSkiaOpenGLWidget.h | b3883366c900b08807a381fe8b9a49cd28fbdd63 | [
"MIT"
] | permissive | Qt-Widgets/QtSkia | 7b67d3f7303cea6c02551c651ff6ad7040dd35c5 | e0ff7bef839f9466857115631e17b50260cb3443 | refs/heads/master | 2020-12-04T22:11:31.621870 | 2020-01-06T18:59:28 | 2020-01-06T18:59:28 | 231,917,869 | 1 | 0 | MIT | 2020-01-06T18:59:30 | 2020-01-05T12:59:54 | null | UTF-8 | C++ | false | false | 574 | h | #pragma once
#include "QtSkia_global.h"
#include <QOpenGLWidget>
class SkCanvas;
class QSkiaOpenGLWidgetPrivate;
class QtSkia_API QSkiaOpenGLWidget : public QOpenGLWidget {
Q_OBJECT
public:
QSkiaOpenGLWidget(QWidget* parent = nullptr);
~QSkiaOpenGLWidget() override;
virtual void draw(SkCanvas* canvas, int elapsed = 16) = 0;
protected:
virtual void initializeGL() override;
virtual void resizeGL(int w, int h) override;
virtual void paintGL() override;
void init(int w, int h);
private:
QSkiaOpenGLWidgetPrivate* m_dptr = nullptr;
};
| [
"wentaojia2014@163.com"
] | wentaojia2014@163.com |
fca9e9dee0fcdcbb30ef78d94eac4ebf01d3e726 | 948f4e13af6b3014582909cc6d762606f2a43365 | /testcases/juliet_test_suite/testcases/CWE590_Free_Memory_Not_on_Heap/s02/CWE590_Free_Memory_Not_on_Heap__delete_array_struct_alloca_33.cpp | b6a2610dabaa969b36b98a01eb2af61f5a82c559 | [] | no_license | junxzm1990/ASAN-- | 0056a341b8537142e10373c8417f27d7825ad89b | ca96e46422407a55bed4aa551a6ad28ec1eeef4e | refs/heads/master | 2022-08-02T15:38:56.286555 | 2022-06-16T22:19:54 | 2022-06-16T22:19:54 | 408,238,453 | 74 | 13 | null | 2022-06-16T22:19:55 | 2021-09-19T21:14:59 | null | UTF-8 | C++ | false | false | 3,176 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE590_Free_Memory_Not_on_Heap__delete_array_struct_alloca_33.cpp
Label Definition File: CWE590_Free_Memory_Not_on_Heap__delete_array.label.xml
Template File: sources-sink-33.tmpl.cpp
*/
/*
* @description
* CWE: 590 Free Memory Not on Heap
* BadSource: alloca Data buffer is allocated on the stack with alloca()
* GoodSource: Allocate memory on the heap
* Sinks:
* BadSink : Print then free data
* Flow Variant: 33 Data flow: use of a C++ reference to data within the same function
*
* */
#include "std_testcase.h"
#include <wchar.h>
namespace CWE590_Free_Memory_Not_on_Heap__delete_array_struct_alloca_33
{
#ifndef OMITBAD
void bad()
{
twoIntsStruct * data;
twoIntsStruct * &dataRef = data;
data = NULL; /* Initialize data */
{
/* FLAW: data is allocated on the stack and deallocated in the BadSink */
twoIntsStruct * dataBuffer = (twoIntsStruct *)ALLOCA(100*sizeof(twoIntsStruct));
{
size_t i;
for (i = 0; i < 100; i++)
{
dataBuffer[i].intOne = 1;
dataBuffer[i].intTwo = 1;
}
}
data = dataBuffer;
}
{
twoIntsStruct * data = dataRef;
printStructLine(&data[0]);
/* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */
delete [] data;
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2B()
{
twoIntsStruct * data;
twoIntsStruct * &dataRef = data;
data = NULL; /* Initialize data */
{
/* FIX: data is allocated on the heap and deallocated in the BadSink */
twoIntsStruct * dataBuffer = new twoIntsStruct[100];
{
size_t i;
for (i = 0; i < 100; i++)
{
dataBuffer[i].intOne = 1;
dataBuffer[i].intTwo = 1;
}
}
data = dataBuffer;
}
{
twoIntsStruct * data = dataRef;
printStructLine(&data[0]);
/* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */
delete [] data;
}
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE590_Free_Memory_Not_on_Heap__delete_array_struct_alloca_33; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| [
"yzhang0701@gmail.com"
] | yzhang0701@gmail.com |
122841e3c8cbe366a2d366ff4ec024903b7e378c | 671c91a52f48c838ea5f7fc23b72a87f3bb4034d | /week 6-3/Source.cpp | 59aa58a52eea925c60fcec203cc79bfe26afa131 | [] | no_license | penpitcha02/week-6-3 | 731da43bdf32560b86049123e9310533ce09df14 | e004fa8e349af283ca6634b83c01eb97823ae676 | refs/heads/master | 2022-12-17T15:44:12.969444 | 2020-09-14T11:10:17 | 2020-09-14T11:10:17 | 295,389,844 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 403 | cpp | #include <stdio.h>
int main()
{
int a, b, c;
printf("a: "); scanf_s("%d", &a);
printf("b: "); scanf_s("%d", &b);
printf("c: "); scanf_s("%d", &c);
if (a > 0 && b > 0 && c > 0)
{
a *= a;
b *= b;
c *= c;
if ((a + b == c) || (a + c == b) || (b + c == a))
{
printf("Yes");
}
else {
printf("No");
}
}
else {
printf("width and height must be greater than 0");
}
return 0;
} | [
"63010709@KMITL.AC.TH"
] | 63010709@KMITL.AC.TH |
7ee6cf2a3ad01d0e567eb1dbd34fe2e1eff450f2 | 9a58ec88b54aa44156bbf9de2c6e5ec9bb3a6661 | /src/szn/array.hpp | 5eb47933b8fa2519590e96873c7a536a748e2b2a | [
"MIT"
] | permissive | TyRoXx/serialization | 284e479a88eb0fb1923fefb953b4f1b7042a1c13 | 02723b672ecd2dc974988f63d15412b2cf12bc56 | refs/heads/master | 2021-01-10T20:00:52.803259 | 2014-04-28T15:14:44 | 2014-04-28T15:14:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,576 | hpp | #ifndef SERIALIZATION_ARRAY_HPP_3AB95632_FCB4_481B_AB69_381567C9695C
#define SERIALIZATION_ARRAY_HPP_3AB95632_FCB4_481B_AB69_381567C9695C
#include <szn/util.hpp>
#include <boost/array.hpp>
#ifndef SZN_NO_CPP11
# include <array>
#endif
namespace szn
{
/// a format for fixed-length sequences of a certain type.
/// Works with std::array and C arrays.
template <std::size_t Length, class ElementFormat>
struct array
{
typedef boost::array<typename ElementFormat::default_type, Length> default_type;
template <class Sink, class Element>
void serialize(Sink &sink, const boost::array<Element, Length> &a) const
{
BOOST_FOREACH (const Element &e, a)
{
szn::serialize(sink, e, ElementFormat());
}
}
template <class Source, class Element>
void deserialize(Source &source, boost::array<Element, Length> &a) const
{
for (std::size_t i = 0; i < Length; ++i)
{
szn::deserialize(source, a[i], ElementFormat());
}
}
template <class Sink, class First, class Second>
typename boost::enable_if_c<Length == 2, void>::type
serialize(Sink &sink, std::pair<First, Second> const &elements)
{
ElementFormat elem;
elem.serialize(sink, elements.first);
elem.serialize(sink, elements.second);
}
template <class Source, class First, class Second>
typename boost::enable_if_c<Length == 2, void>::type
deserialize(Source &source, std::pair<First, Second> &elements)
{
ElementFormat elem;
elem.deserialize(source, elements.first);
elem.deserialize(source, elements.second);
}
#ifndef SZN_NO_CPP11
template <class Sink, class Element>
void serialize(Sink &sink, const std::array<Element, Length> &a) const
{
BOOST_FOREACH (const Element &e, a)
{
szn::serialize(sink, e, ElementFormat());
}
}
template <class Source, class Element>
void deserialize(Source &source, std::array<Element, Length> &a) const
{
for (std::size_t i = 0; i < Length; ++i)
{
szn::deserialize(source, a[i], ElementFormat());
}
}
#endif
//C style array
template <class Sink, class Element>
void serialize(Sink &sink, const Element (&a)[Length]) const
{
BOOST_FOREACH (const Element &e, a)
{
szn::serialize(sink, e, ElementFormat());
}
}
template <class Source, class Element>
void deserialize(Source &source, Element (&a)[Length]) const
{
for (std::size_t i = 0; i < Length; ++i)
{
szn::deserialize(source, a[i], ElementFormat());
}
}
};
}
#endif
| [
"tyroxxxx@gmail.com"
] | tyroxxxx@gmail.com |
50b8d9b1d040510f89ed52ae61cc8395fdfc8001 | f6c1236939cc1ce0c5b340a0ec29fac879cbe536 | /src/problems/P1426 小鱼会有危险吗/1.cpp | 38d2971295563d656839e150571a2dae03f81eec | [] | no_license | chenyiAlone/luogu | 7a6db9da99e8d4d4de44fdce9789dbc762604ee3 | 7c856f8e649f4f8d074563d4b32631372ffe528d | refs/heads/master | 2020-05-30T15:21:38.127036 | 2019-07-14T07:00:49 | 2019-07-14T07:00:49 | 189,815,440 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,572 | cpp | /*
题目描述
有一次,小鱼要从A处沿直线往右边游,小鱼第一秒可以游7米,从第二秒开始每秒游的距离只有前一秒的98%。有个极其邪恶的猎人在距离A处右边s米的地方,安装了一个隐蔽的探测器,探测器左右x米之内是探测范围。一旦小鱼进入探测器的范围,探测器就会在这一秒结束时把信号传递给那个猎人,猎人在一秒后就要对探测器范围内的水域进行抓捕,这时如果小鱼还在这范围内就危险了。也就是说小鱼一旦进入探测器范围,如果能在下1秒的时间内马上游出探测器的范围,还是安全的。现在给出s和x的数据,请你判断小鱼会不会有危险?如果有危险输出'y',没有危险输出'n'。
//感谢黄小U饮品完善题意
输入输出格式
输入格式:
一行内输入两个实数,用空格分隔,表示s和x。均不大于100
输出格式:
一行内输出'y'或者'n'表示小鱼是否会有危险。
输入输出样例
输入样例#1:
14 1
输出样例#1:
n
*/
#include <iostream>
#include <math.h>
using namespace std;
int main() {
int s, x;
cin >> s >> x;
double total = 0;
int i = 0;
while (i <= 45) {
if (total + 7 * pow(0.98, i) > s - x)
break;
total += 7 * pow(0.98, i);
i++;
}
double lt = (s - total) / 7 * pow(0.98, i);
double dist = lt * 7 * pow(0.98, i) + (1 - lt) * 7 * pow(0.98, i + 1);
if (dist <= 2 * x)
cout << 'y';
else
cout << 'n';
return 0;
} | [
"1193642781@qq.com"
] | 1193642781@qq.com |
fe0c6003016a8621dc5d73057a42ea020f29e456 | b162d51fb88e0725006d99dcddf97e6b6ed33557 | /core/src/SoftTimer.cpp | da961ce378c5b375b420f22b1578de7d6234951c | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | Petross404/LIO | 6da7c1b97e8c1cc5a91017ce23dd0c59d6fe56ac | 62578bdee261735afa23f7c0c8437e927425aef6 | refs/heads/master | 2022-12-04T12:09:53.118337 | 2020-08-01T10:52:38 | 2020-08-01T10:52:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,794 | cpp | #include "SoftTimer.h"
#include <thread>
#include <functional>
#include <chrono>
using namespace LIO;
using namespace std;
SoftTimer::SoftTimer():repMode(repeatMode::single),myState(state::idle),
timerThreadExitRequest(false){
promise<void> exitPromise;
timerThreadFuture=exitPromise.get_future();
thread(bind(&SoftTimer::timerTask,this,placeholders::_1),move(exitPromise)).detach();//start thread
StopAndReset();
}
SoftTimer::~SoftTimer(){
timerThreadExitRequest=true;
s.signal();
while(timerThreadFuture.wait_for(100ms)!=future_status::ready){
s.signal();
}
}
void SoftTimer::SetTimeout(std::chrono::milliseconds timeout){
this->timeout=timeout;
}
void SoftTimer::Start(){
if(myState==state::idle){
myState=state::running;
s.signal();
}
}
void SoftTimer::StopAndReset(){
if(myState==state::running){
myState=state::idle;
s.signal();
}
}
void SoftTimer::SetRepeatMode(BasicTimer::repeatMode newRepMode){
repMode=newRepMode;
}
void SoftTimer::timerTask(std::promise<void> &&exitPromise){
while(!timerThreadExitRequest){
switch(myState){
case state::idle:{
s.wait();
break;
}
case state::running:{
if(s.wait_for(timeout.load())==MySignal::sig_status::timeout){
timeoutCallback();
switch(repMode){
case repeatMode::single:
myState=state::idle;
break;
case repeatMode::continuous:
break;
}
}
break;
}
}
}
exitPromise.set_value_at_thread_exit();
}
| [
"vitez.laci@gmail.com"
] | vitez.laci@gmail.com |
a880571b1a6efc612c1750e6b22de91052519f1e | 95c0cc56717cee3f874bdcb4c4dea26099c263f7 | /src/zmq/zmqabstractnotifier.cpp | 044536ef3f7e01060c0b22db4d72833da70bc8a7 | [
"MIT"
] | permissive | scalow2/gechcoin | 9ef636d8ceff5948bf8956f5952df15ca906022b | 7ff9a68c7cb3d19a2c73ae1004fe78c6da0ea716 | refs/heads/master | 2023-02-12T14:13:34.909543 | 2021-01-11T15:20:22 | 2021-01-11T15:20:22 | 328,703,858 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 514 | cpp | // Copyright (c) 2015 The GECH Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "zmqabstractnotifier.h"
#include "util.h"
CZMQAbstractNotifier::~CZMQAbstractNotifier()
{
assert(!psocket);
}
bool CZMQAbstractNotifier::NotifyBlock(const CBlockIndex * /*CBlockIndex*/)
{
return true;
}
bool CZMQAbstractNotifier::NotifyTransaction(const CTransaction &/*transaction*/)
{
return true;
}
| [
"gech@126.com"
] | gech@126.com |
fa4a83bc4bc0bad309ddca571a257bdc98f0321f | d09092dbe69c66e916d8dd76d677bc20776806fe | /.libs/puno_automatic_generated/inc/types/com/sun/star/util/SearchAlgorithms.hpp | bea25b12d6e2dcf5cd3b5a2c8ea156400533841f | [] | no_license | GXhua/puno | 026859fcbc7a509aa34ee857a3e64e99a4568020 | e2f8e7d645efbde5132b588678a04f70f1ae2e00 | refs/heads/master | 2020-03-22T07:35:46.570037 | 2018-07-11T02:19:26 | 2018-07-11T02:19:26 | 139,710,567 | 0 | 0 | null | 2018-07-04T11:03:58 | 2018-07-04T11:03:58 | null | UTF-8 | C++ | false | false | 1,098 | hpp | #ifndef INCLUDED_COM_SUN_STAR_UTIL_SEARCHALGORITHMS_HPP
#define INCLUDED_COM_SUN_STAR_UTIL_SEARCHALGORITHMS_HPP
#include "sal/config.h"
#include "com/sun/star/util/SearchAlgorithms.hdl"
#include "com/sun/star/uno/Type.hxx"
#include "cppu/unotype.hxx"
namespace com { namespace sun { namespace star { namespace util {
inline ::css::uno::Type const & cppu_detail_getUnoType(SAL_UNUSED_PARAMETER ::css::util::SearchAlgorithms const *) {
static typelib_TypeDescriptionReference * the_type = 0;
if ( !the_type )
{
typelib_static_enum_type_init( &the_type,
"com.sun.star.util.SearchAlgorithms",
::css::util::SearchAlgorithms_ABSOLUTE );
}
return * reinterpret_cast< ::css::uno::Type * >( &the_type );
}
} } } }
SAL_DEPRECATED("use cppu::UnoType") inline ::css::uno::Type const & SAL_CALL getCppuType(SAL_UNUSED_PARAMETER ::css::util::SearchAlgorithms const *) {
return ::cppu::UnoType< ::css::util::SearchAlgorithms >::get();
}
#endif // INCLUDED_COM_SUN_STAR_UTIL_SEARCHALGORITHMS_HPP
| [
"guoxinhua@10.10.12.142"
] | guoxinhua@10.10.12.142 |
ba84d0a601e91e8f126d32d514d944a62d4439b8 | 9d364070c646239b2efad7abbab58f4ad602ef7b | /platform/external/chromium_org/extensions/browser/notification_types.h | 4698021fea2a3127f813ea1297e5d82603e4f717 | [
"BSD-3-Clause"
] | permissive | denix123/a32_ul | 4ffe304b13c1266b6c7409d790979eb8e3b0379c | b2fd25640704f37d5248da9cc147ed267d4771c2 | refs/heads/master | 2021-01-17T20:21:17.196296 | 2016-08-16T04:30:53 | 2016-08-16T04:30:53 | 65,786,970 | 0 | 2 | null | 2020-03-06T22:00:52 | 2016-08-16T04:15:54 | null | UTF-8 | C++ | false | false | 2,592 | h | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef EXTENSIONS_BROWSER_NOTIFICATION_TYPES_H_
#define EXTENSIONS_BROWSER_NOTIFICATION_TYPES_H_
#include "content/public/browser/notification_types.h"
namespace extensions {
enum NotificationType {
NOTIFICATION_EXTENSIONS_START = content::NOTIFICATION_CONTENT_END,
NOTIFICATION_CRX_INSTALLER_DONE = NOTIFICATION_EXTENSIONS_START,
NOTIFICATION_EXTENSIONS_READY_DEPRECATED,
NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
NOTIFICATION_EXTENSION_LOAD_ERROR,
NOTIFICATION_EXTENSION_ENABLED,
NOTIFICATION_EXTENSION_UPDATE_DISABLED,
NOTIFICATION_EXTENSION_PERMISSIONS_UPDATED,
NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
NOTIFICATION_EXTENSION_INSTALL_ERROR,
NOTIFICATION_EXTENSION_UNINSTALLED_DEPRECATED,
NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED,
NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
NOTIFICATION_EXTENSION_REMOVED,
NOTIFICATION_EXTENSION_HOST_CREATED,
NOTIFICATION_EXTENSION_HOST_DESTROYED,
NOTIFICATION_EXTENSION_HOST_DID_STOP_LOADING,
NOTIFICATION_EXTENSION_HOST_VIEW_SHOULD_CLOSE,
NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
NOTIFICATION_EXTENSION_BACKGROUND_PAGE_READY,
NOTIFICATION_EXTENSION_PAGE_ACTION_COUNT_CHANGED,
NOTIFICATION_EXTENSION_BROWSER_ACTION_VISIBILITY_CHANGED,
NOTIFICATION_EXTENSION_COMMAND_REMOVED,
NOTIFICATION_EXTENSION_COMMAND_ADDED,
NOTIFICATION_EXTENSION_COMMAND_BROWSER_ACTION_MAC,
NOTIFICATION_EXTENSION_COMMAND_PAGE_ACTION_MAC,
NOTIFICATION_EXTENSION_VIEW_REGISTERED,
NOTIFICATION_EXTENSION_VIEW_UNREGISTERED,
NOTIFICATION_EXTENSION_TEST_PASSED,
NOTIFICATION_EXTENSION_TEST_FAILED,
NOTIFICATION_EXTENSION_TEST_MESSAGE,
NOTIFICATION_EXTENSION_BOOKMARKS_API_INVOKED,
NOTIFICATION_EXTENSION_DOWNLOADS_EVENT,
NOTIFICATION_EXTENSION_OMNIBOX_SUGGESTIONS_READY,
NOTIFICATION_EXTENSION_OMNIBOX_INPUT_ENTERED,
NOTIFICATION_EXTENSION_OMNIBOX_DEFAULT_SUGGESTION_CHANGED,
NOTIFICATION_EXTENSION_UPDATING_STARTED,
NOTIFICATION_EXTENSION_UPDATE_FOUND,
NOTIFICATION_USER_SCRIPTS_UPDATED,
NOTIFICATION_EXTENSIONS_END
};
}
#endif
| [
"allegrant@mail.ru"
] | allegrant@mail.ru |
7eba1d106cd149c873c0bd8a028115e5cc19304a | a7764174fb0351ea666faa9f3b5dfe304390a011 | /src/BinMXCAFDoc/BinMXCAFDoc.cxx | 25610ee97004e670ecb9fbb93e127dff721aad2b | [] | no_license | uel-dataexchange/Opencascade_uel | f7123943e9d8124f4fa67579e3cd3f85cfe52d91 | 06ec93d238d3e3ea2881ff44ba8c21cf870435cd | refs/heads/master | 2022-11-16T07:40:30.837854 | 2020-07-08T01:56:37 | 2020-07-08T01:56:37 | 276,290,778 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,797 | cxx | // File: BinMXCAFDoc.cxx
// Created: Mon Apr 18 17:45:27 2005
// Author: Eugeny NAPALKOV <eugeny.napalkov@opencascade.com>
// Copyright: Open CasCade S.A. 2005
#include <BinMXCAFDoc.ixx>
#include <BinMXCAFDoc_AreaDriver.hxx>
#include <BinMXCAFDoc_CentroidDriver.hxx>
#include <BinMXCAFDoc_ColorDriver.hxx>
#include <BinMXCAFDoc_GraphNodeDriver.hxx>
#include <BinMXCAFDoc_LocationDriver.hxx>
#include <BinMXCAFDoc_VolumeDriver.hxx>
#include <BinMXCAFDoc_DatumDriver.hxx>
#include <BinMXCAFDoc_DimTolDriver.hxx>
#include <BinMXCAFDoc_MaterialDriver.hxx>
#include <BinMXCAFDoc_ColorToolDriver.hxx>
#include <BinMXCAFDoc_DocumentToolDriver.hxx>
#include <BinMXCAFDoc_LayerToolDriver.hxx>
#include <BinMXCAFDoc_ShapeToolDriver.hxx>
#include <BinMXCAFDoc_DimTolToolDriver.hxx>
#include <BinMXCAFDoc_MaterialToolDriver.hxx>
#include <BinMNaming_NamedShapeDriver.hxx>
#include <TNaming_NamedShape.hxx>
//=======================================================================
//function :
//purpose :
//=======================================================================
void BinMXCAFDoc::AddDrivers(const Handle(BinMDF_ADriverTable)& theDriverTable,
const Handle(CDM_MessageDriver)& theMsgDrv) {
theDriverTable->AddDriver( new BinMXCAFDoc_AreaDriver (theMsgDrv));
theDriverTable->AddDriver( new BinMXCAFDoc_CentroidDriver (theMsgDrv));
theDriverTable->AddDriver( new BinMXCAFDoc_ColorDriver (theMsgDrv));
theDriverTable->AddDriver( new BinMXCAFDoc_GraphNodeDriver(theMsgDrv));
//oan: changes for sharing locations map
Handle(BinMNaming_NamedShapeDriver) aNamedShapeDriver;
theDriverTable->GetDriver(STANDARD_TYPE(TNaming_NamedShape), aNamedShapeDriver);
Handle(BinMXCAFDoc_LocationDriver) aLocationDriver = new BinMXCAFDoc_LocationDriver (theMsgDrv);
if( !aNamedShapeDriver.IsNull() )
{
aLocationDriver->SetSharedLocations( &(aNamedShapeDriver->GetShapesLocations()) );
}
theDriverTable->AddDriver( aLocationDriver);
theDriverTable->AddDriver( new BinMXCAFDoc_VolumeDriver (theMsgDrv));
theDriverTable->AddDriver( new BinMXCAFDoc_DatumDriver (theMsgDrv));
theDriverTable->AddDriver( new BinMXCAFDoc_DimTolDriver (theMsgDrv));
theDriverTable->AddDriver( new BinMXCAFDoc_MaterialDriver (theMsgDrv));
theDriverTable->AddDriver( new BinMXCAFDoc_ColorToolDriver (theMsgDrv));
theDriverTable->AddDriver( new BinMXCAFDoc_DocumentToolDriver(theMsgDrv));
theDriverTable->AddDriver( new BinMXCAFDoc_LayerToolDriver (theMsgDrv));
theDriverTable->AddDriver( new BinMXCAFDoc_ShapeToolDriver (theMsgDrv));
theDriverTable->AddDriver( new BinMXCAFDoc_DimTolToolDriver (theMsgDrv));
theDriverTable->AddDriver( new BinMXCAFDoc_MaterialToolDriver(theMsgDrv));
}
| [
"shoka.sho2@excel.co.jp"
] | shoka.sho2@excel.co.jp |
2a1e86abacabaf337803ca81942a5b53d8a99571 | 85c50c7c6999c4f5c754459e1193bd5e05e6b67f | /tty_attacher.cpp | b2c52eb31e0b5ad3bab51b5f7735ecf011ffdfbf | [
"MIT"
] | permissive | dany74q/sshpassten | 89f5bbbfb23051effd306fba57fe613806511375 | ababf73f3a22cd81f99b67565696e0523115d187 | refs/heads/master | 2020-03-27T06:38:35.897533 | 2018-08-26T22:47:15 | 2018-08-26T22:47:15 | 146,122,951 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 597 | cpp | #include "tty_attacher.hpp"
#include "utils.hpp"
#include <unistd.h>
#include <fcntl.h>
namespace sshpassten {
namespace detail {
inline namespace v1 {
void TTYAttacher::attachTo(const std::string& ttyPath) {
// This creates a new session, making the current process the session leader, process-group leader,
// A by-product of this is detaching the current process from its previous TTY.
checkErrno(::setsid);
// Opening a tty file here will attach the current process to it;
// However, we don't need the FD itself open.
{
File(ttyPath, O_RDWR);
}
}
}
}
} | [
"dany74q@gmail.com"
] | dany74q@gmail.com |
0f59361dd6d90afb5c76fee7951b83c0385747c1 | ad822f849322c5dcad78d609f28259031a96c98e | /SDK/ExoticResources_classes.h | c99e386f6d1f4c99db1a22d5217f72d7fd2a9763 | [] | no_license | zH4x-SDK/zAstroneer-SDK | 1cdc9c51b60be619202c0258a0dd66bf96898ac4 | 35047f506eaef251a161792fcd2ddd24fe446050 | refs/heads/main | 2023-07-24T08:20:55.346698 | 2021-08-27T13:33:33 | 2021-08-27T13:33:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 633 | h | #pragma once
// Name: Astroneer-SDK, Version: 1.0.0
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass ExoticResources.ExoticResources_C
// 0x0000 (0x0040 - 0x0040)
class UExoticResources_C : public UItemList
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass ExoticResources.ExoticResources_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"zp2kshield@gmail.com"
] | zp2kshield@gmail.com |
fdf8f3433730bce9e5340b6142306bc257b5692a | f8679bf8a695d31572f441e57502d72930ab2f6d | /offline/packages/trackreco/ALICEKF.h | 45cb89d76b5c306a229907bc757067b252e77c99 | [] | no_license | cipriangal/coresoftware | c6790460bfe5fe8d99200daed9e1dbdfec1352a5 | 7021d0505923823ddde00263c53252214a464b51 | refs/heads/master | 2023-03-29T20:36:48.883411 | 2021-04-02T01:10:32 | 2021-04-02T01:10:32 | 260,228,097 | 0 | 0 | null | 2020-04-30T14:04:53 | 2020-04-30T14:04:52 | null | UTF-8 | C++ | false | false | 1,555 | h | #ifndef ALICEKF_H
#define ALICEKF_H
#include <trackbase_historic/SvtxTrack_v1.h>
#include <trackbase/TrkrDefs.h>
#include <trackbase/TrkrClusterContainer.h>
#include <phfield/PHField.h>
#include <phfield/PHFieldUtility.h>
#include <Eigen/Core>
#include <Eigen/Dense>
#include <vector>
#include <string>
#include <utility>
class ALICEKF
{
public:
ALICEKF(PHCompositeNode *topNode,
TrkrClusterContainer* cmap,
double fieldDir,
unsigned int min_clusters,
double max_sin_phi,
int verbosity)
{
_B = PHFieldUtility::GetFieldMapNode(nullptr,topNode);
_cluster_map = cmap;
_fieldDir = fieldDir;
_max_sin_phi = max_sin_phi;
_v = verbosity;
_min_clusters_per_track = min_clusters;
}
~ALICEKF(){}
std::vector<SvtxTrack_v1> ALICEKalmanFilter(std::vector<std::vector<TrkrDefs::cluskey>> chains, bool use_nhits_limit);
Eigen::Matrix<double,6,6> getEigenCov(SvtxTrack_v1 &track);
bool covIsPosDef(SvtxTrack_v1 &track);
void repairCovariance(SvtxTrack_v1 &track);
bool checknan(double val, const std::string &msg, int num);
double get_Bz(double x, double y, double z);
void CircleFitByTaubin(std::vector<std::pair<double,double>> pts, double &R, double &X0, double &Y0);
private:
PHField* _B;
size_t _min_clusters_per_track = 20;
TrkrClusterContainer* _cluster_map = nullptr;
int Verbosity(){ return _v; }
int _v = 0;
double _Bzconst = 10*0.000299792458f;
double _fieldDir = -1;
double _max_sin_phi = 1.;
bool _use_const_field = false;
};
#endif
| [
"mjpeters@mit.edu"
] | mjpeters@mit.edu |
c086b468ccf049c33b2cbc0770bf14cc69776305 | 20c9c11b8400c6605d869c84e69c41c5faa3f260 | /blmarket/2013/kriiicpc/template.cpp | f2c809aead53604ce699f11c3debe730fa061d30 | [] | no_license | blmarket/icpc | 312ea2c667ec08d16864c1faa6fe75d3864dedbe | febfc2b758b7a4a4d6e5a6f05d24e3a964a3213a | refs/heads/master | 2021-07-23T20:20:19.780664 | 2021-05-15T13:39:04 | 2021-05-15T13:39:04 | 4,029,598 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 705 | cpp | #include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <sstream>
#include <numeric>
#include <iterator>
#include <queue>
#include <set>
#include <map>
#include <vector>
#define mp make_pair
#define pb push_back
#define sqr(x) ((x)*(x))
#define foreach(it,c) for(typeof((c).begin()) it = (c).begin(); it != (c).end(); ++it)
using namespace std;
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef pair<int,int> PII;
template<typename T> int size(const T &a) { return a.size(); }
void process(void) {
}
int main(void)
{
int T;
scanf("%d", &T);
for(int i=1;i<=T;i++) {
process();
// cerr << i << endl;
}
}
| [
"blmarket@gmail.com"
] | blmarket@gmail.com |
c78cc8088fde9dd631bf0ab5d70ec08f8ed27786 | c5718f09a6e4e7fe8ed375981bbab7693817302f | /Classes/Level/Rider/BikeAudio.cpp | 6df89f995c1b01d0357f17d3fd27a6d9950b5a1e | [] | no_license | ryanmcbride/CrashTestMonkeys | 3ef3d4917b8d829005fb9b5c991970e86d282be8 | 236317741c7e769cb43da56cd52ec2681d12aeff | refs/heads/master | 2016-09-06T18:51:47.699575 | 2013-10-01T03:17:03 | 2013-10-01T03:17:03 | 10,875,817 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 18,423 | cpp | /*
* Vehicle.cpp
* CTM
*
* Created by Ryan McBride on 2/5/11.
* Copyright 2011 __MyCompanyName__. All rights reserved.
*
*/
#include "Box2D.h"
#include "SimpleAudioEngine.h"
#include "Rider.h"
#include "BikeAudio.h"
#include "../../FrontEnd/SaveLoad.h"
USING_NS_CC;
using namespace CocosDenshion;
#if (CC_TARGET_PLATFORM != CC_PLATFORM_IOS)
#define AUDIO_DIRECTORY "Audio/"
#else
#define AUDIO_DIRECTORY ""
#endif
static BikeAudioDesc s_CHIMPSBikeAudioStates[BikeAudio::NUM_STATES] =
{
{AUDIO_DIRECTORY"",1.0,BikeAudio::START},
{AUDIO_DIRECTORY"CHIMPSStart.3gp",2.1,BikeAudio::IDLE},
{AUDIO_DIRECTORY"CHIMPSIdle.3gp",4.9,BikeAudio::IDLE},
{AUDIO_DIRECTORY"CHIMPSAccel.3gp",14.55,BikeAudio::IDLE},
{AUDIO_DIRECTORY"CHIMPSDecel.3gp",6.0,BikeAudio::IDLE},
{AUDIO_DIRECTORY"CHIMPSReverse.3gp",10.39,BikeAudio::IDLE},
{AUDIO_DIRECTORY"CHIMPSRough.3gp",2.85,BikeAudio::ROUGH},
{AUDIO_DIRECTORY"CHIMPSBounce.3gp",2.8,BikeAudio::IDLE},
{AUDIO_DIRECTORY"CHIMPS1Loop.3gp",1.95,BikeAudio::IDLE},
{AUDIO_DIRECTORY"CHIMPS2Loop.3gp",4.00,BikeAudio::IDLE},
{AUDIO_DIRECTORY"CHIMPS3Loop.3gp",5.00,BikeAudio::IDLE},
{AUDIO_DIRECTORY"CHIMPSTurbo1.3gp",4.29,BikeAudio::IDLE},
{AUDIO_DIRECTORY"CHIMPSTurbo2.3gp",4.29,BikeAudio::IDLE},
{AUDIO_DIRECTORY"CHIMPSTurbo3.3gp",4.29,BikeAudio::IDLE},
{AUDIO_DIRECTORY"CHIMPSTurbo4.3gp",4.29,BikeAudio::IDLE},
{AUDIO_DIRECTORY"CHIMPSOff.3gp",3.10,BikeAudio::PRESTART},
{AUDIO_DIRECTORY"CHIMPSDecelLow.3gp",3.10,BikeAudio::IDLE},
};
static BikeAudioDesc s_YellerBikeAudioStates[BikeAudio::NUM_STATES] =
{
{AUDIO_DIRECTORY"",1.0,BikeAudio::START},
{AUDIO_DIRECTORY"OldYellerStart.3gp",2.1,BikeAudio::IDLE},
{AUDIO_DIRECTORY"OldYellerIdle.3gp",4.9,BikeAudio::IDLE},
{AUDIO_DIRECTORY"OldYellerAccel.3gp",14.55,BikeAudio::IDLE},
{AUDIO_DIRECTORY"OldYellerDecel.3gp",6.0,BikeAudio::IDLE},
{AUDIO_DIRECTORY"OldYellerReverse.3gp",10.39,BikeAudio::IDLE},
{AUDIO_DIRECTORY"OldYellerRough.3gp",2.85,BikeAudio::ROUGH},
{AUDIO_DIRECTORY"OldYellerBounce.3gp",2.8,BikeAudio::IDLE},
{AUDIO_DIRECTORY"OldYeller1Loop.3gp",1.95,BikeAudio::IDLE},
{AUDIO_DIRECTORY"OldYeller2Loop.3gp",4.00,BikeAudio::IDLE},
{AUDIO_DIRECTORY"OldYeller3Loop.3gp",5.00,BikeAudio::IDLE},
{AUDIO_DIRECTORY"OldYellerTurbo1.3gp",4.29,BikeAudio::IDLE},
{AUDIO_DIRECTORY"OldYellerTurbo2.3gp",4.29,BikeAudio::IDLE},
{AUDIO_DIRECTORY"OldYellerTurbo3.3gp",4.29,BikeAudio::IDLE},
{AUDIO_DIRECTORY"OldYellerTurbo4.3gp",4.29,BikeAudio::IDLE},
{AUDIO_DIRECTORY"OldYellerOff.3gp",3.10,BikeAudio::PRESTART},
{AUDIO_DIRECTORY"OldYellerDecelLow.3gp",3.10,BikeAudio::IDLE},
};
static BikeAudioDesc s_DirtBikeAudioStates[BikeAudio::NUM_STATES] =
{
{AUDIO_DIRECTORY"",1.0,BikeAudio::START},
{AUDIO_DIRECTORY"DirtBikeStart.3gp",2.1,BikeAudio::IDLE},
{AUDIO_DIRECTORY"DirtBikeIdle.3gp",4.9,BikeAudio::IDLE},
{AUDIO_DIRECTORY"DirtBikeAccel.3gp",14.55,BikeAudio::IDLE},
{AUDIO_DIRECTORY"DirtBikeDecel.3gp",6.0,BikeAudio::IDLE},
{AUDIO_DIRECTORY"DirtBikeReverse.3gp",10.39,BikeAudio::IDLE},
{AUDIO_DIRECTORY"DirtBikeRough.3gp",2.85,BikeAudio::ROUGH},
{AUDIO_DIRECTORY"DirtBikeBounce.3gp",2.8,BikeAudio::IDLE},
{AUDIO_DIRECTORY"DirtBike1Loop.3gp",1.95,BikeAudio::IDLE},
{AUDIO_DIRECTORY"DirtBike2Loop.3gp",4.00,BikeAudio::IDLE},
{AUDIO_DIRECTORY"DirtBike3Loop.3gp",5.00,BikeAudio::IDLE},
{AUDIO_DIRECTORY"DirtBikeTurbo1.3gp",4.29,BikeAudio::IDLE},
{AUDIO_DIRECTORY"DirtBikeTurbo2.3gp",4.29,BikeAudio::IDLE},
{AUDIO_DIRECTORY"DirtBikeTurbo3.3gp",4.29,BikeAudio::IDLE},
{AUDIO_DIRECTORY"DirtBikeTurbo4.3gp",4.29,BikeAudio::IDLE},
{AUDIO_DIRECTORY"DirtBikeOff.3gp",3.10,BikeAudio::PRESTART},
{AUDIO_DIRECTORY"DirtBikeDecelLow.3gp",3.10,BikeAudio::IDLE},
};
static BikeAudioDesc s_IslandBikeAudioStates[BikeAudio::NUM_STATES] =
{
{AUDIO_DIRECTORY"",1.0,BikeAudio::START},
{AUDIO_DIRECTORY"IslandStart.3gp",2.1,BikeAudio::IDLE},
{AUDIO_DIRECTORY"IslandIdle.3gp",4.9,BikeAudio::IDLE},
{AUDIO_DIRECTORY"IslandAccel.3gp",14.55,BikeAudio::IDLE},
{AUDIO_DIRECTORY"IslandDecel.3gp",6.0,BikeAudio::IDLE},
{AUDIO_DIRECTORY"IslandReverse.3gp",10.39,BikeAudio::IDLE},
{AUDIO_DIRECTORY"IslandRough.3gp",2.85,BikeAudio::ROUGH},
{AUDIO_DIRECTORY"IslandBounce.3gp",2.8,BikeAudio::IDLE},
{AUDIO_DIRECTORY"Island1Loop.3gp",1.95,BikeAudio::IDLE},
{AUDIO_DIRECTORY"Island2Loop.3gp",4.00,BikeAudio::IDLE},
{AUDIO_DIRECTORY"Island3Loop.3gp",5.00,BikeAudio::IDLE},
{AUDIO_DIRECTORY"IslandTurbo1.3gp",4.29,BikeAudio::IDLE},
{AUDIO_DIRECTORY"IslandTurbo2.3gp",4.29,BikeAudio::IDLE},
{AUDIO_DIRECTORY"IslandTurbo3.3gp",4.29,BikeAudio::IDLE},
{AUDIO_DIRECTORY"IslandTurbo4.3gp",4.29,BikeAudio::IDLE},
{AUDIO_DIRECTORY"IslandOff.3gp",3.10,BikeAudio::PRESTART},
{AUDIO_DIRECTORY"IslandDecelLow.3gp",3.10,BikeAudio::IDLE},
};
static BikeAudioDesc s_ScifiBikeAudioStates[BikeAudio::NUM_STATES] =
{
{AUDIO_DIRECTORY"",1.0,BikeAudio::START},
{AUDIO_DIRECTORY"SciFiStart.3gp",2.1,BikeAudio::IDLE},
{AUDIO_DIRECTORY"SciFiIdle.3gp",4.9,BikeAudio::IDLE},
{AUDIO_DIRECTORY"SciFiAccel.3gp",14.55,BikeAudio::IDLE},
{AUDIO_DIRECTORY"SciFiDecel.3gp",6.0,BikeAudio::IDLE},
{AUDIO_DIRECTORY"SciFiReverse.3gp",10.39,BikeAudio::IDLE},
{AUDIO_DIRECTORY"SciFiRough.3gp",2.85,BikeAudio::ROUGH},
{AUDIO_DIRECTORY"SciFiBounce.3gp",2.8,BikeAudio::IDLE},
{AUDIO_DIRECTORY"SciFi1Loop.3gp",1.95,BikeAudio::IDLE},
{AUDIO_DIRECTORY"SciFi2Loop.3gp",4.00,BikeAudio::IDLE},
{AUDIO_DIRECTORY"SciFi3Loop.3gp",5.00,BikeAudio::IDLE},
{AUDIO_DIRECTORY"SciFiTurbo1.3gp",4.29,BikeAudio::IDLE},
{AUDIO_DIRECTORY"SciFiTurbo2.3gp",4.29,BikeAudio::IDLE},
{AUDIO_DIRECTORY"SciFiTurbo3.3gp",4.29,BikeAudio::IDLE},
{AUDIO_DIRECTORY"SciFiTurbo4.3gp",4.29,BikeAudio::IDLE},
{AUDIO_DIRECTORY"SciFiOff.3gp",3.10,BikeAudio::PRESTART},
{AUDIO_DIRECTORY"SciFiDecelLowq.3gp",3.10,BikeAudio::IDLE},
};
static BikeAudioDesc s_ElectricBikeAudioStates[BikeAudio::NUM_STATES] =
{
{AUDIO_DIRECTORY"",1.0,BikeAudio::START},
{AUDIO_DIRECTORY"ElectricStart.3gp",2.1,BikeAudio::IDLE},
{AUDIO_DIRECTORY"ElectricIdle.3gp",4.9,BikeAudio::IDLE},
{AUDIO_DIRECTORY"ElectricAccel.3gp",14.55,BikeAudio::IDLE},
{AUDIO_DIRECTORY"ElectricDecel.3gp",6.0,BikeAudio::IDLE},
{AUDIO_DIRECTORY"ElectricReverse.3gp",10.39,BikeAudio::IDLE},
{AUDIO_DIRECTORY"ElectricRough.3gp",2.85,BikeAudio::ROUGH},
{AUDIO_DIRECTORY"ElectricBounce.3gp",2.8,BikeAudio::IDLE},
{AUDIO_DIRECTORY"Electric1Loop.3gp",1.95,BikeAudio::IDLE},
{AUDIO_DIRECTORY"Electric2Loop.3gp",4.00,BikeAudio::IDLE},
{AUDIO_DIRECTORY"Electric3Loop.3gp",5.00,BikeAudio::IDLE},
{AUDIO_DIRECTORY"ElectricTurbo1.3gp",4.29,BikeAudio::IDLE},
{AUDIO_DIRECTORY"ElectricTurbo2.3gp",4.29,BikeAudio::IDLE},
{AUDIO_DIRECTORY"ElectricTurbo3.3gp",4.29,BikeAudio::IDLE},
{AUDIO_DIRECTORY"ElectricTurbo4.3gp",4.29,BikeAudio::IDLE},
{AUDIO_DIRECTORY"ElectricOff.3gp",3.10,BikeAudio::PRESTART},
{AUDIO_DIRECTORY"ElectricDecelLow.3gp",3.10,BikeAudio::IDLE},
};
static BikeAudioDesc s_McAcmeBikeAudioStates[BikeAudio::NUM_STATES] =
{
{AUDIO_DIRECTORY"",1.0,BikeAudio::START},
{AUDIO_DIRECTORY"McAcmeStart.3gp",2.1,BikeAudio::IDLE},
{AUDIO_DIRECTORY"McAcmeIdle.3gp",4.9,BikeAudio::IDLE},
{AUDIO_DIRECTORY"McAcmeAccel.3gp",14.55,BikeAudio::IDLE},
{AUDIO_DIRECTORY"McAcmeDecel.3gp",6.0,BikeAudio::IDLE},
{AUDIO_DIRECTORY"McAcmeReverse.3gp",10.39,BikeAudio::IDLE},
{AUDIO_DIRECTORY"McAcmeRough.3gp",2.85,BikeAudio::ROUGH},
{AUDIO_DIRECTORY"McAcmeBounce.3gp",2.8,BikeAudio::IDLE},
{AUDIO_DIRECTORY"McAcme1Loop.3gp",1.95,BikeAudio::IDLE},
{AUDIO_DIRECTORY"McAcme2Loop.3gp",4.00,BikeAudio::IDLE},
{AUDIO_DIRECTORY"McAcme3Loop.3gp",5.00,BikeAudio::IDLE},
{AUDIO_DIRECTORY"McAcmeTurbo1.3gp",4.29,BikeAudio::IDLE},
{AUDIO_DIRECTORY"McAcmeTurbo2.3gp",4.29,BikeAudio::IDLE},
{AUDIO_DIRECTORY"McAcmeTurbo3.3gp",4.29,BikeAudio::IDLE},
{AUDIO_DIRECTORY"McAcmeTurbo4.3gp",4.29,BikeAudio::IDLE},
{AUDIO_DIRECTORY"McAcmeOff.3gp",3.10,BikeAudio::PRESTART},
{AUDIO_DIRECTORY"McAcmeDecelLow.3gp",3.10,BikeAudio::IDLE},
};
static BikeAudioDesc s_PizzaBikeAudioStates[BikeAudio::NUM_STATES] =
{
{AUDIO_DIRECTORY"",1.0,BikeAudio::START},
{AUDIO_DIRECTORY"PizzaScooterStart.3gp",2.1,BikeAudio::IDLE},
{AUDIO_DIRECTORY"PizzaScooterIdle.3gp",4.9,BikeAudio::IDLE},
{AUDIO_DIRECTORY"PizzaScooterAccel.3gp",14.55,BikeAudio::IDLE},
{AUDIO_DIRECTORY"PizzaScooterDecel.3gp",6.0,BikeAudio::IDLE},
{AUDIO_DIRECTORY"PizzaScooterReverse.3gp",10.39,BikeAudio::IDLE},
{AUDIO_DIRECTORY"PizzaScooterRough.3gp",2.85,BikeAudio::ROUGH},
{AUDIO_DIRECTORY"PizzaScooterBounce.3gp",2.8,BikeAudio::IDLE},
{AUDIO_DIRECTORY"PizzaScooter1Loop.3gp",1.95,BikeAudio::IDLE},
{AUDIO_DIRECTORY"PizzaScooter2Loop.3gp",4.00,BikeAudio::IDLE},
{AUDIO_DIRECTORY"PizzaScooter3Loop.3gp",5.00,BikeAudio::IDLE},
{AUDIO_DIRECTORY"PizzaScooterTurbo1.3gp",4.29,BikeAudio::IDLE},
{AUDIO_DIRECTORY"PizzaScooterTurbo2.3gp",4.29,BikeAudio::IDLE},
{AUDIO_DIRECTORY"PizzaScooterTurbo3.3gp",4.29,BikeAudio::IDLE},
{AUDIO_DIRECTORY"PizzaScooterTurbo4.3gp",4.29,BikeAudio::IDLE},
{AUDIO_DIRECTORY"PizzaScooterOff.3gp",3.10,BikeAudio::PRESTART},
{AUDIO_DIRECTORY"PizzaScooterDecelLow.3gp",3.10,BikeAudio::IDLE},
};
void BikeAudio::Preload()
{
for(int i = 1; i < BikeAudio::NUM_STATES; i++)
{
SimpleAudioEngine::sharedEngine()->preloadEffect(m_AudioDesc[i].filename);
}
}
BikeAudio::BikeAudio()
{
m_State = 0;
m_currentSound = 0;
m_nextSound = 0;
m_InterpTime = 0.0f;
m_InterpTimeMax = 0.2f;
m_bIsPaused = false;
m_bEnd = false;
m_LastButtonDown = 0.0f;
m_Attenuation = 0.5f;
const char *ext = SaveLoad::GetBikeExt();
if(strcmp(ext,"_Default")==0)
{
m_Attenuation = 0.4f;
m_AudioDesc = s_YellerBikeAudioStates;
}
if(strcmp(ext,"_DirtBike")==0)
m_AudioDesc = s_DirtBikeAudioStates;
if(strcmp(ext,"_McAcme")==0)
m_AudioDesc = s_McAcmeBikeAudioStates;
if(strcmp(ext,"_Island")==0)
m_AudioDesc = s_IslandBikeAudioStates;
if(strcmp(ext,"_SciFi")==0)
m_AudioDesc = s_ScifiBikeAudioStates;
if(strcmp(ext,"_Electric")==0)
m_AudioDesc = s_ElectricBikeAudioStates;
if(strcmp(ext,"_Pizza")==0)
m_AudioDesc = s_PizzaBikeAudioStates;
if(strcmp(ext,"_Police")==0)
m_AudioDesc = s_CHIMPSBikeAudioStates;
Preload();
}
BikeAudio::~BikeAudio()
{
SimpleAudioEngine::sharedEngine()->stopEffect(m_currentSound);
SimpleAudioEngine::sharedEngine()->stopEffect(m_nextSound);
}
void BikeAudio::PushState(AudioStates state)
{
if(m_InterpTime>0.0f)
{
if(m_State != OFF && state==OFF)
m_bEnd = true;
return;
}
if(m_State == OFF)return;
if(m_State == state)
{
if(state == ACCEL)
{
m_LastButtonDown = 0.0f;
return;
}
if(state == DECEL)return;
if(state == REVERSE)
{
m_LastButtonDown = 0.0f;
return;
}
if(state == BOUNCE)return;
}
if(state==TURBO1)
{
if(m_State==TURBO1)
state=TURBO2;
if(m_State==TURBO2)
state=TURBO3;
if(m_State==TURBO3)
state=TURBO4;
if(m_State==TURBO4)
state=TURBO4;
}
if(m_State>=TURBO1 && m_State<=TURBO4)
{
if(state == ACCEL || state == REVERSE)
{
if(m_TimeInState < 3.0f)
return;
}
}
if(m_currentSound == 0)
{
m_currentSound = SimpleAudioEngine::sharedEngine()->playEffect(m_AudioDesc[state].filename);
SimpleAudioEngine::sharedEngine()->setEffectVolume(m_currentSound, 1.0f-m_Attenuation);
m_State = state;
return;
}
else
{
m_InterpTime = m_InterpTimeMax;
if(state == DECEL && m_TimeInState < 5.0f)
{
m_nextSound = SimpleAudioEngine::sharedEngine()->playEffect(m_AudioDesc[DECEL_LOW].filename);
}
else
{
if(state==IDLE)
{
m_nextSound = SimpleAudioEngine::sharedEngine()->playEffect(m_AudioDesc[state].filename,true);
}
else
{
m_nextSound = SimpleAudioEngine::sharedEngine()->playEffect(m_AudioDesc[state].filename);
}
}
m_TimeInState = 0.0f;
SimpleAudioEngine::sharedEngine()->setEffectVolume(m_nextSound, 0.0f);
m_State = state;
}
}
void BikeAudio::Pause(bool pause)
{
if(m_bIsPaused != pause)
{
if(pause)
{
SimpleAudioEngine::sharedEngine()->pauseEffect(m_currentSound);
if(m_nextSound)
SimpleAudioEngine::sharedEngine()->pauseEffect(m_nextSound);
}
else
{
SimpleAudioEngine::sharedEngine()->resumeEffect(m_currentSound);
if(m_nextSound)
SimpleAudioEngine::sharedEngine()->resumeEffect(m_nextSound);
}
m_bIsPaused = pause;
}
}
void BikeAudio::Update(float dt)
{
if(m_InterpTime>0.0f)
{
m_InterpTime -= dt;
if(m_InterpTime>0.0f)
{
float percent = m_InterpTime/m_InterpTimeMax;
SimpleAudioEngine::sharedEngine()->setEffectVolume(m_currentSound, percent*m_Attenuation);
SimpleAudioEngine::sharedEngine()->setEffectVolume(m_nextSound, (1.0f-percent)*m_Attenuation);
}
else
{
SimpleAudioEngine::sharedEngine()->stopEffect(m_currentSound);
m_currentSound = m_nextSound;
m_nextSound = 0;
}
return;
}
if(Rider::g_isCrashed && m_State != OFF)
{
SimpleAudioEngine::sharedEngine()->stopEffect(m_currentSound);
m_currentSound = 0;
if(m_nextSound != 0)
{
SimpleAudioEngine::sharedEngine()->stopEffect(m_nextSound);
}
m_State = OFF;
}
m_TimeInState += dt;
switch(m_State)
{
case OFF:
m_bEnd = false;
break;
case IDLE:
break;
case PRESTART:
PushState(START);
break;
case ACCEL:
if(m_bEnd)
PushState(OFF);
if(m_TimeInState >= 0.2f && (m_TimeInState-dt)<0.2f)
DoExhaust();
if(m_TimeInState > (m_AudioDesc[m_State].length-m_InterpTimeMax))
PushState((AudioStates)m_AudioDesc[m_State].nextState);
else
{
m_LastButtonDown+=dt;
if(m_LastButtonDown>0.5f)
PushState(DECEL);
}
break;
case REVERSE:
m_LastButtonDown+=dt;
if(m_bEnd)
PushState(OFF);
if(m_TimeInState > (m_AudioDesc[m_State].length-m_InterpTimeMax))
PushState((AudioStates)m_AudioDesc[m_State].nextState);
else
{
m_LastButtonDown+=dt;
if(m_LastButtonDown>0.5f)
PushState(DECEL);
}
break;
default:
if(m_bEnd)
PushState(OFF);
if(m_TimeInState > (m_AudioDesc[m_State].length-m_InterpTimeMax))
PushState((AudioStates)m_AudioDesc[m_State].nextState);
break;
}
}
void BikeAudio::DoExhaust()
{
const char *ext = SaveLoad::GetBikeExt();
if(!(strcmp(ext,"_SciFi")==0 || strcmp(ext,"_Electric")==0))
{
if(Rider::g_MainBody->GetLinearVelocity().x > 10)
return;
/*[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"ctm_VFX.plist"textureFile:@"ctm_VFX.pvr.ccz"];
NSString *name = [NSString stringWithFormat:@"ctm%@_Exhaust.png",ext];
CCSprite *exhaust1 = [CCSprite spriteWithSpriteFrameName:name];
CCSprite *exhaust2 = [CCSprite spriteWithSpriteFrameName:name];
CGPoint vel = ccp(Rider::g_MainBody->GetLinearVelocity().x*PTM_RATIO,0.0);
exhaust1.position = ccp(Rider::g_MainBody->GetWorldCenter().x*PTM_RATIO-30.0f,Rider::g_MainBody->GetWorldCenter().y*PTM_RATIO);
exhaust2.position = ccp(exhaust1.position.x-30,exhaust1.position.y);
exhaust1.scale = 0.01f;
CCSequence *sequence = [CCSequence actions:
[CCDelayTime actionWithDuration:0.05f],
[CCScaleTo actionWithDuration:0.25f scale:1.5f],
[CCCallFuncND actionWithTarget:exhaust1 selector:@selector(removeFromParentAndCleanup:) data:(void*)YES],
[CCCallFuncND actionWithTarget:exhaust1 selector:@selector(removeFromParentAndCleanup:) data:(void*)YES],
nil];
[exhaust1 runAction:sequence];
sequence = [CCSequence actions:
[CCDelayTime actionWithDuration:0.15f],
[CCFadeOut actionWithDuration:0.15f],
nil];
[exhaust1 runAction:sequence];
exhaust2.scale = 0.01f;
sequence = [CCSequence actions:
[CCScaleTo actionWithDuration:0.25f scale:1.5f],
[CCCallFuncND actionWithTarget:exhaust2 selector:@selector(removeFromParentAndCleanup:) data:(void*)YES],
[CCCallFuncND actionWithTarget:exhaust2 selector:@selector(removeFromParentAndCleanup:) data:(void*)YES],
nil];
[exhaust2 runAction:sequence];
sequence = [CCSequence actions:
[CCDelayTime actionWithDuration:0.10f],
[CCFadeOut actionWithDuration:0.15f],
nil];
[exhaust2 runAction:sequence];
CCNode* layer = ((TextureObject*)Rider::g_MainBody->GetUserData())->GetSprite().parent.parent;
[layer addChild:exhaust1];
[layer addChild:exhaust2];
[exhaust1 runAction:[CCMoveBy actionWithDuration:1.0 position:vel]];
[exhaust2 runAction:[CCMoveBy actionWithDuration:1.0 position:vel]];*/
}
}
| [
"administrator@Ryans-iMac-2.local"
] | administrator@Ryans-iMac-2.local |
edeae713fde17f9bfd7cccf7b3641e798a5b8903 | 86609148aee683f1a2f92f9ab5c073b4c29380e4 | /utils/dnp3_src/cpp/libs/src/opendnp3/outstation/EventWriter.h | ff8a0bf983b1f1b687e9fce37bb6d2332955ac69 | [
"Apache-2.0"
] | permissive | thiagoralves/OpenPLC_v3 | 16ba73585ab6b4aff7fb3e0f6388cf31f7aa2fce | cf139121bc15cb960a8fad62c02f34532b36a7c7 | refs/heads/master | 2023-08-07T06:55:19.533734 | 2023-07-19T15:33:35 | 2023-07-19T15:33:35 | 137,387,519 | 817 | 370 | null | 2023-09-14T03:09:01 | 2018-06-14T17:15:49 | C++ | UTF-8 | C++ | false | false | 6,165 | h | /*
* Licensed to Green Energy Corp (www.greenenergycorp.com) under one or
* more contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright ownership.
* Green Energy Corp licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This project was forked on 01/01/2013 by Automatak, LLC and modifications
* may have been made to this file. Automatak, LLC licenses these modifications
* to you under the terms of the License.
*/
#ifndef OPENDNP3_EVENTWRITER_H
#define OPENDNP3_EVENTWRITER_H
#include <openpal/util/Uncopyable.h>
#include <openpal/container/LinkedList.h>
#include "opendnp3/app/HeaderWriter.h"
#include "opendnp3/outstation/SOERecord.h"
#include "opendnp3/outstation/IEventRecorder.h"
namespace opendnp3
{
class EventWriter : openpal::StaticOnly
{
public:
static bool Write(HeaderWriter& writer, IEventRecorder& recorder, openpal::LinkedListIterator<SOERecord> iterator);
private:
class Result
{
public:
Result(bool isFragmentFull_, openpal::LinkedListIterator<SOERecord> location_) : isFragmentFull(isFragmentFull_), location(location_)
{}
bool isFragmentFull;
openpal::LinkedListIterator<SOERecord> location;
private:
Result() = delete;
};
static Result LoadHeader(HeaderWriter& writer, IEventRecorder& recorder, openpal::ListNode<SOERecord>* pLocation);
static Result LoadHeaderBinary(HeaderWriter& writer, IEventRecorder& recorder, openpal::ListNode<SOERecord>* pLocation);
static Result LoadHeaderDoubleBinary(HeaderWriter& writer, IEventRecorder& recorder, openpal::ListNode<SOERecord>* pLocation);
static Result LoadHeaderCounter(HeaderWriter& writer, IEventRecorder& recorder, openpal::ListNode<SOERecord>* pLocation);
static Result LoadHeaderFrozenCounter(HeaderWriter& writer, IEventRecorder& recorder, openpal::ListNode<SOERecord>* pLocation);
static Result LoadHeaderAnalog(HeaderWriter& writer, IEventRecorder& recorder, openpal::ListNode<SOERecord>* pLocation);
static Result LoadHeaderBinaryOutputStatus(HeaderWriter& writer, IEventRecorder& recorder, openpal::ListNode<SOERecord>* pLocation);
static Result LoadHeaderAnalogOutputStatus(HeaderWriter& writer, IEventRecorder& recorder, openpal::ListNode<SOERecord>* pLocation);
static Result LoadHeaderSecurityStat(HeaderWriter& writer, IEventRecorder& recorder, openpal::ListNode<SOERecord>* pLocation);
inline static bool IsWritable(const SOERecord& record)
{
return record.selected && !record.written;
}
template <class Spec>
static Result WriteTypeWithSerializer(HeaderWriter& writer, IEventRecorder& recorder, openpal::ListNode<SOERecord>* pLocation, opendnp3::DNP3Serializer<typename Spec::meas_t> serializer, typename Spec::event_variation_t variation)
{
auto iter = openpal::LinkedListIterator<SOERecord>::From(pLocation);
auto header = writer.IterateOverCountWithPrefix<openpal::UInt16, typename Spec::meas_t>(QualifierCode::UINT16_CNT_UINT16_INDEX, serializer);
openpal::ListNode<SOERecord>* pCurrent = nullptr;
while (recorder.HasMoreUnwrittenEvents() && (pCurrent = iter.Next()))
{
auto& record = pCurrent->value;
if (IsWritable(record))
{
if ((record.type == Spec::EventTypeEnum) && (record.GetValue<Spec>().selectedVariation == variation))
{
auto evt = record.ReadEvent<Spec>();
if (header.Write(evt.value, evt.index))
{
record.written = true;
recorder.RecordWritten(record.clazz, record.type);
}
else
{
auto location = openpal::LinkedListIterator<SOERecord>::From(pCurrent);
return Result(true, location);
}
}
else
{
// drop out and return from current location
break;
}
}
}
auto location = openpal::LinkedListIterator<SOERecord>::From(pCurrent);
return Result(false, location);
}
template <class Spec, class CTOType>
static Result WriteCTOTypeWithSerializer(HeaderWriter& writer, IEventRecorder& recorder, openpal::ListNode<SOERecord>* pLocation, opendnp3::DNP3Serializer<typename Spec::meas_t> serializer, typename Spec::event_variation_t variation)
{
auto iter = openpal::LinkedListIterator<SOERecord>::From(pLocation);
CTOType cto;
cto.time = pLocation->value.GetTime();
auto header = writer.IterateOverCountWithPrefixAndCTO<openpal::UInt16, typename Spec::meas_t, CTOType>(QualifierCode::UINT16_CNT_UINT16_INDEX, serializer, cto);
openpal::ListNode<SOERecord>* pCurrent = nullptr;
while (recorder.HasMoreUnwrittenEvents() && (pCurrent = iter.Next()))
{
auto& record = pCurrent->value;
if (IsWritable(record))
{
if ((record.type == Spec::EventTypeEnum) && (record.GetValue<Spec>().selectedVariation == variation))
{
if (record.GetTime() < cto.time)
{
// drop out and return from current location
break;
}
else
{
auto diff = record.GetTime() - cto.time;
if (diff > openpal::UInt16::Max)
{
// drop out and return from current location
break;
}
else
{
auto evt = record.ReadEvent<Spec>();
evt.value.time = DNPTime(diff);
if (header.Write(evt.value, evt.index))
{
record.written = true;
recorder.RecordWritten(record.clazz, record.type);
}
else
{
auto location = openpal::LinkedListIterator<SOERecord>::From(pCurrent);
return Result(true, location);
}
}
}
}
else
{
// drop out and return from current location
break;
}
}
}
auto location = openpal::LinkedListIterator<SOERecord>::From(pCurrent);
return Result(false, location);
}
};
}
#endif
| [
"thiagoralves@gmail.com"
] | thiagoralves@gmail.com |
10621699a732c58b5b45d45cf34d9a55f00143d8 | dbe63a279c38a526333078c1115a72cfb2361ad5 | /BOJ/탐색/이분 탐색(Binary Search)/8983_사냥꾼.cpp | bcb9cc02dea45e054a92d0086a82e387a2b7388b | [] | no_license | vividswan/Algorithm | a44be0e7f3825f4328253938625920cfc0292b36 | 5a71e7c2a217ef5d47f5dfa711559f9a83c6cf69 | refs/heads/master | 2023-09-01T07:56:25.193571 | 2023-07-30T11:18:15 | 2023-07-30T11:18:15 | 207,740,964 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 718 | cpp | #include <iostream>
#include <algorithm>
using namespace std;
long long m, n, l, arr[100001], res;
int main(void) {
scanf("%lld %lld %lld", &m, &n, &l);
for (int i = 0; i < m; i++) {
long long x;
scanf("%lld", &x);
arr[i] = x;
}
sort(arr, arr + m);
for (int i = 0; i < n; i++) {
long long x, y;
scanf("%lld %lld", &x, &y);
if (y > l) continue;
long long min_x = x - (l - y);
long long max_x = x + (l - y);
long long left = 0;
long long right = m - 1;
while (left <= right) {
long long mid = (right + left) / 2;
if (min_x <= arr[mid] && arr[mid] <= max_x) {
res++;
break;
}
else if (arr[mid] < min_x) left = mid + 1;
else right = mid - 1;
}
}
printf("%lld", res);
} | [
"vividswan@naver.com"
] | vividswan@naver.com |
3b0a540c7150a1d84c03ba4c2a3efa0b793d568d | 0b71368533d0d7dc2ab0bf82b9ebec8f7920b0c8 | /src/knobs.cpp | 069a8ac5b9b3d37ec4984f3448c758fe94cc5b92 | [
"MIT"
] | permissive | carloop/knob_controller | 620da7cc2728e24caa8359c9cd1092837f42d063 | 3d42e4d4e6421d754092da8fe8cc6742d559dd4e | refs/heads/master | 2021-01-18T03:25:12.160932 | 2016-09-25T16:22:12 | 2016-09-25T16:22:12 | 68,562,080 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,972 | cpp | /* Transmit the value of some knobs connected to the Carloop as CAN messages
*/
#include "application.h"
#include "carloop.h"
SYSTEM_THREAD(ENABLED);
void setupKnobs();
void readKnobs();
void readKnob(unsigned i);
void normalizeKnob(unsigned i);
void printKnobs();
void transmitCAN();
Carloop<CarloopRevision2> carloop;
/* Connect potentiometer of each knob to powerPin, groundPin and the
* appropriate knobPin.
* Run the program and adjust knobValueLow and knobValueHigh to get 100%
* when the knob is at each end stop. If values are reversed (100% for
* low stop), reserve powerPin and groundPin.
*/
const unsigned knobCount = 3;
const int powerPin = A2;
const int groundPin = A3;
const int knobPin[knobCount] = { A4, A5, A6 };
uint16_t knobValueRaw[knobCount] = { 0 }; // 3.3V = 4096
uint16_t knobValueLow[knobCount] = { 30, 30, 30 };
uint16_t knobValueHigh[knobCount] = { 4060, 4060, 4060 };
uint16_t knobPercent[knobCount] = { 0 }; // 100% = 32768
const uint16_t knob100Percent = 32768;
/* every
* Helper than runs a function at a regular millisecond interval
*/
template <typename Fn>
void every(unsigned long intervalMillis, Fn fn) {
static unsigned long last = 0;
if (millis() - last > intervalMillis) {
last = millis();
fn();
}
}
void setup() {
Serial.begin(9600);
setupKnobs();
carloop.begin();
}
void setupKnobs() {
pinMode(powerPin, OUTPUT);
digitalWrite(powerPin, HIGH);
pinMode(groundPin, OUTPUT);
digitalWrite(groundPin, LOW);
for (unsigned i = 0; i < knobCount; i++) {
pinMode(knobPin[i], INPUT);
}
}
void loop() {
readKnobs();
printKnobs();
transmitCAN();
}
void readKnobs() {
for (unsigned i = 0; i < knobCount; i++) {
readKnob(i);
normalizeKnob(i);
}
}
void readKnob(unsigned i) {
knobValueRaw[i] = analogRead(knobPin[i]);
}
/* normalizeKnob
* Scale the raw ADC count between the low and high value, normalize
* to a percentage value and limit between 0% and 100%.
*/
void normalizeKnob(unsigned i) {
uint16_t range = knobValueHigh[i] - knobValueLow[i];
int32_t percent = (int32_t)(knobValueRaw[i] - knobValueLow[i]) * knob100Percent / range;
knobPercent[i] = (percent < 0) ? 0 : (percent > knob100Percent) ? knob100Percent : percent;
}
void printKnobs() {
every(200, [] {
for (unsigned i = 0; i < knobCount; i++) {
Serial.printf("%d: %4d adc, %3.1f%% ", i, knobValueRaw[i], knobPercent[i] * 100.0/32768.0);
}
Serial.println("");
});
}
/* transmitCAN
* Send CAN messages with the values of the knobs at regular intervals
* Put multiple every(interval, ...) statements to send multiple CAN
* messages at different intervals
*/
void transmitCAN() {
every(100, [] {
CANMessage message;
message.id = 0x110;
message.len = 3;
message.data[0] = knobPercent[0] * 255 / 32768;
message.data[1] = knobPercent[1] * 255 / 32768;
message.data[2] = knobPercent[2] * 255 / 32768;
carloop.can().transmit(message);
});
}
| [
"jvanier@gmail.com"
] | jvanier@gmail.com |
35f6ca9c6f9cada598c232b65179a4ee51c2a7b5 | 045021ea2e02919fb7617dd08890665a2579aa9a | /Divide&Conquer/6549 히스토그램에서 가장 큰 직사각형/ckw_cpp.cpp | 4e5e67420fcc4c96166ca8a20f6d854e2bc0a240 | [] | no_license | LnC-Study/Acmicpc-net | 258b3c0bc13a370dd5c84d38ba9fc1fb28fd0415 | 1d27cf13f9b11188e9cee9bae15b21c69e1c13f5 | refs/heads/master | 2021-06-21T10:19:17.741283 | 2021-01-24T14:13:06 | 2021-01-24T14:13:06 | 164,632,228 | 8 | 2 | null | 2019-09-01T08:08:41 | 2019-01-08T11:14:57 | C++ | UTF-8 | C++ | false | false | 1,511 | cpp | #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <vector>
#include <algorithm>
using namespace std;
vector<long long> histogram;
long long max_rectangle(int start, int end) {
if (start == end)
return histogram[start];
long long ret = 0;
int mid = (start + end) / 2;
ret = max(ret, max_rectangle(start, mid));
ret = max(ret, max_rectangle(mid + 1, end));
int left = mid;
int right = mid + 1;
long long height = min(histogram[left], histogram[right]);
long long area = height * (right - left + 1);
ret = max(ret, area);
for (; !(left == start && right == end) ;) {
if (left > start && right < end) {
histogram[left - 1] > histogram[right + 1] ? left-- : right++;
height = min(height, histogram[left]);
height = min(height, histogram[right]);
}
else if (left > start) {
left--;
height = min(height, histogram[left]);
}
else {
right++;
height = min(height, histogram[right]);
}
area = height * (right - left + 1);
ret = max(ret, area);
}
return ret;
}
void data_in() {
freopen("input.txt", "r", stdin);
while (true) {
int N;
scanf("%d ", &N);
if (N == 0)
break;
histogram = vector<long long>(N);
for (int i = 0; i < N; i++) {
scanf("%lli ", &histogram[i]);
}
long long result = max_rectangle(0, N - 1);
printf("%lli\n", result);
histogram.erase(histogram.begin(), histogram.end());
}
}
int main() {
data_in();
}
| [
"root@DESKTOP-EI278HI.localdomain"
] | root@DESKTOP-EI278HI.localdomain |
faf49f5d62b5f40833e1bb2371d29017213e6c1c | 66680ad28264fc9cd04f13f15ff91256401f5b23 | /2Kprog/funzioni.hpp | 79faf28380ed2e0b19c16e146211275b1e16e483 | [] | no_license | crysth/thesis | 79c8a782d1d3fda2afdafc5163a2571b61694e10 | 06270cc80e4d9a633f026eebe6179ece83a9c595 | refs/heads/master | 2021-01-11T11:51:21.726039 | 2016-12-17T14:32:55 | 2016-12-17T14:32:55 | 76,727,633 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,678 | hpp | /*--------------------------------------------------------------------
funzioni.hpp
Definizione di alcune funzioni che vengono utilizzate
all'interno del programma.
- quicksort permette di ordinare un vettore di size_t
accoppiato a un altro vettore, mantenendo la relazione
di coppia invariata.
- runtime restituisce il tempo di running del
programma in secondi, con precisione del microsecondo
- show_time e' una macro che stampa a video l'intervallo
di tempo speso da ogni sezione del programma
--------------------------------------------------------------------*/
/*==================================================================*/
#ifndef _FUNZIONI_HPP_
#define _FUNZIONI_HPP_
#include <iostream>
#include <vector>
#include <sys/time.h>
using namespace std;
#define _max(a,b) ((a)>(b)?(a):(b))
/*--------------------------------------------------------------------
funzione quicksort
--------------------------------------------------------------------*/
void quicksort(size_t N, size_t v1[], size_t v2[]);
/*--------------------------------------------------------------------
funzione runtime
--------------------------------------------------------------------*/
double runtime();
/*--------------------------------------------------------------------
macro show_time
--------------------------------------------------------------------*/
#define show_time(t, Dt) t = runtime() - t; cerr<<"-> time "<<t<<" s\n\n"; Dt+=t
/*--------------------------------------------------------------------
massimo di un vector
--------------------------------------------------------------------*/
size_t maxvettore(vector<size_t>);
#endif
| [
"mariacristina.romano@hotmail.it"
] | mariacristina.romano@hotmail.it |
9e3fff7886938dcb7a16e345636e1e604b1f7a81 | 89dedd7f3c7acc81d12e2bcb2e716f9af9e5fa04 | /third_party/WebKit/Source/core/workers/WorkerNavigator.h | b11fdb476f6a49d5a83f5366d369ea29ddac9e65 | [
"BSD-2-Clause",
"LGPL-2.1-only",
"LGPL-2.0-only",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-2.0-only",
"LicenseRef-scancode-other-copyleft"
] | permissive | bino7/chromium | 8d26f84a1b6e38a73d1b97fea6057c634eff68cb | 4666a6bb6fdcb1114afecf77bdaa239d9787b752 | refs/heads/master | 2022-12-22T14:31:53.913081 | 2016-09-06T10:05:11 | 2016-09-06T10:05:11 | 67,410,510 | 1 | 3 | BSD-3-Clause | 2022-12-17T03:08:52 | 2016-09-05T10:11:59 | null | UTF-8 | C++ | false | false | 2,334 | h | /*
* Copyright (C) 2008 Apple Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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.
*/
#ifndef WorkerNavigator_h
#define WorkerNavigator_h
#include "bindings/core/v8/ScriptWrappable.h"
#include "core/frame/NavigatorCPU.h"
#include "core/frame/NavigatorID.h"
#include "core/frame/NavigatorOnLine.h"
#include "platform/Supplementable.h"
#include "platform/heap/Handle.h"
#include "wtf/text/WTFString.h"
namespace blink {
class WorkerNavigator final : public GarbageCollectedFinalized<WorkerNavigator>, public ScriptWrappable, public NavigatorCPU, public NavigatorID, public NavigatorOnLine, public Supplementable<WorkerNavigator> {
DEFINE_WRAPPERTYPEINFO();
USING_GARBAGE_COLLECTED_MIXIN(WorkerNavigator);
public:
static WorkerNavigator* create(const String& userAgent)
{
return new WorkerNavigator(userAgent);
}
virtual ~WorkerNavigator();
String userAgent() const override;
DECLARE_TRACE();
private:
explicit WorkerNavigator(const String&);
String m_userAgent;
};
} // namespace blink
#endif // WorkerNavigator_h
| [
"bino.zh@gmail.com"
] | bino.zh@gmail.com |
17769d14867f273154eee196e132a83957c2fc31 | b72e95e52b64b918fdfd780dbb248db6a72df839 | /SDK/PUBG_P_VehicleDrive_Dirt_BP_functions.cpp | a0b7d98c6b5470152e4a96ceedca49ee7d39776c | [] | no_license | Vukkk/PUBG-SDK | 93b2f42ddb47f75a9ad721a05e9a5c1ec1e728ba | 3a986d2f5d35f3ed82c8b03533ed391a0a31dd4c | refs/heads/master | 2021-01-01T20:03:33.549682 | 2017-07-28T16:19:46 | 2017-07-28T16:19:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,072 | cpp | // PLAYERUNKNOWN BattleGrounds (2.4.22) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace Classes
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function P_VehicleDrive_Dirt_BP.P_VehicleDrive_Dirt_BP_C.UserConstructionScript
// (FUNC_Event, FUNC_Public, FUNC_BlueprintCallable, FUNC_BlueprintEvent)
void AP_VehicleDrive_Dirt_BP_C::UserConstructionScript()
{
static auto fn = UObject::FindObject<UFunction>("Function P_VehicleDrive_Dirt_BP.P_VehicleDrive_Dirt_BP_C.UserConstructionScript");
AP_VehicleDrive_Dirt_BP_C_UserConstructionScript_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function P_VehicleDrive_Dirt_BP.P_VehicleDrive_Dirt_BP_C.OnParameterUpdated
// (FUNC_Event, FUNC_Protected, FUNC_BlueprintEvent)
void AP_VehicleDrive_Dirt_BP_C::OnParameterUpdated()
{
static auto fn = UObject::FindObject<UFunction>("Function P_VehicleDrive_Dirt_BP.P_VehicleDrive_Dirt_BP_C.OnParameterUpdated");
AP_VehicleDrive_Dirt_BP_C_OnParameterUpdated_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function P_VehicleDrive_Dirt_BP.P_VehicleDrive_Dirt_BP_C.ExecuteUbergraph_P_VehicleDrive_Dirt_BP
// (FUNC_HasDefaults)
// Parameters:
// int EntryPoint (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
void AP_VehicleDrive_Dirt_BP_C::ExecuteUbergraph_P_VehicleDrive_Dirt_BP(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function P_VehicleDrive_Dirt_BP.P_VehicleDrive_Dirt_BP_C.ExecuteUbergraph_P_VehicleDrive_Dirt_BP");
AP_VehicleDrive_Dirt_BP_C_ExecuteUbergraph_P_VehicleDrive_Dirt_BP_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"pubgsdk@gmail.com"
] | pubgsdk@gmail.com |
c645aa6b2913cd3aab40c0313930ada986494450 | 5307d5d3d3760240358ad73529723fe9c7411b07 | /src/rpc/blockchain.h | 606d8796ffddc6d64eb62245983d12f8d3f62347 | [
"MIT"
] | permissive | cruro/cruro | b75d4900c760c40d9641c3355350e9ed56723f84 | 80aa93365db5e6653bb8235fb61914ee4aa087e8 | refs/heads/master | 2020-06-18T10:31:58.958195 | 2019-07-12T14:39:43 | 2019-07-12T14:39:43 | 196,270,857 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,580 | h | // Copyright (c) 2017-2018 The Cruro Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_RPC_BLOCKCHAIN_H
#define BITCOIN_RPC_BLOCKCHAIN_H
#include <amount.h>
#include <sync.h>
#include <stdint.h>
#include <vector>
extern RecursiveMutex cs_main;
class CBlock;
class CBlockIndex;
class CTxMemPool;
class UniValue;
static constexpr int NUM_GETBLOCKSTATS_PERCENTILES = 5;
/**
* Get the difficulty of the net wrt to the given block index.
*
* @return A floating point number that is a multiple of the main net minimum
* difficulty (4295032833 hashes).
*/
double GetDifficulty(const CBlockIndex* blockindex);
/** Callback for when block tip changed. */
void RPCNotifyBlockChange(bool ibd, const CBlockIndex *);
/** Block description to JSON */
UniValue blockToJSON(const CBlock& block, const CBlockIndex* tip, const CBlockIndex* blockindex, bool txDetails = false) LOCKS_EXCLUDED(cs_main);
/** Mempool information to JSON */
UniValue MempoolInfoToJSON(const CTxMemPool& pool);
/** Mempool to JSON */
UniValue MempoolToJSON(const CTxMemPool& pool, bool verbose = false);
/** Block header to JSON */
UniValue blockheaderToJSON(const CBlockIndex* tip, const CBlockIndex* blockindex) LOCKS_EXCLUDED(cs_main);
/** Used by getblockstats to get feerates at different percentiles by weight */
void CalculatePercentilesByWeight(CAmount result[NUM_GETBLOCKSTATS_PERCENTILES], std::vector<std::pair<CAmount, int64_t>>& scores, int64_t total_weight);
#endif
| [
"“doctordeep@protonmail.com”"
] | “doctordeep@protonmail.com” |
1d4d9fd19f49b3a3155d8c03b8453592d54b4db6 | b77e257d3e18c7b855fd0f65e4381b93f9f737ff | /Assignment 4/Assignment 4.cpp | 6c70c2e5e7d576517c5d229d907c2938371a691e | [] | no_license | bb511/OOPcpp | 8d8ea00aa7aff699c75fb35e0e4c3e54e4ba093d | 41a9da7b70f72fd65e0809c5a46198f73900f254 | refs/heads/master | 2022-01-11T20:07:04.380388 | 2019-05-14T00:09:20 | 2019-05-14T00:09:20 | 168,223,374 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,750 | cpp | /*
Title: Assignment 4: A Class for Galaxies
Author: Patrick Odagiu
This simple program does blah.
*/
#include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <tuple>
#include <algorithm>
#include "Galaxy.h"
#include "Checks.h"
#include "Menu.h"
using namespace std;
void galaxy::printGalaxy(){
// Prints out the data associated with a galaxy object.
cout.precision(3);
cout<<"Hubble type: "<<hubbleType<<endl;
cout<<"Redshift: "<<redShift<<endl;
cout<<"Total mass: "<<totalMass<<endl;
cout<<"Stellar mass fraction: "<<stellarMassFrac<<endl;
cout<<"Number of satellites: "<<satellites.size()<<endl;
}
tuple<string, double, double, double> getUserInput(){
// Reads in the user input and returns a tuple.
string hubbleType; double redShift, totalMass, stellarMassFrac;
cin>>hubbleType;
if(!hubbleType.compare("stop")) return make_tuple("stop", 0, 0, 0);
cin>>redShift>>totalMass>>stellarMassFrac;
return make_tuple(hubbleType, redShift, totalMass, stellarMassFrac);
}
void storeGalaxy(vector<galaxy> &galaxyList, auto uIn){
try{galaxyList.push_back(
galaxy(get<0>(uIn), get<1>(uIn), get<2>(uIn), get<3>(uIn)));
cout<<"Galaxy stored!\n";}
catch(const exception& e){
cout<<e.what(); cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');}
}
void populateGalaxies(vector<galaxy> &galaxyList){
while(true){
auto userInput = getUserInput();
if (!get<0>(userInput).compare("stop")) {cout<<endl; break;}
storeGalaxy(galaxyList, userInput);
}
}
void storeSatellite(vector<galaxy>::iterator &chosenGalaxy, auto uIn){
try{chosenGalaxy->addSatellite(
galaxy(get<0>(uIn), get<1>(uIn), get<2>(uIn), get<3>(uIn)));
cout<<"Satellite stored!\n";}
catch(const exception& e){
cout<<e.what(); cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');}
}
void populateSatellites(vector<galaxy> &galaxyList){
auto chosenGalaxy{selectGalaxy(galaxyList)};
while(true){
auto userInput = getUserInput();
if (!get<0>(userInput).compare("stop")) break;
storeSatellite(chosenGalaxy, userInput);
}
}
bool checkAnotherChoice(){
cout<<"Would you like to add satellites to any other galaxy?(y/n)\n";
char choice; cin>>choice;
if(choice == 'y') return true;
return false;
}
int main()
{
vector<galaxy> galaxyList;
greetingsInstructions();
populateGalaxies(galaxyList);
displayGalaxies(galaxyList);
cout<<"Choose galaxy and give its satellites and say stop for stopping!\n";
do{populateSatellites(galaxyList);} while(checkAnotherChoice());
while(mainMenu(galaxyList));
return 0;
}
| [
"patrickodagiu@gmail.com"
] | patrickodagiu@gmail.com |
71117c05f6c5e0b9a78bbb2b57ccdc619438afa6 | 961714d4298245d9c762e59c716c070643af2213 | /ThirdParty-mod/java2cpp/org/apache/http/conn/HttpHostConnectException.hpp | 0bad65f2502cac75d5f30606f0d9d3690cef8e23 | [
"MIT"
] | permissive | blockspacer/HQEngine | b072ff13d2c1373816b40c29edbe4b869b4c69b1 | 8125b290afa7c62db6cc6eac14e964d8138c7fd0 | refs/heads/master | 2023-04-22T06:11:44.953694 | 2018-10-02T15:24:43 | 2018-10-02T15:24:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,484 | hpp | /*================================================================================
code generated by: java2cpp
author: Zoran Angelov, mailto://baldzar@gmail.com
class: org.apache.http.conn.HttpHostConnectException
================================================================================*/
#ifndef J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_ORG_APACHE_HTTP_CONN_HTTPHOSTCONNECTEXCEPTION_HPP_DECL
#define J2CPP_ORG_APACHE_HTTP_CONN_HTTPHOSTCONNECTEXCEPTION_HPP_DECL
namespace j2cpp { namespace java { namespace net { class ConnectException; } } }
namespace j2cpp { namespace org { namespace apache { namespace http { class HttpHost; } } } }
#include <java/net/ConnectException.hpp>
#include <org/apache/http/HttpHost.hpp>
namespace j2cpp {
namespace org { namespace apache { namespace http { namespace conn {
class HttpHostConnectException;
class HttpHostConnectException
: public object<HttpHostConnectException>
{
public:
J2CPP_DECLARE_CLASS
J2CPP_DECLARE_METHOD(0)
J2CPP_DECLARE_METHOD(1)
explicit HttpHostConnectException(jobject jobj)
: object<HttpHostConnectException>(jobj)
{
}
operator local_ref<java::net::ConnectException>() const;
HttpHostConnectException(local_ref< org::apache::http::HttpHost > const&, local_ref< java::net::ConnectException > const&);
local_ref< org::apache::http::HttpHost > getHost();
}; //class HttpHostConnectException
} //namespace conn
} //namespace http
} //namespace apache
} //namespace org
} //namespace j2cpp
#endif //J2CPP_ORG_APACHE_HTTP_CONN_HTTPHOSTCONNECTEXCEPTION_HPP_DECL
#else //J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_ORG_APACHE_HTTP_CONN_HTTPHOSTCONNECTEXCEPTION_HPP_IMPL
#define J2CPP_ORG_APACHE_HTTP_CONN_HTTPHOSTCONNECTEXCEPTION_HPP_IMPL
namespace j2cpp {
org::apache::http::conn::HttpHostConnectException::operator local_ref<java::net::ConnectException>() const
{
return local_ref<java::net::ConnectException>(get_jobject());
}
org::apache::http::conn::HttpHostConnectException::HttpHostConnectException(local_ref< org::apache::http::HttpHost > const &a0, local_ref< java::net::ConnectException > const &a1)
: object<org::apache::http::conn::HttpHostConnectException>(
call_new_object<
org::apache::http::conn::HttpHostConnectException::J2CPP_CLASS_NAME,
org::apache::http::conn::HttpHostConnectException::J2CPP_METHOD_NAME(0),
org::apache::http::conn::HttpHostConnectException::J2CPP_METHOD_SIGNATURE(0)
>(a0, a1)
)
{
}
local_ref< org::apache::http::HttpHost > org::apache::http::conn::HttpHostConnectException::getHost()
{
return call_method<
org::apache::http::conn::HttpHostConnectException::J2CPP_CLASS_NAME,
org::apache::http::conn::HttpHostConnectException::J2CPP_METHOD_NAME(1),
org::apache::http::conn::HttpHostConnectException::J2CPP_METHOD_SIGNATURE(1),
local_ref< org::apache::http::HttpHost >
>(get_jobject());
}
J2CPP_DEFINE_CLASS(org::apache::http::conn::HttpHostConnectException,"org/apache/http/conn/HttpHostConnectException")
J2CPP_DEFINE_METHOD(org::apache::http::conn::HttpHostConnectException,0,"<init>","(Lorg/apache/http/HttpHost;Ljava/net/ConnectException;)V")
J2CPP_DEFINE_METHOD(org::apache::http::conn::HttpHostConnectException,1,"getHost","()Lorg/apache/http/HttpHost;")
} //namespace j2cpp
#endif //J2CPP_ORG_APACHE_HTTP_CONN_HTTPHOSTCONNECTEXCEPTION_HPP_IMPL
#endif //J2CPP_INCLUDE_IMPLEMENTATION
| [
"le.hoang.q@gmail.com@2e56ffda-155b-7872-b1f3-609f5c043f28"
] | le.hoang.q@gmail.com@2e56ffda-155b-7872-b1f3-609f5c043f28 |
877c6f0e48db95a5ff3696f23ae2aa6a66d95920 | 5945ee81d8af2a8a8f180bd00f97650f7d6d50d1 | /ttt.cpp | acb4fe893b5d0ca6a18fa8591da06bd9b2856bf9 | [] | no_license | radikru96/TTT | 285480302bbe64b78ee150a28780324b130f415c | b9bfa7880b296580724aa1e951e8bd9268d41fd8 | refs/heads/master | 2022-12-11T22:55:41.672944 | 2020-09-09T22:00:37 | 2020-09-09T22:00:37 | 294,230,346 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 446 | cpp | #include <iostream>
using namespace std;
#include "ttt.h"
int main()
{
Clear_board(board,SIZE);
game = 'X';
step=0;
while (Over(board)==' '&&step<9)
{
Command(board,game,SIZE);
Change_game(game);
++step;
cout << "Step-" << step << endl;
}
Show_board(board);
if (Over(board)==' '){cout << "Over." << endl;}
else {cout << Over(board) << " Winner!" << endl;}
return 0;
}
| [
"user@LinJesUxUs.localdomain"
] | user@LinJesUxUs.localdomain |
e26cdd59077756772b1504650ff237f490b6fda4 | 74ba8472712d0fb18a108dc38e82e7ccfa84cd79 | /src/httpserver.h | 384267dcf10c1c25c26af91995226f0fa21cb808 | [
"MIT"
] | permissive | claritydevs/clarity | d96237b282923bd004b8a2cc5edea4cab42327e2 | d1dd28384f4b3491164f519f62e93d963e960333 | refs/heads/master | 2020-04-18T13:18:34.146577 | 2019-01-27T15:28:59 | 2019-01-27T15:28:59 | 167,558,980 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,094 | h | // Copyright (c) 2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef CLARITY_HTTPSERVER_H
#define CLARITY_HTTPSERVER_H
#include <string>
#include <stdint.h>
#include <boost/thread.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/function.hpp>
static const int DEFAULT_HTTP_THREADS=4;
static const int DEFAULT_HTTP_WORKQUEUE=16;
static const int DEFAULT_HTTP_SERVER_TIMEOUT=30;
struct evhttp_request;
struct event_base;
class CService;
class HTTPRequest;
/** Initialize HTTP server.
* Call this before RegisterHTTPHandler or EventBase().
*/
bool InitHTTPServer();
/** Start HTTP server.
* This is separate from InitHTTPServer to give users race-condition-free time
* to register their handlers between InitHTTPServer and StartHTTPServer.
*/
bool StartHTTPServer();
/** Interrupt HTTP server threads */
void InterruptHTTPServer();
/** Stop HTTP server */
void StopHTTPServer();
/** Handler for requests to a certain HTTP path */
typedef boost::function<void(HTTPRequest* req, const std::string &)> HTTPRequestHandler;
/** Register handler for prefix.
* If multiple handlers match a prefix, the first-registered one will
* be invoked.
*/
void RegisterHTTPHandler(const std::string &prefix, bool exactMatch, const HTTPRequestHandler &handler);
/** Unregister handler for prefix */
void UnregisterHTTPHandler(const std::string &prefix, bool exactMatch);
/** Return evhttp event base. This can be used by submodules to
* queue timers or custom events.
*/
struct event_base* EventBase();
/** In-flight HTTP request.
* Thin C++ wrapper around evhttp_request.
*/
class HTTPRequest
{
private:
struct evhttp_request* req;
bool replySent;
public:
HTTPRequest(struct evhttp_request* req);
~HTTPRequest();
enum RequestMethod {
UNKNOWN,
GET,
POST,
HEAD,
PUT
};
/** Get requested URI.
*/
std::string GetURI();
/** Get CService (address:ip) for the origin of the http request.
*/
CService GetPeer();
/** Get request method.
*/
RequestMethod GetRequestMethod();
/**
* Get the request header specified by hdr, or an empty string.
* Return an pair (isPresent,string).
*/
std::pair<bool, std::string> GetHeader(const std::string& hdr);
/**
* Read request body.
*
* @note As this consumes the underlying buffer, call this only once.
* Repeated calls will return an empty string.
*/
std::string ReadBody();
/**
* Write output header.
*
* @note call this before calling WriteErrorReply or Reply.
*/
void WriteHeader(const std::string& hdr, const std::string& value);
/**
* Write HTTP reply.
* nStatus is the HTTP status code to send.
* strReply is the body of the reply. Keep it empty to send a standard message.
*
* @note Can be called only once. As this will give the request back to the
* main thread, do not call any other HTTPRequest methods after calling this.
*/
void WriteReply(int nStatus, const std::string& strReply = "");
};
/** Event handler closure.
*/
class HTTPClosure
{
public:
virtual void operator()() = 0;
virtual ~HTTPClosure() {}
};
/** Event class. This can be used either as an cross-thread trigger or as a timer.
*/
class HTTPEvent
{
public:
/** Create a new event.
* deleteWhenTriggered deletes this event object after the event is triggered (and the handler called)
* handler is the handler to call when the event is triggered.
*/
HTTPEvent(struct event_base* base, bool deleteWhenTriggered, const boost::function<void(void)>& handler);
~HTTPEvent();
/** Trigger the event. If tv is 0, trigger it immediately. Otherwise trigger it after
* the given time has elapsed.
*/
void trigger(struct timeval* tv);
bool deleteWhenTriggered;
boost::function<void(void)> handler;
private:
struct event* ev;
};
#endif // CLARITY_HTTPSERVER_H
| [
"claritydevs@protonmail.com"
] | claritydevs@protonmail.com |
a7c2d371a8662864421098ac237ce6d3c4331ef9 | a96b15c6a02225d27ac68a7ed5f8a46bddb67544 | /SetGame/Application.hpp | 76fef5eec3e63653410a8dbaf3329aa344342995 | [] | no_license | joelverhagen/Gaza-2D-Game-Engine | 0dca1549664ff644f61fe0ca45ea6efcbad54591 | a3fe5a93e5d21a93adcbd57c67c888388b402938 | refs/heads/master | 2020-05-15T05:08:38.412819 | 2011-04-03T22:22:01 | 2011-04-03T22:22:01 | 1,519,417 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 511 | hpp | #ifndef APPLICATION_HPP
#define APPLICATION_HPP
#include "Common.hpp"
#include "GazaApplication.hpp"
#include "GazaFrameSheet.hpp"
#include "GazaImageManager.hpp"
#include "GazaLogger.hpp"
#include "GameState.hpp"
#include "CardFrameSheetGenerator.hpp"
class Application : public Gaza::Application
{
public:
Application();
~Application();
Gaza::ImageManager * getImageManager();
private:
Gaza::ImageManager imageManager;
Gaza::FrameSheetCollection * cardFrames;
};
#endif | [
"joel.verhagen@gmail.com"
] | joel.verhagen@gmail.com |
d6f83895939b24814da6fd18e4d68a79a1a80758 | 296ad04c65c888b05c4760a975d904ba09984bec | /Codeforces/464/C.cpp | 9ecc344529f83b33c7822ee6c4cdcb068c20877a | [] | no_license | Uditgulati/CpCodes | daf44f19b958fdeee63ed3ae4674ec16ffddc5f5 | 44067672892fe19d2c21826483a5dc8488e7b53b | refs/heads/master | 2021-01-20T16:58:42.432995 | 2018-08-31T14:41:10 | 2018-08-31T14:41:10 | 82,847,473 | 9 | 9 | null | 2020-10-01T16:38:26 | 2017-02-22T20:06:59 | C++ | UTF-8 | C++ | false | false | 858 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int siz = 1e5 + 10;
const ll modu = 1e9 + 7;
int main() {
int n;
scanf("%d", &n);
ll arr[n];
for(int i = 0; i < n; i++)
scanf("%lld", &arr[i]);
int s, f;
scanf("%d%d", &s, &f);
ll pre[n], post[n];
ll sum1 = 0, sum2 = 0;
for(int i = 0; i < n; i++) {
sum1 += arr[i];
pre[i] = sum1;
}
for(int i = n - 1; i >= 0; i--) {
sum2 += arr[i];
post[i] = sum2;
}
ll ans = -1, maxi = -1;
for(int i = 0; i < n; i++) {
int curr = i + 1;
ll temp = 0;
int ind = n - curr + 1;
int ind1 = (ind + (s - 1)) % n;
int ind2 = (ind + (f - 2)) % n;
if(ind1 <= ind2) {
temp += pre[ind2];
if(ind1)
temp -= pre[ind1 - 1];
}
else {
temp += pre[ind2];
temp += post[ind1];
}
if(temp > maxi)
maxi = temp, ans = curr;
}
cout << ans << endl;
return 0;
} | [
"uditgulati0@gmail.com"
] | uditgulati0@gmail.com |
65623520062752a470289add810fab8dec640443 | 06e6ae07a943301309afd5eb56d5f94834b1b540 | /src/CacheClient.cpp | b9fb80f1ec67f0c2bf09abe75aaec2bb529ec578 | [] | no_license | desion/zkcl | 89116155b7077d4d88a71d23bed5bee09e1ba6b5 | 9d3a4190f6fa3a62aeb8f66c4aaad35f6203f777 | refs/heads/master | 2021-01-10T20:31:55.800234 | 2014-03-06T15:01:38 | 2014-03-06T15:01:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,525 | cpp | #include "utils.h"
#include "configuration.h"
#include "log.h"
using namespace std;
using namespace boost;
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;
#define CLIENT_VERSION "1.0"
#define DEBUG 1
#define CACHE_SIZE 102400
Json::Reader reader;
Json::Value root;
Json::Value configuration;
struct cacheConfig conf;
map<string,operateClient> servicePool;
void usage(){
fprintf(stderr,"Usage: CacheClient\n");
fprintf(stderr,"-v -version show the verion\n");
fprintf(stderr,"-h -help show the usage\n");
fprintf(stderr,"-get [rowkey] get the data\n");
fprintf(stderr,"-del [rowkey] delete the data from cache\n");
fprintf(stderr,"-putjson [rowkey] [key] [value] insert the data to cache\n");
fprintf(stderr,"-put [rowkey] [value] insert the data to cache and db\n");
fprintf(stderr,"-dump dump the data to file\n");
fprintf(stderr,"-status get the status of cluster\n");
}
//create the thrift client by host ip
operateClient CreateService(const string& host)
{
Log(CACHE_LOG_DEBUG,"[%d] Create thrift client of %s",(int)pthread_self(),host.c_str());
shared_ptr<TTransport> socket(new TSocket(host, conf.thriftPort));
//shared_ptr<TTransport> transport(new TFramedTransport(socket));
//shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
//shared_ptr<TProtocol> protocol(new TCompactProtocol(transport));
//shared_ptr<TTransport> socket(new TSocket(host, conf.thriftPort));
//shared_ptr<TTransport> transport(new TBufferedTransport(socket));
//shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
shared_ptr<TTransport> transport(new TBufferedTransport(socket));
shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
operateClient client(protocol);
try {
transport->open();
return client;
} catch (TException &tx) {
tx.what();
transport->close();
return client;
}
}
class CacheService{
private:
shared_ptr<TTransport> transport;
string host;
int port;
public:
CacheService(){}
CacheService(string _host,int _port){
host = _host;
port = _port;
shared_ptr<TTransport> _socket(new TSocket(host, port));
shared_ptr<TTransport> _transport(new TFramedTransport(_socket));
shared_ptr<TProtocol> _protocol(new TBinaryProtocol(_transport));
try {
transport = _transport;
_transport->open();
} catch (TException &tx) {
tx.what();
_transport->close();
}
}
void close(){
transport->close();
}
};
struct thread_data{
long group;
vector<pair<string,string> > *group_data;
char first_service[32];
char second_service[32];
};
struct thread_res{
double use_time;
long load_record;
long group;
char first_service[32];
char second_service[32];
};
int main(int argc,char *argv[]){
//load the config file
loadConfig("./service.ini",conf);
if(argc == 2){
if(strcmp(argv[1],"-v") == 0 || strcmp(argv[1],"-version") == 0){
printf("CacheClient Vserion: %s",CLIENT_VERSION);
}else if(strcmp(argv[1],"-h") == 0 || strcmp(argv[1],"-help") ==0 ){
usage();
}else if(strcmp(argv[1],"-dump") == 0){
long start_usecs = get_time_usecs();
operateClient client = CreateService("127.0.0.1");
client.dump();
long end_usecs = get_time_usecs();
double secs = (double)(end_usecs - start_usecs) / (double)1000;
cout << " use time:" << secs << endl;
}else if(strcmp(argv[1],"-status") == 0){
vector<string>::iterator serverIter = conf.serverGroup.begin();
for(;serverIter != conf.serverGroup.end();++serverIter){
try{
string status;
operateClient client = CreateService(*serverIter);
client.status(status);
cout << status << endl;
}catch(TException &tx){
cout << "server has down" << endl;
}
}
printf("total cache server %d",conf.serverGroup.size());
}else if(strcmp(argv[1],"-shutdown") == 0){
vector<string>::iterator serverIter = conf.serverGroup.begin();
for(;serverIter != conf.serverGroup.end();++serverIter){
operateClient client = CreateService(*serverIter);
try{
client.shutdown();
}catch(TException &tx){
Log(CACHE_LOG_WARNING,"%s server has been shutdown!",serverIter->c_str());
}
}
printf("all servers have been shutdown");
}else{
usage();
}
}else if(argc == 3){
if(strcmp(argv[1],"-get") == 0 ){
//get the data from db
long start_usecs = get_time_usecs();
char* uid = argv[2];
unsigned int hash = genHashFunction((const unsigned char *)uid, strlen(uid));
int groupNum = conf.serverGroup.size();
string group = conf.serverGroup[hash%groupNum];
long timestamp = get_time_usecs();
string jsonStr;
if(timestamp % 2 == 0){
operateClient client = CreateService(group);
client.get(jsonStr,string(uid));
cout << "get record from:" << group << '\n';
}else{
operateClient client = CreateService(group);
client.get(jsonStr,string(uid));
cout << "get record from:" << group << '\n';
}
cout << jsonStr << endl;
long end_usecs = get_time_usecs();
double secs = (double)(end_usecs - start_usecs) / (double)1000;
cout << " use time:" << secs << endl;
}else if(strcmp(argv[1],"-del") == 0){
//delete the data by row key
char* uid = argv[2];
unsigned int hash = genHashFunction((const unsigned char *)uid, strlen(uid));
int groupNum = conf.serverGroup.size();
string group = conf.serverGroup[hash%groupNum];
operateClient client = CreateService(group);
client.delkey(string(uid));
}else if(strcmp(argv[1],"-shutdown") == 0){
//shutdown the spcify server
try{
string host = string(argv[2]);
operateClient client = CreateService(host);
client.shutdown();
}catch(TException &tx){
Log(CACHE_LOG_WARNING,"%s server has been shutdown!",argv[2]);
}
printf("server %s has been shutdown",argv[2]);
}else{
usage();
}
}else if(argc == 4){
if(strcmp(argv[1], "-put") == 0){
char* key = argv[2];
string value = string(argv[3]);
unsigned int hash = genHashFunction((const unsigned char *)key, strlen(key));
int groupNum = conf.serverGroup.size();
string group = conf.serverGroup[hash%groupNum];
operateClient client = CreateService(group);
client.put(string(key),value);
}else{
usage();
}
}else{
usage();
}
return 0;
}
| [
"root@i-31nn5uml.pek1.qingcloud.com"
] | root@i-31nn5uml.pek1.qingcloud.com |
6ff45b80998c2938e1119fabedb9753cef080c61 | a98c0ec02f0dbd7a41b38b90214ea5dcf02271ad | /hw40.cpp | cb248d9cd69097bbaa324f215c1a65df451318d7 | [] | no_license | tks2807/practice1 | 0c58f614a6400788979e4a3c3c773a65d0db5a8e | 7850b8a3ec72af0cc685be0f0c9accefe28b5e71 | refs/heads/master | 2020-09-13T02:17:10.328539 | 2019-11-22T06:54:23 | 2019-11-22T06:54:23 | 222,631,204 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 167 | cpp | #include <iostream>
#include <cmath>
using namespace std;
int main() {
double x;
cin>>x;
if (-10<x && x<10){
cout<<x+5;
}
else {
cout<<x-10;
}
return 0;
}
| [
"toxambayev2807@gmail.com"
] | toxambayev2807@gmail.com |
cd8bbc7d82b8382591b0b62a8931ec69b81d9fba | a3a45403753957632ff88f3c52df20563c3a6708 | /module_2/error2.cpp | e45d301d0e5e19a5b14a3e8d12c9bfc0a9e2cbbe | [] | no_license | BosnaZmaj/cpeg_676 | 9ea010231e2fb58b6a9dce9de5bb879b8598d722 | 040fff129738f054ce320425ba23eb9dfe458f30 | refs/heads/master | 2022-07-11T01:08:40.084292 | 2020-05-14T19:33:08 | 2020-05-14T19:33:08 | 256,377,852 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 212 | cpp | //
// Created by BosnaZmaj on 4/23/2020.
//
#include <iostream>
#include <cstdlib>
using namespace std;
int main(){
int* x = (int*) malloc(32);
x[0] = 23;
cout << x[0] << endl;
return 0;
} | [
"indysubasic@gmail.com"
] | indysubasic@gmail.com |
7dee8ab932a7b8a2e18868149e029f18320e1018 | 97e6a86106c611ccaa4724c7f2b0a03da7bbcdd3 | /server/common/gen_rpc/com.cpp | 70eb9ce613464193556039ec9c63fb68f80ab7be | [] | no_license | daxingyou/mlbb | 69ac11a7cc5928a82de10163e8c454bc5c24bb78 | f2d1cba16f7800a2d2914f87bb42ea5ed45f42a1 | refs/heads/master | 2022-02-26T12:01:03.782205 | 2019-09-02T06:26:02 | 2019-09-02T06:26:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 69,760 | cpp | /* arpcc auto generated cpp file. */
#include "FieldMask.h"
#include "com.h"
//=============================================================
static void initFuncMajorVersion(EnumInfo* e)
{
e->items_.push_back("Major_0");
e->items_.push_back("MajorNumber");
}
EnumInfo enumMajorVersion("MajorVersion", initFuncMajorVersion);
//=============================================================
static void initFuncMinorVersion(EnumInfo* e)
{
e->items_.push_back("Minor_0");
e->items_.push_back("Minor_1");
e->items_.push_back("Minor_2");
e->items_.push_back("Minor_3");
e->items_.push_back("Minor_4");
e->items_.push_back("Minor_5");
e->items_.push_back("Minor_6");
e->items_.push_back("MinorNumber");
}
EnumInfo enumMinorVersion("MinorVersion", initFuncMinorVersion);
//=============================================================
static void initFuncPatchVersion(EnumInfo* e)
{
e->items_.push_back("Patch_0");
e->items_.push_back("Patch_1");
e->items_.push_back("Patch_2");
e->items_.push_back("Patch_3");
e->items_.push_back("Patch_4");
e->items_.push_back("Patch_5");
e->items_.push_back("PatchNumber");
}
EnumInfo enumPatchVersion("PatchVersion", initFuncPatchVersion);
//=============================================================
static void initFuncPetQuality(EnumInfo* e)
{
e->items_.push_back("PE_None");
e->items_.push_back("PE_White");
e->items_.push_back("PE_Green");
e->items_.push_back("PE_Blue");
e->items_.push_back("PE_Purple");
e->items_.push_back("PE_Golden");
e->items_.push_back("PE_Orange");
e->items_.push_back("PE_Pink");
}
EnumInfo enumPetQuality("PetQuality", initFuncPetQuality);
//=============================================================
static void initFuncErrorNo(EnumInfo* e)
{
e->items_.push_back("EN_None");
e->items_.push_back("EN_VersionNotMatch");
e->items_.push_back("EN_AccountNameSame");
e->items_.push_back("EN_PlayerNameSame");
e->items_.push_back("EN_FilterWord");
e->items_.push_back("EN_CannotfindPlayer");
e->items_.push_back("EN_AcceptQuestNotFound");
e->items_.push_back("EN_AcceptQuestNoItem");
e->items_.push_back("EN_AcceptSecendDaily");
e->items_.push_back("EN_DailyNoNum");
e->items_.push_back("EN_AcceptSecendProfession");
e->items_.push_back("EN_Battle");
e->items_.push_back("EN_MoneyLess");
e->items_.push_back("EN_DiamondLess");
e->items_.push_back("EN_NoSubSyste");
e->items_.push_back("EN_InTeam");
e->items_.push_back("EN_NoTeamLeader");
e->items_.push_back("EN_TeamPassword");
e->items_.push_back("EN_TeamIsFull");
e->items_.push_back("EN_NoTeam");
e->items_.push_back("EN_TeamIsRunning");
e->items_.push_back("EN_TeamMemberLeaving");
e->items_.push_back("EN_NoBackTeam");
e->items_.push_back("EN_InTeamBlackList");
e->items_.push_back("EN_EmployeeIsFull");
e->items_.push_back("EN_NoUpSkill");
e->items_.push_back("EN_PropisNull");
e->items_.push_back("EN_DoubleExpTimeFull");
e->items_.push_back("EN_DoubleExpTimeNULL");
e->items_.push_back("EN_NoTeamNoTongji");
e->items_.push_back("EN_TongjiTimesMax");
e->items_.push_back("EN_TongjiTeamMemberTimesMax");
e->items_.push_back("EN_NoTeamLeaderNoTongji");
e->items_.push_back("EN_TeamSizeTongjiError");
e->items_.push_back("EN_GetPoisonMushroom");
e->items_.push_back("EN_GetMushroom");
e->items_.push_back("EN_TongjiTeamLevelTooLow");
e->items_.push_back("EN_PlayerIsInTeam");
e->items_.push_back("EN_AcceptQuestBagMax");
e->items_.push_back("EN_SubmitQuestBagMax");
e->items_.push_back("EN_GuildNameSame");
e->items_.push_back("EN_PlayerGoldLess");
e->items_.push_back("EN_PlayerHasGuild");
e->items_.push_back("EN_InRequestErr");
e->items_.push_back("EN_RequestListFull");
e->items_.push_back("EN_joinGuildRequestOk");
e->items_.push_back("EN_JoinOtherGuild");
e->items_.push_back("EN_PremierQuitError");
e->items_.push_back("EN_CommandPositionLess");
e->items_.push_back("EN_PositionUpMax");
e->items_.push_back("EN_MallBuyOk");
e->items_.push_back("EN_MallBuyFailBagFull");
e->items_.push_back("EN_MallBuyFailBabyFull");
e->items_.push_back("EN_MallBuyFailDiamondLess");
e->items_.push_back("EN_MallBuyFailSelled");
e->items_.push_back("EN_OpenBaoXiangBagFull");
e->items_.push_back("EN_NoBaby");
e->items_.push_back("EN_BagFull");
e->items_.push_back("EN_BagSizeMax");
e->items_.push_back("EN_BabyStorageFull");
e->items_.push_back("EN_BabyFullToStorage");
e->items_.push_back("EN_NewItemError");
e->items_.push_back("EN_BabyFull");
e->items_.push_back("EN_RemouldBabyLevel");
e->items_.push_back("EN_SkillSoltFull");
e->items_.push_back("EN_WorldChatPayError");
e->items_.push_back("EN_DontTalk");
e->items_.push_back("EN_BadMushroom");
e->items_.push_back("EN_ItemMushroom");
e->items_.push_back("EN_GetMailItemBagFull");
e->items_.push_back("EN_Materialless");
e->items_.push_back("EN_OpenGatherlose");
e->items_.push_back("EN_OpenGatherRepetition");
e->items_.push_back("EN_GatherLevelLess");
e->items_.push_back("EN_GatherTimesLess");
e->items_.push_back("EN_OpenBaoXiangLevel");
e->items_.push_back("EN_NoBattleBaby");
e->items_.push_back("EN_NoThisPoint");
e->items_.push_back("EN_BabyLevelHigh");
e->items_.push_back("EN_AddMoney1W");
e->items_.push_back("EN_AddDionmand100");
e->items_.push_back("EN_AddMoney2W");
e->items_.push_back("EN_AddDionmand200");
e->items_.push_back("EN_AddMoney3W");
e->items_.push_back("EN_AddDionmand300");
e->items_.push_back("EN_AddMoney4W");
e->items_.push_back("EN_AddDionmand400");
e->items_.push_back("EN_AddMoney5W");
e->items_.push_back("EN_AddDionmand500");
e->items_.push_back("EN_AddMoney6W");
e->items_.push_back("EN_AddDionmand600");
e->items_.push_back("EN_DelBaby1000");
e->items_.push_back("EN_DelBaby30");
e->items_.push_back("EN_DelBaby54");
e->items_.push_back("EN_DelBaby10030");
e->items_.push_back("EN_DelBaby10015");
e->items_.push_back("EN_DelBaby10157");
e->items_.push_back("EN_DelDefaultSkill");
e->items_.push_back("EN_GreenBoxFreeNum");
e->items_.push_back("EM_NotNormalVip");
e->items_.push_back("EN_NotSuperVip");
e->items_.push_back("EN_FirendNotOpen");
e->items_.push_back("EN_BlackCannotFriend");
e->items_.push_back("EN_HasFriend");
e->items_.push_back("EN_HunderdNoNum");
e->items_.push_back("EN_HunderdTier");
e->items_.push_back("EN_HunderdLevel");
e->items_.push_back("EN_SkillExperr");
e->items_.push_back("EN_TimeMushroom");
e->items_.push_back("EN_TimeTongji");
e->items_.push_back("EN_TimeXiji");
e->items_.push_back("EN_Storefull");
e->items_.push_back("EN_HasBattleTime");
e->items_.push_back("EN_HourLess24");
e->items_.push_back("EN_HourLess24_Join");
e->items_.push_back("EN_TeamMemberHourLess24");
e->items_.push_back("EN_GuildBattleJoinSceneMoveValue");
e->items_.push_back("EN_IdgenNull");
e->items_.push_back("EN_Idgenhas");
e->items_.push_back("EN_Gifthas");
e->items_.push_back("EN_UseMakeRepeat");
e->items_.push_back("EN_WishNull");
e->items_.push_back("EN_NoGuild");
e->items_.push_back("EN_GuildMemberMax");
e->items_.push_back("EN_LevelupGuildBuilding");
e->items_.push_back("EN_LevelupGuildBuildingLevelMax");
e->items_.push_back("EN_LevelupGuildBuildingMoneyLess");
e->items_.push_back("EN_LevelupGuildBuildingHallBuildLevelLess");
e->items_.push_back("EN_AddGuildMoneyMax");
e->items_.push_back("EN_PresentGuildOk");
e->items_.push_back("EN_RefreshShopTimeLess");
e->items_.push_back("EN_TeamMemberNoGuild");
e->items_.push_back("EN_MagicCurrencyLess");
e->items_.push_back("EN_DisShopLimitLess");
e->items_.push_back("EN_FamilyPremierCanntDelete");
e->items_.push_back("EN_MyFamilyMonster");
e->items_.push_back("EN_NoBattleTime");
e->items_.push_back("EN_OtherNoBattleTime");
e->items_.push_back("EN_GuildBattleTimeout2");
e->items_.push_back("EN_GuildBattleHasTeam");
e->items_.push_back("EN_AccountIsSeal");
e->items_.push_back("EN_PlayerNoOnline");
e->items_.push_back("EN_ActivityNoTime");
e->items_.push_back("EN_NoTeamExist");
e->items_.push_back("EN_GuildNoMember");
e->items_.push_back("EN_MallSellTimeLess");
e->items_.push_back("EN_GuildMemberLess24");
e->items_.push_back("EN_InviteeLeaveGuildLess24");
e->items_.push_back("EN_PboneNumberSuccess");
e->items_.push_back("EN_PhoneNumberError");
e->items_.push_back("EN_OtherPlayerInBattle");
e->items_.push_back("EN_GuildBattleNotMatch");
e->items_.push_back("EN_GuildBattleIsStart");
e->items_.push_back("EN_GuileBattleIsClose");
e->items_.push_back("EN_GuildBattleTeamNoSameGuild");
e->items_.push_back("EN_BackTeamCommandLeaderInGuildHomeSceneAndYouAreNotSameGuild");
e->items_.push_back("EN_AccecptRandQuestSizeLimitError");
e->items_.push_back("EN_Max");
}
EnumInfo enumErrorNo("ErrorNo", initFuncErrorNo);
//=============================================================
static void initFuncOperateType(EnumInfo* e)
{
e->items_.push_back("OT_0");
e->items_.push_back("OT_P1");
e->items_.push_back("OT_P2");
e->items_.push_back("OT_B");
}
EnumInfo enumOperateType("OperateType", initFuncOperateType);
//=============================================================
static void initFuncBindType(EnumInfo* e)
{
e->items_.push_back("BIT_None");
e->items_.push_back("BIT_Bag");
e->items_.push_back("BIT_Use");
e->items_.push_back("BIT_Max");
}
EnumInfo enumBindType("BindType", initFuncBindType);
//=============================================================
static void initFuncReconnectType(EnumInfo* e)
{
e->items_.push_back("RECT_None");
e->items_.push_back("RECT_LoginOk");
e->items_.push_back("RECT_EnterGameOk");
e->items_.push_back("RECT_JoinTeamOk");
e->items_.push_back("RECT_EnterSceneOk");
e->items_.push_back("RECT_EnterBattleOk");
e->items_.push_back("RECT_Max");
}
EnumInfo enumReconnectType("ReconnectType", initFuncReconnectType);
//=============================================================
static void initFuncSexType(EnumInfo* e)
{
e->items_.push_back("ST_Unknown");
e->items_.push_back("ST_Male");
e->items_.push_back("ST_Female");
}
EnumInfo enumSexType("SexType", initFuncSexType);
//=============================================================
static void initFuncBattleType(EnumInfo* e)
{
e->items_.push_back("BT_None");
e->items_.push_back("BT_PVE");
e->items_.push_back("BT_PVR");
e->items_.push_back("BT_PVP");
e->items_.push_back("BT_PVH");
e->items_.push_back("BT_PET");
e->items_.push_back("BT_PK1");
e->items_.push_back("BT_PK2");
e->items_.push_back("BT_Guild");
e->items_.push_back("BT_MAX");
}
EnumInfo enumBattleType("BattleType", initFuncBattleType);
//=============================================================
static void initFuncEntityType(EnumInfo* e)
{
e->items_.push_back("ET_None");
e->items_.push_back("ET_Player");
e->items_.push_back("ET_Baby");
e->items_.push_back("ET_Monster");
e->items_.push_back("ET_Boss");
e->items_.push_back("ET_Emplyee");
e->items_.push_back("ET_Max");
}
EnumInfo enumEntityType("EntityType", initFuncEntityType);
//=============================================================
static void initFuncMineType(EnumInfo* e)
{
e->items_.push_back("MT_None");
e->items_.push_back("MT_JinShu");
e->items_.push_back("MT_MuCai");
e->items_.push_back("MT_BuLiao");
e->items_.push_back("MT_Max");
}
EnumInfo enumMineType("MineType", initFuncMineType);
//=============================================================
static void initFuncGroupType(EnumInfo* e)
{
e->items_.push_back("GT_None");
e->items_.push_back("GT_Up");
e->items_.push_back("GT_Down");
}
EnumInfo enumGroupType("GroupType", initFuncGroupType);
//=============================================================
static void initFuncSkillTargetType(EnumInfo* e)
{
e->items_.push_back("STT_None");
e->items_.push_back("STT_Self");
e->items_.push_back("STT_Team");
e->items_.push_back("STT_TeamDead");
e->items_.push_back("STT_TeamNoSelf");
e->items_.push_back("STT_All");
e->items_.push_back("STT_AllNoSelf");
e->items_.push_back("STT_Max");
}
EnumInfo enumSkillTargetType("SkillTargetType", initFuncSkillTargetType);
//=============================================================
static void initFuncSkillType(EnumInfo* e)
{
e->items_.push_back("SKT_None");
e->items_.push_back("SKT_DefaultSecActive");
e->items_.push_back("SKT_DefaultSecPassive");
e->items_.push_back("SKT_DefaultActive");
e->items_.push_back("SKT_DefaultPassive");
e->items_.push_back("SKT_Active");
e->items_.push_back("SKT_Passive");
e->items_.push_back("SKT_Gather");
e->items_.push_back("SKT_Make");
e->items_.push_back("SKT_CannotUse");
e->items_.push_back("SKT_GuildPlayerSkill");
e->items_.push_back("SKT_GuildBabySkill");
e->items_.push_back("SKT_Max");
}
EnumInfo enumSkillType("SkillType", initFuncSkillType);
//=============================================================
static void initFuncPassiveType(EnumInfo* e)
{
e->items_.push_back("PAT_None");
e->items_.push_back("PAT_Buff");
e->items_.push_back("PAT_Deference");
e->items_.push_back("PAT_Dodge");
e->items_.push_back("PAT_Counter");
e->items_.push_back("PAT_Change");
e->items_.push_back("PAT_Guard");
e->items_.push_back("PAT_Runaway");
e->items_.push_back("PAT_BabyInnout");
e->items_.push_back("PAT_SecKill");
}
EnumInfo enumPassiveType("PassiveType", initFuncPassiveType);
//=============================================================
static void initFuncPlayerStatus(EnumInfo* e)
{
e->items_.push_back("PS_Idle");
e->items_.push_back("PS_Login");
e->items_.push_back("PS_Game");
e->items_.push_back("PS_Logout");
e->items_.push_back("PS_Illegal");
}
EnumInfo enumPlayerStatus("PlayerStatus", initFuncPlayerStatus);
//=============================================================
static void initFuncOccupationType(EnumInfo* e)
{
e->items_.push_back("OT_None");
e->items_.push_back("OT_HeavyArmor");
e->items_.push_back("OT_LightArmor");
e->items_.push_back("OT_Spell");
e->items_.push_back("OT_Max");
}
EnumInfo enumOccupationType("OccupationType", initFuncOccupationType);
//=============================================================
static void initFuncPeriodType(EnumInfo* e)
{
e->items_.push_back("PT_Daily");
e->items_.push_back("PT_Weekly");
e->items_.push_back("PT_Customly");
}
EnumInfo enumPeriodType("PeriodType", initFuncPeriodType);
//=============================================================
static void initFuncJobType(EnumInfo* e)
{
e->items_.push_back("JT_None");
e->items_.push_back("JT_Newbie");
e->items_.push_back("JT_Axe");
e->items_.push_back("JT_Sword");
e->items_.push_back("JT_Knight");
e->items_.push_back("JT_Archer");
e->items_.push_back("JT_Fighter");
e->items_.push_back("JT_Ninja");
e->items_.push_back("JT_Mage");
e->items_.push_back("JT_Sage");
e->items_.push_back("JT_Wizard");
e->items_.push_back("JT_Word");
}
EnumInfo enumJobType("JobType", initFuncJobType);
//=============================================================
static void initFuncRaceType(EnumInfo* e)
{
e->items_.push_back("RT_None");
e->items_.push_back("RT_Human");
e->items_.push_back("RT_Insect");
e->items_.push_back("RT_Plant");
e->items_.push_back("RT_Extra");
e->items_.push_back("RT_Dragon");
e->items_.push_back("RT_Animal");
e->items_.push_back("RT_Fly");
e->items_.push_back("RT_Undead");
e->items_.push_back("RT_Metal");
e->items_.push_back("RT_Max");
}
EnumInfo enumRaceType("RaceType", initFuncRaceType);
//=============================================================
static void initFuncBabyInitGear(EnumInfo* e)
{
e->items_.push_back("BIG_None");
e->items_.push_back("BIG_Stama");
e->items_.push_back("BIG_Strength");
e->items_.push_back("BIG_Power");
e->items_.push_back("BIG_Speed");
e->items_.push_back("BIG_Magic");
e->items_.push_back("BIG_Max");
}
EnumInfo enumBabyInitGear("BabyInitGear", initFuncBabyInitGear);
//=============================================================
static void initFuncQualityColor(EnumInfo* e)
{
e->items_.push_back("QC_None");
e->items_.push_back("QC_White");
e->items_.push_back("QC_Green");
e->items_.push_back("QC_Blue");
e->items_.push_back("QC_Blue1");
e->items_.push_back("QC_Purple");
e->items_.push_back("QC_Purple1");
e->items_.push_back("QC_Purple2");
e->items_.push_back("QC_Golden");
e->items_.push_back("QC_Golden1");
e->items_.push_back("QC_Golden2");
e->items_.push_back("QC_Orange");
e->items_.push_back("QC_Orange1");
e->items_.push_back("QC_Orange2");
e->items_.push_back("QC_Pink");
e->items_.push_back("QC_Max");
}
EnumInfo enumQualityColor("QualityColor", initFuncQualityColor);
//=============================================================
static void initFuncPropertyType(EnumInfo* e)
{
e->items_.push_back("PT_None");
e->items_.push_back("PT_NoSleep");
e->items_.push_back("PT_NoPetrifaction");
e->items_.push_back("PT_NoDrunk");
e->items_.push_back("PT_NoChaos");
e->items_.push_back("PT_NoForget");
e->items_.push_back("PT_NoPoison");
e->items_.push_back("PT_Assassinate");
e->items_.push_back("PT_Money");
e->items_.push_back("PT_Diamond");
e->items_.push_back("PT_MagicCurrency");
e->items_.push_back("PT_EmployeeCurrency");
e->items_.push_back("PT_Gather");
e->items_.push_back("PT_Level");
e->items_.push_back("PT_Exp");
e->items_.push_back("PT_ConvertExp");
e->items_.push_back("PT_OneDayReputation");
e->items_.push_back("PT_Reputation");
e->items_.push_back("PT_TableId");
e->items_.push_back("PT_AssetId");
e->items_.push_back("PT_Sex");
e->items_.push_back("PT_BagNum");
e->items_.push_back("PT_Race");
e->items_.push_back("PT_Profession");
e->items_.push_back("PT_ProfessionLevel");
e->items_.push_back("PT_Stama");
e->items_.push_back("PT_Strength");
e->items_.push_back("PT_Power");
e->items_.push_back("PT_Speed");
e->items_.push_back("PT_Magic");
e->items_.push_back("PT_Durability");
e->items_.push_back("PT_HpCurr");
e->items_.push_back("PT_MpCurr");
e->items_.push_back("PT_HpMax");
e->items_.push_back("PT_MpMax");
e->items_.push_back("PT_Attack");
e->items_.push_back("PT_Defense");
e->items_.push_back("PT_Agile");
e->items_.push_back("PT_Spirit");
e->items_.push_back("PT_Reply");
e->items_.push_back("PT_Magicattack");
e->items_.push_back("PT_Magicdefense");
e->items_.push_back("PT_Damage");
e->items_.push_back("PT_SneakAttack");
e->items_.push_back("PT_Hit");
e->items_.push_back("PT_Dodge");
e->items_.push_back("PT_Crit");
e->items_.push_back("PT_counterpunch");
e->items_.push_back("PT_Front");
e->items_.push_back("PT_Wind");
e->items_.push_back("PT_Land");
e->items_.push_back("PT_Water");
e->items_.push_back("PT_Fire");
e->items_.push_back("PT_Free");
e->items_.push_back("PT_Title");
e->items_.push_back("PT_GuildID");
e->items_.push_back("PT_Glamour");
e->items_.push_back("PT_DoubleExp");
e->items_.push_back("PT_TongjiComplateTimes");
e->items_.push_back("PT_VipLevel");
e->items_.push_back("PT_VipTime");
e->items_.push_back("PT_FightingForce");
e->items_.push_back("PT_Max");
}
EnumInfo enumPropertyType("PropertyType", initFuncPropertyType);
//=============================================================
static void initFuncVipLevel(EnumInfo* e)
{
e->items_.push_back("VL_None");
e->items_.push_back("VL_1");
e->items_.push_back("VL_2");
e->items_.push_back("VL_Max");
}
EnumInfo enumVipLevel("VipLevel", initFuncVipLevel);
//=============================================================
static void initFuncItemMainType(EnumInfo* e)
{
e->items_.push_back("IMT_None");
e->items_.push_back("IMT_Quest");
e->items_.push_back("IMT_Consumables");
e->items_.push_back("IMT_Equip");
e->items_.push_back("IMT_Employee");
e->items_.push_back("IMT_EmployeeEquip");
e->items_.push_back("IMT_Debris");
e->items_.push_back("IMT_FuWen");
e->items_.push_back("IMT_BabyEquip");
e->items_.push_back("IMT_Max");
}
EnumInfo enumItemMainType("ItemMainType", initFuncItemMainType);
//=============================================================
static void initFuncItemSubType(EnumInfo* e)
{
e->items_.push_back("IST_None");
e->items_.push_back("IST_Axe");
e->items_.push_back("IST_Sword");
e->items_.push_back("IST_Spear");
e->items_.push_back("IST_Bow");
e->items_.push_back("IST_Stick");
e->items_.push_back("IST_Knife");
e->items_.push_back("IST_Hat");
e->items_.push_back("IST_Helmet");
e->items_.push_back("IST_Clothes");
e->items_.push_back("IST_Robe");
e->items_.push_back("IST_Armor");
e->items_.push_back("IST_Boot");
e->items_.push_back("IST_Shoes");
e->items_.push_back("IST_Shield");
e->items_.push_back("IST_Crystal");
e->items_.push_back("IST_Charm");
e->items_.push_back("IST_Earrings");
e->items_.push_back("IST_Bracelet");
e->items_.push_back("IST_Ring");
e->items_.push_back("IST_Necklace");
e->items_.push_back("IST_Headband");
e->items_.push_back("IST_Instruments");
e->items_.push_back("IST_EquipMax");
e->items_.push_back("IST_Ornament");
e->items_.push_back("IST_Lottery");
e->items_.push_back("IST_Coupun");
e->items_.push_back("IST_OpenGird");
e->items_.push_back("IST_ConsBegin");
e->items_.push_back("IST_Consumables");
e->items_.push_back("IST_Blood");
e->items_.push_back("IST_Buff");
e->items_.push_back("IST_Gem");
e->items_.push_back("IST_Material");
e->items_.push_back("IST_ItemDebris");
e->items_.push_back("IST_BabyDebris");
e->items_.push_back("IST_EmployeeDebris");
e->items_.push_back("IST_BabyExp");
e->items_.push_back("IST_SkillExp");
e->items_.push_back("IST_ConsEnd");
e->items_.push_back("IST_Gloves");
e->items_.push_back("IST_EmployeeEquip");
e->items_.push_back("IST_PVP");
e->items_.push_back("IST_Fashion");
e->items_.push_back("IST_FuWenAttack");
e->items_.push_back("IST_FuWenDefense");
e->items_.push_back("IST_FuWenAssist");
e->items_.push_back("IST_Max");
}
EnumInfo enumItemSubType("ItemSubType", initFuncItemSubType);
//=============================================================
static void initFuncItemUseFlag(EnumInfo* e)
{
e->items_.push_back("IUF_None");
e->items_.push_back("IUF_Battle");
e->items_.push_back("IUF_Scene");
e->items_.push_back("IUF_All");
}
EnumInfo enumItemUseFlag("ItemUseFlag", initFuncItemUseFlag);
//=============================================================
static void initFuncEquipmentSlot(EnumInfo* e)
{
e->items_.push_back("ES_None");
e->items_.push_back("ES_Boot");
e->items_.push_back("ES_SingleHand");
e->items_.push_back("ES_Ornament_0");
e->items_.push_back("ES_Head");
e->items_.push_back("ES_Ornament_1");
e->items_.push_back("ES_Body");
e->items_.push_back("ES_DoubleHand");
e->items_.push_back("ES_Crystal");
e->items_.push_back("ES_Fashion");
e->items_.push_back("ES_Max");
}
EnumInfo enumEquipmentSlot("EquipmentSlot", initFuncEquipmentSlot);
//=============================================================
static void initFuncWeaponType(EnumInfo* e)
{
e->items_.push_back("WT_None");
e->items_.push_back("WT_Axe");
e->items_.push_back("WT_Sword");
e->items_.push_back("WT_Spear");
e->items_.push_back("WT_Bow");
e->items_.push_back("WT_Stick");
e->items_.push_back("WT_Knife");
e->items_.push_back("WT_Hoe");
e->items_.push_back("WT_Pickax");
e->items_.push_back("WT_Lumberaxe");
e->items_.push_back("WT_Gloves");
e->items_.push_back("WT_Max");
}
EnumInfo enumWeaponType("WeaponType", initFuncWeaponType);
//=============================================================
static void initFuncChatKind(EnumInfo* e)
{
e->items_.push_back("CK_None");
e->items_.push_back("CK_World");
e->items_.push_back("CK_Team");
e->items_.push_back("CK_System");
e->items_.push_back("CK_Friend");
e->items_.push_back("CK_GM");
e->items_.push_back("CK_Guild");
e->items_.push_back("CK_Max");
}
EnumInfo enumChatKind("ChatKind", initFuncChatKind);
//=============================================================
static void initFuncBattlePosition(EnumInfo* e)
{
e->items_.push_back("BP_None");
e->items_.push_back("BP_Down0");
e->items_.push_back("BP_Down1");
e->items_.push_back("BP_Down2");
e->items_.push_back("BP_Down3");
e->items_.push_back("BP_Down4");
e->items_.push_back("BP_Down5");
e->items_.push_back("BP_Down6");
e->items_.push_back("BP_Down7");
e->items_.push_back("BP_Down8");
e->items_.push_back("BP_Down9");
e->items_.push_back("BP_Up0");
e->items_.push_back("BP_Up1");
e->items_.push_back("BP_Up2");
e->items_.push_back("BP_Up3");
e->items_.push_back("BP_Up4");
e->items_.push_back("BP_Up5");
e->items_.push_back("BP_Up6");
e->items_.push_back("BP_Up7");
e->items_.push_back("BP_Up8");
e->items_.push_back("BP_Up9");
e->items_.push_back("BP_Max");
}
EnumInfo enumBattlePosition("BattlePosition", initFuncBattlePosition);
//=============================================================
static void initFuncBattleJudgeType(EnumInfo* e)
{
e->items_.push_back("BJT_None");
e->items_.push_back("BJT_Continue");
e->items_.push_back("BJT_Win");
e->items_.push_back("BJT_Lose");
}
EnumInfo enumBattleJudgeType("BattleJudgeType", initFuncBattleJudgeType);
//=============================================================
static void initFuncOrderParamType(EnumInfo* e)
{
e->items_.push_back("OPT_None");
e->items_.push_back("OPT_BabyId");
e->items_.push_back("OPT_Unite");
e->items_.push_back("OPT_Huwei");
e->items_.push_back("OPT_IsNo");
e->items_.push_back("OPT_Max");
}
EnumInfo enumOrderParamType("OrderParamType", initFuncOrderParamType);
//=============================================================
static void initFuncOrderStatus(EnumInfo* e)
{
e->items_.push_back("OS_None");
e->items_.push_back("OS_ActiveOk");
e->items_.push_back("OS_RunawayOk");
e->items_.push_back("OS_FangBaobao");
e->items_.push_back("OS_ShouBaobao");
e->items_.push_back("OS_Weapon");
e->items_.push_back("OS_Zhuachong");
e->items_.push_back("OS_Flee");
e->items_.push_back("OS_Summon");
}
EnumInfo enumOrderStatus("OrderStatus", initFuncOrderStatus);
//=============================================================
static void initFuncAIEvent(EnumInfo* e)
{
e->items_.push_back("ME_None");
e->items_.push_back("ME_Born");
e->items_.push_back("ME_Deadth");
e->items_.push_back("ME_AttackGo");
e->items_.push_back("ME_SkillGO");
e->items_.push_back("ME_Update");
e->items_.push_back("ME_Max");
}
EnumInfo enumAIEvent("AIEvent", initFuncAIEvent);
//=============================================================
static void initFuncSyncIPropType(EnumInfo* e)
{
e->items_.push_back("SPT_None");
e->items_.push_back("SPT_Player");
e->items_.push_back("SPT_Baby");
e->items_.push_back("SPT_Employee");
e->items_.push_back("SPT_Max");
}
EnumInfo enumSyncIPropType("SyncIPropType", initFuncSyncIPropType);
//=============================================================
static void initFuncBoxType(EnumInfo* e)
{
e->items_.push_back("BX_None");
e->items_.push_back("BX_Normal");
e->items_.push_back("BX_Blue");
e->items_.push_back("BX_Glod");
}
EnumInfo enumBoxType("BoxType", initFuncBoxType);
//=============================================================
static void initFuncQuestKind(EnumInfo* e)
{
e->items_.push_back("QK_None");
e->items_.push_back("QK_Main");
e->items_.push_back("QK_Daily");
e->items_.push_back("QK_Profession");
e->items_.push_back("QK_Sub");
e->items_.push_back("QK_Tongji");
e->items_.push_back("QK_Copy");
e->items_.push_back("QK_Wishing");
e->items_.push_back("QK_Guild");
e->items_.push_back("QK_Rand");
e->items_.push_back("QK_Sub1");
e->items_.push_back("QK_Max");
}
EnumInfo enumQuestKind("QuestKind", initFuncQuestKind);
//=============================================================
static void initFuncQuestType(EnumInfo* e)
{
e->items_.push_back("QT_None");
e->items_.push_back("QT_Dialog");
e->items_.push_back("QT_Battle");
e->items_.push_back("QT_Kill");
e->items_.push_back("QT_KillAI");
e->items_.push_back("QT_Item");
e->items_.push_back("QT_Profession");
e->items_.push_back("QT_Other");
e->items_.push_back("QT_GiveItem");
e->items_.push_back("QT_GiveBaby");
e->items_.push_back("QT_Max");
}
EnumInfo enumQuestType("QuestType", initFuncQuestType);
//=============================================================
static void initFuncRequireType(EnumInfo* e)
{
e->items_.push_back("RT_Nil");
}
EnumInfo enumRequireType("RequireType", initFuncRequireType);
//=============================================================
static void initFuncTeamType(EnumInfo* e)
{
e->items_.push_back("TT_None");
e->items_.push_back("TT_MainQuest");
e->items_.push_back("TT_TongjiQuest");
e->items_.push_back("TT_Daochang");
e->items_.push_back("TT_CaoMoGu");
e->items_.push_back("TT_Zhanchang");
e->items_.push_back("TT_Hero");
e->items_.push_back("TT_Pet");
e->items_.push_back("TT_JJC");
e->items_.push_back("TT_ShuaGuai");
e->items_.push_back("TT_Copy");
e->items_.push_back("TT_Max");
}
EnumInfo enumTeamType("TeamType", initFuncTeamType);
//=============================================================
static void initFuncStateType(EnumInfo* e)
{
e->items_.push_back("ST_None");
e->items_.push_back("ST_Normal");
e->items_.push_back("ST_Defense");
e->items_.push_back("ST_Dodge");
e->items_.push_back("ST_ActionAbsorb");
e->items_.push_back("ST_MagicAbsorb");
e->items_.push_back("ST_Shield");
e->items_.push_back("ST_ActionBounce");
e->items_.push_back("ST_MagicBounce");
e->items_.push_back("ST_ActionInvalid");
e->items_.push_back("ST_MagicInvalid");
e->items_.push_back("ST_Defend");
e->items_.push_back("ST_NoDodge");
e->items_.push_back("ST_Poison");
e->items_.push_back("ST_Basilisk");
e->items_.push_back("ST_Sleep");
e->items_.push_back("ST_Chaos");
e->items_.push_back("ST_Drunk");
e->items_.push_back("ST_Forget");
e->items_.push_back("ST_BeatBack");
e->items_.push_back("ST_Recover");
e->items_.push_back("ST_StrongRecover");
e->items_.push_back("ST_GroupRecover");
e->items_.push_back("ST_MagicDef");
e->items_.push_back("ST_Max");
}
EnumInfo enumStateType("StateType", initFuncStateType);
//=============================================================
static void initFuncSceneType(EnumInfo* e)
{
e->items_.push_back("SCT_None");
e->items_.push_back("SCT_New");
e->items_.push_back("SCT_Home");
e->items_.push_back("SCT_Scene");
e->items_.push_back("SCT_City");
e->items_.push_back("SCT_Bairen");
e->items_.push_back("SCT_Instance");
e->items_.push_back("SCT_AlonePK");
e->items_.push_back("SCT_TeamPK");
e->items_.push_back("SCT_GuildHome");
e->items_.push_back("SCT_GuildBattleScene");
e->items_.push_back("SCT_Max");
}
EnumInfo enumSceneType("SceneType", initFuncSceneType);
//=============================================================
static void initFuncBornType(EnumInfo* e)
{
e->items_.push_back("BOT_None");
e->items_.push_back("BOT_BornPos");
e->items_.push_back("BOT_Cached");
e->items_.push_back("BOT_FromSceneEntry");
e->items_.push_back("BOT_FromMazeEntry");
e->items_.push_back("BOT_NormalMazeEntry");
e->items_.push_back("BOT_Max");
}
EnumInfo enumBornType("BornType", initFuncBornType);
//=============================================================
static void initFuncWeaponActionType(EnumInfo* e)
{
e->items_.push_back("WAT_None");
e->items_.push_back("WAT_Chop");
e->items_.push_back("WAT_Stab");
e->items_.push_back("WAT_Bow");
e->items_.push_back("WAT_Throw");
e->items_.push_back("WAT_Max");
}
EnumInfo enumWeaponActionType("WeaponActionType", initFuncWeaponActionType);
//=============================================================
static void initFuncSceneOutpuType(EnumInfo* e)
{
e->items_.push_back("SOT_None");
e->items_.push_back("SOT_PVE");
e->items_.push_back("SOT_PVP");
e->items_.push_back("SOT_Max");
}
EnumInfo enumSceneOutpuType("SceneOutpuType", initFuncSceneOutpuType);
//=============================================================
static void initFuncTogetherStateType(EnumInfo* e)
{
e->items_.push_back("TST_None");
e->items_.push_back("TST_Self");
e->items_.push_back("TST_Enemy");
e->items_.push_back("TST_Max");
}
EnumInfo enumTogetherStateType("TogetherStateType", initFuncTogetherStateType);
//=============================================================
static void initFuncGuideAimType(EnumInfo* e)
{
e->items_.push_back("GAT_None");
e->items_.push_back("GAT_FirstAchievement");
e->items_.push_back("GAT_FirstSkill");
e->items_.push_back("GAT_FirstLevelSkill");
e->items_.push_back("GAT_FirstQuest");
e->items_.push_back("GAT_DialogUI");
e->items_.push_back("GAT_MainTeamBtn");
e->items_.push_back("GAT_MainTaskBtn");
e->items_.push_back("GAT_QuestMiniFirst");
e->items_.push_back("GAT_QuestMiniSecond");
e->items_.push_back("GAT_QuestMiniThird");
e->items_.push_back("GAT_MainCrystal");
e->items_.push_back("GAT_MainCastle");
e->items_.push_back("GAT_MainJJC");
e->items_.push_back("GAT_OfflineJJC");
e->items_.push_back("GAT_OfflineJJC4");
e->items_.push_back("GAT_WorldMapER");
e->items_.push_back("GAT_WorldMapFL");
e->items_.push_back("GAT_WorldMapWorldBtn");
e->items_.push_back("GAT_MiniMap");
e->items_.push_back("GAT_TeamCreateBtn");
e->items_.push_back("GAT_TeamWorldMapBtn");
e->items_.push_back("GAT_FirstPartner_PosUI");
e->items_.push_back("GAT_FreeLootPartner");
e->items_.push_back("GAT_FriendAddBtn");
e->items_.push_back("GAT_PartnerShowCancel");
e->items_.push_back("GAT_PartnerPositionTab");
e->items_.push_back("GAT_PartnerDetailBaseTab");
e->items_.push_back("GAT_PartnerDetailBodySlot");
e->items_.push_back("GAT_PartnerDetailEquipBtn");
e->items_.push_back("GAT_PartnerDetailBaseFirstSkill");
e->items_.push_back("GAT_PartnerDetailBaseSkillLvUpBtn");
e->items_.push_back("GAT_LearnSkillAttackSkillTab");
e->items_.push_back("GAT_LearnSkillAttackMagicTab");
e->items_.push_back("GAT_LearnSkillStatusMagicTab");
e->items_.push_back("GAT_LearnSkillAidSkillTab");
e->items_.push_back("GAT_LearnSkillBtn");
e->items_.push_back("GAT_FirstLearningBabySkill");
e->items_.push_back("GAT_FirstLearningBabySkill_BabyList");
e->items_.push_back("GAT_ThirdLearningBabySkill_SkillSlot");
e->items_.push_back("GAT_BabySkillLearningBtn");
e->items_.push_back("GAT_MessageBoxOkBtn");
e->items_.push_back("GAT_MainReturn");
e->items_.push_back("GAT_MainBag");
e->items_.push_back("GAT_MainBagTipUseItem");
e->items_.push_back("GAT_MainbagTipEquip");
e->items_.push_back("GAT_MainBagFuwenTab");
e->items_.push_back("GAT_MainBagFuwenFirstItem");
e->items_.push_back("GAT_MainBagFuwenTipsCombieBtn");
e->items_.push_back("GAT_MainBagFuwenTipsInsertBtn");
e->items_.push_back("GAT_MainFuwenUICombieBtn");
e->items_.push_back("GAT_MainFuwenCloseBtn");
e->items_.push_back("GAT_MainSkill");
e->items_.push_back("GAT_MainMake");
e->items_.push_back("GAT_MainMakeSword");
e->items_.push_back("GAT_MainMakeAxe");
e->items_.push_back("GAT_MainMakeStick");
e->items_.push_back("GAT_MainMakeBow");
e->items_.push_back("GAT_MainMakeCompoundBtn");
e->items_.push_back("GAT_MainMakeLevel10");
e->items_.push_back("GAT_MainMakeSubFirst");
e->items_.push_back("GAT_MainMakeSubSecond");
e->items_.push_back("GAT_MainMakeSubThird");
e->items_.push_back("GAT_MainMakeGemBtn");
e->items_.push_back("GAT_MainMakeGemClose");
e->items_.push_back("GAT_MainMakeGemFirst");
e->items_.push_back("GAT_MainBaby");
e->items_.push_back("GAT_MainBabyStatusBtn");
e->items_.push_back("GAT_MainBabyPropertyBtn");
e->items_.push_back("GAT_MainBabyPropertyContainer");
e->items_.push_back("GAT_MainBabyPropertyConfirm");
e->items_.push_back("GAT_MainBabyClose");
e->items_.push_back("GAT_MainMagic");
e->items_.push_back("GAT_MainMagicLevelFirst");
e->items_.push_back("GAT_MainMagicLevelBtn");
e->items_.push_back("GAT_MainFriend");
e->items_.push_back("GAT_MainPartner");
e->items_.push_back("GAT_MainSetting");
e->items_.push_back("GAT_MainRecharge");
e->items_.push_back("GAT_MainActivity");
e->items_.push_back("GAT_MainPlayerInfo");
e->items_.push_back("GAT_MainPlayerInfoStatusBtn");
e->items_.push_back("GAT_MainPlayerInfoPropertyBtn");
e->items_.push_back("GAT_MainPlayerInfoPropertyContainer");
e->items_.push_back("GAT_MainPlayerInfoPropertyConfirm");
e->items_.push_back("GAT_MainPlayerInfoClose");
e->items_.push_back("GAT_MainJiubaHouse");
e->items_.push_back("GAT_MainStick");
e->items_.push_back("GAT_MainAchievement");
e->items_.push_back("GAT_MainRaise");
e->items_.push_back("GAT_MainFamily");
e->items_.push_back("GAT_BattleAttack");
e->items_.push_back("GAT_BattleSkill");
e->items_.push_back("GAT_BattleBabySkill");
e->items_.push_back("GAT_BattleDeference");
e->items_.push_back("GAT_BattleChangePosition");
e->items_.push_back("GAT_BattleAuto");
e->items_.push_back("GAT_BattleBag");
e->items_.push_back("GAT_BattleCatch");
e->items_.push_back("GAT_BattleBaby");
e->items_.push_back("GAT_BattleRunaway");
e->items_.push_back("GAT_BattlePlayerInfo");
e->items_.push_back("GAT_BattleRewardClose");
e->items_.push_back("GAT_FirstAutoSkill");
e->items_.push_back("GAT_PlayerAuto");
e->items_.push_back("GAT_Max");
}
EnumInfo enumGuideAimType("GuideAimType", initFuncGuideAimType);
//=============================================================
static void initFuncScriptGameEvent(EnumInfo* e)
{
e->items_.push_back("SGE_None");
e->items_.push_back("SGE_MainPanelOpen");
e->items_.push_back("SGE_FirstEnterMainScene");
e->items_.push_back("SGE_EnterScene");
e->items_.push_back("SGE_EnterMainScene");
e->items_.push_back("SGE_Talk_FirstEnterMainScene");
e->items_.push_back("SGE_Talk_BattleReady");
e->items_.push_back("SGE_Talk_ActorReady");
e->items_.push_back("SGE_Talk_BattleOver");
e->items_.push_back("SGE_WorldMapOpen");
e->items_.push_back("SGE_WorldMapToWorld");
e->items_.push_back("SGE_MiniMapOpen");
e->items_.push_back("SGE_TeamUIOpen");
e->items_.push_back("SGE_AchievementUIOpen");
e->items_.push_back("SGE_AchievementReceived");
e->items_.push_back("SGE_TeamUISelectMapOpen");
e->items_.push_back("SGE_PartnerForBattle");
e->items_.push_back("SGE_PartnerPositionTabShow");
e->items_.push_back("SGE_PartnerListTabShow");
e->items_.push_back("SGE_PartnerDetailUIOpen");
e->items_.push_back("SGE_PartnerDetailBaseOpen");
e->items_.push_back("SGE_PartnerDetailEquipClick");
e->items_.push_back("SGE_PartnerDetailEquipSucc");
e->items_.push_back("SGE_PartnerDetailBaseSkillOpen");
e->items_.push_back("SGE_ParnterDetailBaseSkillLvUpSucc");
e->items_.push_back("SGE_MainMakeSub");
e->items_.push_back("SGE_MainMakeSubDetail");
e->items_.push_back("SGE_MainMakeItemOk");
e->items_.push_back("SGE_MainMakeGemUI");
e->items_.push_back("SGE_MainMakeGemOk");
e->items_.push_back("SGE_MainMakeGemUIClose");
e->items_.push_back("SGE_MainTeamUI");
e->items_.push_back("SGE_MainTaskUI");
e->items_.push_back("SGE_MainTaskFlushOk");
e->items_.push_back("SGE_JJCEntryUI");
e->items_.push_back("SGE_OfflineJJCUI");
e->items_.push_back("SGE_BagItemDoubleClick");
e->items_.push_back("SGE_BagFuwenOpen");
e->items_.push_back("SGE_BagFuwenCombieUI");
e->items_.push_back("SGE_BagFuwenCombieSuccess");
e->items_.push_back("SGE_BagFuwenClickTipsInsertBtn");
e->items_.push_back("SGE_FuwenUIClose");
e->items_.push_back("SGE_NpcDialogBegin");
e->items_.push_back("SGE_NpcRenwuUIOpen");
e->items_.push_back("SGE_NpcRenwuPreAccept");
e->items_.push_back("SGE_NpcRenwuAccept");
e->items_.push_back("SGE_NpcRenwuSubmit");
e->items_.push_back("SGE_EnterNPCBattle");
e->items_.push_back("SGE_EnterBattle");
e->items_.push_back("SGE_MessageBoxOpen");
e->items_.push_back("SGE_BeforeEnterBattle");
e->items_.push_back("SGE_PlayerLevelUp");
e->items_.push_back("SGE_PlayerUIOpen");
e->items_.push_back("SGE_PlayerUIStatusSwitch");
e->items_.push_back("SGE_PlayerUIPropertySwitch");
e->items_.push_back("SGE_PlayerUIAddPoint");
e->items_.push_back("SGE_PlayerUIPropertyConfirmClick");
e->items_.push_back("SGE_PlayerUIClose");
e->items_.push_back("SGE_BabyLevelUp");
e->items_.push_back("SGE_BabyUIOpen");
e->items_.push_back("SGE_BabyUIStatusSwitch");
e->items_.push_back("SGE_BabyUIPropertySwitch");
e->items_.push_back("SGE_BabyUIAddPoint");
e->items_.push_back("SGE_BabyUIPropertyConfirmClick");
e->items_.push_back("SGE_BabyUIClose");
e->items_.push_back("SGE_BattleTurn");
e->items_.push_back("SGE_ExitBattle");
e->items_.push_back("SGE_SelectTarget");
e->items_.push_back("SGE_SelectTargetOk");
e->items_.push_back("SGE_BabySelectSkill");
e->items_.push_back("SGE_SelectSkill");
e->items_.push_back("SGE_SelectSkillLevel");
e->items_.push_back("SGE_StickDisplay");
e->items_.push_back("SGE_StickTouchDown");
e->items_.push_back("SGE_StickTouchMove");
e->items_.push_back("SGE_StickTouchUp");
e->items_.push_back("SGE_BattleOverRewardOpen");
e->items_.push_back("SGE_BattleOverRewardClose");
e->items_.push_back("SGE_CheckState");
e->items_.push_back("SGE_TogetherState");
e->items_.push_back("SGE_BagTipOpen");
e->items_.push_back("SGE_UseItem");
e->items_.push_back("SGE_GainItem");
e->items_.push_back("SGE_EquipItem");
e->items_.push_back("SGE_MainLearningUI");
e->items_.push_back("SGE_MainLearningClickTab");
e->items_.push_back("SGE_MainLearningOneSkillClick");
e->items_.push_back("SGE_MainLearningSkillOk");
e->items_.push_back("SGE_MainMakeUIOpen");
e->items_.push_back("SGE_MainMagicTipClose");
e->items_.push_back("SGE_MainMagicUIOpen");
e->items_.push_back("SGE_MainMagicLevelUp");
e->items_.push_back("SGE_MainMagicFirstClick");
e->items_.push_back("SGE_PartnerShowUI");
e->items_.push_back("SGE_PartnerHideUI");
e->items_.push_back("SGE_BabyLearningSkillUI");
e->items_.push_back("SGE_BabyLearningSkill_BabyListUI");
e->items_.push_back("SGE_BabyLearningSkill_BabySkillUI");
e->items_.push_back("SGE_BabyLearningSkillOk");
e->items_.push_back("SGE_ClickBabyLearningSkill");
e->items_.push_back("SGE_ClickMiniQuest");
e->items_.push_back("SGE_ClickMainBag");
e->items_.push_back("SGE_ClickMainSkill");
e->items_.push_back("SGE_ClickMainBaby");
e->items_.push_back("SGE_ClickMainFriend");
e->items_.push_back("SGE_ClickMainPartner");
e->items_.push_back("SGE_ClickMainSetting");
e->items_.push_back("SGE_ClickMainRecharge");
e->items_.push_back("SGE_ClickMainActivity");
e->items_.push_back("SGE_ClickMainInfo");
e->items_.push_back("SGE_ClickBattleAttack");
e->items_.push_back("SGE_ClickBattleSkill");
e->items_.push_back("SGE_ClickBattleBabySkill");
e->items_.push_back("SGE_ClickBattleDeference");
e->items_.push_back("SGE_ClickBattleChangePosition");
e->items_.push_back("SGE_ClickBattleAuto");
e->items_.push_back("SGE_ClickBattleBag");
e->items_.push_back("SGE_ClickBattleBaby");
e->items_.push_back("SGE_ClickBattleRunaway");
e->items_.push_back("SGE_ClickBattleInfo");
e->items_.push_back("SGE_ClickAddFriendBtn");
e->items_.push_back("SGE_ClickMainFamily");
e->items_.push_back("SGE_ClickRaiseUpBtn");
e->items_.push_back("SGE_UseItemOk");
e->items_.push_back("SGE_CheckBuff");
e->items_.push_back("SGE_PlayerPropUpdate");
e->items_.push_back("SGE_NpcTalked");
e->items_.push_back("SGE_EnterCopy");
e->items_.push_back("SGE_PlayerAutoOrder");
e->items_.push_back("SGE_OpenAutoPanel");
e->items_.push_back("SGE_SenseEnter2");
e->items_.push_back("SGE_WaitTalk");
e->items_.push_back("SGE_SenseTalked");
e->items_.push_back("SGE_ExitSense");
e->items_.push_back("SGE_Max");
}
EnumInfo enumScriptGameEvent("ScriptGameEvent", initFuncScriptGameEvent);
//=============================================================
static void initFuncSenseActorType(EnumInfo* e)
{
e->items_.push_back("SAT_Guard");
e->items_.push_back("SAT_Ambassdor");
e->items_.push_back("SAT_King");
e->items_.push_back("SAT_Yingzi");
e->items_.push_back("SAT_VillageKing");
e->items_.push_back("SAT_Archor");
e->items_.push_back("SAT_Axe");
e->items_.push_back("SAT_Sage");
e->items_.push_back("SAT_Mage");
e->items_.push_back("SAT_Girl");
e->items_.push_back("SAT_AllMonster");
}
EnumInfo enumSenseActorType("SenseActorType", initFuncSenseActorType);
//=============================================================
static void initFuncGameEventType(EnumInfo* e)
{
e->items_.push_back("GET_None");
e->items_.push_back("GET_Online");
e->items_.push_back("GET_Offline");
e->items_.push_back("GET_CreatePlayerOK");
e->items_.push_back("GET_Kill");
e->items_.push_back("GET_Die");
e->items_.push_back("GET_LevelUp");
e->items_.push_back("GET_Flee");
e->items_.push_back("GET_LearnSkill");
e->items_.push_back("GET_SkillLevelUp");
e->items_.push_back("GET_UseSkill");
e->items_.push_back("GET_EnterJJC");
e->items_.push_back("GET_MakeEquip");
e->items_.push_back("GET_RecruitEmp");
e->items_.push_back("GET_EmployeeEvolve");
e->items_.push_back("GET_AddBaby");
e->items_.push_back("GET_DelBaby");
e->items_.push_back("GET_CatchBaby");
e->items_.push_back("GET_DepositBaby");
e->items_.push_back("GET_BabyLevelUp");
e->items_.push_back("GET_ResetBaby");
e->items_.push_back("GET_BabyNo");
e->items_.push_back("GET_BabyLearnSkill");
e->items_.push_back("GET_AddSkillExp");
e->items_.push_back("GET_HalfHourAgo");
e->items_.push_back("GET_Sign");
e->items_.push_back("GET_BattleChangeProp");
e->items_.push_back("GET_BattleOver");
e->items_.push_back("GET_TalkNpc");
e->items_.push_back("GET_Activity");
e->items_.push_back("GET_PvR");
e->items_.push_back("GET_JJC");
e->items_.push_back("GET_Challenge");
e->items_.push_back("GET_Zhuanpan");
e->items_.push_back("GET_Richang");
e->items_.push_back("GET_Pet");
e->items_.push_back("GET_Tongji");
e->items_.push_back("GET_Babyintensify");
e->items_.push_back("GET_CreateGuild");
e->items_.push_back("GET_JoinGuild");
e->items_.push_back("GET_GuildBattleWin");
e->items_.push_back("GET_GuildBattleLose");
e->items_.push_back("GET_OpenGuildBattle");
e->items_.push_back("GET_CloseGuildBattle");
e->items_.push_back("GET_OpenGuildDemonInvaded");
e->items_.push_back("GET_CloseGuildDemonInvaded");
e->items_.push_back("GET_OpenGuildLeaderInvaded");
e->items_.push_back("GET_CloseGuildLeaderInvaded");
e->items_.push_back("GET_Exam");
e->items_.push_back("GET_Wish");
e->items_.push_back("GET_ChangeMoney");
e->items_.push_back("GET_ChangeDiamond");
e->items_.push_back("GET_ChangeMagicCurrency");
e->items_.push_back("GET_WearEquip");
e->items_.push_back("GET_AddFleeProp");
e->items_.push_back("GET_Gather");
e->items_.push_back("GET_AddFriend");
e->items_.push_back("GET_ExtendStorage");
e->items_.push_back("GET_FinishAch");
e->items_.push_back("GET_AddTeamMemberCondition");
e->items_.push_back("GET_Shenqishengji");
e->items_.push_back("GET_NewServer");
e->items_.push_back("GET_Recharge");
e->items_.push_back("GET_PhoneNumber");
e->items_.push_back("GET_ChangeProfession");
e->items_.push_back("GET_BagFullSendMail");
e->items_.push_back("GET_WearFuwen");
e->items_.push_back("GET_Max");
}
EnumInfo enumGameEventType("GameEventType", initFuncGameEventType);
//=============================================================
static void initFuncSneakAttackType(EnumInfo* e)
{
e->items_.push_back("SAT_None");
e->items_.push_back("SAT_SneakAttack");
e->items_.push_back("SAT_SurpriseAttack");
e->items_.push_back("SAT_Max");
}
EnumInfo enumSneakAttackType("SneakAttackType", initFuncSneakAttackType);
//=============================================================
static void initFuncShopType(EnumInfo* e)
{
e->items_.push_back("SIT_None");
e->items_.push_back("SIT_FirstRecharge");
e->items_.push_back("SIT_Recharge");
e->items_.push_back("SIT_Shop");
e->items_.push_back("SIT_EmployeeShop");
e->items_.push_back("SIT_VIP");
e->items_.push_back("SIT_Fund");
e->items_.push_back("SIT_Giftbag");
e->items_.push_back("SIT_CourseGiftBag");
e->items_.push_back("SIT_Equip");
e->items_.push_back("SIT_Max");
}
EnumInfo enumShopType("ShopType", initFuncShopType);
//=============================================================
static void initFuncShopPayType(EnumInfo* e)
{
e->items_.push_back("SPT_Nil");
e->items_.push_back("SPT_RMB");
e->items_.push_back("SPT_Diamond");
e->items_.push_back("SPT_MagicCurrency");
e->items_.push_back("SPT_Gold");
}
EnumInfo enumShopPayType("ShopPayType", initFuncShopPayType);
//=============================================================
static void initFuncGuidePointerRotateType(EnumInfo* e)
{
e->items_.push_back("GPRT_None");
e->items_.push_back("GPRT_R45");
e->items_.push_back("GPRT_R90");
e->items_.push_back("GPRT_R135");
e->items_.push_back("GPRT_R180");
e->items_.push_back("GPRT_R225");
e->items_.push_back("GPRT_R270");
e->items_.push_back("GPRT_R315");
e->items_.push_back("GPRT_Max");
}
EnumInfo enumGuidePointerRotateType("GuidePointerRotateType", initFuncGuidePointerRotateType);
//=============================================================
static void initFuncNpcType(EnumInfo* e)
{
e->items_.push_back("NT_None");
e->items_.push_back("NT_Normal");
e->items_.push_back("NT_Tongji");
e->items_.push_back("NT_SinglePK");
e->items_.push_back("NT_TeamPK");
e->items_.push_back("NT_Mogu");
e->items_.push_back("NT_Xiji");
e->items_.push_back("NT_Caiji1");
e->items_.push_back("NT_Caiji2");
e->items_.push_back("NT_Caiji3");
e->items_.push_back("NT_Max");
}
EnumInfo enumNpcType("NpcType", initFuncNpcType);
//=============================================================
static void initFuncOpenSubSystemFlag(EnumInfo* e)
{
e->items_.push_back("OSSF_None");
e->items_.push_back("OSSF_Skill");
e->items_.push_back("OSSF_Baby");
e->items_.push_back("OSSF_Friend");
e->items_.push_back("OSSF_EmployeeGet");
e->items_.push_back("OSSF_EmployeeList");
e->items_.push_back("OSSF_EmployeePosition");
e->items_.push_back("OSSF_EmployeeEquip");
e->items_.push_back("OSSF_Bar");
e->items_.push_back("OSSF_Castle");
e->items_.push_back("OSSF_JJC");
e->items_.push_back("OSSF_PVPJJC");
e->items_.push_back("OSSF_Make");
e->items_.push_back("OSSF_Hundred");
e->items_.push_back("OSSF_Activity");
e->items_.push_back("OSSF_Handbook");
e->items_.push_back("OSSF_EveryTask");
e->items_.push_back("OSSF_Achieve");
e->items_.push_back("OSSF_Rank");
e->items_.push_back("OSSF_OnKyTalk");
e->items_.push_back("OSSF_Setting");
e->items_.push_back("OSSF_Shop");
e->items_.push_back("OSSF_DoubleExp");
e->items_.push_back("OSSF_Family");
e->items_.push_back("OSSF_AuctionHouse");
e->items_.push_back("OSSF_BabyLeranSkill");
e->items_.push_back("OSSF_MagicItem");
e->items_.push_back("OSSF_EmployeePos10");
e->items_.push_back("OSSF_EmployeePos15");
e->items_.push_back("OSSF_EmployeePos20");
e->items_.push_back("OSSF_Guid");
e->items_.push_back("OSSF_Team");
e->items_.push_back("OSSF_choujiang");
e->items_.push_back("OSSF_Cystal");
e->items_.push_back("OSSF_PetEquip");
e->items_.push_back("OSSF_Max");
}
EnumInfo enumOpenSubSystemFlag("OpenSubSystemFlag", initFuncOpenSubSystemFlag);
//=============================================================
static void initFuncAchievementType(EnumInfo* e)
{
e->items_.push_back("AT_None");
e->items_.push_back("AT_EarnConis");
e->items_.push_back("AT_SpendMoney");
e->items_.push_back("AT_SpendDiamond");
e->items_.push_back("AT_Recharge");
e->items_.push_back("AT_RoleLevel");
e->items_.push_back("AT_PetLevel");
e->items_.push_back("AT_AttackLevel");
e->items_.push_back("AT_DefenseLevel");
e->items_.push_back("AT_AgileLevel");
e->items_.push_back("AT_WearCrystal");
e->items_.push_back("AT_WearAccessories");
e->items_.push_back("AT_TotalDamage");
e->items_.push_back("AT_TotalTreatment");
e->items_.push_back("AT_HasSkillNum");
e->items_.push_back("AT_BabySkill");
e->items_.push_back("AT_CatchPet");
e->items_.push_back("AT_RecruitPartner");
e->items_.push_back("AT_PartnerCard");
e->items_.push_back("AT_PartnersUpgradeGreen");
e->items_.push_back("AT_PartnersUpgradeBlue");
e->items_.push_back("AT_PartnersUpgradePurple");
e->items_.push_back("AT_PartnersUpgradeGold");
e->items_.push_back("AT_PartnersUpgradeOrangle");
e->items_.push_back("AT_PartnersUpgradePink");
e->items_.push_back("AT_QualifyingAdvanced");
e->items_.push_back("AT_ArenaWin");
e->items_.push_back("AT_KillMonster");
e->items_.push_back("AT_KillBoss");
e->items_.push_back("AT_KillPlayer");
e->items_.push_back("AT_MakeEquipment");
e->items_.push_back("AT_Reward50");
e->items_.push_back("AT_EverydayActivities");
e->items_.push_back("AT_Sign");
e->items_.push_back("AT_Wanted");
e->items_.push_back("AT_Copy30");
e->items_.push_back("AT_Copy40");
e->items_.push_back("AT_Blood");
e->items_.push_back("AT_Magic");
e->items_.push_back("AT_Bag");
e->items_.push_back("AT_PetBag");
e->items_.push_back("AT_GoodMake");
e->items_.push_back("AT_PetIntensive");
e->items_.push_back("AT_PetHuman");
e->items_.push_back("AT_PetInsect");
e->items_.push_back("AT_PetPlant");
e->items_.push_back("AT_PetExtra");
e->items_.push_back("AT_PetDragon");
e->items_.push_back("AT_PetAnimal");
e->items_.push_back("AT_PetFly");
e->items_.push_back("AT_PetUndead");
e->items_.push_back("AT_PetMetal");
e->items_.push_back("AT_Home");
e->items_.push_back("AT_CollectMaterial");
e->items_.push_back("AT_Friend");
e->items_.push_back("AT_Billboard");
e->items_.push_back("AT_OwnConis");
e->items_.push_back("AT_MagicEquip");
e->items_.push_back("AT_RunesLevel");
e->items_.push_back("AT_Max");
}
EnumInfo enumAchievementType("AchievementType", initFuncAchievementType);
//=============================================================
static void initFuncCategoryType(EnumInfo* e)
{
e->items_.push_back("ACH_All");
e->items_.push_back("ACH_Growup");
e->items_.push_back("ACH_Battle");
e->items_.push_back("ACH_Pet");
e->items_.push_back("ACH_Partner");
e->items_.push_back("ACH_Illustrations");
e->items_.push_back("ACH_Max");
}
EnumInfo enumCategoryType("CategoryType", initFuncCategoryType);
//=============================================================
static void initFuncClassifyType(EnumInfo* e)
{
e->items_.push_back("SD_Debris");
e->items_.push_back("SD_Data");
e->items_.push_back("SD_Pet");
e->items_.push_back("SD_Fashion");
e->items_.push_back("SD_Diamond");
e->items_.push_back("SD_1Ji");
e->items_.push_back("SD_2Ji");
}
EnumInfo enumClassifyType("ClassifyType", initFuncClassifyType);
//=============================================================
static void initFuncFunctionalPointType(EnumInfo* e)
{
e->items_.push_back("FPT_None");
e->items_.push_back("FPT_Tongji");
e->items_.push_back("FPT_Mogu");
e->items_.push_back("FPT_Xiji");
e->items_.push_back("FPT_Npc");
e->items_.push_back("FPT_Max");
}
EnumInfo enumFunctionalPointType("FunctionalPointType", initFuncFunctionalPointType);
//=============================================================
static void initFuncActivityType(EnumInfo* e)
{
e->items_.push_back("ACT_None");
e->items_.push_back("ACT_Tongji");
e->items_.push_back("ACT_Mogu");
e->items_.push_back("ACT_Richang");
e->items_.push_back("ACT_Pet");
e->items_.push_back("ACT_AlonePK");
e->items_.push_back("ACT_TeamPK");
e->items_.push_back("ACT_JJC");
e->items_.push_back("ACT_Challenge");
e->items_.push_back("ACT_Exam");
e->items_.push_back("ACT_Copy");
e->items_.push_back("ACT_Xuyuan");
e->items_.push_back("ACT_Family_0");
e->items_.push_back("ACT_Family_1");
e->items_.push_back("ACT_Family_2");
e->items_.push_back("ACT_Family_3");
e->items_.push_back("ACT_Family_4");
e->items_.push_back("ACT_Warrior");
e->items_.push_back("ACT_Money");
e->items_.push_back("ACT_Rand");
e->items_.push_back("ACT_Max");
}
EnumInfo enumActivityType("ActivityType", initFuncActivityType);
//=============================================================
static void initFuncMailType(EnumInfo* e)
{
e->items_.push_back("MT_Normal");
e->items_.push_back("MT_System");
}
EnumInfo enumMailType("MailType", initFuncMailType);
//=============================================================
static void initFuncHelpType(EnumInfo* e)
{
e->items_.push_back("HT_None");
e->items_.push_back("HT_Money");
e->items_.push_back("HT_Diamond");
e->items_.push_back("HT_Role");
e->items_.push_back("HT_Baby");
e->items_.push_back("HT_Employee");
e->items_.push_back("HT_Skill");
e->items_.push_back("HT_Exp");
e->items_.push_back("HT_Magic");
e->items_.push_back("HT_Equip");
}
EnumInfo enumHelpType("HelpType", initFuncHelpType);
//=============================================================
static void initFuncGuildJob(EnumInfo* e)
{
e->items_.push_back("GJ_None");
e->items_.push_back("GJ_People");
e->items_.push_back("GJ_Minister");
e->items_.push_back("GJ_SecretaryHead");
e->items_.push_back("GJ_VicePremier");
e->items_.push_back("GJ_Premier");
e->items_.push_back("GJ_Max");
}
EnumInfo enumGuildJob("GuildJob", initFuncGuildJob);
//=============================================================
static void initFuncModifyListFlag(EnumInfo* e)
{
e->items_.push_back("MLF_Add");
e->items_.push_back("MLF_Delete");
e->items_.push_back("MLF_ChangeOnline");
e->items_.push_back("MLF_ChangeOffline");
e->items_.push_back("MLF_ChangePosition");
e->items_.push_back("MLF_ChangeContribution");
e->items_.push_back("MLF_ChangeLevel");
e->items_.push_back("MLF_ChangeProfession");
e->items_.push_back("MLF_ChangeGuuildBattleCon");
}
EnumInfo enumModifyListFlag("ModifyListFlag", initFuncModifyListFlag);
//=============================================================
static void initFuncGuildBuildingType(EnumInfo* e)
{
e->items_.push_back("GBT_MIN");
e->items_.push_back("GBT_Main");
e->items_.push_back("GBT_Bank");
e->items_.push_back("GBT_Shop");
e->items_.push_back("GBT_Collection");
e->items_.push_back("GBT_Goddess");
e->items_.push_back("GBT_Progenitus");
e->items_.push_back("GBT_MAX");
}
EnumInfo enumGuildBuildingType("GuildBuildingType", initFuncGuildBuildingType);
//=============================================================
static void initFuncSellItemType(EnumInfo* e)
{
e->items_.push_back("SelIT_None");
e->items_.push_back("SelIT_Max");
}
EnumInfo enumSellItemType("SellItemType", initFuncSellItemType);
//=============================================================
static void initFuncDiamondConfigClass(EnumInfo* e)
{
e->items_.push_back("DBT_Type_None");
e->items_.push_back("DBT_Type_Mine_Famu");
e->items_.push_back("DBT_Type_Mine_Caikuang");
e->items_.push_back("DBT_Type_Mine_Zhibu");
e->items_.push_back("DBT_Type_Max");
}
EnumInfo enumDiamondConfigClass("DiamondConfigClass", initFuncDiamondConfigClass);
//=============================================================
static void initFuncDiamondConfigType(EnumInfo* e)
{
e->items_.push_back("DBT_None");
e->items_.push_back("DBT_Day");
e->items_.push_back("DBT_Week");
e->items_.push_back("DBT_Month");
e->items_.push_back("DBT_Max");
}
EnumInfo enumDiamondConfigType("DiamondConfigType", initFuncDiamondConfigType);
//=============================================================
static void initFuncFixType(EnumInfo* e)
{
e->items_.push_back("FT_None");
e->items_.push_back("FT_Money");
e->items_.push_back("FT_Diamond");
e->items_.push_back("FT_Max");
}
EnumInfo enumFixType("FixType", initFuncFixType);
//=============================================================
static void initFuncStorageType(EnumInfo* e)
{
e->items_.push_back("ST_Item");
e->items_.push_back("ST_Baby");
}
EnumInfo enumStorageType("StorageType", initFuncStorageType);
//=============================================================
static void initFuncEmployeesBattleGroup(EnumInfo* e)
{
e->items_.push_back("EBG_None");
e->items_.push_back("EBG_Free");
e->items_.push_back("EBG_GroupOne");
e->items_.push_back("EBG_GroupTwo");
e->items_.push_back("EBG_Max");
}
EnumInfo enumEmployeesBattleGroup("EmployeesBattleGroup", initFuncEmployeesBattleGroup);
//=============================================================
static void initFuncGiftType(EnumInfo* e)
{
e->items_.push_back("GFT_Bug");
e->items_.push_back("GFT_UC1");
e->items_.push_back("GFT_UC2");
e->items_.push_back("GFT_Group");
}
EnumInfo enumGiftType("GiftType", initFuncGiftType);
//=============================================================
static void initFuncGMT_Protocol(EnumInfo* e)
{
e->items_.push_back("GMT_None");
e->items_.push_back("GMT_GMCommand");
e->items_.push_back("GMT_Notice");
e->items_.push_back("GMT_InsertMail");
e->items_.push_back("GMT_QueryPlayer");
e->items_.push_back("GMT_LoginActivity");
e->items_.push_back("GMT_7Days");
e->items_.push_back("GMT_Cards");
e->items_.push_back("GMT_ExtractEmployee");
e->items_.push_back("GMT_ChargeTotal");
e->items_.push_back("GMT_ChargeEvery");
e->items_.push_back("GMT_DiscountStore");
e->items_.push_back("GMT_Foundation");
e->items_.push_back("GMT_LoginTotal");
e->items_.push_back("GMT_OnlineReward");
e->items_.push_back("GMT_HotRole");
e->items_.push_back("GMT_SelfChargeTotal");
e->items_.push_back("GMT_SelfChargeEvery");
e->items_.push_back("GMT_MinGiftBag");
e->items_.push_back("GMT_DoScript");
e->items_.push_back("GNT_MakeOrder");
e->items_.push_back("GMT_Zhuanpan");
e->items_.push_back("GMT_IntegralShop");
e->items_.push_back("GMT_QueryRoleList");
e->items_.push_back("GMT_QueryRMB");
e->items_.push_back("GMT_QueryDia");
e->items_.push_back("GMT_QueryMoney");
e->items_.push_back("GMT_MAX");
}
EnumInfo enumGMT_Protocol("GMT_Protocol", initFuncGMT_Protocol);
//=============================================================
static void initFuncGMCommandType(EnumInfo* e)
{
e->items_.push_back("GMCT_NoTalk");
e->items_.push_back("GMCT_Freeze");
e->items_.push_back("GMCT_Seal");
e->items_.push_back("GMCT_Kick");
e->items_.push_back("GMCT_OpenTalk");
e->items_.push_back("GMCT_Unseal");
e->items_.push_back("GMCT_SkipGuide");
e->items_.push_back("GMCT_AddMoney");
e->items_.push_back("GMCT_AddDiamond");
e->items_.push_back("GMCT_AddExp");
e->items_.push_back("GMCT_OpenGM");
e->items_.push_back("GMCT_CloseGM");
e->items_.push_back("GMCT_DoScript");
e->items_.push_back("GMCT_Max");
}
EnumInfo enumGMCommandType("GMCommandType", initFuncGMCommandType);
//=============================================================
static void initFuncNoticeSendType(EnumInfo* e)
{
e->items_.push_back("NST_Immediately");
e->items_.push_back("NST_Timming");
e->items_.push_back("NST_Loop");
}
EnumInfo enumNoticeSendType("NoticeSendType", initFuncNoticeSendType);
//=============================================================
static void initFuncInsertMailType(EnumInfo* e)
{
e->items_.push_back("IGMT_PlayerId");
e->items_.push_back("IGMT_AllOnline");
e->items_.push_back("IGMT_AllRegist");
}
EnumInfo enumInsertMailType("InsertMailType", initFuncInsertMailType);
//=============================================================
static void initFuncItemContainerType(EnumInfo* e)
{
e->items_.push_back("ICT_EquipContainer");
e->items_.push_back("ICT_BagContainer");
}
EnumInfo enumItemContainerType("ItemContainerType", initFuncItemContainerType);
//=============================================================
static void initFuncUIBehaviorType(EnumInfo* e)
{
e->items_.push_back("UBT_None");
e->items_.push_back("UBT_Bag");
e->items_.push_back("UBT_Baby");
e->items_.push_back("UBT_Employee");
e->items_.push_back("UBT_SkillView");
e->items_.push_back("UBT_SkillLearn");
e->items_.push_back("UBT_Task");
e->items_.push_back("UBT_Make");
e->items_.push_back("UBT_Gather");
e->items_.push_back("UBT_MagicItem");
e->items_.push_back("UBT_Store");
e->items_.push_back("UBT_Help");
e->items_.push_back("UBT_Friend");
e->items_.push_back("UBT_Email");
e->items_.push_back("UBT_Auction");
e->items_.push_back("UBT_Activity");
e->items_.push_back("UBT_SignUp");
e->items_.push_back("UBT_EmployessList");
e->items_.push_back("UBT_EmployessPos");
e->items_.push_back("UBT_EmployessTavern");
e->items_.push_back("UBT_PlayerProperty");
e->items_.push_back("UBT_Max");
}
EnumInfo enumUIBehaviorType("UIBehaviorType", initFuncUIBehaviorType);
//=============================================================
static void initFuncHelpRaiseType(EnumInfo* e)
{
e->items_.push_back("HRT_None");
e->items_.push_back("HRT_PlayerAddProp");
e->items_.push_back("HRT_PlayerResetProp");
e->items_.push_back("HRT_PlayerAddEvolve");
e->items_.push_back("HRT_BabyAddProp");
e->items_.push_back("HRT_BabyReset");
e->items_.push_back("HRT_BabyStr");
e->items_.push_back("HRT_BabySkill");
e->items_.push_back("HRT_BabyChange");
e->items_.push_back("HRT_SkillAuto");
e->items_.push_back("HRT_SkillItem");
e->items_.push_back("HRT_EquipCompound");
e->items_.push_back("HRT_EquipGem");
e->items_.push_back("HRT_EmployeeBuy");
e->items_.push_back("HRT_EmployeePos");
e->items_.push_back("HRT_EmployeeSkill");
e->items_.push_back("HRT_EmployeeEquip");
e->items_.push_back("HRT_EmployeeEvolve");
e->items_.push_back("HRT_MagicLevelUp");
e->items_.push_back("HRT_MagicEvolve");
e->items_.push_back("HRT_Max");
}
EnumInfo enumHelpRaiseType("HelpRaiseType", initFuncHelpRaiseType);
//=============================================================
static void initFuncSceneFilterType(EnumInfo* e)
{
e->items_.push_back("SFT_None");
e->items_.push_back("SFT_Team");
e->items_.push_back("SFT_Friend");
e->items_.push_back("SFT_Guild");
e->items_.push_back("SFT_All");
e->items_.push_back("SFT_Max");
}
EnumInfo enumSceneFilterType("SceneFilterType", initFuncSceneFilterType);
//=============================================================
static void initFuncGatherStateType(EnumInfo* e)
{
e->items_.push_back("GST_None");
e->items_.push_back("GST_Vulgar");
e->items_.push_back("GST_Advanced");
e->items_.push_back("GST_Max");
}
EnumInfo enumGatherStateType("GatherStateType", initFuncGatherStateType);
//=============================================================
static void initFuncWishType(EnumInfo* e)
{
e->items_.push_back("WIT_None");
e->items_.push_back("WIT_Exp");
e->items_.push_back("WIT_Money");
e->items_.push_back("WIT_Baby");
e->items_.push_back("WIT_Employee");
e->items_.push_back("WIT_Max");
}
EnumInfo enumWishType("WishType", initFuncWishType);
//=============================================================
static void initFuncADType(EnumInfo* e)
{
e->items_.push_back("ADT_None");
e->items_.push_back("ADT_7Days");
e->items_.push_back("ADT_Cards");
e->items_.push_back("ADT_ChargeTotal");
e->items_.push_back("ADT_ChargeEvery");
e->items_.push_back("ADT_DiscountStore");
e->items_.push_back("ADT_Foundation");
e->items_.push_back("ADT_LoginTotal");
e->items_.push_back("ADT_OnlineReward");
e->items_.push_back("ADT_HotRole");
e->items_.push_back("ADT_SelfChargeTotal");
e->items_.push_back("ADT_SelfChargeEvery");
e->items_.push_back("ADT_SelfDiscountStore");
e->items_.push_back("ADT_BuyEmployee");
e->items_.push_back("ADT_PhoneNumber");
e->items_.push_back("ADT_Level");
e->items_.push_back("ADT_Sign");
e->items_.push_back("ADT_GiftBag");
e->items_.push_back("ADT_Zhuanpan");
e->items_.push_back("ADT_IntegralShop");
e->items_.push_back("ADT_Max");
}
EnumInfo enumADType("ADType", initFuncADType);
//=============================================================
static void initFuncEmployeeSkillType(EnumInfo* e)
{
e->items_.push_back("EKT_GroupDamage");
e->items_.push_back("EKT_DeadlyDamage");
e->items_.push_back("EKT_BattleTimeLimit");
e->items_.push_back("EKT_Thump");
e->items_.push_back("EKT_SiegeDamage");
e->items_.push_back("EKT_SuperMagic");
e->items_.push_back("EKT_Debuff");
e->items_.push_back("EKT_PhysicalDefense");
e->items_.push_back("EKT_Max");
}
EnumInfo enumEmployeeSkillType("EmployeeSkillType", initFuncEmployeeSkillType);
//=============================================================
static void initFuncEmployeeQuestColor(EnumInfo* e)
{
e->items_.push_back("EQC_White");
e->items_.push_back("EQC_Blue");
e->items_.push_back("EQC_Purple");
e->items_.push_back("EQC_Max");
}
EnumInfo enumEmployeeQuestColor("EmployeeQuestColor", initFuncEmployeeQuestColor);
//=============================================================
static void initFuncEmployeeQuestStatus(EnumInfo* e)
{
e->items_.push_back("EQS_None");
e->items_.push_back("EQS_Running");
e->items_.push_back("EQS_Complate");
}
EnumInfo enumEmployeeQuestStatus("EmployeeQuestStatus", initFuncEmployeeQuestStatus);
//=============================================================
static void initFuncRobotActionType(EnumInfo* e)
{
e->items_.push_back("RAT_None");
e->items_.push_back("RAT_Resting");
e->items_.push_back("RAT_Move");
e->items_.push_back("RAT_QuestMove");
e->items_.push_back("RAT_TeamMove");
e->items_.push_back("RAT_Max");
}
EnumInfo enumRobotActionType("RobotActionType", initFuncRobotActionType);
| [
"heycylc@icloud.com"
] | heycylc@icloud.com |
4b3868b58f4a0a69dcaf2e59140ad0e6859229d0 | d03bf3b5db60d6b2e9183f3072a638dfdb3b24b9 | /PLCSim2016/PLC.cpp | 273c5aae18a429b9f362340c53863751b8e26421 | [] | no_license | gnh1201/plcsim2016 | 1708536e0c85558540e58b2b032f15060b31fb04 | 572f2bfccbcb4dac439ace6b1e56ff4a027fd71e | refs/heads/master | 2022-12-22T23:07:41.229102 | 2022-11-25T16:13:37 | 2022-11-25T16:13:37 | 64,678,021 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,947 | cpp | // PLC.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "PLC.h"
#include "PLCDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CPLCApp
BEGIN_MESSAGE_MAP(CPLCApp, CWinApp)
//{{AFX_MSG_MAP(CPLCApp)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG
ON_COMMAND(ID_HELP, CWinApp::OnHelp)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CPLCApp construction
CPLCApp::CPLCApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
/////////////////////////////////////////////////////////////////////////////
// The one and only CPLCApp object
CPLCApp theApp;
/////////////////////////////////////////////////////////////////////////////
// CPLCApp initialization
BOOL CPLCApp::InitInstance()
{
AfxEnableControlContainer();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need.
#ifdef _AFXDLL
Enable3dControls(); // Call this when using MFC in a shared DLL
#else
Enable3dControlsStatic(); // Call this when linking to MFC statically
#endif
CPLCDlg dlg;
m_pMainWnd = &dlg;
int nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: Place code here to handle when the dialog is
// dismissed with OK
}
else if (nResponse == IDCANCEL)
{
// TODO: Place code here to handle when the dialog is
// dismissed with Cancel
}
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}
| [
"gnh1201@gmail.com"
] | gnh1201@gmail.com |
5eb2dd1381abcb2b295654e071f2bb36aa1d42be | 02c9046641c6b26edaefcf60533a20a536f657ea | /剑指Office二刷/面试题19-正则表达式匹配.cpp | 1686c0539d2b171bfb544fff5ea56818b67bce34 | [] | no_license | Sumelt/Daily-Coding | ed6512c0a50c6f1ca13a5b5b05cdb2c1952bc1ee | 532b319dcec7627f94b61bfad175287612cea88b | refs/heads/master | 2021-07-13T01:19:52.358604 | 2020-05-31T09:42:02 | 2020-05-31T09:42:02 | 148,486,920 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,736 | cpp | /*----------------------------------------------------------------
* @Author: Su
* @Description:
* @Creath Date:
----------------------------------------------------------------*/
#include <iostream>
#include <vector>
#include <cassert>
using namespace std;
class Solution {
private:
const char END = '\0';
bool mathCode( char* str, char* pattern ) {
if( *str == END && *pattern == END )
return true; //匹配全部完成
if( *str != END && *pattern == END )//目标串还未匹配完,模已经匹配完
return false;
//对于串匹配完,而模还未匹配完这种情况是有效的,比如 a ab*
//第二位是*
if( *( pattern + 1 ) == '*' ) {
//这里*str != END要求不越界
if( *str != END && ( *pattern == '.' || *str == *pattern ) )
return
//匹配,一一匹配
mathCode( str + 1, pattern + 2 ) ||
//不匹配,又因为*可以匹配0个字符
mathCode( str, pattern + 2 ) ||
//匹配,又因为*可以匹配多个字符
mathCode( str + 1, pattern );
//不匹配,串不动,模后移动,因为*可以匹配0个字符
else return mathCode( str, pattern + 2 );
}
//第二位不是*
//这里*str != END要求不越界
else if( *str != END && ( *pattern == '.' || *str == *pattern ) )
return mathCode( str + 1, pattern + 1 );
//第二位不是*,同时第一位也不是.
else return false;
}
public:
bool match(char* str, char* pattern) {
if( str == nullptr && pattern == nullptr )
return false;
else return mathCode( str, pattern );
}
};
int main(int argc, char *argv[])
{
return 0;
} | [
"40728261+Sumelt@users.noreply.github.com"
] | 40728261+Sumelt@users.noreply.github.com |
76692cfd622fa79f410f4b57122f284708b445ec | 1b12e6096c47312b67fa6ff223216945d2efb70c | /sandbox/qt/pixmaps/imgfilter/imgfilter.h | 40bab36a0823675263f7eccdaf3624ecdc9ff92c | [
"Apache-2.0"
] | permissive | rboman/progs | 6e3535bc40f78d692f1f63b1a43193deb60d8d24 | 03eea35771e37d4b3111502c002e74014ec65dc3 | refs/heads/master | 2023-09-02T17:12:18.272518 | 2023-08-31T15:40:04 | 2023-08-31T15:40:04 | 32,989,349 | 5 | 2 | Apache-2.0 | 2022-06-22T10:58:38 | 2015-03-27T14:04:01 | MATLAB | UTF-8 | C++ | false | false | 6,484 | h | // Copyright 2019 Romain Boman
//
// 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 <QWidget>
#include <QColor>
#include <iostream>
#include <QHBoxLayout>
#include <QMainWindow>
#include <QImage>
#include <QLabel>
#include <QString>
#include <QAction>
#include <QMenuBar>
#include <QMenu>
#include <QToolBar>
#include "config.h"
class MainWindow : public QMainWindow
{
Q_OBJECT;
QImage *img1;
QImage *img2;
QLabel *lbl1;
QLabel *lbl2;
public:
MainWindow(QWidget *parent = 0)
: QMainWindow(parent), img1(nullptr), img2(nullptr)
{
this->setWindowTitle("Filters");
this->initUI();
}
void initUI()
{
QWidget *centralw = new QWidget();
QHBoxLayout *hbox = new QHBoxLayout(centralw);
QString srcDir = CMAKE_SOURCE_DIR;
std::cout << srcDir.toStdString() << '\n';
QString imgfile = srcDir + "/../snipercat.jpg";
this->img1 = new QImage(imgfile);
this->img2 = new QImage(imgfile);
this->lbl1 = new QLabel(centralw);
this->lbl1->setPixmap(QPixmap::fromImage(*this->img1));
hbox->addWidget(this->lbl1);
this->lbl2 = new QLabel(centralw);
this->lbl2->setPixmap(QPixmap::fromImage(*this->img2));
hbox->addWidget(this->lbl2);
centralw->setLayout(hbox);
this->setCentralWidget(centralw);
// action(s)
QString iconfile = srcDir + "/../../exit.png";
QAction *exitAct = new QAction(QIcon(iconfile), "Exit", this);
// exitAct->setShortcut("Ctrl+Q");
exitAct->setStatusTip("Exit application");
connect(exitAct, &QAction::triggered, this, &QMainWindow::close);
QAction *resetAct = new QAction("Reset", this);
connect(resetAct, &QAction::triggered, this, &MainWindow::reset_image);
QAction *filter1Act = new QAction("Filter 1 - grid", this);
connect(filter1Act, &QAction::triggered, this, &MainWindow::filter1);
QAction *filter2Act = new QAction("Filter 2 - mirror Y", this);
connect(filter2Act, &QAction::triggered, this, &MainWindow::filter2);
QAction *filter3Act = new QAction("Filter 3 - chg colour", this);
connect(filter3Act, &QAction::triggered, this, &MainWindow::filter3);
QAction *filter4Act = new QAction("Filter 4 - blur", this);
connect(filter4Act, &QAction::triggered, this, &MainWindow::filter4);
// menu
QMenuBar *menubar = this->menuBar();
QMenu *fileMenu = menubar->addMenu("&File");
fileMenu->addAction(exitAct);
QMenu *filterMenu = menubar->addMenu("Filters");
filterMenu->addAction(resetAct);
filterMenu->addAction(filter1Act);
filterMenu->addAction(filter2Act);
filterMenu->addAction(filter3Act);
filterMenu->addAction(filter4Act);
// status bar
this->statusBar();
// toolbar
QToolBar *toolbar = this->addToolBar("Exit");
toolbar->addAction(exitAct);
this->setGeometry(300, 300, 350, 250);
this->setWindowTitle("snipercat");
this->show();
}
private:
void update_image()
{
this->lbl2->setPixmap(QPixmap::fromImage(*this->img2));
}
public slots:
void reset_image()
{
std::cout << "reset\n";
*this->img2 = this->img1->copy();
this->update_image();
}
void filter1()
{
std::cout << "filter1 - add grid\n";
*this->img2 = this->img1->copy();
for (int i = 0; i < this->img1->width(); i += 2)
for (int j = 0; j < this->img1->height(); j += 2)
this->img2->setPixelColor(i, j, QColor(255, 0, 0));
this->update_image();
}
void filter2()
{
std::cout << "filter2 - mirror Y\n";
*this->img2 = this->img1->mirrored();
this->update_image();
}
void filter3()
{
std::cout << "filter3 - chg colour\n";
*this->img2 = this->img1->copy();
for (int i = 0; i < this->img1->width(); i += 1)
for (int j = 0; j < this->img1->height(); j += 1)
{
QColor col = this->img1->pixelColor(i, j);
// newcol = col.darker()
// newcol = col.lighter()
// mean = (col.red() + col.green() + col.blue())/3
int mean = col.value();
QColor newcol(mean, mean, mean);
this->img2->setPixelColor(i, j, newcol);
}
this->update_image();
}
void filter4()
{
std::cout << "filter4 - blur\n";
*this->img2 = this->img1->copy();
const int iK = 5;
const int jK = 5;
double K[iK][jK];
for (int i = 0; i < iK; ++i)
for (int j = 0; j < iK; ++j)
K[i][j] = 1.0;
int ni = (iK - 1) / 2;
int nj = (jK - 1) / 2;
for (int i = 0; i < this->img1->width(); i += 1)
for (int j = 0; j < this->img1->height(); j += 1)
{
double r = 0.0;
double g = 0.0;
double b = 0.0;
double np = 0.0;
for (int k = -ni; k < ni + 1; ++k)
for (int l = -nj; l < nj + 1; ++l)
if (this->img1->valid(i + k, j + l))
{
QColor col = this->img1->pixelColor(i + k, j + l);
double w = K[k + ni][l + nj];
r += col.redF() * w;
g += col.greenF() * w;
b += col.blueF() * w;
np += w;
}
r /= np;
g /= np;
b /= np;
QColor newcol;
newcol.setRgbF(r, g, b);
this->img2->setPixelColor(i, j, newcol);
}
this->update_image();
}
};
| [
"romain.boman@gmail.com"
] | romain.boman@gmail.com |
1531074409b1ee765b1087e66964d9374836de1c | ae81fa0bf375bef3c632eae0b673e0b78e17af1d | /Intermediate/Build/Win64/UE4/Inc/SavgaProject/SaveGameData.gen.cpp | 9e58b7adb13b11b71d8d9baf978f95bef1ce1e55 | [
"CC0-1.0"
] | permissive | cagataysarioglu/SavgaProject | d666c396a894eb2059baa2a8d5521a9f8b840b5f | 9da7119c010b2fdb632bbc8816cedf42b4e509e5 | refs/heads/main | 2023-05-01T21:03:41.729185 | 2021-05-23T15:42:37 | 2021-05-23T15:42:37 | 349,444,031 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,198 | cpp | // Copyright Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/GeneratedCppIncludes.h"
#include "SavgaProject/SaveGameData.h"
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable : 4883)
#endif
PRAGMA_DISABLE_DEPRECATION_WARNINGS
void EmptyLinkFunctionForGeneratedCodeSaveGameData() {}
// Cross Module References
SAVGAPROJECT_API UClass* Z_Construct_UClass_USaveGameData_NoRegister();
SAVGAPROJECT_API UClass* Z_Construct_UClass_USaveGameData();
ENGINE_API UClass* Z_Construct_UClass_USaveGame();
UPackage* Z_Construct_UPackage__Script_SavgaProject();
// End Cross Module References
void USaveGameData::StaticRegisterNativesUSaveGameData()
{
}
UClass* Z_Construct_UClass_USaveGameData_NoRegister()
{
return USaveGameData::StaticClass();
}
struct Z_Construct_UClass_USaveGameData_Statics
{
static UObject* (*const DependentSingletons[])();
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[];
#endif
static const FCppClassTypeInfoStatic StaticCppClassTypeInfo;
static const UE4CodeGen_Private::FClassParams ClassParams;
};
UObject* (*const Z_Construct_UClass_USaveGameData_Statics::DependentSingletons[])() = {
(UObject* (*)())Z_Construct_UClass_USaveGame,
(UObject* (*)())Z_Construct_UPackage__Script_SavgaProject,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_USaveGameData_Statics::Class_MetaDataParams[] = {
{ "Comment", "/**\n * \n */" },
{ "IncludePath", "SaveGameData.h" },
{ "ModuleRelativePath", "SaveGameData.h" },
};
#endif
const FCppClassTypeInfoStatic Z_Construct_UClass_USaveGameData_Statics::StaticCppClassTypeInfo = {
TCppClassTypeTraits<USaveGameData>::IsAbstract,
};
const UE4CodeGen_Private::FClassParams Z_Construct_UClass_USaveGameData_Statics::ClassParams = {
&USaveGameData::StaticClass,
nullptr,
&StaticCppClassTypeInfo,
DependentSingletons,
nullptr,
nullptr,
nullptr,
UE_ARRAY_COUNT(DependentSingletons),
0,
0,
0,
0x001000A0u,
METADATA_PARAMS(Z_Construct_UClass_USaveGameData_Statics::Class_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UClass_USaveGameData_Statics::Class_MetaDataParams))
};
UClass* Z_Construct_UClass_USaveGameData()
{
static UClass* OuterClass = nullptr;
if (!OuterClass)
{
UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_USaveGameData_Statics::ClassParams);
}
return OuterClass;
}
IMPLEMENT_CLASS(USaveGameData, 1359938358);
template<> SAVGAPROJECT_API UClass* StaticClass<USaveGameData>()
{
return USaveGameData::StaticClass();
}
static FCompiledInDefer Z_CompiledInDefer_UClass_USaveGameData(Z_Construct_UClass_USaveGameData, &USaveGameData::StaticClass, TEXT("/Script/SavgaProject"), TEXT("USaveGameData"), false, nullptr, nullptr, nullptr);
DEFINE_VTABLE_PTR_HELPER_CTOR(USaveGameData);
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#ifdef _MSC_VER
#pragma warning (pop)
#endif
| [
"sarioglucagatay@gmail.com"
] | sarioglucagatay@gmail.com |
3f273e72e66ff966c0c176213a7933110456b23b | 02ebedcfd6b717648b3fd40fb9cb4990da83c9b2 | /cf/edu47/c.cpp | 090bf1d5e02342e7678e9e3c60ce776f3bcad425 | [] | no_license | RandomVar/ACM | 22570363b0b2a02be8113f3f659d443975bdd2e2 | 1f3c765c88bf5d52c58bde139887d2a98ee88c51 | refs/heads/master | 2021-06-27T12:29:37.456528 | 2019-04-30T02:03:01 | 2019-04-30T02:03:01 | 144,880,431 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,150 | cpp | #include<cstdio>
#include<iostream>
#include<queue>
#include<stack>
#include<cmath>
#include<cstring>
#include<string>
#include<map>
#include<sstream>
#include<algorithm>
#define pb(x) push_back(x)
#define fir first
#define sec second
#define mem(a,x) memset(a,x,sizeof(a))
typedef long long ll;
using namespace std;
const int inf=0x3f3f3f3f;
const ll INF= 0x3f3f3f3f3f3f3f3f;
/*
#ifndef ONLINE_JUDGE
freopen("data.in","r",stdin);
freopen("data.out","w",stdout);
#endif
*/
int main(){
ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
int n,m;
while(cin>>n>>m)
{
ll ans=0;
for(int i=1;i<=m;i++)
{
ll x,d;
cin>>x>>d;
if(d>=0)
{
ans+=n*x+d*(n-1)*n/2;
}
else{
if(n%2){
int t=(n+1)/2;
ans+=n*x+2*d*t*(t-1)/2;
}
else{
int t=n/2;
ans+=n*x+2*d*t*(t-1)/2+(n-t)*d;
}
}
}
double daan=(double)ans/(1.0*n);
printf("%.7lf\n",daan);
//cout<<daan<<endl;
}
}
/*
5 3
-1 -3
-4 -6
-3 -10
*/ | [
"1035909127@qq.com"
] | 1035909127@qq.com |
3fe14fdd7a762b5c0e0f3ab64116d8ef434fea05 | 8cc50f8a0d4b031a1f33f4257170cac3b24068df | /Data-Structures/Solutions/Diameter-Of-Tree.cpp | 1e4b455d57f773761379f165f8c05f920ccf4cab | [] | no_license | ravikeshri/Competitive-Programming | beea789036160697cbf0cb50ef6a86676acb11e3 | a4a9b844bb3966cd202963ddb027521a83b2837f | refs/heads/master | 2023-02-10T10:32:46.358840 | 2021-01-09T10:32:19 | 2021-01-09T10:32:19 | 255,426,354 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 2,101 | cpp | #include<iostream>
#include<cstring>
#include<vector>
#include<queue>
#include<climits>
#include<algorithm>
#define MAX 100005
#define ll long long
using namespace std;
int diameter[MAX];
bool visited[MAX];
int node; // farthest node from source
int max_height; // max height
void resetBFS() {
memset(visited, false, sizeof(visited));
memset(diameter, 0, sizeof(diameter));
}
int bfs(int s, vector<vector<int> > &adj) {
resetBFS();
queue<int> q;
q.push(s);
visited[s] = true;
while(!q.empty()) {
int u = q.front();
q.pop();
int n = adj[u].size();
for(int i=0; i<n; i++) {
int v = adj[u][i];
if(!visited[v]) {
visited[v] = true;
diameter[v] = diameter[u] + 1;
q.push(v);
}
}
}
// returning node(index) with max diameter
return max_element(diameter, diameter + adj.size()) - diameter;
}
int diameterBFS(vector<vector<int> > &adj) {
// farthest node from 1
int node1 = bfs(1, adj);
// farthest node from that node
int node2 = bfs(node1, adj);
return diameter[node2];
}
void resetDFS() {
max_height = INT_MIN;
memset(visited, false, sizeof(visited));
}
void dfs(int s, vector<vector<int> > &adj, int height) {
visited[s] = true;
height++;
int n = (int)adj[s].size();
for(int i=0; i<n; i++) {
int v = adj[s][i];
if(!visited[v]) {
if(height >= max_height) {
max_height = height;
// save the node value whenever max_height updated
node = v;
}
dfs(v, adj, height);
}
}
}
int diameterDFS(vector<vector<int> > &adj) {
// farthest node from 1
resetDFS();
dfs(1, adj, 0);
// farthest node from that node
resetDFS();
dfs(node, adj, 0);
return max_height;
}
int main() {
int n;
cin >> n;
int a, b;
vector<vector<int> > adj(n+5);
// graph/tree input
for(int i=0; i<n-1; i++) {
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
// diameter using bfs
cout << diameterBFS(adj) << " ";
// diameter using dfs
cout << diameterDFS(adj);
return 0;
}
| [
"61163354+ravikeshri@users.noreply.github.com"
] | 61163354+ravikeshri@users.noreply.github.com |
2cce71acd5e3eaf370c8628304944f4a21817a06 | 6b29271fd614128208a5fecf542c086867986cbe | /test/main.cpp | 85de49dda80db19d5595708ae8e29d5bd061902c | [] | no_license | PPakalns/grafika | 0976fd8b540544bc80007d623d7f0e8980e5abe4 | 5ffb51666637d138c94495507ba7aa9cfc96eb0f | refs/heads/master | 2020-03-28T14:46:41.335197 | 2018-12-10T06:34:20 | 2018-12-10T06:34:20 | 148,521,687 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 337 | cpp | #include <core/Utility.h>
int safe_main(int argc, char** argv )
{
cv::Mat image = core::ReadImage(argc, argv);
namedWindow("Display Image", cv::WINDOW_AUTOSIZE);
imshow("Display Image", image);
cv::waitKey(0);
return 0;
}
int main(int argc, char** argv)
{
return core::CatchExceptions(safe_main, argc, argv);
}
| [
"peterispakalns@gmail.com"
] | peterispakalns@gmail.com |
2772b350d4002b49f88a62f7ec113f6b83b4d931 | 492976adfdf031252c85de91a185bfd625738a0c | /src/Game/AI/Action/actionDgnObj_DLC_CogWheel_Reject.h | 73a1494bfcca32ac438587c049d1da3a1e376c4a | [] | no_license | zeldaret/botw | 50ccb72c6d3969c0b067168f6f9124665a7f7590 | fd527f92164b8efdb746cffcf23c4f033fbffa76 | refs/heads/master | 2023-07-21T13:12:24.107437 | 2023-07-01T20:29:40 | 2023-07-01T20:29:40 | 288,736,599 | 1,350 | 117 | null | 2023-09-03T14:45:38 | 2020-08-19T13:16:30 | C++ | UTF-8 | C++ | false | false | 587 | h | #pragma once
#include "KingSystem/ActorSystem/actAiAction.h"
namespace uking::action {
class DgnObj_DLC_CogWheel_Reject : public ksys::act::ai::Action {
SEAD_RTTI_OVERRIDE(DgnObj_DLC_CogWheel_Reject, ksys::act::ai::Action)
public:
explicit DgnObj_DLC_CogWheel_Reject(const InitArg& arg);
~DgnObj_DLC_CogWheel_Reject() override;
bool init_(sead::Heap* heap) override;
void enter_(ksys::act::ai::InlineParamPack* params) override;
void leave_() override;
void loadParams_() override;
protected:
void calc_() override;
};
} // namespace uking::action
| [
"leo@leolam.fr"
] | leo@leolam.fr |
82e370de5f934cdb605de19f940aa0052bbcd9d7 | 68f017539ff0dbe04fbaa1af61e2825f11192cc3 | /include/Net/Util/HTTPUtil.h | 2702e5744e59859b877d99d9a12c083e3a9b74c8 | [
"MIT"
] | permissive | corymonroe/GrinPlusPlus | e8cd51add8ab74290ea6ed341c592c791524e8ea | bfdcbbcd65872f08270fc3084992eefea234b05e | refs/heads/master | 2020-12-15T19:22:28.016386 | 2020-01-16T09:33:20 | 2020-01-16T09:33:20 | 235,227,935 | 0 | 0 | MIT | 2020-01-21T00:55:15 | 2020-01-21T00:55:14 | null | UTF-8 | C++ | false | false | 6,191 | h | #pragma once
#include "civetweb/include/civetweb.h"
#include <Net/Clients/HTTP/HTTP.h>
#include <Net/Clients/HTTP/HTTPException.h>
#include <Common/Util/StringUtil.h>
#include <Core/Exceptions/DeserializationException.h>
#include <Core/Util/JsonUtil.h>
#include <json/json.h>
#include <string>
#include <optional>
class HTTPUtil
{
public:
// Strips away the base URI and any query strings.
// Ex: Given "/v1/blocks/<hash>?compact" and baseURI "/v1/blocks/", this would return <hash>.
static std::string GetURIParam(struct mg_connection* conn, const std::string& baseURI)
{
const struct mg_request_info* req_info = mg_get_request_info(conn);
const std::string requestURI(req_info->request_uri);
return requestURI.substr(baseURI.size(), requestURI.size() - baseURI.size());
}
static std::string GetQueryString(struct mg_connection* conn)
{
const struct mg_request_info* req_info = mg_get_request_info(conn);
if (req_info->query_string == nullptr)
{
return "";
}
return req_info->query_string;
}
static bool HasQueryParam(struct mg_connection* conn, const std::string& parameterName)
{
const std::string queryString = HTTPUtil::GetQueryString(conn);
if (!queryString.empty())
{
std::vector<std::string> tokens = StringUtil::Split(queryString, "&");
for (const std::string& token : tokens)
{
if (token == parameterName || StringUtil::StartsWith(token, parameterName + "="))
{
return true;
}
}
}
return false;
}
static std::optional<std::string> GetQueryParam(struct mg_connection* conn, const std::string& parameterName)
{
const std::string queryString = HTTPUtil::GetQueryString(conn);
if (!queryString.empty())
{
std::vector<std::string> tokens = StringUtil::Split(queryString, "&");
for (const std::string& token : tokens)
{
if (token == parameterName)
{
return std::make_optional("");
}
if (StringUtil::StartsWith(token, parameterName + "="))
{
std::vector<std::string> parameterTokens = StringUtil::Split(token, "=");
if (parameterTokens.size() != 2)
{
throw HTTPException();
}
return std::make_optional(parameterTokens[1]);
}
}
}
return std::nullopt;
}
static std::optional<std::string> GetHeaderValue(mg_connection* conn, const std::string& headerName)
{
const char* pHeaderValue = mg_get_header(conn, headerName.c_str());
if (pHeaderValue != nullptr)
{
return std::make_optional(std::string(pHeaderValue));
}
return std::nullopt;
}
static HTTP::EHTTPMethod GetHTTPMethod(struct mg_connection* conn)
{
const struct mg_request_info* req_info = mg_get_request_info(conn);
if (req_info->request_method == std::string("GET"))
{
return HTTP::EHTTPMethod::GET;
}
else if (req_info->request_method == std::string("POST"))
{
return HTTP::EHTTPMethod::POST;
}
throw HTTPException();
}
static std::optional<Json::Value> GetRequestBody(mg_connection* conn)
{
const struct mg_request_info* req_info = mg_get_request_info(conn);
const long long contentLength = req_info->content_length;
if (contentLength <= 0)
{
return std::nullopt;
}
std::string requestBody;
requestBody.resize(contentLength);
const int bytesRead = mg_read(conn, requestBody.data(), contentLength);
if (bytesRead != contentLength)
{
throw HTTPException();
}
Json::Value json;
if (!JsonUtil::Parse(requestBody, json))
{
throw DESERIALIZATION_EXCEPTION();
}
return std::make_optional(json);
}
static int BuildSuccessResponseJSON(struct mg_connection* conn, const Json::Value& json)
{
Json::StreamWriterBuilder builder;
builder["indentation"] = ""; // Removes whitespaces
const std::string output = Json::writeString(builder, json);
return HTTPUtil::BuildSuccessResponse(conn, output);
}
static int BuildSuccessResponse(struct mg_connection* conn, const std::string& response)
{
unsigned long len = (unsigned long)response.size();
if (response.empty())
{
mg_printf(conn,
"HTTP/1.1 200 OK\r\n"
"Content-Length: 0\r\n"
"Connection: close\r\n\r\n");
}
else
{
mg_printf(conn,
"HTTP/1.1 200 OK\r\n"
"Content-Length: %lu\r\n"
"Content-Type: application/json\r\n"
"Connection: close\r\n\r\n",
len);
}
mg_write(conn, response.c_str(), len);
return 200;
}
static int BuildBadRequestResponse(struct mg_connection* conn, const std::string& response)
{
unsigned long len = (unsigned long)response.size();
mg_printf(conn,
"HTTP/1.1 400 Bad Request\r\n"
"Content-Length: %lu\r\n"
"Content-Type: text/plain\r\n"
"Connection: close\r\n\r\n",
len);
mg_write(conn, response.c_str(), len);
return 400;
}
static int BuildConflictResponse(struct mg_connection* conn, const std::string& response)
{
unsigned long len = (unsigned long)response.size();
mg_printf(conn,
"HTTP/1.1 409 Conflict\r\n"
"Content-Length: %lu\r\n"
"Content-Type: text/plain\r\n"
"Connection: close\r\n\r\n",
len);
mg_write(conn, response.c_str(), len);
return 409;
}
static int BuildUnauthorizedResponse(struct mg_connection* conn, const std::string& response)
{
unsigned long len = (unsigned long)response.size();
mg_printf(conn,
"HTTP/1.1 401 Unauthorized\r\n"
"Content-Length: %lu\r\n"
"Content-Type: text/plain\r\n"
"Connection: close\r\n\r\n",
len);
mg_write(conn, response.c_str(), len);
return 401;
}
static int BuildNotFoundResponse(struct mg_connection* conn, const std::string& response)
{
unsigned long len = (unsigned long)response.size();
mg_printf(conn,
"HTTP/1.1 404 Not Found\r\n"
"Content-Length: %lu\r\n"
"Content-Type: text/plain\r\n"
"Connection: close\r\n\r\n",
len);
mg_write(conn, response.c_str(), len);
return 400;
}
static int BuildInternalErrorResponse(struct mg_connection* conn, const std::string& response)
{
unsigned long len = (unsigned long)response.size();
mg_printf(conn,
"HTTP/1.1 500 Internal Server Error\r\n"
"Content-Length: %lu\r\n"
"Content-Type: text/plain\r\n"
"Connection: close\r\n\r\n",
len);
mg_write(conn, response.c_str(), len);
return 500;
}
}; | [
"davidburkett38@gmail.com"
] | davidburkett38@gmail.com |
2b184278cbcb94636c989123684d2ec5fd487c64 | 6f874ccb136d411c8ec7f4faf806a108ffc76837 | /code/VCSamples/VC2008Samples/ComTypeLibfor7/freethrd/server/server.h | 0089143df028a9a2122473b0a0c8c1fdb59d1985 | [
"MIT"
] | permissive | JetAr/ZDoc | c0f97a8ad8fd1f6a40e687b886f6c25bb89b6435 | e81a3adc354ec33345e9a3303f381dcb1b02c19d | refs/heads/master | 2022-07-26T23:06:12.021611 | 2021-07-11T13:45:57 | 2021-07-11T13:45:57 | 33,112,803 | 8 | 8 | null | null | null | null | UTF-8 | C++ | false | false | 2,827 | h | /*+==========================================================================
File: SERVER.H
Summary: Internal include file for the FRESERVE.DLL server code
sample. Contains class declarations, Resource IDs and
string macros for internal use in constructing this DLL
as a COM component server. Declares the CServer server
control object class.
For a comprehensive tutorial code tour of this module's
contents and offerings see the accompanying FRESERVE.TXT
file. For more specific technical details on the internal
workings see the comments dispersed throughout the module's
source code.
Classes: CServer.
Functions: none
Origin: 4-5-96: atrent - Editor-inheritance from SERVER.H in
the DLLSERVE OLE Tutorial Code Sample.
----------------------------------------------------------------------------
This file is part of the Microsoft OLE Tutorial Code Samples.
Copyright (c) Microsoft Corporation, 1996. All rights reserved.
This source code is intended only as a supplement to Microsoft
Development Tools and/or on-line documentation. See these other
materials for detailed information regarding Microsoft code samples.
THIS CODE AND INFORMATION IS 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.
==========================================================================+*/
#if !defined(SERVER_H)
#define SERVER_H
// Error-related String Identifiers.
#define IDS_ASSERT_FAIL 2200
#ifdef __cplusplus
/*C+C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C+++C
Class: CServer
Summary: Class to encapsulate control of this COM server (eg, handle
Lock and Object counting, encapsulate otherwise global data).
Methods: none
C---C---C---C---C---C---C---C---C---C---C---C---C---C---C---C---C---C---C-C*/
class CServer : public CThreaded
{
public:
CServer(void);
~CServer(void);
// Methods for server lifetime control: object counts and lock counts.
void Lock(void);
void Unlock(void);
void ObjectsUp(void);
void ObjectsDown(void);
HRESULT CanUnloadNow(void);
// A place to store the handle to loaded instance of this DLL module.
HINSTANCE m_hDllInst;
// A place to store a client's parent window.
HINSTANCE m_hWndParent;
// Global DLL Server living Object count.
LONG m_cObjects;
// Global DLL Server Client Lock count.
LONG m_cLocks;
};
#endif // __cplusplus
// Allow other internal FRESERVE modules to get at the globals.
extern CServer* g_pServer;
#endif // SERVER_H
| [
"126.org@gmail.com"
] | 126.org@gmail.com |
b90fd9d1ee0e60dc8212d4d969f9e5991cb6eac1 | 6787c15402e29dacf69af04aa3260a13087153e1 | /BaekJoon/q2014.cpp | 9eae9f5de5cf7b0207519917dba1cc2df36d1518 | [] | no_license | meeso/AlgoritmStudy | 90cd13afc572992cb2faba3b469cbdb8deaa8a2c | 39dfa2c89ba84f76e42e2295522a43fb7cd44955 | refs/heads/master | 2020-03-29T13:25:41.210527 | 2019-10-20T09:20:05 | 2019-10-20T09:20:05 | 149,958,570 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 853 | cpp | #include <stdio.h>
#include <queue>
#include <functional>
#include <vector>
using namespace std;
int main(){
priority_queue <unsigned long long int,
vector<unsigned long long int>,
greater <unsigned long long int>> pq;
int k, n; // k개의 소수로 만든 N번째 숫자 출력하는것이 문제
int sosu[100]; //입력 받은 소수들
unsigned long long int temp_minor;
scanf("%d %d", &k, &n);
for (int i = 0; i < k; i++){
scanf("%d", &sosu[i]); //받은 소수들 배열에 입력
//push to priority Queue
pq.push(sosu[i]);
}
for (int i = 1; i <= n;i++){
//pop the minor value from the Queue
temp_minor = pq.top();
pq.pop();
//push to priority Queue
for (int j = 0; j < k; j++){
pq.push(temp_minor*sosu[j]);
if (temp_minor%sosu[j] == 0)
break;
}
if (i == n)printf("%d", temp_minor);
}
return 0;
}
| [
"whry13240@naver.com"
] | whry13240@naver.com |
50e8dbfb7c821058a240fb222235347e11e34556 | c97098b838ef5968431c716bd13f4f063412002e | /old.good/hdrc/modules/HDR_Services/FATx.h | ce4ae3574283da9066486dea32a16f23f0aecfff | [] | no_license | hackerlank/usnap | 9cc6f2969639c529cd81a4f4662e81850dd80465 | 2ab43c81c85ddb3d3aa23a15905d965d14710c2b | refs/heads/master | 2020-06-11T00:14:53.268772 | 2012-10-15T09:51:46 | 2012-10-15T09:51:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,690 | h | // FATx.h : Declaration of the CFATx
#ifndef __FATX_H_
#define __FATX_H_
#include "resource.h" // main symbols
#include "HDR_ServicesCP.h"
/////////////////////////////////////////////////////////////////////////////
// CFATx
class ATL_NO_VTABLE CFATx :
public CComObjectRootEx<CComSingleThreadModel>,
public CComCoClass<CFATx, &CLSID_FATx>,
public ISupportErrorInfo,
public IConnectionPointContainerImpl<CFATx>,
public IDispatchImpl<IFSPMapper, &IID_IFSPMapper, &LIBID_HDR_ServicesLib>,
public IDispatchImpl<IFSPReconstruct, &IID_IFSPReconstruct, &LIBID_HDR_ServicesLib>,
public IDispatchImpl<IFSPRecstrMonitor, &IID_IFSPRecstrMonitor, &LIBID_HDR_ServicesLib>,
public IDispatchImpl<IFSPAddInsMgr, &IID_IFSPAddInsMgr, &LIBID_HDR_ServicesLib>,
public IDispatchImpl<IFSPFATxParser, &IID_IFSPFATxParser, &LIBID_HDR_ServicesLib>,
public CProxy_IFSPMapperEvents< CFATx >
{
public:
CFATx()
{
}
DECLARE_REGISTRY_RESOURCEID(IDR_FATX)
DECLARE_PROTECT_FINAL_CONSTRUCT()
BEGIN_COM_MAP(CFATx)
COM_INTERFACE_ENTRY2(IDispatch, IFSPMapper)
COM_INTERFACE_ENTRY(ISupportErrorInfo)
COM_INTERFACE_ENTRY(IFSPMapper)
COM_INTERFACE_ENTRY(IFSPReconstruct)
COM_INTERFACE_ENTRY(IFSPRecstrMonitor)
COM_INTERFACE_ENTRY(IFSPAddInsMgr)
COM_INTERFACE_ENTRY(IFSPFATxParser)
COM_INTERFACE_ENTRY(IConnectionPointContainer)
COM_INTERFACE_ENTRY_IMPL(IConnectionPointContainer)
END_COM_MAP()
BEGIN_CONNECTION_POINT_MAP(CFATx)
CONNECTION_POINT_ENTRY(DIID__IFSPMapperEvents)
END_CONNECTION_POINT_MAP()
// ISupportsErrorInfo
STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid);
// IFSPMapper
public:
STDMETHOD(get_FiltersCount)(/*[out, retval]*/ long *pVal);
};
#endif //__FATX_H_
| [
"pub.lenik@bodz.net"
] | pub.lenik@bodz.net |
4625431d61c22f42fb16e0153f98ddbb24e263e3 | 6fb059f3680d2d41661e6f36a94451bee60b4173 | /stt2ng/include/graphbuilder.h | 5aed06a1bd15b21629389e3e694e02cbecb634c5 | [] | no_license | STT-NG/STT2NG | 0ceff41bf27326357607eaf37a79e6ab0578e93d | 6953b220c3a53f6e7bffb05d37111b6da17b5a8c | refs/heads/master | 2022-11-30T05:05:26.069149 | 2020-08-14T11:33:48 | 2020-08-14T11:33:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 697 | h | #pragma once
#include <GRNode>
#include <GRBuilder>
#include <QObject>
#include <memory>
class GraphModel;
class GraphBuilder : public QObject
{
Q_OBJECT
using GRNode = GeomRel::GRNode;
using GRBuilder = GeomRel::GRBuilder;
public:
GraphBuilder(GraphModel *model, QObject *parent = nullptr);
virtual ~GraphBuilder() {};
void build(int order, double tolerance, std::function<void(void)> progressCallback = [](){});
void clearAll();
void clearNodes();
void clearEdges();
int getNodeCount();
void addNodes(std::vector<std::unique_ptr<GRNode> > nodes);
signals:
void buildCompleted();
private:
GraphModel *model;
GRBuilder builder;
};
| [
"y.j.paetzelt@gmail.com"
] | y.j.paetzelt@gmail.com |
f12f9e9d1877548dc858e8d8b968feb121e24bb9 | df83f9ebcba0f0fb87eb58608f66924e48015b84 | /Common/inc/HI_PLAY_RingBuffer.h | c98e9a9fd77b7230c4915a510791eca654830179 | [] | no_license | smallfishincup/biyesheji | 29c02b00f93256e81968a2fdc3fe68299c043507 | 8273f3d19ecaa6b00b06b9ce73640e121c15b486 | refs/heads/master | 2021-01-02T23:07:09.289548 | 2015-05-05T23:51:33 | 2015-05-05T23:51:33 | 34,637,013 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,977 | h | // **************************************************************
// File : hi_play_ringbuffer.h
// Description : 音频缓冲类
// Author :
// Date :
// Revisions :
// **************************************************************
#if !defined(AFX_HI_PLAY_RINGBUFFER_H__B935304D_CA29_4CE9_A292_EAD05A0F4364__INCLUDED_)
#define AFX_HI_PLAY_RINGBUFFER_H__B935304D_CA29_4CE9_A292_EAD05A0F4364__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "HI_PLAY_AudioBase.h"
typedef enum RB_STAT_ENUM
{
E_RB_TotalReadError,
E_RB_TotalWriteError,
E_RB_TotalWriteSize,
E_RB_TotalReadSize,
E_RB_TotalReadTimes,
E_RB_TotalWriteTimes,
E_RB_STAT_END
}RB_STAT_E;
class CHI_PLAY_RingBuffer : public CHI_PLAY_AudioBase
{
public:
CHI_PLAY_RingBuffer();
virtual ~CHI_PLAY_RingBuffer();
VOID RB_Init_Stat();
VOID RB_Do_Stat(RB_STAT_E, unsigned __int64 value);
VOID RB_Disp_Stat();
UINT RB_MaxReadSize();
UINT RB_MaxWriteSize();
UINT RB_MAXSize();
int RB_Init (UINT ulSize);
VOID RB_Clear();
VOID RB_Destroy();
int RB_Write(unsigned char *pData, UINT ulLen, UINT *pulWriteLen);
int RB_Read(unsigned char *pData, UINT ulLen, UINT *pulRead);
int RB_Write_X(unsigned char *pData, UINT ulDataLen, UINT *pulWriteLen);
int RB_Read_X(unsigned char *pData, UINT *pulData);
UINT RB_GetLen_X();
unsigned char RB_GetFirstHI_U8(); /*从Read指针读取值*/
unsigned short RB_GetFirstHI_U16(); /*2Byte*/
UINT RB_GetFirstHI_U32();
UINT RB_GetMaxWritePercent();
UINT RB_GetMaxReadPercent();
private:
UINT m_ulSize; /*Buffer 的总长度*/
unsigned char *m_pRB; /*Buffer的开始地址*/
UINT m_ulWritePos; /*写的位置, 偏移位*/
UINT m_ulReadPos; /*读的位置, 偏移位*/
unsigned short m_usMediaType; /*媒体类型*/
unsigned __int64 m_stat[E_RB_STAT_END];
};
#endif // !defined(AFX_HI_PLAY_RINGBUFFER_H__B935304D_CA29_4CE9_A292_EAD05A0F4364__INCLUDED_)
| [
"zhanghanupc@gmail.com"
] | zhanghanupc@gmail.com |
8d898250e19305483f2d90d3a9a087f2ac7f7cb4 | 97e4b961fa101bc637934dbe01ac93152f0850fa | /c++/CMPooltest2/CMPooltest1/PageCache.h | 8a8e5b181eae25e1dd018a1a2b57f7540a63c5a5 | [] | no_license | emmanuelfils435/C-C-_memory | b7150cfe7c2f32a481e40873a0c5b35a8426e13d | 0a6b26e2fc3b19132183161380b72c5f50ba9ca8 | refs/heads/master | 2023-03-19T20:35:32.166421 | 2020-04-30T08:00:39 | 2020-04-30T08:00:39 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 819 | h | #pragma once
#include"Common.h"
//1.page cache 是一个以页为单位的span自由链表
//2.为了保证全局只有唯一的page cache,这个类被设计成了单例模式
class PageCache
{
public:
static PageCache* GetInstance()
{
return &_inst;
}
Span* NewSpan(size_t npage);
//获取从对象到span的映射
Span* MapObjectToSpan(void* obj);
//释放空闲span回到Pagecache,合并相邻的span
void ReleaseSpanToPageCache(Span* span);
private:
SpanList _pagelist[NPAGES];
private:
PageCache() = default;
PageCache(const PageCache&) = delete;
PageCache operator=(const PageCache&) = delete;
static PageCache _inst;
//用map或unordered_map存放PagID,Span* 的映射关系,用于合并
//std::unordered_map<PageID, Span*> _id_span_map;
std::map<PageID, Span*> _id_span_map;
}; | [
"1023826776@qq.com"
] | 1023826776@qq.com |
b673ed76e3c5ba66329d8e2815f07f36c9457d03 | 2336d94ed08becd1e680491fed2757964b41645e | /src/features/TemplateFilesFeatureClass.cpp | 4adca323f52ae38ea3e41d5bb295a23f507cec0a | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | adjustive/triumph4php | 1360e6110dd717717bc10a5bb09b4ca14a8c525f | 5eda79f0a9bf9bd6b5752bb66e9015cabb23f5cf | refs/heads/master | 2021-01-17T21:47:13.337615 | 2015-07-22T00:43:18 | 2015-07-22T00:43:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,943 | cpp | /**
* @copyright 2013 Roberto Perpuly
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*
* This software is released under the terms of the MIT License
*
* 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 "features/TemplateFilesFeatureClass.h"
#include <vector>
#include "actions/CallStackActionClass.h"
#include "actions/SequenceClass.h"
#include "actions/TemplateFileTagsDetectorActionClass.h"
#include "globals/Assets.h"
#include "globals/Errors.h"
#include "language_php/TemplateFileTagClass.h"
#include "Triumph.h"
t4p::TemplateFilesFeatureClass::TemplateFilesFeatureClass(t4p::AppClass& app)
: FeatureClass(app) {
}
void t4p::TemplateFilesFeatureClass::StartDetection() {
// start the chain reaction
if (App.Sequences.Running()) {
wxMessageBox(_("Please wait for the current background task to finish"));
return;
}
std::vector<t4p::GlobalActionClass*> actions;
// the sequence class will own this pointer
t4p::CallStackActionClass* callStackAction = new t4p::CallStackActionClass(App.SqliteRunningThreads, t4p::ID_EVENT_ACTION_CALL_STACK);
t4p::UrlTagClass urlTag = App.Globals.CurrentUrl;
callStackAction->SetCallStackStart(urlTag.FileName,
t4p::WxToIcu(urlTag.ClassName),
t4p::WxToIcu(urlTag.MethodName),
App.Globals.DetectorCacheDbFileName);
actions.push_back(callStackAction);
actions.push_back(
new t4p::TemplateFileTagsDetectorActionClass(App.SqliteRunningThreads, t4p::ID_EVENT_ACTION_TEMPLATE_FILE_TAG_DETECTOR));
App.Sequences.Build(actions);
}
t4p::UrlTagFinderClass& t4p::TemplateFilesFeatureClass::Urls() {
return App.Globals.UrlTagFinder;
}
void t4p::TemplateFilesFeatureClass::SetCurrentUrl(t4p::UrlTagClass url) {
App.Globals.CurrentUrl = url;
}
| [
"robertop2004@gmail.com"
] | robertop2004@gmail.com |
274bb9ecf978785c2e5004fbb9f5f94532e7e0c6 | aecf4944523b50424831f8af3debef67e3163b97 | /xr_3da/xrGame/dRay/xrGame/UIWeapon.h | f995b42833c99c47977fa017b4c26bb2618d2c5b | [] | no_license | xrLil-Batya/gitxray | bc8c905444e40c4da5d77f69d03b41d5b9cec378 | 58aaa5185f7a682b8cf5f5f376a2e5b6ca16fed4 | refs/heads/main | 2023-03-31T07:43:57.500002 | 2020-12-12T21:12:25 | 2020-12-12T21:12:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 408 | h | #ifndef __XR_UIWEAPON_H__
#define __XR_UIWEAPON_H__
#pragma once
#include "uistaticitem.h"
// refs
class CWeapon;
class CUIWeapon
{
Ivector2 position;
CUIStaticItem back;
CUIStaticItem weapon;
ref_shader cur_shader;
public:
CUIWeapon ();
virtual ~CUIWeapon ();
void Render ();
void Out (CWeapon* wpn);
void Init ();
};
#endif //__XR_UIWEAPON_H__
| [
"slipch@localhost"
] | slipch@localhost |
13b7142392000a7f3045d1f138b897edcb4dd366 | bb6ebff7a7f6140903d37905c350954ff6599091 | /third_party/WebKit/Source/core/rendering/RenderReplaced.h | fa20c6b9a7e1e22a43bc48ceb4a00eb40bd774c5 | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"LGPL-2.0-only",
"BSD-2-Clause",
"LGPL-2.1-only",
"BSD-3-Clause"
] | permissive | PDi-Communication-Systems-Inc/lollipop_external_chromium_org | faa6602bd6bfd9b9b6277ce3cd16df0bd26e7f2f | ccadf4e63dd34be157281f53fe213d09a8c66d2c | refs/heads/master | 2022-12-23T18:07:04.568931 | 2016-04-11T16:03:36 | 2016-04-11T16:03:36 | 53,677,925 | 0 | 1 | BSD-3-Clause | 2022-12-09T23:46:46 | 2016-03-11T15:49:07 | C++ | UTF-8 | C++ | false | false | 3,806 | h | /*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* Copyright (C) 2004, 2005, 2006, 2007, 2009 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#ifndef RenderReplaced_h
#define RenderReplaced_h
#include "core/rendering/RenderBox.h"
namespace WebCore {
class RenderReplaced : public RenderBox {
public:
RenderReplaced(Element*);
RenderReplaced(Element*, const LayoutSize& intrinsicSize);
virtual ~RenderReplaced();
virtual LayoutUnit computeReplacedLogicalWidth(ShouldComputePreferred = ComputeActual) const OVERRIDE;
virtual LayoutUnit computeReplacedLogicalHeight() const OVERRIDE;
bool hasReplacedLogicalHeight() const;
LayoutRect replacedContentRect(const LayoutSize* overriddenIntrinsicSize = 0) const;
virtual bool needsPreferredWidthsRecalculation() const OVERRIDE;
protected:
virtual void willBeDestroyed() OVERRIDE;
virtual void layout() OVERRIDE;
virtual LayoutSize intrinsicSize() const OVERRIDE FINAL { return m_intrinsicSize; }
virtual void computeIntrinsicRatioInformation(FloatSize& intrinsicSize, double& intrinsicRatio) const OVERRIDE;
virtual void computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const OVERRIDE FINAL;
virtual LayoutUnit intrinsicContentLogicalHeight() const { return intrinsicLogicalHeight(); }
virtual LayoutUnit minimumReplacedHeight() const { return LayoutUnit(); }
virtual void setSelectionState(SelectionState) OVERRIDE FINAL;
bool isSelected() const;
virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
void setIntrinsicSize(const LayoutSize& intrinsicSize) { m_intrinsicSize = intrinsicSize; }
virtual void intrinsicSizeChanged();
virtual void paint(PaintInfo&, const LayoutPoint&) OVERRIDE;
bool shouldPaint(PaintInfo&, const LayoutPoint&);
LayoutRect localSelectionRect(bool checkWhetherSelected = true) const; // This is in local coordinates, but it's a physical rect (so the top left corner is physical top left).
virtual RenderBox* embeddedContentBox() const { return 0; }
private:
virtual const char* renderName() const OVERRIDE { return "RenderReplaced"; }
virtual bool canHaveChildren() const OVERRIDE { return false; }
virtual void computePreferredLogicalWidths() OVERRIDE FINAL;
virtual void paintReplaced(PaintInfo&, const LayoutPoint&) { }
virtual LayoutRect clippedOverflowRectForPaintInvalidation(const RenderLayerModelObject* paintInvalidationContainer) const OVERRIDE;
virtual PositionWithAffinity positionForPoint(const LayoutPoint&) OVERRIDE FINAL;
virtual bool canBeSelectionLeaf() const OVERRIDE { return true; }
virtual LayoutRect selectionRectForPaintInvalidation(const RenderLayerModelObject* paintInvalidationContainer, bool clipToVisibleContent = true) OVERRIDE FINAL;
void computeAspectRatioInformationForRenderBox(RenderBox*, FloatSize& constrainedSize, double& intrinsicRatio) const;
mutable LayoutSize m_intrinsicSize;
};
}
#endif
| [
"mrobbeloth@pdiarm.com"
] | mrobbeloth@pdiarm.com |
6b3f013c3c8da2e125bb9bdf051d9b77f7ab9d40 | 9bbe6ae2502a99e4472df492ac31b24cb3f1b6b1 | /GLSL_example/main.cpp | 3e5fa36205a21b2326a66cc91bc28305abbc9a5c | [] | no_license | ds282547/2018_NCTU-CG_HW2 | 7a338f04e830512d467e87962d8c4fba92d93ef6 | 4b8ff5ae8bc43023578babd491a8cd423487b10f | refs/heads/main | 2023-03-16T15:24:33.404552 | 2021-03-21T11:35:16 | 2021-03-21T11:35:16 | 349,973,324 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,775 | cpp | #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h> /* offsetof */
#include "../GL/glew.h"
#include "../GL/glut.h"
#include "../shader_lib/shader.h"
void init(void);
void display(void);
void reshape(int width, int height);
void keyboard(unsigned char key, int x, int y);
void idle(void);
GLuint program;
GLuint vboName;
unsigned int PG = 0;
int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutCreateWindow("OpenGL Shading Language Example");
glutReshapeWindow(512, 512);
glewInit();
init();
glutReshapeFunc(reshape);
glutDisplayFunc(display);
glutIdleFunc(idle);
glutKeyboardFunc(keyboard);
glutMainLoop();
return 0;
}
void init(void) {
GLuint vert = createShader("Shaders/sin.vert", "vertex");
GLuint frag = createShader("Shaders/sin.frag", "fragment");
program = createProgram(vert, frag);
glGenBuffers(1, &vboName);
glBindBuffer(GL_ARRAY_BUFFER, vboName);
float vertices[] = { 1.0, 0.0, 0.5, 0.0,
0.5, 0.0, 0.0, 0.0,
0.0, 0.0, -0.5, 0.0,
-0.5, 0.0, -1.0, 0.0 };
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 16, vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0); // stride 0 for tightly packed
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(program);
glDrawArrays(GL_LINES, 0, 8);
glUseProgram(0);
glutSwapBuffers();
}
void reshape(int width, int height)
{
glViewport(0, 0, width, height);
}
void keyboard(unsigned char key, int x, int y) {
switch (key) {
case 27:
{ //ESC
exit(0);
break;
}
default:
{
break;
}
}
}
void idle(void)
{
glutPostRedisplay();
} | [
"c14026183@mail.ncku.edu.tw3"
] | c14026183@mail.ncku.edu.tw3 |
37829880a8bf41c28b7bbc3a071d3ed9b701f451 | 43e764edb96eb644c0c4c19deb04f50835e75617 | /Other_Platform_Problems/Hacker_Rank_Day_24_More_Linked_List_Duplicate_Values.cpp | 9b6673e9a63e664a6853565fa2bc91600997a056 | [] | no_license | NakulChauhan1/Data-Structure | b7800ece3f20d73af6bae8bd5ce398c44f358092 | f466defa0828b786634bdd51ba9bb2225aab1ea6 | refs/heads/master | 2021-08-15T02:12:18.932818 | 2021-08-13T09:48:56 | 2021-08-13T09:48:56 | 249,900,437 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,424 | cpp | #include <cstddef>
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
class Node
{
public:
int data;
Node *next;
Node(int d){
data=d;
next=NULL;
}
};
class Solution{
public:
Node* removeDuplicates(Node *head)
{
//Write your code here
if(head==NULL)
{
return NULL;
}
else
{
Node * temp=head;
while(temp->next!=NULL)
{
while(temp->data==temp->next->data)
{
Node * p=temp->next;
if(p->next==NULL)
{
temp->next=NULL;
}
else
{
temp->next=temp->next->next;
p->next=NULL;
}
delete p;
if(temp->next==NULL)
{
break;
}
}
if(temp->next==NULL)
break;
temp=temp->next;
}
}
return head;
}
Node* insert(Node *head,int data)
{
Node* p=new Node(data);
if(head==NULL){
head=p;
}
else if(head->next==NULL){
head->next=p;
}
else{
Node *start=head;
while(start->next!=NULL){
start=start->next;
}
start->next=p;
}
return head;
}
void display(Node *head)
{
Node *start=head;
while(start)
{
cout<<start->data<<" ";
start=start->next;
}
}
};
int main()
{
Node* head=NULL;
Solution mylist;
int T,data;
cin>>T;
while(T-->0){
cin>>data;
head=mylist.insert(head,data);
}
head=mylist.removeDuplicates(head);
mylist.display(head);
}
| [
"48352040+NakulChauhan1@users.noreply.github.com"
] | 48352040+NakulChauhan1@users.noreply.github.com |
46039f1e63bd23c4642d7290ff5d4c16a1c7530d | 867a94c4b137da3f08014854cd68cec2ca42ab78 | /Trees/BinaryTreeZigzagLeverorderTraversal.cpp | 439f200bad8b693eb8a86eec62baedc204df3e05 | [] | no_license | sakshistar/LeetcodeSolutions | 9391bdf6ebd7b4c86a75358c51f43374423a618e | 13ff8e61caf6c0bcff32a964c81060e1c28497a5 | refs/heads/master | 2022-12-29T20:13:28.083884 | 2020-10-23T13:31:01 | 2020-10-23T13:31:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,184 | cpp | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> ans;
if(root==NULL) return ans;
queue<TreeNode*> q;
q.push(root);
bool left=true;
while(!q.empty()){
int n=q.size();
vector<int> temp;
for(int i=0;i<n;i++){
TreeNode* f=q.front();
q.pop();
temp.push_back(f->val);
if(f->left) q.push(f->left);
if(f->right) q.push(f->right);
}
if(left){
ans.push_back(temp);
left=false;
}else{
reverse(temp.begin(),temp.end());
ans.push_back(temp);
left=true;
}
}
return ans;
}
}; | [
"nishantc.co.17@nsit.net.in"
] | nishantc.co.17@nsit.net.in |
97c1f1a360d822f6948da6a6f270bb2bb6b99026 | a80fb9a780318a776388767d30f2d7698c9ad747 | /run/cavityHighRe/1.7/U | b895e97a17bd8b4dfe527890383c6b10b5994354 | [] | no_license | SebastianJohansen/openFOAM | 31bef4c8437fd468e3094d510d3ff392e2ea7d94 | 59ce09358ccf3c2390450183257373292e1b72ee | refs/heads/master | 2020-03-20T09:03:31.969919 | 2018-07-02T14:31:58 | 2018-07-02T14:31:58 | 137,327,058 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,020 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 5.x |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volVectorField;
location "1.7";
object U;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 1 -1 0 0 0 0];
internalField nonuniform List<vector>
400
(
(0.000252854 -0.000254981 0)
(7.54439e-05 0.000125299 0)
(-0.00133456 0.000549563 0)
(-0.00363577 0.000825153 0)
(-0.0064489 0.000966786 0)
(-0.00946603 0.00100964 0)
(-0.0124315 0.000972508 0)
(-0.0151089 0.000856222 0)
(-0.0172552 0.000652182 0)
(-0.01862 0.000355281 0)
(-0.0189728 -2.37938e-05 0)
(-0.0181557 -0.000451488 0)
(-0.0161457 -0.000864592 0)
(-0.0131072 -0.00118228 0)
(-0.00941281 -0.0013231 0)
(-0.00560992 -0.00123051 0)
(-0.00232375 -0.00089894 0)
(-0.000108909 -0.00039259 0)
(0.000738171 0.000139257 0)
(0.000402586 0.000383348 0)
(-0.000139864 -8.83984e-05 0)
(-0.00192257 0.00183262 0)
(-0.0063102 0.00370995 0)
(-0.0124791 0.00497004 0)
(-0.0196627 0.00561772 0)
(-0.0272045 0.00574377 0)
(-0.0344929 0.00540454 0)
(-0.0409385 0.00460888 0)
(-0.0459601 0.00334696 0)
(-0.0490029 0.00163765 0)
(-0.0496041 -0.000426352 0)
(-0.0474861 -0.00265079 0)
(-0.0426657 -0.00473765 0)
(-0.0355411 -0.00632491 0)
(-0.0269112 -0.00706297 0)
(-0.0179073 -0.00672016 0)
(-0.00980892 -0.00529014 0)
(-0.00375267 -0.00306456 0)
(-0.000406906 -0.000668963 0)
(0.000271669 0.000772854 0)
(-0.000677181 0.00145267 0)
(-0.00434172 0.00638071 0)
(-0.0117877 0.0106729 0)
(-0.0215306 0.0135318 0)
(-0.0324724 0.0149524 0)
(-0.0437362 0.0150746 0)
(-0.0544789 0.0139944 0)
(-0.0638766 0.0117402 0)
(-0.0711278 0.00833045 0)
(-0.0754882 0.00386579 0)
(-0.0763528 -0.00138589 0)
(-0.073369 -0.0069392 0)
(-0.0665598 -0.0121022 0)
(-0.056426 -0.0160564 0)
(-0.0439854 -0.0180182 0)
(-0.0307123 -0.0174634 0)
(-0.0183303 -0.0143635 0)
(-0.00845111 -0.00934881 0)
(-0.00221456 -0.00374882 0)
(-5.61514e-05 0.000305246 0)
(-0.00117366 0.0043286 0)
(-0.00665023 0.0135885 0)
(-0.0170438 0.0209263 0)
(-0.0301191 0.0256478 0)
(-0.0444405 0.0278596 0)
(-0.0589703 0.027792 0)
(-0.0727208 0.0255925 0)
(-0.0847266 0.0213176 0)
(-0.0940504 0.0150306 0)
(-0.0998184 0.00694008 0)
(-0.101303 -0.00247491 0)
(-0.0980383 -0.0123953 0)
(-0.0899542 -0.02167 0)
(-0.0775085 -0.0289344 0)
(-0.0617775 -0.0328493 0)
(-0.044457 -0.0324562 0)
(-0.0276846 -0.0275848 0)
(-0.0136394 -0.0191622 0)
(-0.00413938 -0.00927796 0)
(-0.000362217 -0.00112974 0)
(-0.00160408 0.00840791 0)
(-0.00871201 0.0232377 0)
(-0.0217956 0.0341568 0)
(-0.0378946 0.0408994 0)
(-0.0552572 0.0438545 0)
(-0.0727292 0.0434201 0)
(-0.0892444 0.0398228 0)
(-0.103768 0.033153 0)
(-0.115288 0.0235141 0)
(-0.122832 0.0112105 0)
(-0.125537 -0.00308686 0)
(-0.122751 -0.0182405 0)
(-0.114186 -0.0326335 0)
(-0.100093 -0.0442933 0)
(-0.0814426 -0.0511813 0)
(-0.0600428 -0.0516825 0)
(-0.0384572 -0.0452373 0)
(-0.0196016 -0.0329021 0)
(-0.0062639 -0.0175314 0)
(-0.000654948 -0.00356323 0)
(-0.0019606 0.0135318 0)
(-0.0104541 0.0350535 0)
(-0.0258538 0.0500564 0)
(-0.0445733 0.0589777 0)
(-0.0645956 0.0626607 0)
(-0.0846953 0.0617631 0)
(-0.103785 0.0566285 0)
(-0.120824 0.0473828 0)
(-0.134773 0.0341447 0)
(-0.144588 0.0172646 0)
(-0.149251 -0.00246302 0)
(-0.147862 -0.0236465 0)
(-0.139786 -0.0442462 0)
(-0.124892 -0.06164 0)
(-0.103844 -0.0729212 0)
(-0.0783919 -0.0755019 0)
(-0.051479 -0.0680273 0)
(-0.026922 -0.051352 0)
(-0.00886526 -0.0290482 0)
(-0.00099862 -0.00712354 0)
(-0.00223103 0.0195052 0)
(-0.0118041 0.0486591 0)
(-0.0290381 0.0681895 0)
(-0.0498598 0.0794551 0)
(-0.0720542 0.0839081 0)
(-0.0943713 0.0825596 0)
(-0.115757 0.0759119 0)
(-0.135221 0.0641262 0)
(-0.151756 0.047296 0)
(-0.164281 0.0257406 0)
(-0.171635 0.000268812 0)
(-0.172635 -0.0276008 0)
(-0.166215 -0.055499 0)
(-0.15169 -0.0801684 0)
(-0.129172 -0.0976863 0)
(-0.100075 -0.104116 0)
(-0.0675185 -0.0967186 0)
(-0.0362734 -0.075551 0)
(-0.0122986 -0.0446817 0)
(-0.00147709 -0.0121186 0)
(-0.00240033 0.0260929 0)
(-0.0126886 0.0635857 0)
(-0.0311719 0.0879969 0)
(-0.0534438 0.101763 0)
(-0.0771625 0.107072 0)
(-0.101096 0.105381 0)
(-0.124275 0.0973958 0)
(-0.145817 0.0833156 0)
(-0.164815 0.0631656 0)
(-0.180222 0.0371424 0)
(-0.190793 0.0059322 0)
(-0.195096 -0.0289941 0)
(-0.191611 -0.0651036 0)
(-0.178985 -0.0986188 0)
(-0.156521 -0.124551 0)
(-0.1249 -0.13726 0)
(-0.0869763 -0.13188 0)
(-0.0482663 -0.106687 0)
(-0.016961 -0.0656158 0)
(-0.00219287 -0.0190646 0)
(-0.00245768 0.0330218 0)
(-0.013055 0.0792856 0)
(-0.0321171 0.108803 0)
(-0.0550514 0.125173 0)
(-0.0794512 0.131424 0)
(-0.104139 0.129542 0)
(-0.128272 0.120494 0)
(-0.151144 0.104531 0)
(-0.172024 0.0815776 0)
(-0.19 0.051624 0)
(-0.203869 0.0150918 0)
(-0.212068 -0.0267923 0)
(-0.21271 -0.0715809 0)
(-0.203763 -0.115232 0)
(-0.18352 -0.151827 0)
(-0.151473 -0.173833 0)
(-0.109516 -0.173477 0)
(-0.0632684 -0.14583 0)
(-0.0232741 -0.0933053 0)
(-0.00327998 -0.0287074 0)
(-0.00240818 0.0400004 0)
(-0.0129099 0.0951646 0)
(-0.031844 0.129835 0)
(-0.0545429 0.148794 0)
(-0.078581 0.155991 0)
(-0.102865 0.15403 0)
(-0.126724 0.144207 0)
(-0.149687 0.12686 0)
(-0.171288 0.10181 0)
(-0.190878 0.0687871 0)
(-0.207463 0.0278331 0)
(-0.219553 -0.0202705 0)
(-0.225112 -0.0734669 0)
(-0.221577 -0.12785 0)
(-0.206183 -0.176968 0)
(-0.176843 -0.211543 0)
(-0.133642 -0.220331 0)
(-0.0811366 -0.193456 0)
(-0.0316534 -0.129306 0)
(-0.00492653 -0.0420508 0)
(-0.00228871 0.046766 0)
(-0.012372 0.110653 0)
(-0.0305237 0.150279 0)
(-0.0520408 0.171593 0)
(-0.0745099 0.179556 0)
(-0.0969596 0.177486 0)
(-0.118942 0.167087 0)
(-0.140278 0.148842 0)
(-0.160853 0.1225 0)
(-0.180409 0.0875313 0)
(-0.198346 0.0435408 0)
(-0.2135 -0.00929277 0)
(-0.224013 -0.0696635 0)
(-0.227114 -0.134246 0)
(-0.219185 -0.196738 0)
(-0.196427 -0.246752 0)
(-0.156334 -0.269571 0)
(-0.100836 -0.248757 0)
(-0.0424137 -0.174925 0)
(-0.00739964 -0.0603874 0)
(-0.00219078 0.0531676 0)
(-0.0117398 0.125322 0)
(-0.0286354 0.169369 0)
(-0.0480632 0.192464 0)
(-0.0676546 0.200713 0)
(-0.0866359 0.198259 0)
(-0.104854 0.187298 0)
(-0.122488 0.168525 0)
(-0.139839 0.141681 0)
(-0.157129 0.106022 0)
(-0.174305 0.0607249 0)
(-0.190826 0.00529344 0)
(-0.205315 -0.0599097 0)
(-0.215237 -0.132687 0)
(-0.216682 -0.207744 0)
(-0.204412 -0.274726 0)
(-0.172946 -0.316346 0)
(-0.120021 -0.308833 0)
(-0.0555445 -0.230604 0)
(-0.0110527 -0.0853057 0)
(-0.00229973 0.0593002 0)
(-0.0115858 0.139055 0)
(-0.0270798 0.186506 0)
(-0.0436283 0.210297 0)
(-0.0589846 0.217933 0)
(-0.0727373 0.214506 0)
(-0.0851544 0.202757 0)
(-0.0968458 0.183648 0)
(-0.108571 0.156973 0)
(-0.121071 0.121858 0)
(-0.134912 0.0771322 0)
(-0.150279 0.021674 0)
(-0.166622 -0.0451238 0)
(-0.182202 -0.1226 0)
(-0.193509 -0.207304 0)
(-0.194676 -0.290434 0)
(-0.177576 -0.35408 0)
(-0.134763 -0.368074 0)
(-0.0702912 -0.294942 0)
(-0.0162644 -0.118577 0)
(-0.00297142 0.0657278 0)
(-0.0129032 0.152254 0)
(-0.0272883 0.201353 0)
(-0.0402678 0.224021 0)
(-0.0499428 0.22962 0)
(-0.0565907 0.224287 0)
(-0.0611045 0.211297 0)
(-0.0646128 0.191865 0)
(-0.0683446 0.165868 0)
(-0.0735311 0.132378 0)
(-0.081316 0.0900138 0)
(-0.0926188 0.0371943 0)
(-0.107862 -0.0275623 0)
(-0.126507 -0.105122 0)
(-0.146271 -0.194436 0)
(-0.161894 -0.289791 0)
(-0.163825 -0.375493 0)
(-0.139589 -0.418161 0)
(-0.0845213 -0.3635 0)
(-0.0232065 -0.161727 0)
(-0.00487745 0.0738723 0)
(-0.0173268 0.16606 0)
(-0.031249 0.213797 0)
(-0.039766 0.232491 0)
(-0.0419362 0.234026 0)
(-0.0393046 0.225565 0)
(-0.0336712 0.210747 0)
(-0.0267737 0.19091 0)
(-0.0202905 0.165965 0)
(-0.0158537 0.134969 0)
(-0.015061 0.0964548 0)
(-0.0194421 0.0486147 0)
(-0.0303271 -0.0105789 0)
(-0.0485118 -0.0831785 0)
(-0.0735542 -0.170506 0)
(-0.102191 -0.270969 0)
(-0.125521 -0.374201 0)
(-0.127706 -0.449021 0)
(-0.0939587 -0.427983 0)
(-0.0312615 -0.215282 0)
(-0.00921174 0.0867485 0)
(-0.0272944 0.182462 0)
(-0.0409985 0.223607 0)
(-0.0428894 0.234081 0)
(-0.0345161 0.228943 0)
(-0.0195843 0.216001 0)
(-0.00109046 0.198826 0)
(0.018581 0.178587 0)
(0.0373788 0.155083 0)
(0.0534103 0.12733 0)
(0.0648054 0.0938692 0)
(0.0696362 0.0528919 0)
(0.065885 0.00223848 0)
(0.0516085 -0.0607081 0)
(0.0252953 -0.138941 0)
(-0.0127756 -0.23496 0)
(-0.0568501 -0.346141 0)
(-0.0910576 -0.45037 0)
(-0.0915399 -0.476476 0)
(-0.0379202 -0.278293 0)
(-0.0176934 0.11046 0)
(-0.0451949 0.203436 0)
(-0.0554744 0.228672 0)
(-0.0444128 0.225096 0)
(-0.0195169 0.210516 0)
(0.0124053 0.19215 0)
(0.0471872 0.172654 0)
(0.0820264 0.152535 0)
(0.114761 0.131241 0)
(0.143501 0.107683 0)
(0.166361 0.080474 0)
(0.181287 0.0479878 0)
(0.185872 0.00829564 0)
(0.177451 -0.0410956 0)
(0.153001 -0.10368 0)
(0.109808 -0.184724 0)
(0.0485362 -0.289839 0)
(-0.0198353 -0.412511 0)
(-0.0671755 -0.493434 0)
(-0.0371659 -0.346522 0)
(-0.030746 0.156223 0)
(-0.0669595 0.225388 0)
(-0.0566273 0.217472 0)
(-0.0167618 0.194269 0)
(0.0345309 0.170082 0)
(0.0887648 0.147901 0)
(0.142104 0.128164 0)
(0.19234 0.110235 0)
(0.237923 0.0930356 0)
(0.2775 0.07537 0)
(0.309587 0.0560175 0)
(0.332369 0.0337066 0)
(0.34343 0.00700488 0)
(0.339939 -0.0258814 0)
(0.318054 -0.0677782 0)
(0.272961 -0.124295 0)
(0.200165 -0.206533 0)
(0.10007 -0.327014 0)
(-0.00534695 -0.456529 0)
(-0.0153621 -0.39876 0)
(-0.0282485 0.226544 0)
(-0.0422051 0.223652 0)
(0.0373462 0.166032 0)
(0.127062 0.128171 0)
(0.208487 0.102257 0)
(0.281033 0.0827964 0)
(0.345475 0.0677735 0)
(0.402104 0.0557181 0)
(0.451013 0.0453044 0)
(0.492031 0.0354441 0)
(0.524538 0.0252493 0)
(0.547366 0.0139461 0)
(0.558604 0.000782618 0)
(0.555944 -0.0149537 0)
(0.535576 -0.0349775 0)
(0.492024 -0.0626501 0)
(0.416962 -0.107548 0)
(0.297241 -0.193998 0)
(0.132909 -0.333159 0)
(0.0673982 -0.369503 0)
(0.261498 0.137372 0)
(0.32407 0.118083 0)
(0.455299 0.0773658 0)
(0.560426 0.0519977 0)
(0.633183 0.0365664 0)
(0.687066 0.0263948 0)
(0.729612 0.0194583 0)
(0.763869 0.0145812 0)
(0.791338 0.0109119 0)
(0.8128 0.0078478 0)
(0.828432 0.00496803 0)
(0.837905 0.00197099 0)
(0.840459 -0.00138138 0)
(0.834783 -0.00514117 0)
(0.818685 -0.00988246 0)
(0.788861 -0.0164622 0)
(0.737891 -0.0274026 0)
(0.647964 -0.0517989 0)
(0.474687 -0.111387 0)
(0.341588 -0.15579 0)
)
;
boundaryField
{
movingWall
{
type fixedValue;
value uniform (1 0 0);
}
fixedWalls
{
type noSlip;
}
frontAndBack
{
type empty;
}
}
// ************************************************************************* //
| [
"cebastian.johansen@gmail.com"
] | cebastian.johansen@gmail.com | |
42ea241b83baf69580fea8cff76967ac1755fffd | 2b31b6a58a6677f23422a07b9aebbc0ae89e8cb0 | /libvis/src/libvis/render_window_qt_vulkan.cc | 1e3568738c0fd72ebfe221602d6d30936631d083 | [
"BSD-3-Clause"
] | permissive | SnowCarter/surfelmeshing | eef27c8d8797432f0706502e8507e45adee7323b | 5b1c8d160c1d64f5144b58309b725812d8e6e3ab | refs/heads/master | 2020-04-03T06:25:35.202401 | 2018-10-02T12:31:55 | 2018-10-02T12:31:55 | 155,074,298 | 1 | 0 | BSD-3-Clause | 2018-10-28T13:30:43 | 2018-10-28T13:30:42 | null | UTF-8 | C++ | false | false | 34,700 | cc | // Copyright 2018 ETH Zürich, Thomas Schöps
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include "libvis/render_window_qt_vulkan.h"
#include <unordered_map>
#if defined(VK_USE_PLATFORM_WIN32_KHR)
#include <windows.h>
#elif defined(VK_USE_PLATFORM_XCB_KHR)
#include <QX11Info>
#endif
#include <glog/logging.h>
#include <QResizeEvent>
#include <QTimer>
#include "libvis/qt_thread.h"
namespace vis {
RenderWidgetVulkan::RenderWidgetVulkan()
: QWindow(),
vulkan_initialized_(false) {}
RenderWidgetVulkan::~RenderWidgetVulkan() {
StopAndWaitForRendering();
DestroySurfaceDependentObjects();
vkDestroyCommandPool(device_.device(), command_pool_, nullptr);
vkDestroySwapchainKHR(device_.device(), swap_chain_, nullptr);
vkDestroySemaphore(device_.device(), image_available_semaphore_, nullptr);
vkDestroySemaphore(device_.device(), render_finished_semaphore_, nullptr);
vkDestroySurfaceKHR(instance_.instance(), surface_, nullptr);
}
void RenderWidgetVulkan::Render() {
// Asynchronously get the next image from the swap chain.
// image_available_semaphore_ will be signaled when the image becomes
// available. The index refers to the swap_chain_images_ array.
u32 image_index;
VkResult result = vkAcquireNextImageKHR(
device_.device(), swap_chain_,
/* timeout */ numeric_limits<uint64_t>::max(),
image_available_semaphore_, VK_NULL_HANDLE, &image_index);
if (result == VK_ERROR_OUT_OF_DATE_KHR) {
RecreateSwapChain();
return;
} else if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR) {
LOG(ERROR) << "Failed to acquire swap chain image.";
return;
}
// Submit the right command buffer for the image.
VkSubmitInfo submit_info = {};
submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
// Wait with the color attachment output until the image_available_semaphore_
// was signaled.
submit_info.waitSemaphoreCount = 1;
VkSemaphore wait_semaphores[] = {image_available_semaphore_};
submit_info.pWaitSemaphores = wait_semaphores;
// Could use VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, but then one must
// create a dependency for the render pass to have the swap chain image
// acquired, otherwise the image format transition at the start of the render
// pass cannot work.
VkPipelineStageFlags wait_stages[] = {VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT};
submit_info.pWaitDstStageMask = wait_stages;
// Specify the command buffer(s) to submit.
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers = &command_buffers_[image_index];
// Signal the render_finished_semaphore_ after the command buffers finished.
VkSemaphore signal_semaphores[] = {render_finished_semaphore_};
submit_info.signalSemaphoreCount = 1;
submit_info.pSignalSemaphores = signal_semaphores;
if (vkQueueSubmit(device_.graphics_queue(), 1, &submit_info, VK_NULL_HANDLE) != VK_SUCCESS) {
LOG(ERROR) << "Failed to submit draw command buffer.";
}
// Put the image back into the swap chain for presentation.
VkPresentInfoKHR present_info = {};
present_info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
present_info.waitSemaphoreCount = 1;
present_info.pWaitSemaphores = signal_semaphores;
VkSwapchainKHR swap_chains[] = {swap_chain_};
present_info.swapchainCount = 1;
present_info.pSwapchains = swap_chains;
present_info.pImageIndices = &image_index;
// Only useful if using more than one swap chain.
present_info.pResults = nullptr;
result = vkQueuePresentKHR(device_.presentation_queue(), &present_info);
if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR) {
RecreateSwapChain();
} else if (result != VK_SUCCESS) {
LOG(ERROR) << "Failed to present swap chain image.";
return;
}
}
void RenderWidgetVulkan::resizeEvent(QResizeEvent* event) {
if (event->size().width() == 0 || event->size().height() == 0) {
return;
}
if (!vulkan_initialized_) {
InitializeVulkan();
} else {
RecreateSwapChain();
}
}
bool RenderWidgetVulkan::InitializeVulkan() {
// Enable debug layers in debug builds only. CMake's RelWithDebInfo defines
// NDEBUG by default and will therefore not enable debug layers.
#ifdef NDEBUG
constexpr bool kEnableDebugLayers = false;
#else
constexpr bool kEnableDebugLayers = true;
#endif
vector<string> instance_extensions;
vector<string> device_extensions;
// Choose the instance extensions to enable.
// Since this Vulkan instance is used for rendering with the output being
// presented on the screen, we need to enable the surface extensions.
instance_extensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
#if VK_USE_PLATFORM_WIN32_KHR
instance_extensions.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME);
#elif VK_USE_PLATFORM_XCB_KHR
instance_extensions.push_back(VK_KHR_XCB_SURFACE_EXTENSION_NAME);
#else
LOG(ERROR) << "No supported surface extension for this platform.";
return false;
#endif
// For the same reason, the swap chain device extension is needed.
device_extensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
// Initialize the Vulkan instance.
if (!instance_.Initialize(instance_extensions, kEnableDebugLayers)) {
return false;
}
// Create the VkSurfaceKHR, which represents the surface to present rendered
// images to. This should be done before the physical device selection because
// some devices may not be able to present to the created surface.
#if VK_USE_PLATFORM_WIN32_KHR
VkWin32SurfaceCreateInfoKHR create_info = {};
create_info.sType = VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR;
create_info.hinstance = GetModuleHandle(nullptr);
create_info.hwnd = reinterpret_cast<HWND> (this->winId());
auto vkCreateWin32SurfaceKHR = (PFN_vkCreateWin32SurfaceKHR) vkGetInstanceProcAddr(instance_.instance(), "vkCreateWin32SurfaceKHR");
if (!vkCreateWin32SurfaceKHR) {
LOG(ERROR) << "vkCreateWin32SurfaceKHR() not available.";
return false;
}
if (vkCreateWin32SurfaceKHR(instance_.instance(), &create_info, nullptr, &surface_) != VK_SUCCESS) {
LOG(ERROR) << "vkCreateWin32SurfaceKHR() failed.";
return false;
}
#elif VK_USE_PLATFORM_XCB_KHR
VkXcbSurfaceCreateInfoKHR create_info = {};
create_info.sType = VK_STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR;
create_info.connection = QX11Info::connection();
create_info.window = static_cast<xcb_window_t>(this->winId());
auto vkCreateXcbSurfaceKHR = (PFN_vkCreateXcbSurfaceKHR) vkGetInstanceProcAddr(instance_.instance(), "vkCreateXcbSurfaceKHR");
if (!vkCreateXcbSurfaceKHR) {
LOG(ERROR) << "vkCreateXcbSurfaceKHR() not available.";
return false;
}
if (vkCreateXcbSurfaceKHR(instance_.instance(), &create_info, nullptr, &surface_) != VK_SUCCESS) {
LOG(ERROR) << "vkCreateXcbSurfaceKHR() failed.";
return false;
}
#endif
// Find the best suited physical device.
// TODO: The scoring of the devices should be also be influenced by some model
// of the renderer that will be used, which may request certain
// features.
std::multimap<float, VulkanPhysicalDevice*> scored_devices;
// Holds the index of a suitable queue family for each device.
std::unordered_map<VulkanPhysicalDevice*, u32> selected_graphics_queue_family_indices;
std::unordered_map<VulkanPhysicalDevice*, u32> selected_presentation_queue_family_indices;
for (const shared_ptr<VulkanPhysicalDevice>& device : instance_.physical_devices()) {
// Check for support of the required queues.
bool has_graphics_queue = false;
bool has_presentation_queue = false;
for (u32 queue_family_index = 0; queue_family_index < device->queue_families().size(); ++ queue_family_index) {
const VkQueueFamilyProperties& family_properties = device->queue_families().at(queue_family_index);
// NOTE: For compatibility reasons, it may be good not to require a queue
// count higher than 1: On an Intel Ivy Bridge integrated GPU, only
// one queue is available (using the driver available to me at the
// time of writing, January 2017).
if (family_properties.queueCount > 0 && family_properties.queueFlags & VK_QUEUE_GRAPHICS_BIT) {
selected_graphics_queue_family_indices[device.get()] = queue_family_index;
has_graphics_queue = true;
}
VkBool32 presentation_support = false;
vkGetPhysicalDeviceSurfaceSupportKHR(device->device(), queue_family_index, surface_, &presentation_support);
if (family_properties.queueCount > 0 && presentation_support) {
selected_presentation_queue_family_indices[device.get()] = queue_family_index;
has_presentation_queue = true;
}
// If we found a queue which supports both graphics and presentation,
// do an early exit.
if (has_graphics_queue && has_presentation_queue &&
selected_graphics_queue_family_indices[device.get()] ==
selected_presentation_queue_family_indices[device.get()]) {
break;
}
}
if (!has_graphics_queue || !has_presentation_queue) {
continue;
}
// Check for support of the required extensions.
float device_score = 0;
for (const string& requested_extension : device_extensions) {
bool found = false;
for (const VkExtensionProperties& extension_properties : device->available_extensions()) {
if (requested_extension == extension_properties.extensionName) {
found = true;
break;
}
}
if (!found) {
device_score = -1;
break;
}
}
if (device_score < 0) {
continue;
}
// Check for support of the required swap chain details given our surface.
// This query must be done after the extensions check (because the swap
// chain extension might not be available).
VulkanSwapChainSupport swap_chain_support;
device->QuerySwapChainSupport(surface_, &swap_chain_support);
bool swap_chain_support_ok = !swap_chain_support.formats.empty() &&
!swap_chain_support.present_modes.empty();
if (!swap_chain_support_ok) {
continue;
}
// Score the device according to its type.
if (device->properties().deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) {
device_score += 10;
} else if (device->properties().deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU) {
device_score += 8;
} else if (device->properties().deviceType == VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU) {
device_score += 6;
} else if (device->properties().deviceType == VK_PHYSICAL_DEVICE_TYPE_CPU) {
device_score += 4;
}
scored_devices.insert(make_pair(device_score, device.get()));
}
if (scored_devices.empty()) {
LOG(ERROR) << "No suitable Vulkan device found.";
return false;
}
selected_physical_device_ = scored_devices.crbegin()->second;
u32 selected_graphics_queue_family_index = selected_graphics_queue_family_indices.at(selected_physical_device_);
u32 selected_presentation_queue_family_index = selected_presentation_queue_family_indices.at(selected_physical_device_);
// Create a logical device for the selected physical device.
if (!device_.Initialize(selected_physical_device_->device(),
device_extensions,
selected_graphics_queue_family_index,
selected_presentation_queue_family_index,
instance_)) {
return false;
}
// Create command pool.
VkCommandPoolCreateInfo pool_info = {};
pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
pool_info.queueFamilyIndex = selected_graphics_queue_family_index;
// Possible flags:
// - VK_COMMAND_POOL_CREATE_TRANSIENT_BIT:
// Hint that command buffers are re-recorded very often.
// - VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT:
// Allows command buffers to be re-recorded individually.
pool_info.flags = 0;
if (vkCreateCommandPool(device_.device(), &pool_info, nullptr, &command_pool_) != VK_SUCCESS) {
LOG(ERROR) << "Failed to create a command pool.";
return false;
}
// Create semaphores.
VkSemaphoreCreateInfo semaphore_info = {};
semaphore_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
if (vkCreateSemaphore(device_.device(), &semaphore_info, nullptr, &image_available_semaphore_) != VK_SUCCESS ||
vkCreateSemaphore(device_.device(), &semaphore_info, nullptr, &render_finished_semaphore_) != VK_SUCCESS) {
LOG(ERROR) << "Failed to create a semaphore.";
return false;
}
// Create surface dependent objects.
if (!CreateSurfaceDependentObjects(VK_NULL_HANDLE)) {
return false;
}
vulkan_initialized_ = true;
// Start rendering timer for continuous rendering.
render_timer_ = new QTimer(this);
render_timer_->setInterval(1);
connect(render_timer_, &QTimer::timeout, this, &RenderWidgetVulkan::Render);
render_timer_->start();
return true;
}
void RenderWidgetVulkan::RecreateSwapChain() {
StopAndWaitForRendering();
// TODO: It seems like a more elaborate solution to find the objects to
// recreate could pay off here. For example, some dependent objects
// may only need to be recreated if the swap chain's format changes,
// which is extremely unlikely.
DestroySurfaceDependentObjects();
CreateSurfaceDependentObjects(swap_chain_);
// Restart rendering.
// TODO: Should not be done for event-based rendering.
render_timer_->start();
}
void RenderWidgetVulkan::StopAndWaitForRendering() {
render_timer_->stop();
vkDeviceWaitIdle(device_.device());
}
bool RenderWidgetVulkan::CreateSurfaceDependentObjects(VkSwapchainKHR old_swap_chain) {
// Gather information for creating a swap chain.
VulkanSwapChainSupport swap_chain_support;
selected_physical_device_->QuerySwapChainSupport(surface_, &swap_chain_support);
if (VLOG_IS_ON(1)) {
VLOG(1) << "Selected swap chain:";
VLOG(1) << " minImageCount: " << swap_chain_support.capabilities.minImageCount;
VLOG(1) << " maxImageCount: " << swap_chain_support.capabilities.maxImageCount;
VLOG(1) << " currentExtent: (" << swap_chain_support.capabilities.currentExtent.width << ", " << swap_chain_support.capabilities.currentExtent.height << ")";
VLOG(1) << " minImageExtent: (" << swap_chain_support.capabilities.minImageExtent.width << ", " << swap_chain_support.capabilities.minImageExtent.height << ")";
VLOG(1) << " maxImageExtent: (" << swap_chain_support.capabilities.maxImageExtent.width << ", " << swap_chain_support.capabilities.maxImageExtent.height << ")";
VLOG(1) << " maxImageArrayLayers: " << swap_chain_support.capabilities.maxImageArrayLayers;
VLOG(1) << " supportedTransforms: " << swap_chain_support.capabilities.supportedTransforms;
VLOG(1) << " currentTransform: " << swap_chain_support.capabilities.currentTransform;
VLOG(1) << " supportedCompositeAlpha: " << swap_chain_support.capabilities.supportedCompositeAlpha;
VLOG(1) << " supportedUsageFlags: " << swap_chain_support.capabilities.supportedUsageFlags;
VLOG(1) << " #supported formats: " << swap_chain_support.formats.size();
string present_mode_names;
for (VkPresentModeKHR mode : swap_chain_support.present_modes) {
if (!present_mode_names.empty()) {
present_mode_names += ", ";
}
if (mode == VK_PRESENT_MODE_IMMEDIATE_KHR) {
present_mode_names += "immediate";
} else if (mode == VK_PRESENT_MODE_MAILBOX_KHR) {
present_mode_names += "mailbox";
} else if (mode == VK_PRESENT_MODE_FIFO_KHR) {
present_mode_names += "fifo";
} else if (mode == VK_PRESENT_MODE_FIFO_RELAXED_KHR) {
present_mode_names += "fifo_relaxed";
}
}
VLOG(1) << " supported present modes: " << present_mode_names;
}
// Find the best available surface format. This determines the way colors are
// represented. We prefer a standard 32 bits-per-pixel unsigned normalized
// format in BGRA pixel ordering (the corresponding RGBA format wasn't
// available on an Intel IvyBridge mobile GPU), and sRGB color space.
// NOTE: The only other available format on the IvyBridge mobile GPU is:
// VK_FORMAT_R8G8B8A8_SRGB.
// TODO: Test this and see how it differs.
VkSurfaceFormatKHR preferred_surface_format;
preferred_surface_format.format = VK_FORMAT_B8G8R8A8_UNORM;
preferred_surface_format.colorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
VkSurfaceFormatKHR selected_surface_format;
if (swap_chain_support.formats.size() == 1 &&
swap_chain_support.formats[0].format == VK_FORMAT_UNDEFINED) {
// Any format is allowed. Choose our preferred one.
selected_surface_format = preferred_surface_format;
} else {
// Go through the list of supported formats to see if the preferred format
// is supported.
bool found = false;
for (const auto& available_format : swap_chain_support.formats) {
if (available_format.format == preferred_surface_format.format &&
available_format.colorSpace == preferred_surface_format.colorSpace) {
selected_surface_format = preferred_surface_format;
found = true;
break;
}
}
if (!found) {
// The preferred surface format is not available. Simply choose the first
// available one.
// TODO: Could rank the available formats and choose the best.
LOG(WARNING) << "The preferred surface format for the swap chain is not available. Choosing format: " << swap_chain_support.formats[0].format;
LOG(WARNING) << "Available formats:";
for (const auto& available_format : swap_chain_support.formats) {
LOG(WARNING) << " VkFormat " << available_format.format << " VkColorSpaceKHR " << available_format.colorSpace;
}
selected_surface_format = swap_chain_support.formats[0];
}
}
swap_chain_image_format_ = selected_surface_format.format;
// Find the best available presentation mode.
// Out of the 4 modes offered by Vulkan, 2 are interesing for us (since they
// are the ones to avoid tearing):
// VK_PRESENT_MODE_FIFO_KHR: The swap chain is a queue. On a vertical blank,
// the first image is taken and displayed. If the queue is full, the
// application has to wait. Similar to VSync. This mode is guaranteed to
// be supported.
// VK_PRESENT_MODE_MAILBOX_KHR: Differing from the mode above, if the queue is
// full, new images can replace the existing ones. Can be used to
// implement triple buffering.
// Policy: Choose VK_PRESENT_MODE_MAILBOX_KHR is available, otherwise
// VK_PRESENT_MODE_FIFO_KHR.
VkPresentModeKHR selected_present_mode = VK_PRESENT_MODE_FIFO_KHR;
for (VkPresentModeKHR present_mode : swap_chain_support.present_modes) {
if (present_mode == VK_PRESENT_MODE_MAILBOX_KHR) {
selected_present_mode = VK_PRESENT_MODE_MAILBOX_KHR;
break;
}
}
// Choose the resolution of the swap chain images equal to the window size,
// if possible.
if (swap_chain_support.capabilities.currentExtent.width != std::numeric_limits<uint32_t>::max()) {
// The extent that shall be used is given.
swap_chain_extent_ = swap_chain_support.capabilities.currentExtent;
} else {
// We can choose the extent ourselves.
swap_chain_extent_ = {static_cast<u32>(width()), static_cast<u32>(height())};
swap_chain_extent_.width =
std::max(swap_chain_support.capabilities.minImageExtent.width,
std::min(swap_chain_support.capabilities.maxImageExtent.width,
swap_chain_extent_.width));
swap_chain_extent_.height =
std::max(swap_chain_support.capabilities.minImageExtent.height,
std::min(swap_chain_support.capabilities.maxImageExtent.height,
swap_chain_extent_.height));
}
// Decide on the number of images in the swap chain.
// Policy: If VK_PRESENT_MODE_MAILBOX_KHR is available, use triple buffering:
// Ideally, one frame is used for display, while one is being rendered to, and
// the third frame is ready for display. Thus, the frame which is ready can be
// updated until it is put on display. Con: frames may be rendered and never
// shown; It is not clear which frame will be displayed in the end, so it is
// not clear at which time the application state should be rendered if
// something is moving, so movements will not be completely fluid. If
// VK_PRESENT_MODE_FIFO_KHR is used, use double buffering to
// reduce the latency.
u32 image_count =
(selected_present_mode == VK_PRESENT_MODE_MAILBOX_KHR) ? 3 : 2;
image_count = std::max(image_count, swap_chain_support.capabilities.minImageCount);
if (swap_chain_support.capabilities.maxImageCount > 0 &&
image_count > swap_chain_support.capabilities.maxImageCount) {
image_count = swap_chain_support.capabilities.maxImageCount;
}
// Create the swap chain.
VkSwapchainCreateInfoKHR swap_chain_create_info = {};
swap_chain_create_info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
swap_chain_create_info.surface = surface_;
swap_chain_create_info.minImageCount = image_count;
swap_chain_create_info.imageFormat = selected_surface_format.format;
swap_chain_create_info.imageColorSpace = selected_surface_format.colorSpace;
swap_chain_create_info.imageExtent = swap_chain_extent_;
swap_chain_create_info.imageArrayLayers = 1;
// Potentially use VK_IMAGE_USAGE_TRANSFER_DST_BIT here if the scene is
// rendered to a different image first and then transferred to the output:
swap_chain_create_info.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
u32 shared_queue_family_indices[] = {static_cast<u32>(device_.graphics_queue_family_index()),
static_cast<u32>(device_.presentation_queue_family_index())};
if (device_.graphics_queue_family_index() != device_.presentation_queue_family_index()) {
// NOTE: VK_SHARING_MODE_EXCLUSIVE would also be possible using explicit
// ownership transfers.
swap_chain_create_info.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
swap_chain_create_info.queueFamilyIndexCount = 2;
swap_chain_create_info.pQueueFamilyIndices = shared_queue_family_indices;
} else {
swap_chain_create_info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
swap_chain_create_info.queueFamilyIndexCount = 0;
swap_chain_create_info.pQueueFamilyIndices = nullptr;
}
// Do not use any special transforms. At the time of writing (January 2017),
// the potentially available transformations are rotation and mirroring of
// the image.
swap_chain_create_info.preTransform = swap_chain_support.capabilities.currentTransform;
// Do not use the alpha channel to blend with other windows in the window
// system.
swap_chain_create_info.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
swap_chain_create_info.presentMode = selected_present_mode;
// Do not care about the colors of pixels that are obscured (for example by
// other windows in the window system).
swap_chain_create_info.clipped = VK_TRUE;
swap_chain_create_info.oldSwapchain = old_swap_chain;
if (vkCreateSwapchainKHR(device_.device(), &swap_chain_create_info, nullptr, &swap_chain_) != VK_SUCCESS) {
LOG(ERROR) << "Swap chain creation failed.";
return false;
}
if (old_swap_chain != VK_NULL_HANDLE) {
vkDestroySwapchainKHR(device_.device(), old_swap_chain, nullptr);
}
// Get the handles of the images in the swap chain.
// NOTE: image_count passed into swap_chain_create_info.minImageCount only
// specifies the minimum image count. More images could have been
// actually created.
vkGetSwapchainImagesKHR(device_.device(), swap_chain_, &image_count, nullptr);
VLOG(1) << "Swap chain image count: " << image_count;
swap_chain_images_.resize(image_count);
vkGetSwapchainImagesKHR(device_.device(), swap_chain_, &image_count, swap_chain_images_.data());
// Create image views for each image in the swap chain.
swap_chain_image_views_.resize(swap_chain_images_.size());
for (usize i = 0; i < swap_chain_image_views_.size(); ++ i) {
VkImageViewCreateInfo image_view_create_info = {};
image_view_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
image_view_create_info.image = swap_chain_images_[i];
image_view_create_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
image_view_create_info.format = swap_chain_image_format_;
// Do not use any color channel swizzling or constant 0 / 1 mapping.
image_view_create_info.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
image_view_create_info.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
image_view_create_info.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
image_view_create_info.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
image_view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
image_view_create_info.subresourceRange.baseMipLevel = 0;
image_view_create_info.subresourceRange.levelCount = 1;
image_view_create_info.subresourceRange.baseArrayLayer = 0;
image_view_create_info.subresourceRange.layerCount = 1;
if (vkCreateImageView(device_.device(), &image_view_create_info, nullptr, &swap_chain_image_views_[i]) != VK_SUCCESS) {
LOG(ERROR) << "Failed to create an image view.";
return false;
}
}
// Create render subpass.
VkAttachmentReference color_attachment_ref = {};
// This references the index in render_pass_info.pAttachments.
color_attachment_ref.attachment = 0;
color_attachment_ref.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkSubpassDescription subpass = {};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.colorAttachmentCount = 1;
// The index of the attachment in this array will be referenced from shaders,
// for example: layout(location = 0) out vec4 out_color
subpass.pColorAttachments = &color_attachment_ref;
// Create render pass.
VkAttachmentDescription color_attachment = {};
color_attachment.format = swap_chain_image_format_;
// Do not use multisampling:
color_attachment.samples = VK_SAMPLE_COUNT_1_BIT;
// Alternatives:
// - VK_ATTACHMENT_LOAD_OP_LOAD: Retain the previous content.
// - VK_ATTACHMENT_LOAD_OP_DONT_CARE: Start with undefined content.
color_attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
color_attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
// Ignore the stencil buffer:
color_attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
color_attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
// Do not care about the previous image format. This prevents preserving the
// contents, but this does not matter here as the image is cleared.
color_attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
// The image should be ready for presentation after rendering.
color_attachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
VkRenderPassCreateInfo render_pass_info = {};
render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
render_pass_info.attachmentCount = 1;
render_pass_info.pAttachments = &color_attachment;
render_pass_info.subpassCount = 1;
render_pass_info.pSubpasses = &subpass;
if (vkCreateRenderPass(device_.device(), &render_pass_info, nullptr, &render_pass_) != VK_SUCCESS) {
LOG(ERROR) << "Failed to create a render pass.";
return false;
}
// Create a framebuffer for each swap chain image to be able to bind it as an
// attachment to the render pass. A framebuffer references all attachments,
// but here we only use one color image.
swap_chain_framebuffers_.resize(swap_chain_image_views_.size());
for (usize i = 0; i < swap_chain_image_views_.size(); ++ i) {
VkImageView attachments[] = {swap_chain_image_views_[i]};
VkFramebufferCreateInfo framebuffer_info = {};
framebuffer_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
framebuffer_info.renderPass = render_pass_;
framebuffer_info.attachmentCount = 1;
framebuffer_info.pAttachments = attachments;
framebuffer_info.width = swap_chain_extent_.width;
framebuffer_info.height = swap_chain_extent_.height;
framebuffer_info.layers = 1;
if (vkCreateFramebuffer(device_.device(), &framebuffer_info, nullptr, &swap_chain_framebuffers_[i]) != VK_SUCCESS) {
LOG(ERROR) << "Failed to create a framebuffer.";
return false;
}
}
// Create command buffers: one for each framebuffer.
command_buffers_.resize(swap_chain_framebuffers_.size());
VkCommandBufferAllocateInfo command_buffers_info = {};
command_buffers_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
command_buffers_info.commandPool = command_pool_;
// Primary buffers can be submitted directly, while secondary buffers can be
// called from primary buffers.
command_buffers_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
command_buffers_info.commandBufferCount = command_buffers_.size();
if (vkAllocateCommandBuffers(device_.device(), &command_buffers_info, command_buffers_.data()) != VK_SUCCESS) {
LOG(ERROR) << "Failed to allocate command buffers.";
return false;
}
for (size_t i = 0; i < command_buffers_.size(); i++) {
// Begin recording.
VkCommandBufferBeginInfo begin_info = {};
begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
// Possible values:
// - VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT indicates that each
// recording of the command buffer will only be submitted once, and the
// command buffer will be reset and recorded again between each
// submission.
// - VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT indicates that a
// secondary command buffer is considered to be entirely inside a render
// pass. If this is a primary command buffer, then this bit is ignored.
// - Setting VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT allows the command
// buffer to be resubmitted to a queue or recorded into a primary command
// buffer while it is pending execution.
begin_info.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT;
begin_info.pInheritanceInfo = nullptr;
// This resets a buffer if it had been recorded before.
vkBeginCommandBuffer(command_buffers_[i], &begin_info);
// Start the render pass.
VkRenderPassBeginInfo render_pass_info = {};
render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
render_pass_info.renderPass = render_pass_;
render_pass_info.framebuffer = swap_chain_framebuffers_[i];
render_pass_info.renderArea.offset = {0, 0};
render_pass_info.renderArea.extent = swap_chain_extent_;
VkClearValue clear_color;
clear_color.color.float32[0] = 0.8f;
clear_color.color.float32[1] = 0.2f;
clear_color.color.float32[2] = 0.2f;
clear_color.color.float32[3] = 1.0f;
render_pass_info.clearValueCount = 1;
render_pass_info.pClearValues = &clear_color;
// If contents is VK_SUBPASS_CONTENTS_INLINE, the contents of the subpass
// will be recorded inline in the primary command buffer, and secondary
// command buffers must not be executed within the subpass. If contents is
// VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS, the contents are recorded
// in secondary command buffers that will be called from the primary command
// buffer, and vkCmdExecuteCommands is the only valid command on the command
// buffer until vkCmdNextSubpass or vkCmdEndRenderPass.
vkCmdBeginRenderPass(command_buffers_[i], &render_pass_info, VK_SUBPASS_CONTENTS_INLINE);
// No actual rendering commands yet. They would be placed here.
// End the render pass.
vkCmdEndRenderPass(command_buffers_[i]);
// End recording.
if (vkEndCommandBuffer(command_buffers_[i]) != VK_SUCCESS) {
LOG(ERROR) << "Failed to record a command buffer.";
return false;
}
}
// TODO: Continue with shaders. #include "shader.frag.h" and #include "shader.vert.h" from the build directory.
return true;
}
void RenderWidgetVulkan::DestroySurfaceDependentObjects() {
vkFreeCommandBuffers(device_.device(), command_pool_, command_buffers_.size(), command_buffers_.data());
for (const VkFramebuffer& framebuffer : swap_chain_framebuffers_) {
vkDestroyFramebuffer(device_.device(), framebuffer, nullptr);
}
vkDestroyRenderPass(device_.device(), render_pass_, nullptr);
for (const VkImageView& image_view : swap_chain_image_views_) {
vkDestroyImageView(device_.device(), image_view, nullptr);
}
}
RenderWindowQtVulkan::RenderWindowQtVulkan(const string& title, int width, int height, const shared_ptr<RenderWindowCallbacks>& callbacks)
: RenderWindowQt(title, width, height, callbacks) {
QtThread::Instance()->RunInQtThreadBlocking([&](){
// Add the Vulkan render widget to the window created by the parent class.
render_widget_ = new RenderWidgetVulkan();
window_->setCentralWidget(QWidget::createWindowContainer(render_widget_));
});
}
void RenderWindowQtVulkan::RenderFrame() {
// TODO
}
}
| [
"tom.schoeps@gmail.com"
] | tom.schoeps@gmail.com |
e407c353af34b22a0ed3db26003e9dbc41bd72e4 | 2ba32b74d75a4a51c6928017207b89b1cccabb32 | /GuiHomeStack_list.h | 1bbaf466cc5bae93a58b375152f72c9054a53858 | [
"MIT"
] | permissive | fighterkaka22/NeuTalk_mainwindow | d4cf85b3922c9dbe27e19d180f01db5774f086e2 | cec11411fb7c7b3cec0bf13152de9329d9035ad4 | refs/heads/main | 2023-07-13T09:02:19.497256 | 2021-08-27T15:40:22 | 2021-08-27T15:45:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 814 | h | #ifndef GUIHOMESTACK_LIST_H
#define GUIHOMESTACK_LIST_H
#include "GuiScrollStack.h"
#include "GlobalData.h"
class GuiHomeStack_list;
class GuiListItem;
class GuiListItem : public QWidget
{
Q_OBJECT
public:
explicit GuiListItem(UsrProfileStruct *usrProfileStruct, QWidget *parent = 0);
~GuiListItem();
void refreshUsrProfile(UsrProfileStruct *usrProfileStruct);
private:
GuiAvatarButton *avatar_button;
QLabel *name_label;
QLabel *ip_label;
};
class GuiHomeStack_list : public GuiScrollStack
{
Q_OBJECT
public:
explicit GuiHomeStack_list(QWidget *parent);
~GuiHomeStack_list();
void addUsr(UsrProfileStruct *usrProfileStruct);
void refreshUsrProfile(UsrProfileStruct *usrProfileStruct);
private:
QMap<QString, GuiListItem*> list_item_map;
};
#endif // GUIHOMESTACK_LIST_H
| [
"fightermilan22@foxmail.com"
] | fightermilan22@foxmail.com |
a2a339302794a96caca06e7a720eca1aedcf6d98 | c3869ba42919ce534216a7585931c0e0a8216955 | /upp/bazaar/TestHelpViewer/app.tpp/JointExternalTimber1_it-it.tpp | 7dc75f38a906ce88f337d7e47a4caeb24b7106e4 | [] | no_license | RanJi0128/Chromium-customization | 018c977c26a270387a2d9b3c1855a0668691b477 | 89b3550d7fc6f1b61f5e6023c293b82c521c509d | refs/heads/master | 2020-07-13T01:31:26.499121 | 2019-08-29T07:07:17 | 2019-08-29T07:07:17 | 204,954,330 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 327 | tpp | topic "";
[ $$0,0#00000000000000000000000000000000:Default]
[{_}%EN-US
[s0;=* &]
[s0;= [* GIUNTO RIGIDO A GUANCIALI ESTERNI]&]
[s0; &]
[s0;# Si tratta del classico collegamento, principalmente per taglio/momento
flettente, tra due elementi lignei tramite guanciali esterni
e bulloni/spinotti in acciaio :&]
[s0;#2 &]
[s0;2 ] | [
"you@example.com"
] | you@example.com |
6e3f73442fc1005b37c1143cca31ddd46b89c7ba | d3e8594c73a23b723e328588cb8837cd22528431 | /reLOC-0.x/src/core/multirobot.cpp | 403bb134e528f8dd20d5a01819fde909f69a1292 | [] | no_license | zuxichen/reLOC | 9609e629f4456f5c41c6db264e6b0480643f17b7 | 4faa7e0ba21d25025234aa5fbae52cc984b5c4f8 | refs/heads/master | 2020-12-14T12:17:19.515513 | 2019-11-17T15:30:30 | 2019-11-17T15:30:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 176,762 | cpp | /*============================================================================*/
/* */
/* */
/* reLOC 0.21-robik */
/* */
/* (C) Copyright 2019 Pavel Surynek */
/* http://www.surynek.com | <pavel@surynek.com> */
/* */
/* */
/*============================================================================*/
/* multirobot.cpp / 0.21-robik_020 */
/*----------------------------------------------------------------------------*/
//
// Multirobot coordinated path-finding solving package.
//
/*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <map>
#include "config.h"
#include "compile.h"
#include "version.h"
#include "defs.h"
#include "types.h"
#include "result.h"
#include "cnf.h"
#include "multirobot.h"
#include "compress.h"
#include "statistics.h"
using namespace std;
using namespace sReloc;
/*----------------------------------------------------------------------------*/
namespace sReloc
{
/*----------------------------------------------------------------------------*/
// sRobotArrangement
sRobotArrangement::sRobotArrangement()
{
// nothing
}
sRobotArrangement::sRobotArrangement(int N_Vertices, int N_Robots, bool random)
: m_robot_Locs(N_Robots + 1),
m_vertex_Occups(N_Vertices)
{
for (int i = 0; i < N_Vertices; ++i)
{
m_vertex_Occups[i] = VACANT_VERTEX;
}
if (random)
{
Vertices_vector Vertices;
for (int i = 0; i < N_Vertices; ++i)
{
Vertices.push_back(i);
}
int remain = N_Vertices;
for (int r = N_Robots; r >= 1;)
{
if (remain <= 0)
{
break;
}
int rnd = rand() % remain;
place_Robot(r--, Vertices[rnd]);
Vertices[rnd] = Vertices[--remain];
}
}
else
{
for (int i = 0; i <= N_Robots; ++i)
{
m_robot_Locs[i] = UNDEFINED_LOCATION;
}
}
}
sRobotArrangement::sRobotArrangement(const sRobotArrangement &initial_arrangement, int N_Vertices, int N_Robots, bool random)
: m_robot_Locs(N_Robots + 1),
m_vertex_Occups(N_Vertices)
{
for (int i = 0; i < N_Vertices; ++i)
{
m_vertex_Occups[i] = VACANT_VERTEX;
}
if (random)
{
Vertices_vector Vertices;
int remain = 0;
for (int i = 0; i < N_Vertices; ++i)
{
if (initial_arrangement.get_VertexOccupancy(i) == 0)
{
Vertices.push_back(i);
++remain;
}
}
for (int r = N_Robots; r >= 1;)
{
if (remain <= 0)
{
break;
}
int rnd = rand() % remain;
place_Robot(r--, Vertices[rnd]);
Vertices[rnd] = Vertices[--remain];
}
}
else
{
for (int i = 0; i <= N_Robots; ++i)
{
m_robot_Locs[i] = UNDEFINED_LOCATION;
}
}
}
sRobotArrangement::sRobotArrangement(const sRobotArrangement &initial_arrangement, int N_Vertices, int N_Robots, int N_fixed, bool random)
: m_robot_Locs(N_Robots + 1),
m_vertex_Occups(N_Vertices)
{
for (int i = 0; i < N_Vertices; ++i)
{
m_vertex_Occups[i] = VACANT_VERTEX;
}
if (random)
{
Vertices_vector Vertices;
int remain = 0;
for (int i = 0; i < N_Vertices; ++i)
{
if (initial_arrangement.get_VertexOccupancy(i) == 0)
{
Vertices.push_back(i);
++remain;
}
}
int r = N_Robots;
for (int f = 0; f < N_fixed; ++f)
{
place_Robot(r, initial_arrangement.get_RobotLocation(r));
--r;
}
while (r >= 1)
{
if (remain <= 0)
{
break;
}
int rnd = rand() % remain;
place_Robot(r--, Vertices[rnd]);
Vertices[rnd] = Vertices[--remain];
}
}
else
{
for (int i = 0; i <= N_Robots; ++i)
{
m_robot_Locs[i] = UNDEFINED_LOCATION;
}
}
}
bool sRobotArrangement::operator==(const sRobotArrangement &robot_arrangement) const
{
sASSERT(m_robot_Locs.size() == robot_arrangement.m_robot_Locs.size());
Robots_vector::const_iterator robot_A, robot_B;
for (robot_A = m_robot_Locs.begin(), robot_B = robot_arrangement.m_robot_Locs.begin();
robot_A != m_robot_Locs.end();
++robot_A, ++robot_B)
{
if (*robot_A != *robot_B)
{
return false;
}
}
return true;
}
bool sRobotArrangement::operator<(const sRobotArrangement &robot_arrangement) const
{
sASSERT(m_robot_Locs.size() == robot_arrangement.m_robot_Locs.size());
Robots_vector::const_iterator robot_A, robot_B;
for (robot_A = m_robot_Locs.begin(), robot_B = robot_arrangement.m_robot_Locs.begin();
robot_A != m_robot_Locs.end();
++robot_A, ++robot_B)
{
if (*robot_A < *robot_B)
{
return true;
}
else
{
if (*robot_A > *robot_B)
{
return false;
}
}
}
return false;
}
int sRobotArrangement::get_RobotCount(void) const
{
return (m_robot_Locs.size() - 1);
}
int sRobotArrangement::get_VertexCount(void) const
{
return m_vertex_Occups.size();
}
int sRobotArrangement::get_RobotLocation(int robot_id) const
{
sASSERT(robot_id > 0 && robot_id < m_robot_Locs.size());
return m_robot_Locs[robot_id];
}
int sRobotArrangement::get_VertexOccupancy(int vertex_id) const
{
sASSERT(vertex_id < m_vertex_Occups.size());
return m_vertex_Occups[vertex_id];
}
void sRobotArrangement::place_Robot(int robot_id, int vertex_id)
{
sASSERT(robot_id > 0 && robot_id < m_robot_Locs.size());
sASSERT(vertex_id < m_vertex_Occups.size());
sASSERT(m_vertex_Occups[vertex_id] == VACANT_VERTEX);
m_robot_Locs[robot_id] = vertex_id;
m_vertex_Occups[vertex_id] = robot_id;
}
void sRobotArrangement::place_CapacityRobot(int robot_id, int vertex_id)
{
sASSERT(robot_id > 0 && robot_id < m_robot_Locs.size());
sASSERT(vertex_id < m_vertex_Occups.size());
m_robot_Locs[robot_id] = vertex_id;
// m_vertex_Occups[vertex_id] = robot_id;
}
void sRobotArrangement::remove_Robot(int robot_id)
{
sASSERT(robot_id > 0 && robot_id < m_robot_Locs.size());
m_vertex_Occups[m_robot_Locs[robot_id]] = VACANT_VERTEX;
m_robot_Locs[robot_id] = UNDEFINED_LOCATION;
}
void sRobotArrangement::clean_Vertex(int vertex_id)
{
sASSERT(vertex_id < m_vertex_Occups.size());
m_robot_Locs[m_vertex_Occups[vertex_id]] = UNDEFINED_LOCATION;
m_vertex_Occups[vertex_id] = VACANT_VERTEX;
}
void sRobotArrangement::move_Robot(int robot_id, int dest_vertex_id)
{
sASSERT(robot_id > 0 && robot_id < m_robot_Locs.size());
sASSERT(dest_vertex_id < m_vertex_Occups.size());
// printf("%d # %d -> %d\n", robot_id, m_robot_Locs[robot_id], dest_vertex_id);
#ifdef sDEBUG
{
/*
if (m_vertex_Occups[dest_vertex_id] != VACANT_VERTEX)
{
printf("--> %d # %d -> %d\n", robot_id, m_robot_Locs[robot_id], dest_vertex_id);
printf("Target occupied by: %d\n", m_vertex_Occups[dest_vertex_id]);
}
*/
//sASSERT(m_vertex_Occups[dest_vertex_id] == VACANT_VERTEX);
}
#endif
m_vertex_Occups[m_robot_Locs[robot_id]] = VACANT_VERTEX;
m_robot_Locs[robot_id] = dest_vertex_id;
m_vertex_Occups[dest_vertex_id] = robot_id;
#ifdef sSTATISTICS
{
++s_GlobalPhaseStatistics.get_CurrentPhase().m_move_Executions;
}
#endif
}
bool sRobotArrangement::is_VertexForced(int vertex_id) const
{
for (int r = 1; r < m_robot_Locs.size(); ++r)
{
if (m_robot_Locs[r] == vertex_id)
{
return true;
}
}
return false;
}
bool sRobotArrangement::is_VertexUnforced(int vertex_id) const
{
return !is_VertexForced(vertex_id);
}
void sRobotArrangement::force_Robot(int robot_id, int dest_vertex_id)
{
m_robot_Locs[robot_id] = dest_vertex_id;
}
bool sRobotArrangement::verify_Move(int robot_id, int dest_vertex_id, const sUndirectedGraph &graph) const
{
if ( (robot_id > 0 && robot_id < m_robot_Locs.size())
&& (dest_vertex_id < m_vertex_Occups.size())
&& (m_vertex_Occups[dest_vertex_id] == VACANT_VERTEX)
&& (m_vertex_Occups[m_robot_Locs[robot_id]] == robot_id)
&& graph.is_Adjacent(m_robot_Locs[robot_id], dest_vertex_id))
{
return true;
}
#ifdef sDEBUG
{
printf("%d # %d -> %d (adjacent:%d)\n", robot_id, m_robot_Locs[robot_id], dest_vertex_id, graph.is_Adjacent(m_robot_Locs[robot_id], dest_vertex_id) ? 1 : 0);
}
#endif
return false;
}
bool sRobotArrangement::verify_Move(int robot_id, int dest_vertex_id) const
{
if ( (robot_id > 0 && robot_id < m_robot_Locs.size())
&& (dest_vertex_id < m_vertex_Occups.size())
&& (m_vertex_Occups[dest_vertex_id] == VACANT_VERTEX)
&& (m_vertex_Occups[m_robot_Locs[robot_id]] == robot_id))
{
return true;
}
#ifdef sDEBUG
{
printf("%d # %d -> %d\n", robot_id, m_robot_Locs[robot_id], dest_vertex_id);
}
#endif
return false;
}
bool sRobotArrangement::check_Move(
#ifdef sDEBUG
int robot_id,
#else
int,
#endif
int dest_vertex_id) const
{
if ( (dest_vertex_id < m_vertex_Occups.size())
&& (m_vertex_Occups[dest_vertex_id] == VACANT_VERTEX))
{
return true;
}
#ifdef sDEBUG
{
printf("%d -> %d\n", robot_id, dest_vertex_id);
}
#endif
return false;
}
void sRobotArrangement::generate_Walk(const sRobotArrangement &initial_arrangement, const sUndirectedGraph &environment)
{
for (int robot_id = 1; robot_id < m_robot_Locs.size(); ++robot_id)
{
const sVertex *vertex = environment.get_Vertex(initial_arrangement.get_RobotLocation(robot_id));
for (int i = 0; i < RANDOM_WALK_LENGTH; ++i)
{
if (!vertex->m_Neighbors.empty())
{
int rn = rand() % vertex->m_Neighbors.size();
sVertex::Neighbors_list::const_iterator neighbor = vertex->m_Neighbors.begin();
for (int n = 0; n < rn; ++n)
{
++neighbor;
}
vertex = (*neighbor)->m_target;
}
else
{
break;
}
}
for (int i = 0; i < RANDOM_WALK_LENGTH; ++i)
{
if (get_VertexOccupancy(vertex->m_id) == VACANT_VERTEX)
{
place_Robot(robot_id, vertex->m_id);
break;
}
if (!vertex->m_Neighbors.empty())
{
int rn = rand() % vertex->m_Neighbors.size();
sVertex::Neighbors_list::const_iterator neighbor = vertex->m_Neighbors.begin();
for (int n = 0; n < rn; ++n)
{
++neighbor;
}
vertex = (*neighbor)->m_target;
}
else
{
sASSERT(false);
break;
}
}
}
}
void sRobotArrangement::generate_DisjointWalk(const sRobotArrangement &initial_arrangement, const sUndirectedGraph &environment)
{
for (int robot_id = 1; robot_id < m_robot_Locs.size(); ++robot_id)
{
const sVertex *vertex = environment.get_Vertex(initial_arrangement.get_RobotLocation(robot_id));
for (int i = 0; i < RANDOM_WALK_LENGTH; ++i)
{
if (!vertex->m_Neighbors.empty())
{
int rn = rand() % vertex->m_Neighbors.size();
sVertex::Neighbors_list::const_iterator neighbor = vertex->m_Neighbors.begin();
for (int n = 0; n < rn; ++n)
{
++neighbor;
}
vertex = (*neighbor)->m_target;
}
else
{
break;
}
}
bool stand_in = true;
for (int i = 0; i < RANDOM_WALK_LENGTH || stand_in; ++i)
{
if (get_VertexOccupancy(vertex->m_id) == VACANT_VERTEX)
{
place_Robot(robot_id, vertex->m_id);
break;
}
if (!vertex->m_Neighbors.empty())
{
int rn = rand() % vertex->m_Neighbors.size();
sVertex::Neighbors_list::const_iterator neighbor = vertex->m_Neighbors.begin();
for (int n = 0; n < rn; ++n)
{
++neighbor;
}
vertex = (*neighbor)->m_target;
}
else
{
sASSERT(false);
break;
}
stand_in = false;
if (initial_arrangement.get_RobotLocation(robot_id) == get_RobotLocation(robot_id))
{
stand_in = true;
}
}
}
}
void sRobotArrangement::generate_NovelWalk(const sRobotArrangement &initial_arrangement, const sUndirectedGraph &environment)
{
sRobotArrangement robot_arrangement = initial_arrangement;
bool stand_in = false;
for (int i = 0; i < RANDOM_WALK_LENGTH || stand_in; ++i)
{
for (int robot_id = 1; robot_id < m_robot_Locs.size(); ++robot_id)
{
const sVertex *vertex = environment.get_Vertex(robot_arrangement.get_RobotLocation(robot_id));
if (!vertex->m_Neighbors.empty())
{
int rn = rand() % vertex->m_Neighbors.size();
sVertex::Neighbors_list::const_iterator neighbor = vertex->m_Neighbors.begin();
for (int n = 0; n < rn; ++n)
{
++neighbor;
}
vertex = (*neighbor)->m_target;
if (robot_arrangement.get_VertexOccupancy(vertex->m_id) == VACANT_VERTEX)
{
robot_arrangement.move_Robot(robot_id, vertex->m_id);
}
}
}
/*
stand_in = false;
for (int robot_id = 1; robot_id < m_robot_Locs.size(); ++robot_id)
{
if (initial_arrangement.get_RobotLocation(robot_id) == robot_arrangement.get_RobotLocation(robot_id))
{
stand_in = true;
break;
}
}
*/
}
*this = robot_arrangement;
}
sResult sRobotArrangement::generate_Nonconflicting(int N_Vertices, int N_Robots, const sUndirectedGraph &environment)
{
m_robot_Locs.resize(N_Robots + 1);
m_vertex_Occups.resize(N_Vertices);
for (int i = 0; i < N_Vertices; ++i)
{
m_vertex_Occups[i] = VACANT_VERTEX;
}
Vertices_vector Vertices;
int remain = 0;
for (int i = 0; i < N_Vertices; ++i)
{
Vertices.push_back(i);
++remain;
}
int r = N_Robots;
while (r >= 1)
{
if (remain <= 0)
{
return -1;
}
int rnd = rand() % remain;
int pos = Vertices[rnd];
place_Robot(r, Vertices[rnd]);
Vertices[rnd] = Vertices[--remain];
sVertex::VertexIDs_vector Conflicts = environment.m_Vertices[pos].m_Conflicts;
for (sVertex::VertexIDs_vector::const_iterator conflict = Conflicts.begin(); conflict != Conflicts.end(); ++conflict)
{
for (int i = 0; i < remain; ++i)
{
if (Vertices[i] == *conflict)
{
Vertices[i] = Vertices[--remain];
break;
}
}
}
--r;
}
return sRESULT_SUCCESS;
}
void sRobotArrangement::generate_NovelNonconflictingWalk(const sRobotArrangement &initial_arrangement, const sUndirectedGraph &environment)
{
sRobotArrangement robot_arrangement = initial_arrangement;
bool stand_in = false;
for (int i = 0; i < RANDOM_WALK_LENGTH || stand_in; ++i)
{
for (int robot_id = 1; robot_id < m_robot_Locs.size(); ++robot_id)
{
const sVertex *vertex = environment.get_Vertex(robot_arrangement.get_RobotLocation(robot_id));
if (!vertex->m_Neighbors.empty())
{
int rn = rand() % vertex->m_Neighbors.size();
sVertex::Neighbors_list::const_iterator neighbor = vertex->m_Neighbors.begin();
for (int n = 0; n < rn; ++n)
{
++neighbor;
}
vertex = (*neighbor)->m_target;
if (robot_arrangement.get_VertexOccupancy(vertex->m_id) == VACANT_VERTEX)
{
bool non_conflict = true;
sVertex::VertexIDs_vector Conflicts = environment.m_Vertices[vertex->m_id].m_Conflicts;
for (sVertex::VertexIDs_vector::const_iterator conflict = Conflicts.begin(); conflict != Conflicts.end(); ++conflict)
{
if (robot_arrangement.get_VertexOccupancy(*conflict) != VACANT_VERTEX && robot_arrangement.get_VertexOccupancy(*conflict) != robot_id)
{
non_conflict = false;
break;
}
}
if (non_conflict)
{
robot_arrangement.move_Robot(robot_id, vertex->m_id);
}
}
}
}
/*
stand_in = false;
for (int robot_id = 1; robot_id < m_robot_Locs.size(); ++robot_id)
{
if (initial_arrangement.get_RobotLocation(robot_id) == robot_arrangement.get_RobotLocation(robot_id))
{
stand_in = true;
break;
}
}
*/
}
*this = robot_arrangement;
}
void sRobotArrangement::generate_Walk(const sRobotArrangement &initial_arrangement, const sUndirectedGraph &environment, int N_fixed)
{
for (int robot_id = 1; robot_id < N_fixed; ++robot_id)
{
place_Robot(robot_id, initial_arrangement.get_RobotLocation(robot_id));
}
for (int robot_id = N_fixed; robot_id < m_robot_Locs.size(); ++robot_id)
{
const sVertex *vertex = environment.get_Vertex(initial_arrangement.get_RobotLocation(robot_id));
for (int i = 0; i < RANDOM_WALK_LENGTH; ++i)
{
if (!vertex->m_Neighbors.empty())
{
int rn = rand() % vertex->m_Neighbors.size();
sVertex::Neighbors_list::const_iterator neighbor = vertex->m_Neighbors.begin();
for (int n = 0; n < rn; ++n)
{
++neighbor;
}
vertex = (*neighbor)->m_target;
}
else
{
break;
}
}
for (int i = 0; i < RANDOM_WALK_LENGTH; ++i)
{
if (get_VertexOccupancy(vertex->m_id) == VACANT_VERTEX)
{
place_Robot(robot_id, vertex->m_id);
break;
}
if (!vertex->m_Neighbors.empty())
{
int rn = rand() % vertex->m_Neighbors.size();
sVertex::Neighbors_list::const_iterator neighbor = vertex->m_Neighbors.begin();
for (int n = 0; n < rn; ++n)
{
++neighbor;
}
vertex = (*neighbor)->m_target;
}
else
{
sASSERT(false);
break;
}
}
}
}
void sRobotArrangement::generate_Equidistant(const sRobotArrangement &initial_arrangement, sUndirectedGraph &environment, int distance)
{
int N_Robots = initial_arrangement.get_RobotCount();
int N_Vertices = environment.get_VertexCount();
for (int robot_id = 1; robot_id <= N_Robots; ++robot_id)
{
int s_id = initial_arrangement.get_RobotLocation(robot_id);
VertexIDs_vector equidistant_IDs, free_equidistant_IDs;
environment.collect_EquidistantVertices(s_id, distance, equidistant_IDs);
for (VertexIDs_vector::const_iterator equidistant = equidistant_IDs.begin(); equidistant != equidistant_IDs.end(); ++equidistant)
{
if (get_VertexOccupancy(*equidistant) == VACANT_VERTEX)
{
free_equidistant_IDs.push_back(*equidistant);
}
}
if (free_equidistant_IDs.empty())
{
VertexIDs_vector free_vertex_IDs;
for (int i = 0; i < N_Vertices; ++i)
{
if (get_VertexOccupancy(i) == VACANT_VERTEX)
{
free_vertex_IDs.push_back(i);
}
}
int rnd = rand() % free_vertex_IDs.size();
place_Robot(robot_id, free_vertex_IDs[rnd]);
}
else
{
int rnd = rand() % free_equidistant_IDs.size();
place_Robot(robot_id, free_equidistant_IDs[rnd]);
}
}
}
/*----------------------------------------------------------------------------*/
void sRobotArrangement::to_Screen(const sString &indent) const
{
to_Stream(stdout, indent);
}
void sRobotArrangement::to_Stream(FILE *fw, const sString &indent) const
{
fprintf(fw, "%sRobot arrangement: (|R| = %ld, |V| = %ld) [\n", indent.c_str(), m_robot_Locs.size() - 1, m_vertex_Occups.size());
fprintf(fw, "%s%s robot locations: {", indent.c_str(), sRELOC_INDENT.c_str());
int N_Robots_1 = m_robot_Locs.size();
for (int i = 1; i < N_Robots_1; ++i)
{
fprintf(fw, "%d#%d ", i, m_robot_Locs[i]);
}
fprintf(fw, "}\n");
fprintf(fw, "%s%s vertex occupancy: {", indent.c_str(), sRELOC_INDENT.c_str());
int N_Vertices = m_vertex_Occups.size();
for (int i = 0; i < N_Vertices; ++i)
{
fprintf(fw, "%d#%d ", m_vertex_Occups[i], i);
}
fprintf(fw, "}\n");
if (!m_robot_Sizes.empty())
{
fprintf(fw, "%s%s robot sizes: {", indent.c_str(), sRELOC_INDENT.c_str());
for (int i = 1; i < N_Robots_1; ++i)
{
fprintf(fw, "%d(%d) ", i, m_robot_Sizes[i]);
}
fprintf(fw, "}\n");
}
fprintf(fw, "%s]\n", indent.c_str());
}
void sRobotArrangement::to_Screen_brief(const sString &indent) const
{
to_Stream_brief(stdout, indent);
}
void sRobotArrangement::to_Stream_brief(FILE *fw, const sString &indent) const
{
fprintf(fw, "%sRobot arrangement (brief): (|R| = %ld, |V| = %ld) [\n", indent.c_str(), m_robot_Locs.size() - 1, m_vertex_Occups.size());
fprintf(fw, "%s%s robot locations: {", indent.c_str(), sRELOC_INDENT.c_str());
int N_Robots_1 = m_robot_Locs.size();
for (int i = 1; i < N_Robots_1; ++i)
{
fprintf(fw, "%d#%d ", i, m_robot_Locs[i]);
}
fprintf(fw, "}\n");
fprintf(fw, "%s]\n", indent.c_str());
}
sResult sRobotArrangement::to_File_multirobot(const sString &filename, const sString &indent) const
{
FILE *fw;
if ((fw = fopen(filename.c_str(), "w")) == NULL)
{
return sROBOT_ARRANGEMENT_OPEN_ERROR;
}
to_Stream_multirobot(fw, indent);
fclose(fw);
return sRESULT_SUCCESS;
}
void sRobotArrangement::to_Stream_multirobot(FILE *fw, const sString &indent) const
{
fprintf(fw, "%sV =\n", indent.c_str());
int N_Vertices = m_vertex_Occups.size();
for (int i = 0; i < N_Vertices; ++i)
{
fprintf(fw, "(%d:-1)[%d:-1:-1]\n", i, m_vertex_Occups[i]);
}
}
sResult sRobotArrangement::from_File_multirobot(const sString &filename, int component)
{
sResult result;
FILE *fr;
if ((fr = fopen(filename.c_str(), "r")) == NULL)
{
return sROBOT_ARRANGEMENT_OPEN_ERROR;
}
result = from_Stream_multirobot(fr, component);
if (sFAILED(result))
{
fclose(fr);
return result;
}
fclose(fr);
return sRESULT_SUCCESS;
}
sResult sRobotArrangement::from_Stream_multirobot(FILE *fr, int component)
{
m_robot_Locs.clear();
m_vertex_Occups.clear();
int N_Robots = 0;
int N_Vertices = 0;
int c = fgetc(fr);
while (c != 'V')
{
if (c != '\n')
{
while(fgetc(fr) != '\n');
}
c = fgetc(fr);
}
fscanf(fr, " =\n");
long position = ftell(fr);
c = fgetc(fr);
while (c == '(')
{
int vertex_id, cycle_id, robot_id;
switch (component)
{
case 0:
{
fscanf(fr, "%d:%d)[%d", &vertex_id, &cycle_id, &robot_id);
break;
}
case 1:
{
int dummy_robot_1_id;
fscanf(fr, "%d:%d)[%d:%d", &vertex_id, &cycle_id, &dummy_robot_1_id, &robot_id);
break;
}
case 2:
{
int dummy_robot_1_id, dummy_robot_2_id;
fscanf(fr, "%d:%d)[%d:%d:%d", &vertex_id, &cycle_id, &dummy_robot_1_id, &dummy_robot_2_id, &robot_id);
break;
}
default:
{
sASSERT(false);
break;
}
}
if (robot_id > 0)
{
++N_Robots;
}
++N_Vertices;
if (c != '\n')
{
while(fgetc(fr) != '\n');
}
c = fgetc(fr);
// printf("read: %d,%d,%d\n", vertex_id, cycle_id, robot_id);
}
if (fseek(fr, position, SEEK_SET) != 0)
{
return sROBOT_ARRANGEMENT_SEEK_ERROR;
}
c = fgetc(fr);
m_robot_Locs.resize(N_Robots + 1, (const int)UNDEFINED_LOCATION);
m_vertex_Occups.resize(N_Vertices, (const int)VACANT_VERTEX);
while (c == '(')
{
int vertex_id, cycle_id, robot_id;
switch (component)
{
case 0:
{
fscanf(fr, "%d:%d)[%d", &vertex_id, &cycle_id, &robot_id);
break;
}
case 1:
{
int dummy_robot_1_id;
fscanf(fr, "%d:%d)[%d:%d", &vertex_id, &cycle_id, &dummy_robot_1_id, &robot_id);
break;
}
case 2:
{
int dummy_robot_1_id, dummy_robot_2_id;
fscanf(fr, "%d:%d)[%d:%d:%d", &vertex_id, &cycle_id, &dummy_robot_1_id, &dummy_robot_2_id, &robot_id);
break;
}
default:
{
sASSERT(false);
break;
}
}
if (robot_id > 0)
{
m_robot_Locs[robot_id] = vertex_id;
m_vertex_Occups[vertex_id] = robot_id;
}
if (c != '\n')
{
while(fgetc(fr) != '\n');
}
c = fgetc(fr);
}
return sRESULT_SUCCESS;
}
sResult sRobotArrangement::to_File_capacitated_multirobot(const sString &filename, const sUndirectedGraph &environment, const sString &indent) const
{
FILE *fw;
if ((fw = fopen(filename.c_str(), "w")) == NULL)
{
return sROBOT_ARRANGEMENT_OPEN_ERROR;
}
to_Stream_capacitated_multirobot(fw, environment, indent);
fclose(fw);
return sRESULT_SUCCESS;
}
void sRobotArrangement::to_Stream_capacitated_multirobot(FILE *fw, const sUndirectedGraph &environment, const sString &indent) const
{
fprintf(fw, "%sV =\n", indent.c_str());
int N_Vertices = m_vertex_Occups.size();
for (int i = 0; i < N_Vertices; ++i)
{
fprintf(fw, "(%d:-1:%d)[%d:-1:-1]\n", i, environment.m_Vertices[i].m_capacity, m_vertex_Occups[i]);
}
}
sResult sRobotArrangement::from_File_capacitated_multirobot(const sString &filename, sUndirectedGraph &environment, int component)
{
sResult result;
FILE *fr;
if ((fr = fopen(filename.c_str(), "r")) == NULL)
{
return sROBOT_ARRANGEMENT_OPEN_ERROR;
}
result = from_Stream_capacitated_multirobot(fr, environment, component);
if (sFAILED(result))
{
fclose(fr);
return result;
}
fclose(fr);
return sRESULT_SUCCESS;
}
sResult sRobotArrangement::from_Stream_capacitated_multirobot(FILE *fr, sUndirectedGraph &environment, int component)
{
m_robot_Locs.clear();
m_vertex_Occups.clear();
int N_Robots = 0;
int N_Vertices = 0;
int c = fgetc(fr);
while (c != 'V')
{
if (c != '\n')
{
while(fgetc(fr) != '\n');
}
c = fgetc(fr);
}
fscanf(fr, " =\n");
long position = ftell(fr);
c = fgetc(fr);
while (c == '(')
{
int vertex_id, cycle_id, robot_id, capacity;
switch (component)
{
case 0:
{
fscanf(fr, "%d:%d:%d)[%d", &vertex_id, &cycle_id, &capacity, &robot_id);
break;
}
case 1:
{
int dummy_robot_1_id;
fscanf(fr, "%d:%d:%d)[%d:%d", &vertex_id, &cycle_id, &capacity, &dummy_robot_1_id, &robot_id);
break;
}
case 2:
{
int dummy_robot_1_id, dummy_robot_2_id;
fscanf(fr, "%d:%d:%d)[%d:%d:%d", &vertex_id, &cycle_id, &capacity, &dummy_robot_1_id, &dummy_robot_2_id, &robot_id);
break;
}
default:
{
sASSERT(false);
break;
}
}
if (robot_id > 0)
{
++N_Robots;
}
++N_Vertices;
if (c != '\n')
{
while(fgetc(fr) != '\n');
}
c = fgetc(fr);
// printf("read: %d,%d,%d\n", vertex_id, cycle_id, robot_id);
}
if (fseek(fr, position, SEEK_SET) != 0)
{
return sROBOT_ARRANGEMENT_SEEK_ERROR;
}
c = fgetc(fr);
m_robot_Locs.resize(N_Robots + 1, (const int)UNDEFINED_LOCATION);
m_vertex_Occups.resize(N_Vertices, (const int)VACANT_VERTEX);
while (c == '(')
{
int vertex_id, cycle_id, robot_id, capacity;
switch (component)
{
case 0:
{
fscanf(fr, "%d:%d:%d)[%d", &vertex_id, &cycle_id, &capacity, &robot_id);
break;
}
case 1:
{
int dummy_robot_1_id;
fscanf(fr, "%d:%d:%d)[%d:%d", &vertex_id, &cycle_id, &capacity, &dummy_robot_1_id, &robot_id);
break;
}
case 2:
{
int dummy_robot_1_id, dummy_robot_2_id;
fscanf(fr, "%d:%d:%d)[%d:%d:%d", &vertex_id, &cycle_id, &capacity, &dummy_robot_1_id, &dummy_robot_2_id, &robot_id);
break;
}
default:
{
sASSERT(false);
break;
}
}
if (robot_id > 0)
{
m_robot_Locs[robot_id] = vertex_id;
m_vertex_Occups[vertex_id] = robot_id;
}
if (c != '\n')
{
while(fgetc(fr) != '\n');
}
c = fgetc(fr);
environment.m_Vertices[vertex_id].m_capacity = capacity;
}
return sRESULT_SUCCESS;
}
/*----------------------------------------------------------------------------*/
// sRobotGoal
sRobotGoal::sRobotGoal()
{
// nothing
}
sRobotGoal::sRobotGoal(int N_Vertices, int N_Robots)
: m_robot_Goals(N_Robots + 1)
, m_goal_Compats(N_Vertices)
{
// nothing
}
sRobotGoal::sRobotGoal(int N_Vertices, int N_Robots, int N_Goals)
: m_robot_Goals(N_Robots + 1)
, m_goal_Compats(N_Vertices)
{
for (int i = 1; i <= N_Robots; ++i)
{
int rnd_N_goals = 1 + rand() % N_Goals;
sRobotArrangement::Vertices_vector vertex_IDs;
for (int j = 0; j < N_Vertices; ++j)
{
vertex_IDs.push_back(j);
}
for (int j = 0; j < rnd_N_goals; ++j)
{
int rnd_vertex_ID = rand() % vertex_IDs.size();
charge_Robot(i, rnd_vertex_ID);
vertex_IDs[rnd_vertex_ID] = *vertex_IDs.rbegin();
vertex_IDs.pop_back();
}
}
}
sRobotGoal::sRobotGoal(const sRobotArrangement &sUNUSED(initial_arrangement), int N_Vertices, int N_Robots, int sUNUSED(N_Goals))
: m_robot_Goals(N_Robots + 1)
, m_goal_Compats(N_Vertices)
{
sASSERT(false);
}
sRobotGoal::sRobotGoal(const sRobotArrangement &robot_arrangement)
: m_robot_Goals(robot_arrangement.get_RobotCount() + 1)
, m_goal_Compats(robot_arrangement.get_VertexCount())
{
int N_Vertices = robot_arrangement.get_VertexCount();
for (int i = 0; i < N_Vertices; ++i)
{
int robot_id = robot_arrangement.get_VertexOccupancy(i);
if (robot_id > 0)
{
assign_Goal(i, robot_id);
}
}
}
int sRobotGoal::get_RobotCount(void) const
{
return (m_robot_Goals.size() - 1);
}
int sRobotGoal::get_VertexCount(void) const
{
return m_goal_Compats.size();
}
const sRobotGoal::Vertices_set& sRobotGoal::get_RobotGoal(int robot_id) const
{
sASSERT(robot_id > 0 && robot_id < m_robot_Goals.size());
return m_robot_Goals[robot_id];
}
sRobotGoal::Vertices_set& sRobotGoal::provide_RobotGoal(int robot_id)
{
sASSERT(robot_id > 0 && robot_id < m_robot_Goals.size());
return m_robot_Goals[robot_id];
}
const sRobotGoal::Robots_set& sRobotGoal::get_GoalCompatibility(int goal_id) const
{
sASSERT(goal_id >= 0 && goal_id < m_goal_Compats.size());
return m_goal_Compats[goal_id];
}
sRobotGoal::Robots_set& sRobotGoal::provide_GoalCompatibility(int goal_id)
{
sASSERT(goal_id >= 0 && goal_id < m_goal_Compats.size());
return m_goal_Compats[goal_id];
}
void sRobotGoal::charge_Robot(int robot_id, int goal_id)
{
sASSERT(robot_id > 0 && robot_id < m_robot_Goals.size());
sASSERT(goal_id >= 0 && goal_id < m_goal_Compats.size());
m_robot_Goals[robot_id].insert(goal_id);
m_goal_Compats[goal_id].insert(robot_id);
}
void sRobotGoal::charge_Robot(int robot_id, const Vertices_set &goal_IDs)
{
sASSERT(robot_id > 0 && robot_id < m_robot_Goals.size());
m_robot_Goals[robot_id].insert(goal_IDs.begin(), goal_IDs.end());
for (Vertices_set::const_iterator goal_id = goal_IDs.begin(); goal_id != goal_IDs.end(); ++goal_id)
{
sASSERT(*goal_id >= 0 && *goal_id < m_goal_Compats.size());
m_goal_Compats[*goal_id].insert(robot_id);
}
}
void sRobotGoal::assign_Goal(int goal_id, int robot_id)
{
sASSERT(robot_id > 0 && robot_id < m_robot_Goals.size());
sASSERT(goal_id >= 0 && goal_id < m_goal_Compats.size());
m_goal_Compats[goal_id].insert(robot_id);
m_robot_Goals[robot_id].insert(goal_id);
}
void sRobotGoal::assign_Goal(int goal_id, const Robots_set &robot_IDs)
{
sASSERT(goal_id >= 0 && goal_id < m_goal_Compats.size());
m_goal_Compats[goal_id].insert(robot_IDs.begin(), robot_IDs.end());
for (Robots_set::const_iterator robot_id = robot_IDs.begin(); robot_id != robot_IDs.end(); ++robot_id)
{
sASSERT(*robot_id > 0 && *robot_id < m_robot_Goals.size());
m_robot_Goals[*robot_id].insert(goal_id);
}
}
void sRobotGoal::discharge_Robot(int robot_id)
{
sASSERT(robot_id > 0 && robot_id < m_robot_Goals.size());
const Vertices_set &goal_IDs = m_robot_Goals[robot_id];
for (Vertices_set::const_iterator goal_id = goal_IDs.begin(); goal_id != goal_IDs.end(); ++goal_id)
{
m_goal_Compats[*goal_id].erase(robot_id);
}
m_robot_Goals[robot_id].clear();
}
void sRobotGoal::discharge_Robot(int robot_id, int goal_id)
{
sASSERT(robot_id > 0 && robot_id < m_robot_Goals.size());
sASSERT(goal_id >= 0 && goal_id < m_goal_Compats.size());
m_robot_Goals[robot_id].erase(goal_id);
m_goal_Compats[goal_id].erase(robot_id);
}
void sRobotGoal::discharge_Robot(int robot_id, const Vertices_set &goal_IDs)
{
sASSERT(robot_id > 0 && robot_id < m_robot_Goals.size());
for (Vertices_set::const_iterator goal_id = goal_IDs.begin(); goal_id != goal_IDs.end(); ++goal_id)
{
m_goal_Compats[*goal_id].erase(robot_id);
}
m_robot_Goals[robot_id].erase(goal_IDs.begin(), goal_IDs.end());
}
bool sRobotGoal::is_Satisfied(const sRobotArrangement &robot_arrangement) const
{
int N_Robots = robot_arrangement.get_RobotCount();
for (int robot_id = 1; robot_id <= N_Robots; ++robot_id)
{
const Vertices_set &robot_goal = get_RobotGoal(robot_id);
if (robot_goal.find(robot_arrangement.get_RobotLocation(robot_id)) == robot_goal.end())
{
return false;
}
}
return true;
}
/*----------------------------------------------------------------------------*/
void sRobotGoal::to_Screen(const sString &indent) const
{
to_Stream(stdout, indent);
}
void sRobotGoal::to_Stream(FILE *fw, const sString &indent) const
{
fprintf(fw, "%sRobot goal: (|R| = %ld, |V| = %ld) [\n", indent.c_str(), m_robot_Goals.size() - 1, m_goal_Compats.size());
fprintf(fw, "%s%srobot goals: {\n", indent.c_str(), sRELOC_INDENT.c_str());
int N_Robots_1 = m_robot_Goals.size();
for (int i = 1; i < N_Robots_1; ++i)
{
const Vertices_set &goal_IDs = m_robot_Goals[i];
fprintf(fw, "%s%s%s%d#{", indent.c_str(), sRELOC_INDENT.c_str(), sRELOC_INDENT.c_str(), i);
if (!goal_IDs.empty())
{
Vertices_set::const_iterator goal_id = goal_IDs.begin();
fprintf(fw, "%d", *goal_id);
while (++goal_id != goal_IDs.end())
{
fprintf(fw, ",%d", *goal_id);
}
}
fprintf(fw, "}\n");
}
fprintf(fw, "%s%s}\n", indent.c_str(), sRELOC_INDENT.c_str());
fprintf(fw, "%s%svertex compatibilities: {\n", indent.c_str(), sRELOC_INDENT.c_str());
int N_Vertices = m_goal_Compats.size();
for (int i = 0; i < N_Vertices; ++i)
{
const Robots_set &robot_IDs = m_goal_Compats[i];
fprintf(fw, "%s%s%s%d@{", indent.c_str(), sRELOC_INDENT.c_str(), sRELOC_INDENT.c_str(), i);
if (!robot_IDs.empty())
{
Robots_set::const_iterator robot_id = robot_IDs.begin();
fprintf(fw, "%d", *robot_id);
while (++robot_id != robot_IDs.end())
{
fprintf(fw, ",%d", *robot_id);
}
}
fprintf(fw, "}\n");
}
fprintf(fw, "%s%s}\n", indent.c_str(), sRELOC_INDENT.c_str());
fprintf(fw, "%s]\n", indent.c_str());
}
void sRobotGoal::to_Screen_brief(const sString &indent) const
{
to_Stream_brief(stdout, indent);
}
void sRobotGoal::to_Stream_brief(FILE *fw, const sString &indent) const
{
fprintf(fw, "%sRobot goal (brief): (|R| = %ld, |V| = %ld) [\n", indent.c_str(), m_robot_Goals.size() - 1, m_goal_Compats.size());
fprintf(fw, "%s%srobot goals: {\n", indent.c_str(), sRELOC_INDENT.c_str());
int N_Robots_1 = m_robot_Goals.size();
for (int i = 1; i < N_Robots_1; ++i)
{
const Vertices_set &goal_IDs = m_robot_Goals[i];
fprintf(fw, "%s%s%s%d#{", indent.c_str(), sRELOC_INDENT.c_str(), sRELOC_INDENT.c_str(), i);
if (!goal_IDs.empty())
{
Vertices_set::const_iterator goal_id = goal_IDs.begin();
fprintf(fw, "%d", *goal_id);
while (++goal_id != goal_IDs.end())
{
fprintf(fw, ",%d", *goal_id);
}
}
fprintf(fw, "}\n");
}
fprintf(fw, "%s%s}\n", indent.c_str(), sRELOC_INDENT.c_str());
fprintf(fw, "%s]\n", indent.c_str());
}
sResult sRobotGoal::to_File_multirobot(const sString &filename, const sString &indent) const
{
FILE *fw;
if ((fw = fopen(filename.c_str(), "w")) == NULL)
{
return sROBOT_GOAL_OPEN_ERROR;
}
to_Stream_multirobot(fw, indent);
fclose(fw);
return sRESULT_SUCCESS;
}
void sRobotGoal::to_Stream_multirobot(FILE *fw, const sString &indent) const
{
fprintf(fw, "%sV =\n", indent.c_str());
int N_Compats = m_goal_Compats.size();
for (int i = 0; i < N_Compats; ++i)
{
const Robots_set &robot_IDs = m_goal_Compats[i];
fprintf(fw, "(%d:-1)[", i);
to_Stream_multirobot(fw, robot_IDs, indent);
fprintf(fw, ":-1:-1]\n");
}
}
void sRobotGoal::to_Stream_multirobot(FILE *fw, const Robots_set &robot_IDs, const sString &sUNUSED(indent)) const
{
fprintf(fw, "{");
if (!robot_IDs.empty())
{
Robots_set::const_iterator robot_id = robot_IDs.begin();
fprintf(fw, "%d", *robot_id);
while (++robot_id != robot_IDs.end())
{
fprintf(fw, ",%d", *robot_id);
}
}
fprintf(fw, "}");
}
sResult sRobotGoal::from_File_multirobot(const sString &filename, int component)
{
sResult result;
FILE *fr;
if ((fr = fopen(filename.c_str(), "r")) == NULL)
{
return sROBOT_GOAL_OPEN_ERROR;
}
result = from_Stream_multirobot(fr, component);
if (sFAILED(result))
{
fclose(fr);
return result;
}
fclose(fr);
return sRESULT_SUCCESS;
}
sResult sRobotGoal::from_Stream_multirobot(FILE *fr, int component)
{
Robots_set all_robot_IDs;
m_robot_Goals.clear();
m_goal_Compats.clear();
int N_Robots = 0;
int N_Vertices = 0;
int c = fgetc(fr);
while (c != 'V')
{
if (c != '\n')
{
while(fgetc(fr) != '\n');
}
c = fgetc(fr);
}
fscanf(fr, " =\n");
long position = ftell(fr);
c = fgetc(fr);
while (c == '(')
{
int vertex_id, cycle_id, robot_id = 0;
switch (component)
{
case 0:
{
fscanf(fr, "%d:%d)[", &vertex_id, &cycle_id);
c = fgetc(fr);
ungetc(c, fr);
if (c == '{')
{
Robots_set robot_IDs;
from_Stream_multirobot(fr, robot_IDs);
all_robot_IDs.insert(robot_IDs.begin(), robot_IDs.end());
}
else
{
fscanf(fr, "%d", &robot_id);
if (robot_id > 0)
{
all_robot_IDs.insert(robot_id);
}
}
break;
}
case 1:
{
int dummy_robot_1_id;
fscanf(fr, "%d:%d)[%d:", &vertex_id, &cycle_id, &dummy_robot_1_id);
c = fgetc(fr);
ungetc(c, fr);
if (c == '{')
{
Robots_set robot_IDs;
from_Stream_multirobot(fr, robot_IDs);
all_robot_IDs.insert(robot_IDs.begin(), robot_IDs.end());
}
else
{
fscanf(fr, "%d", &robot_id);
if (robot_id > 0)
{
all_robot_IDs.insert(robot_id);
}
}
break;
}
case 2:
{
int dummy_robot_1_id, dummy_robot_2_id;
fscanf(fr, "%d:%d)[%d:%d:", &vertex_id, &cycle_id, &dummy_robot_1_id, &dummy_robot_2_id);
c = fgetc(fr);
ungetc(c, fr);
if (c == '{')
{
Robots_set robot_IDs;
from_Stream_multirobot(fr, robot_IDs);
all_robot_IDs.insert(robot_IDs.begin(), robot_IDs.end());
}
else
{
fscanf(fr, "%d", &robot_id);
if (robot_id > 0)
{
all_robot_IDs.insert(robot_id);
}
}
break;
}
default:
{
sASSERT(false);
break;
}
}
++N_Vertices;
if (c != '\n')
{
while(fgetc(fr) != '\n');
}
c = fgetc(fr);
}
N_Robots = all_robot_IDs.size();
if (fseek(fr, position, SEEK_SET) != 0)
{
return sROBOT_GOAL_SEEK_ERROR;
}
c = fgetc(fr);
m_robot_Goals.resize(N_Robots + 1);
m_goal_Compats.resize(N_Vertices);
while (c == '(')
{
int vertex_id, cycle_id, robot_id;
switch (component)
{
case 0:
{
fscanf(fr, "%d:%d)[", &vertex_id, &cycle_id);
c = fgetc(fr);
ungetc(c, fr);
if (c == '{')
{
Robots_set robot_IDs;
from_Stream_multirobot(fr, robot_IDs);
if (!robot_IDs.empty())
{
assign_Goal(vertex_id, robot_IDs);
}
}
else
{
fscanf(fr, "%d", &robot_id);
if (robot_id > 0)
{
assign_Goal(vertex_id, robot_id);
}
}
break;
}
case 1:
{
int dummy_robot_1_id;
fscanf(fr, "%d:%d)[%d:", &vertex_id, &cycle_id, &dummy_robot_1_id);
c = fgetc(fr);
ungetc(c, fr);
if (c == '{')
{
Robots_set robot_IDs;
from_Stream_multirobot(fr, robot_IDs);
if (!robot_IDs.empty())
{
assign_Goal(vertex_id, robot_IDs);
}
}
else
{
fscanf(fr, "%d", &robot_id);
if (robot_id > 0)
{
assign_Goal(vertex_id, robot_id);
}
}
break;
}
case 2:
{
int dummy_robot_1_id, dummy_robot_2_id;
fscanf(fr, "%d:%d)[%d:%d:", &vertex_id, &cycle_id, &dummy_robot_1_id, &dummy_robot_2_id);
c = fgetc(fr);
ungetc(c, fr);
if (c == '{')
{
Robots_set robot_IDs;
from_Stream_multirobot(fr, robot_IDs);
if (!robot_IDs.empty())
{
assign_Goal(vertex_id, robot_IDs);
}
}
else
{
fscanf(fr, "%d", &robot_id);
if (robot_id > 0)
{
assign_Goal(vertex_id, robot_id);
}
}
break;
}
default:
{
sASSERT(false);
break;
}
}
if (c != '\n')
{
while(fgetc(fr) != '\n');
}
c = fgetc(fr);
}
return sRESULT_SUCCESS;
}
sResult sRobotGoal::from_Stream_multirobot(FILE *fr, Robots_set &robot_IDs)
{
fscanf(fr, "{");
int robot_ID;
int c = fgetc(fr);
while (c != '}')
{
if (c != ',')
{
ungetc(c, fr);
}
fscanf(fr, "%d", &robot_ID);
robot_IDs.insert(robot_ID);
c = fgetc(fr);
}
fscanf(fr, "}");
return sRESULT_SUCCESS;
}
sResult sRobotGoal::to_File_capacitated_multirobot(const sString &filename, const sUndirectedGraph &environment, const sString &indent) const
{
FILE *fw;
if ((fw = fopen(filename.c_str(), "w")) == NULL)
{
return sROBOT_GOAL_OPEN_ERROR;
}
to_Stream_capacitated_multirobot(fw, environment, indent);
fclose(fw);
return sRESULT_SUCCESS;
}
void sRobotGoal::to_Stream_capacitated_multirobot(FILE *fw, const sUndirectedGraph &environment, const sString &indent) const
{
fprintf(fw, "%sV =\n", indent.c_str());
int N_Compats = m_goal_Compats.size();
for (int i = 0; i < N_Compats; ++i)
{
const Robots_set &robot_IDs = m_goal_Compats[i];
fprintf(fw, "(%d:-1:%d)[", i, environment.m_Vertices[i].m_capacity);
to_Stream_multirobot(fw, robot_IDs, indent);
fprintf(fw, ":-1:-1]\n");
}
}
sResult sRobotGoal::from_File_capacitated_multirobot(const sString &filename, sUndirectedGraph &environment, int component)
{
sResult result;
FILE *fr;
if ((fr = fopen(filename.c_str(), "r")) == NULL)
{
return sROBOT_GOAL_OPEN_ERROR;
}
result = from_Stream_capacitated_multirobot(fr, environment, component);
if (sFAILED(result))
{
fclose(fr);
return result;
}
fclose(fr);
return sRESULT_SUCCESS;
}
sResult sRobotGoal::from_Stream_capacitated_multirobot(FILE *fr, sUndirectedGraph &environment, int component)
{
Robots_set all_robot_IDs;
m_robot_Goals.clear();
m_goal_Compats.clear();
int N_Robots = 0;
int N_Vertices = 0;
int c = fgetc(fr);
while (c != 'V')
{
if (c != '\n')
{
while(fgetc(fr) != '\n');
}
c = fgetc(fr);
}
fscanf(fr, " =\n");
long position = ftell(fr);
c = fgetc(fr);
while (c == '(')
{
int vertex_id, cycle_id, robot_id = 0, capacity = 1;
switch (component)
{
case 0:
{
fscanf(fr, "%d:%d:%d)[", &vertex_id, &cycle_id, &capacity);
c = fgetc(fr);
ungetc(c, fr);
if (c == '{')
{
Robots_set robot_IDs;
from_Stream_multirobot(fr, robot_IDs);
all_robot_IDs.insert(robot_IDs.begin(), robot_IDs.end());
}
else
{
fscanf(fr, "%d", &robot_id);
if (robot_id > 0)
{
all_robot_IDs.insert(robot_id);
}
}
break;
}
case 1:
{
int dummy_robot_1_id;
fscanf(fr, "%d:%d:%d)[%d:", &vertex_id, &cycle_id, &capacity, &dummy_robot_1_id);
c = fgetc(fr);
ungetc(c, fr);
if (c == '{')
{
Robots_set robot_IDs;
from_Stream_multirobot(fr, robot_IDs);
all_robot_IDs.insert(robot_IDs.begin(), robot_IDs.end());
}
else
{
fscanf(fr, "%d", &robot_id);
if (robot_id > 0)
{
all_robot_IDs.insert(robot_id);
}
}
break;
}
case 2:
{
int dummy_robot_1_id, dummy_robot_2_id;
fscanf(fr, "%d:%d:%d)[%d:%d:", &vertex_id, &cycle_id, &capacity, &dummy_robot_1_id, &dummy_robot_2_id);
c = fgetc(fr);
ungetc(c, fr);
if (c == '{')
{
Robots_set robot_IDs;
from_Stream_multirobot(fr, robot_IDs);
all_robot_IDs.insert(robot_IDs.begin(), robot_IDs.end());
}
else
{
fscanf(fr, "%d", &robot_id);
if (robot_id > 0)
{
all_robot_IDs.insert(robot_id);
}
}
break;
}
default:
{
sASSERT(false);
break;
}
}
++N_Vertices;
if (c != '\n')
{
while(fgetc(fr) != '\n');
}
c = fgetc(fr);
}
N_Robots = all_robot_IDs.size();
if (fseek(fr, position, SEEK_SET) != 0)
{
return sROBOT_GOAL_SEEK_ERROR;
}
c = fgetc(fr);
m_robot_Goals.resize(N_Robots + 1);
m_goal_Compats.resize(N_Vertices);
while (c == '(')
{
int vertex_id, cycle_id, robot_id, capacity;
switch (component)
{
case 0:
{
fscanf(fr, "%d:%d:%d)[", &vertex_id, &cycle_id, &capacity);
c = fgetc(fr);
ungetc(c, fr);
if (c == '{')
{
Robots_set robot_IDs;
from_Stream_multirobot(fr, robot_IDs);
if (!robot_IDs.empty())
{
assign_Goal(vertex_id, robot_IDs);
}
}
else
{
fscanf(fr, "%d", &robot_id);
if (robot_id > 0)
{
assign_Goal(vertex_id, robot_id);
}
}
break;
}
case 1:
{
int dummy_robot_1_id;
fscanf(fr, "%d:%d:%d)[%d:", &vertex_id, &cycle_id, &capacity, &dummy_robot_1_id);
c = fgetc(fr);
ungetc(c, fr);
if (c == '{')
{
Robots_set robot_IDs;
from_Stream_multirobot(fr, robot_IDs);
if (!robot_IDs.empty())
{
assign_Goal(vertex_id, robot_IDs);
}
}
else
{
fscanf(fr, "%d", &robot_id);
if (robot_id > 0)
{
assign_Goal(vertex_id, robot_id);
}
}
break;
}
case 2:
{
int dummy_robot_1_id, dummy_robot_2_id;
fscanf(fr, "%d:%d:%d)[%d:%d:", &vertex_id, &cycle_id, &capacity, &dummy_robot_1_id, &dummy_robot_2_id);
c = fgetc(fr);
ungetc(c, fr);
if (c == '{')
{
Robots_set robot_IDs;
from_Stream_multirobot(fr, robot_IDs);
if (!robot_IDs.empty())
{
assign_Goal(vertex_id, robot_IDs);
}
}
else
{
fscanf(fr, "%d", &robot_id);
if (robot_id > 0)
{
assign_Goal(vertex_id, robot_id);
}
}
break;
}
default:
{
sASSERT(false);
break;
}
}
environment.m_Vertices[vertex_id].m_capacity = capacity;
if (c != '\n')
{
while(fgetc(fr) != '\n');
}
c = fgetc(fr);
}
return sRESULT_SUCCESS;
}
/*----------------------------------------------------------------------------*/
// sMultirobotEncodingContext_CNFsat
const int sMultirobotEncodingContext_CNFsat::UNDEFINED_LAYER_COUNT = -1;
/*----------------------------------------------------------------------------*/
sMultirobotEncodingContext_CNFsat::sMultirobotEncodingContext_CNFsat()
: m_N_Layers(UNDEFINED_LAYER_COUNT)
, m_max_total_cost(0)
, m_extra_cost(-1)
, m_max_total_fuel(0)
, m_extra_fuel(-1)
, m_fuel_makespan(-1)
, m_state_clause_generator(NULL)
, m_advanced_clause_generator(NULL)
, m_bitwise_clause_generator(NULL)
, m_bit_clause_generator(NULL)
{
m_state_Identifiers[sINT_32_MAX] = NULL;
m_bit_Identifiers[sINT_32_MAX] = NULL;
switchTo_StandardGeneratingMode();
}
sMultirobotEncodingContext_CNFsat::sMultirobotEncodingContext_CNFsat(int N_Layers)
: m_N_Layers(N_Layers)
, m_max_total_cost(0)
, m_extra_cost(-1)
, m_max_total_fuel(0)
, m_extra_fuel(-1)
, m_fuel_makespan(-1)
, m_state_clause_generator(&m_variable_store)
, m_advanced_clause_generator(&m_variable_store)
, m_bitwise_clause_generator(&m_variable_store)
, m_bit_clause_generator(&m_variable_store)
{
m_state_Identifiers[sINT_32_MAX] = NULL;
m_bit_Identifiers[sINT_32_MAX] = NULL;
switchTo_StandardGeneratingMode();
}
sMultirobotEncodingContext_CNFsat::sMultirobotEncodingContext_CNFsat(const sMultirobotEncodingContext_CNFsat &encoding_context)
: m_N_Layers(encoding_context.m_N_Layers)
, m_max_total_cost(encoding_context.m_max_total_cost)
, m_extra_cost(encoding_context.m_extra_cost)
, m_max_total_fuel(encoding_context.m_max_total_fuel)
, m_extra_fuel(encoding_context.m_extra_fuel)
, m_fuel_makespan(encoding_context.m_fuel_makespan)
, m_variable_store(encoding_context.m_variable_store)
, m_state_clause_generator(encoding_context.m_state_clause_generator)
, m_advanced_clause_generator(encoding_context.m_advanced_clause_generator)
, m_bitwise_clause_generator(encoding_context.m_bitwise_clause_generator)
, m_bit_clause_generator(encoding_context.m_bit_clause_generator)
, m_vertex_occupancy(encoding_context.m_vertex_occupancy)
, m_robot_location(encoding_context.m_robot_location)
, m_transition_action(encoding_context.m_transition_action)
, m_vertex_occupancy_by_water(encoding_context.m_vertex_occupancy_by_water)
, m_vertex_occupancy_by_water_(encoding_context.m_vertex_occupancy_by_water_)
, m_vertex_occupancy_by_gas_(encoding_context.m_vertex_occupancy_by_gas_)
, m_unified_vertex_occupancy_by_water_(encoding_context.m_unified_vertex_occupancy_by_water_)
, m_wet_vertex_occupancy_by_water_(encoding_context.m_wet_vertex_occupancy_by_water_)
, m_vertex_water_cardinality_(encoding_context.m_vertex_water_cardinality_)
, m_vertex_occupancy_by_robot(encoding_context.m_vertex_occupancy_by_robot)
, m_robot_location_in_vertex(encoding_context.m_robot_location_in_vertex)
, m_edge_occupancy_by_water(encoding_context.m_edge_occupancy_by_water)
, m_edge_occupancy_by_water_(encoding_context.m_edge_occupancy_by_water_)
, m_edge_occupancy_by_water__(encoding_context.m_edge_occupancy_by_water__)
, m_unified_edge_occupancy_by_water__(encoding_context.m_unified_edge_occupancy_by_water__)
, m_wet_edge_occupancy_by_water__(encoding_context.m_wet_edge_occupancy_by_water__)
, m_transition_Actions(encoding_context.m_transition_Actions)
{
register_InternalIdentifiers();
switch_GeneratingMode(encoding_context.get_GeneratingMode());
}
const sMultirobotEncodingContext_CNFsat& sMultirobotEncodingContext_CNFsat::operator=(const sMultirobotEncodingContext_CNFsat &encoding_context)
{
m_N_Layers = encoding_context.m_N_Layers;
m_max_total_cost = encoding_context.m_max_total_cost;
m_extra_cost = encoding_context.m_extra_cost;
m_max_total_fuel = encoding_context.m_max_total_fuel;
m_extra_fuel = encoding_context.m_extra_fuel;
m_fuel_makespan = encoding_context.m_fuel_makespan;
m_variable_store = encoding_context.m_variable_store;
m_clause_generator = encoding_context.m_clause_generator;
m_bit_generator = encoding_context.m_bit_generator;
m_state_clause_generator = encoding_context.m_state_clause_generator;
m_advanced_clause_generator = encoding_context.m_advanced_clause_generator;
m_bitwise_clause_generator = encoding_context.m_bitwise_clause_generator;
m_bit_clause_generator = encoding_context.m_bit_clause_generator;
m_vertex_occupancy = encoding_context.m_vertex_occupancy;
m_robot_location = encoding_context.m_robot_location;
m_robot_location_in_vertex = encoding_context.m_robot_location_in_vertex;
m_edge_occupancy_by_water = encoding_context.m_edge_occupancy_by_water;
m_edge_occupancy_by_water_ = encoding_context.m_edge_occupancy_by_water_;
m_edge_occupancy_by_water__ = encoding_context.m_edge_occupancy_by_water__;
m_unified_edge_occupancy_by_water__ = encoding_context.m_unified_edge_occupancy_by_water__;
m_wet_edge_occupancy_by_water__ = encoding_context.m_wet_edge_occupancy_by_water__;
m_transition_action = encoding_context.m_transition_action;
m_vertex_occupancy_by_water = encoding_context.m_vertex_occupancy_by_water;
m_vertex_occupancy_by_water_ = encoding_context.m_vertex_occupancy_by_water_;
m_vertex_occupancy_by_gas_ = encoding_context.m_vertex_occupancy_by_gas_;
m_unified_vertex_occupancy_by_water_ = encoding_context.m_unified_vertex_occupancy_by_water_;
m_wet_vertex_occupancy_by_water_ = encoding_context.m_wet_vertex_occupancy_by_water_;
m_vertex_water_cardinality_ = encoding_context.m_vertex_water_cardinality_;
m_vertex_occupancy_by_robot = encoding_context.m_vertex_occupancy_by_robot;
m_transition_Actions = encoding_context.m_transition_Actions;
switch_GeneratingMode(encoding_context.get_GeneratingMode());
register_InternalIdentifiers();
return *this;
}
sMultirobotEncodingContext_CNFsat::GeneratingMode sMultirobotEncodingContext_CNFsat::get_GeneratingMode(void) const
{
return m_generating_mode;
}
void sMultirobotEncodingContext_CNFsat::switch_GeneratingMode(GeneratingMode generating_mode)
{
m_generating_mode = generating_mode;
switch (generating_mode)
{
case GENERATING_STANDARD:
{
m_clause_generator = &m_state_clause_generator;
break;
}
case GENERATING_ADVANCED:
{
m_clause_generator = &m_advanced_clause_generator;
break;
}
case GENERATING_BITWISE:
{
m_clause_generator = &m_bitwise_clause_generator;
break;
}
default:
{
sASSERT(false);
break;
}
}
m_bit_generator = &m_bit_clause_generator;
}
void sMultirobotEncodingContext_CNFsat::switchTo_StandardGeneratingMode(void)
{
m_clause_generator = &m_state_clause_generator;
m_bit_generator = &m_bit_clause_generator;
m_generating_mode = GENERATING_STANDARD;
}
void sMultirobotEncodingContext_CNFsat::switchTo_AdvancedGeneratingMode(void)
{
m_clause_generator = &m_advanced_clause_generator;
m_bit_generator = &m_bit_clause_generator;
m_generating_mode = GENERATING_ADVANCED;
}
void sMultirobotEncodingContext_CNFsat::switchTo_BitwiseGeneratingMode(void)
{
m_clause_generator = &m_bitwise_clause_generator;
m_bit_generator = &m_bit_clause_generator;
m_generating_mode = GENERATING_BITWISE;
}
void sMultirobotEncodingContext_CNFsat::register_InternalIdentifiers(void)
{
m_state_Identifiers.clear();
m_state_Identifiers[sINT_32_MAX] = NULL;
m_bit_Identifiers.clear();
m_bit_Identifiers[sINT_32_MAX] = NULL;
if (!m_vertex_occupancy.is_Anonymous())
{
register_TranslateIdentifier(m_vertex_occupancy);
}
if (!m_robot_location.is_Anonymous())
{
register_TranslateIdentifier(m_robot_location);
}
if (!m_robot_location_in_vertex.is_Anonymous())
{
register_TranslateIdentifier(m_robot_location_in_vertex);
}
if (!m_vertex_occupancy_by_robot.is_Anonymous())
{
register_TranslateIdentifier(m_vertex_occupancy_by_robot);
}
for (StateIdentifiers_vector::iterator transition_action = m_transition_Actions.begin(); transition_action != m_transition_Actions.end(); ++transition_action)
{
if (!transition_action->is_Anonymous())
{
register_TranslateIdentifier(*transition_action);
}
}
for (BitIdentifiers_vector::iterator edge_occupancy = m_edge_occupancy_by_water.begin(); edge_occupancy != m_edge_occupancy_by_water.end(); ++edge_occupancy)
{
if (!edge_occupancy->is_Anonymous())
{
register_TranslateIdentifier(*edge_occupancy);
}
}
for (BitIdentifiers_2d_vector::iterator edge_occupancy_ = m_edge_occupancy_by_water_.begin(); edge_occupancy_ != m_edge_occupancy_by_water_.end(); ++edge_occupancy_)
{
for (BitIdentifiers_vector::iterator edge_occupancy = edge_occupancy_->begin(); edge_occupancy != edge_occupancy_->end(); ++edge_occupancy)
{
if (!edge_occupancy->is_Anonymous())
{
register_TranslateIdentifier(*edge_occupancy);
}
}
}
for (BitIdentifiers_2d_vector::iterator wet_edge_occupancy__ = m_wet_edge_occupancy_by_water__.begin(); wet_edge_occupancy__ != m_wet_edge_occupancy_by_water__.end(); ++wet_edge_occupancy__)
{
for (BitIdentifiers_vector::iterator wet_edge_occupancy = wet_edge_occupancy__->begin(); wet_edge_occupancy != wet_edge_occupancy__->end(); ++wet_edge_occupancy)
{
if (!wet_edge_occupancy->is_Anonymous())
{
register_TranslateIdentifier(*wet_edge_occupancy);
}
}
}
for (BitIdentifiers_2d_vector::iterator vertex_occupancy_ = m_vertex_occupancy_by_water_.begin(); vertex_occupancy_ != m_vertex_occupancy_by_water_.end(); ++vertex_occupancy_)
{
for (BitIdentifiers_vector::iterator vertex_occupancy = vertex_occupancy_->begin(); vertex_occupancy != vertex_occupancy_->end(); ++vertex_occupancy)
{
if (!vertex_occupancy->is_Anonymous())
{
register_TranslateIdentifier(*vertex_occupancy);
}
}
}
for (BitIdentifiers_2d_vector::iterator vertex_occupancy_ = m_vertex_occupancy_by_gas_.begin(); vertex_occupancy_ != m_vertex_occupancy_by_gas_.end(); ++vertex_occupancy_)
{
for (BitIdentifiers_vector::iterator vertex_occupancy = vertex_occupancy_->begin(); vertex_occupancy != vertex_occupancy_->end(); ++vertex_occupancy)
{
if (!vertex_occupancy->is_Anonymous())
{
register_TranslateIdentifier(*vertex_occupancy);
}
}
}
for (BitIdentifiers_vector::iterator unified_vertex_occupancy = m_unified_vertex_occupancy_by_water_.begin(); unified_vertex_occupancy != m_unified_vertex_occupancy_by_water_.end(); ++unified_vertex_occupancy)
{
if (!unified_vertex_occupancy->is_Anonymous())
{
register_TranslateIdentifier(*unified_vertex_occupancy);
}
}
for (BitIdentifiers_vector::iterator wet_vertex_occupancy = m_wet_vertex_occupancy_by_water_.begin(); wet_vertex_occupancy != m_wet_vertex_occupancy_by_water_.end(); ++wet_vertex_occupancy)
{
if (!wet_vertex_occupancy->is_Anonymous())
{
register_TranslateIdentifier(*wet_vertex_occupancy);
}
}
for (BitIdentifiers_2d_vector::iterator vertex_cardinality_ = m_vertex_water_cardinality_.begin(); vertex_cardinality_ != m_vertex_water_cardinality_.end(); ++vertex_cardinality_)
{
for (BitIdentifiers_vector::iterator vertex_cardinality = vertex_cardinality_->begin(); vertex_cardinality != vertex_cardinality_->end(); ++vertex_cardinality)
{
if (!vertex_cardinality->is_Anonymous())
{
register_TranslateIdentifier(*vertex_cardinality);
}
}
}
for (BitIdentifiers_3d_vector::iterator edge_occupancy__ = m_edge_occupancy_by_water__.begin(); edge_occupancy__ != m_edge_occupancy_by_water__.end(); ++edge_occupancy__)
{
for (BitIdentifiers_2d_vector::iterator edge_occupancy_ = edge_occupancy__->begin(); edge_occupancy_ != edge_occupancy__->end(); ++edge_occupancy_)
{
for (BitIdentifiers_vector::iterator edge_occupancy = edge_occupancy_->begin(); edge_occupancy != edge_occupancy_->end(); ++edge_occupancy)
{
if (!edge_occupancy->is_Anonymous())
{
register_TranslateIdentifier(*edge_occupancy);
}
}
}
}
for (BitIdentifiers_2d_vector::iterator unified_edge_occupancy_ = m_unified_edge_occupancy_by_water__.begin(); unified_edge_occupancy_ != m_unified_edge_occupancy_by_water__.end(); ++unified_edge_occupancy_)
{
for (BitIdentifiers_vector::iterator unified_edge_occupancy = unified_edge_occupancy_->begin(); unified_edge_occupancy != unified_edge_occupancy_->end(); ++unified_edge_occupancy)
{
if (!unified_edge_occupancy->is_Anonymous())
{
register_TranslateIdentifier(*unified_edge_occupancy);
}
}
}
}
void sMultirobotEncodingContext_CNFsat::register_TranslateIdentifier(sIndexableStateIdentifier &state_identifier)
{
if (state_identifier.get_First_CNFVariable() >= 1)
{
m_state_Identifiers[state_identifier.get_First_CNFVariable()] = &state_identifier;
}
}
void sMultirobotEncodingContext_CNFsat::register_TranslateIdentifier(sIndexableBitIdentifier &bit_identifier)
{
if (bit_identifier.get_First_CNFVariable() >= 1)
{
m_bit_Identifiers[bit_identifier.get_First_CNFVariable()] = &bit_identifier;
}
}
sSpecifiedIdentifier sMultirobotEncodingContext_CNFsat::translate_CNF_Variable(int cnf_variable) const
{
sSpecifiedIdentifier state_translation;
StateIdentifiers_map::const_iterator state_identifier = m_state_Identifiers.upper_bound(cnf_variable);
if (state_identifier != m_state_Identifiers.end())
{
if (state_identifier->first > cnf_variable)
{
--state_identifier;
}
if (state_identifier != m_state_Identifiers.end() && state_identifier->second != NULL)
{
state_translation = state_identifier->second->translate_CNFVariable(cnf_variable);
}
}
if (!state_translation.is_Null())
{
return state_translation;
}
else
{
sSpecifiedIdentifier bit_translation;
BitIdentifiers_map::const_iterator bit_identifier = m_bit_Identifiers.upper_bound(cnf_variable);
/*
printf("bit_var:%d,%ld\n", cnf_variable, m_bit_Identifiers.size());
for (BitIdentifiers_map::const_iterator identifier = m_bit_Identifiers.begin(); identifier != m_bit_Identifiers.end(); ++identifier)
{
if (identifier->second != NULL)
{
// identifier->second->to_Screen();
printf("%d\n", identifier->first);
}
}
*/
if (bit_identifier != m_bit_Identifiers.end())
{
if (bit_identifier->first > cnf_variable)
{
--bit_identifier;
}
if (bit_identifier != m_bit_Identifiers.end() && bit_identifier->second != NULL)
{
bit_translation = bit_identifier->second->translate_CNFVariable(cnf_variable);
}
}
if (!bit_translation.is_Null())
{
return bit_translation;
}
else
{
return m_clause_generator->translate_AuxiliaryCNFVariable(cnf_variable);
}
}
return sSpecifiedIdentifier();
}
void sMultirobotEncodingContext_CNFsat::to_Screen_identifiers(const sString &indent) const
{
printf("%sEncoding identifiers {\n", indent.c_str());
printf("%s%sState identifiers (%ld) [\n", indent.c_str(), sRELOC_INDENT.c_str(), m_state_Identifiers.size());
for (StateIdentifiers_map::const_iterator state_identifier = m_state_Identifiers.begin(); state_identifier != m_state_Identifiers.end(); ++state_identifier)
{
if (state_identifier->first < sINT_32_MAX)
{
printf("%s%s%d --->\n", indent.c_str(), sRELOC_2_INDENT.c_str(), state_identifier->first);
state_identifier->second->to_Screen(indent + sRELOC_3_INDENT);
}
}
printf("%s%s]\n", indent.c_str(), sRELOC_INDENT.c_str());
printf("%s%sBit identifiers (%ld) [\n", indent.c_str(), sRELOC_INDENT.c_str(), m_bit_Identifiers.size());
for (BitIdentifiers_map::const_iterator bit_identifier = m_bit_Identifiers.begin(); bit_identifier != m_bit_Identifiers.end(); ++bit_identifier)
{
if (bit_identifier->first < sINT_32_MAX)
{
printf("%s%s%d --->\n", indent.c_str(), sRELOC_2_INDENT.c_str(), bit_identifier->first);
bit_identifier->second->to_Screen(indent + sRELOC_3_INDENT);
}
}
printf("%s%s]\n", indent.c_str(), sRELOC_INDENT.c_str());
printf("%s}\n", indent.c_str());
}
/*----------------------------------------------------------------------------*/
// sMultirobotInstance
sMultirobotInstance::sMultirobotInstance()
{
// nothing
}
sMultirobotInstance::sMultirobotInstance(const sUndirectedGraph &environment, const sRobotArrangement &initial_arrangement, const sRobotArrangement &goal_arrangement)
: m_goal_type(GOAL_TYPE_ARRANGEMENT)
, m_environment(environment)
, m_initial_arrangement(initial_arrangement)
, m_goal_arrangement(goal_arrangement)
, m_ratio(-1.0)
, m_robustness(1)
, m_range(0)
{
sASSERT(environment.get_VertexCount() == initial_arrangement.get_VertexCount() && environment.get_VertexCount() == goal_arrangement.get_VertexCount());
m_environment.build_SpanningTree(initial_arrangement.get_RobotLocation(1), m_sparse_environment);
sUndirectedGraph::VertexPairs_vector vertex_Pairs;
int N_Robots = m_initial_arrangement.get_RobotCount();
for (int robot = 1; robot <= N_Robots; ++robot)
{
vertex_Pairs.push_back(sUndirectedGraph::Vertex_pair(initial_arrangement.get_RobotLocation(robot), goal_arrangement.get_RobotLocation(robot)));
}
m_environment.build_SparseGraph(vertex_Pairs, m_sparse_environment);
}
sMultirobotInstance::sMultirobotInstance(const sUndirectedGraph &environment,
const sUndirectedGraph &sparse_environment,
const sRobotArrangement &initial_arrangement,
const sRobotArrangement &goal_arrangement)
: m_goal_type(GOAL_TYPE_ARRANGEMENT)
, m_environment(environment)
, m_sparse_environment(sparse_environment)
, m_initial_arrangement(initial_arrangement)
, m_goal_arrangement(goal_arrangement)
, m_ratio(-1.0)
, m_robustness(1)
, m_range(0)
{
sASSERT(environment.get_VertexCount() == initial_arrangement.get_VertexCount() && environment.get_VertexCount() == goal_arrangement.get_VertexCount());
}
sMultirobotInstance::sMultirobotInstance(const sUndirectedGraph &environment,
const sRobotArrangement &initial_arrangement,
const sRobotArrangement &goal_arrangement,
double ratio,
int robustness,
int range)
: m_goal_type(GOAL_TYPE_ARRANGEMENT)
, m_environment(environment)
, m_initial_arrangement(initial_arrangement)
, m_goal_arrangement(goal_arrangement)
, m_ratio(ratio)
, m_robustness(robustness)
, m_range(range)
{
sASSERT(environment.get_VertexCount() == initial_arrangement.get_VertexCount() && environment.get_VertexCount() == goal_arrangement.get_VertexCount());
m_environment.build_SpanningTree(initial_arrangement.get_RobotLocation(1), m_sparse_environment);
sUndirectedGraph::VertexPairs_vector vertex_Pairs;
int N_Robots = m_initial_arrangement.get_RobotCount();
for (int robot = 1; robot <= N_Robots; ++robot)
{
vertex_Pairs.push_back(sUndirectedGraph::Vertex_pair(initial_arrangement.get_RobotLocation(robot), goal_arrangement.get_RobotLocation(robot)));
}
m_environment.build_SparseGraph(vertex_Pairs, m_sparse_environment);
}
sMultirobotInstance::sMultirobotInstance(const sUndirectedGraph &environment,
const sUndirectedGraph &sparse_environment,
const sRobotArrangement &initial_arrangement,
const sRobotArrangement &goal_arrangement,
double ratio,
int robustness,
int range)
: m_goal_type(GOAL_TYPE_ARRANGEMENT)
, m_environment(environment)
, m_sparse_environment(sparse_environment)
, m_initial_arrangement(initial_arrangement)
, m_goal_arrangement(goal_arrangement)
, m_ratio(ratio)
, m_robustness(robustness)
, m_range(range)
{
sASSERT(environment.get_VertexCount() == initial_arrangement.get_VertexCount() && environment.get_VertexCount() == goal_arrangement.get_VertexCount());
}
sMultirobotInstance::sMultirobotInstance(const sUndirectedGraph &environment, const sRobotArrangement &initial_arrangement, const sRobotGoal &goal_specification)
: m_goal_type(GOAL_TYPE_SPECIFICATION)
, m_environment(environment)
, m_initial_arrangement(initial_arrangement)
, m_goal_specification(goal_specification)
, m_ratio(-1.0)
, m_robustness(1)
, m_range(0)
{
sASSERT(environment.get_VertexCount() == initial_arrangement.get_VertexCount() && environment.get_VertexCount() == goal_specification.get_VertexCount());
// m_environment.build_SpanningTree(initial_arrangement.get_RobotLocation(1), m_sparse_environment);
sUndirectedGraph::VertexPairs_vector vertex_Pairs;
int N_Robots = m_initial_arrangement.get_RobotCount();
for (int robot = 1; robot <= N_Robots; ++robot)
{
double p = (double)rand() / RAND_MAX;
// printf("%f\n", p);
if (p <= 1.0)
{
const sRobotGoal::Vertices_set &robot_goal = goal_specification.get_RobotGoal(robot);
if (robot_goal.size() == 1)
{
vertex_Pairs.push_back(sUndirectedGraph::Vertex_pair(initial_arrangement.get_RobotLocation(robot), *robot_goal.begin()));
}
else
{
sASSERT(false);
}
}
}
// m_environment.build_SparseGraph(vertex_Pairs, m_sparse_environment);
// m_environment.build_SpanningTree(0, m_sparse_environment);
// printf("%.3f\n", (double)m_sparse_environment.get_EdgeCount() / m_environment.get_EdgeCount());
}
sMultirobotInstance::sMultirobotInstance(const sUndirectedGraph &environment,
const sUndirectedGraph &sparse_environment,
const sRobotArrangement &initial_arrangement,
const sRobotGoal &goal_specification)
: m_goal_type(GOAL_TYPE_SPECIFICATION)
, m_environment(environment)
, m_sparse_environment(sparse_environment)
, m_initial_arrangement(initial_arrangement)
, m_goal_specification(goal_specification)
, m_ratio(-1.0)
, m_robustness(1)
, m_range(0)
{
sASSERT(environment.get_VertexCount() == initial_arrangement.get_VertexCount() && environment.get_VertexCount() == goal_specification.get_VertexCount());
}
sMultirobotInstance::sMultirobotInstance(const sUndirectedGraph &environment, const sRobotArrangement &initial_arrangement, const sRobotGoal &goal_specification, double ratio, int robustness, int range)
: m_goal_type(GOAL_TYPE_SPECIFICATION)
, m_environment(environment)
, m_initial_arrangement(initial_arrangement)
, m_goal_specification(goal_specification)
, m_ratio(ratio)
, m_robustness(robustness)
, m_range(range)
{
sASSERT(environment.get_VertexCount() == initial_arrangement.get_VertexCount() && environment.get_VertexCount() == goal_specification.get_VertexCount());
// m_environment.build_SpanningTree(initial_arrangement.get_RobotLocation(1), m_sparse_environment);
sUndirectedGraph::VertexPairs_vector vertex_Pairs;
int N_Robots = m_initial_arrangement.get_RobotCount();
for (int robot = 1; robot <= N_Robots; ++robot)
{
double p = (double)rand() / RAND_MAX;
// printf("%f\n", p);
if (p <= 1.0)
{
const sRobotGoal::Vertices_set &robot_goal = goal_specification.get_RobotGoal(robot);
if (robot_goal.size() == 1)
{
vertex_Pairs.push_back(sUndirectedGraph::Vertex_pair(initial_arrangement.get_RobotLocation(robot), *robot_goal.begin()));
}
else
{
sASSERT(false);
}
}
}
// m_environment.build_SparseGraph(vertex_Pairs, m_sparse_environment);
// m_environment.build_SpanningTree(0, m_sparse_environment);
// printf("%.3f\n", (double)m_sparse_environment.get_EdgeCount() / m_environment.get_EdgeCount());
}
sMultirobotInstance::sMultirobotInstance(const sUndirectedGraph &environment,
const sUndirectedGraph &sparse_environment,
const sRobotArrangement &initial_arrangement,
const sRobotGoal &goal_specification,
double ratio,
int robustness,
int range)
: m_goal_type(GOAL_TYPE_SPECIFICATION)
, m_environment(environment)
, m_sparse_environment(sparse_environment)
, m_initial_arrangement(initial_arrangement)
, m_goal_specification(goal_specification)
, m_ratio(ratio)
, m_robustness(robustness)
, m_range(range)
{
sASSERT(environment.get_VertexCount() == initial_arrangement.get_VertexCount() && environment.get_VertexCount() == goal_specification.get_VertexCount());
}
/*----------------------------------------------------------------------------*/
void sMultirobotInstance::collect_Endpoints(VertexIDs_vector &source_IDs, VertexIDs_vector &goal_IDs)
{
int N_Robots = m_initial_arrangement.get_RobotCount();
for (int robot_id = 1; robot_id <= N_Robots; ++robot_id)
{
int robot_source_vertex_id = m_initial_arrangement.get_RobotLocation(robot_id);
int robot_sink_vertex_id;
switch (m_goal_type)
{
case GOAL_TYPE_ARRANGEMENT:
{
robot_sink_vertex_id = m_goal_arrangement.get_RobotLocation(robot_id);
break;
}
case GOAL_TYPE_SPECIFICATION:
{
const sRobotGoal::Vertices_set &goal_IDs = m_goal_specification.get_RobotGoal(robot_id);
sASSERT(goal_IDs.size() == 1);
robot_sink_vertex_id = *goal_IDs.begin();
break;
}
default:
{
break;
}
}
source_IDs.push_back(robot_source_vertex_id);
goal_IDs.push_back(robot_sink_vertex_id);
}
}
int sMultirobotInstance::analyze_EdgeHeights(int max_total_cost)
{
int min_total_cost = INT_MAX;
VertexIDs_vector source_IDs;
VertexIDs_vector goal_IDs;
collect_Endpoints(source_IDs, goal_IDs);
m_environment.calc_AllPairsShortestPaths(source_IDs, goal_IDs);
const sUndirectedGraph::Distances_2d_vector &all_pairs_Distances = m_environment.get_AllPairsShortestPaths();
for (sUndirectedGraph::Edges_list::const_iterator edge = m_environment.m_Edges.begin(); edge != m_environment.m_Edges.end(); ++edge)
{
int min_edge_robot_id = -1;
int min_edge_cost = INT_MAX;
int edge_vertex_u_id = edge->m_arc_uv.m_source->m_id;
int edge_vertex_v_id = edge->m_arc_uv.m_target->m_id;
int N_Robots = m_initial_arrangement.get_RobotCount();
for (int robot_id = 1; robot_id <= N_Robots; ++robot_id)
{
int robot_source_vertex_id = m_initial_arrangement.get_RobotLocation(robot_id);
int robot_sink_vertex_id;
switch (m_goal_type)
{
case GOAL_TYPE_ARRANGEMENT:
{
robot_sink_vertex_id = m_goal_arrangement.get_RobotLocation(robot_id);
break;
}
case GOAL_TYPE_SPECIFICATION:
{
const sRobotGoal::Vertices_set &goal_IDs = m_goal_specification.get_RobotGoal(robot_id);
sASSERT(goal_IDs.size() == 1);
robot_sink_vertex_id = *goal_IDs.begin();
break;
}
default:
{
break;
}
}
int edge_cost = sMIN(all_pairs_Distances[robot_source_vertex_id][edge_vertex_u_id] + all_pairs_Distances[edge_vertex_v_id][robot_sink_vertex_id],
all_pairs_Distances[robot_source_vertex_id][edge_vertex_v_id] + all_pairs_Distances[edge_vertex_u_id][robot_sink_vertex_id]);
if (edge_cost < min_edge_cost)
{
min_edge_cost = edge_cost;
min_edge_robot_id = robot_id;
}
}
int rest_cost = 0;
for (int robot_id = 1; robot_id <= N_Robots; ++robot_id)
{
if (robot_id != min_edge_robot_id)
{
int robot_source_vertex_id = m_initial_arrangement.get_RobotLocation(robot_id);
int robot_sink_vertex_id;
switch (m_goal_type)
{
case GOAL_TYPE_ARRANGEMENT:
{
robot_sink_vertex_id = m_goal_arrangement.get_RobotLocation(robot_id);
break;
}
case GOAL_TYPE_SPECIFICATION:
{
const sRobotGoal::Vertices_set &goal_IDs = m_goal_specification.get_RobotGoal(robot_id);
sASSERT(goal_IDs.size() == 1);
robot_sink_vertex_id = *goal_IDs.begin();
break;
}
default:
{
break;
}
}
rest_cost += all_pairs_Distances[robot_source_vertex_id][robot_sink_vertex_id];
}
}
int total_cost = min_edge_cost + rest_cost;
int edge_height = max_total_cost - total_cost;
printf("Edge height: %d\n", edge_height);
if (min_total_cost > total_cost)
{
min_total_cost = total_cost;
}
}
return min_total_cost;
}
int sMultirobotInstance::analyze_EdgeHeights_(int max_total_cost, int &max_vertex_height)
{
sUndirectedGraph::VertexIDs_set reachable_IDs;
return analyze_EdgeHeights_(max_total_cost, max_vertex_height, reachable_IDs);
}
int sMultirobotInstance::analyze_EdgeHeights_(int max_total_cost, int &max_vertex_height, sUndirectedGraph::VertexIDs_set &reachable_IDs)
{
VertexIDs_vector source_IDs;
VertexIDs_vector goal_IDs;
collect_Endpoints(source_IDs, goal_IDs);
m_environment.calc_AllPairsShortestPaths(source_IDs, goal_IDs);
const sUndirectedGraph::Distances_2d_vector &all_pairs_Distances = m_environment.get_AllPairsShortestPaths();
max_vertex_height = 0;
int min_total_cost = 0;
int N_Robots = m_initial_arrangement.get_RobotCount();
for (int robot_id = 1; robot_id <= N_Robots; ++robot_id)
{
int robot_source_vertex_id = m_initial_arrangement.get_RobotLocation(robot_id);
int robot_sink_vertex_id;
switch (m_goal_type)
{
case GOAL_TYPE_ARRANGEMENT:
{
robot_sink_vertex_id = m_goal_arrangement.get_RobotLocation(robot_id);
break;
}
case GOAL_TYPE_SPECIFICATION:
{
const sRobotGoal::Vertices_set &goal_IDs = m_goal_specification.get_RobotGoal(robot_id);
sASSERT(goal_IDs.size() == 1);
robot_sink_vertex_id = *goal_IDs.begin();
break;
}
default:
{
break;
}
}
int robot_cost = all_pairs_Distances[robot_source_vertex_id][robot_sink_vertex_id];
min_total_cost += robot_cost;
}
for (sUndirectedGraph::Vertices_vector::const_iterator vertex = m_environment.m_Vertices.begin(); vertex != m_environment.m_Vertices.end(); ++vertex)
{
int min_robot_cost = INT_MAX;
int min_robot_id = -1;
int N_Robots = m_initial_arrangement.get_RobotCount();
for (int robot_id = 1; robot_id <= N_Robots; ++robot_id)
{
int robot_source_vertex_id = m_initial_arrangement.get_RobotLocation(robot_id);
int robot_sink_vertex_id;
switch (m_goal_type)
{
case GOAL_TYPE_ARRANGEMENT:
{
robot_sink_vertex_id = m_goal_arrangement.get_RobotLocation(robot_id);
break;
}
case GOAL_TYPE_SPECIFICATION:
{
const sRobotGoal::Vertices_set &goal_IDs = m_goal_specification.get_RobotGoal(robot_id);
sASSERT(goal_IDs.size() == 1);
robot_sink_vertex_id = *goal_IDs.begin();
break;
}
default:
{
break;
}
}
int cost = all_pairs_Distances[robot_source_vertex_id][vertex->m_id] + all_pairs_Distances[vertex->m_id][robot_sink_vertex_id];
if (cost < min_robot_cost)
{
min_robot_cost = cost;
min_robot_id = robot_id;
}
}
printf("Min robot:%d (cost:%d)\n", min_robot_id, min_robot_cost);
int rest_cost = 0;
int overlaps = 0;
for (int robot_id = 1; robot_id <= N_Robots; ++robot_id)
{
if (robot_id != min_robot_id)
{
int robot_source_vertex_id = m_initial_arrangement.get_RobotLocation(robot_id);
int robot_sink_vertex_id;
switch (m_goal_type)
{
case GOAL_TYPE_ARRANGEMENT:
{
robot_sink_vertex_id = m_goal_arrangement.get_RobotLocation(robot_id);
break;
}
case GOAL_TYPE_SPECIFICATION:
{
const sRobotGoal::Vertices_set &goal_IDs = m_goal_specification.get_RobotGoal(robot_id);
sASSERT(goal_IDs.size() == 1);
robot_sink_vertex_id = *goal_IDs.begin();
break;
}
default:
{
break;
}
}
int cost = all_pairs_Distances[robot_source_vertex_id][robot_sink_vertex_id];
int overlap_cost = all_pairs_Distances[robot_source_vertex_id][vertex->m_id] + all_pairs_Distances[vertex->m_id][robot_sink_vertex_id];
if (cost == overlap_cost)
{
++overlaps;
}
rest_cost += cost;
}
}
int total_cost = min_robot_cost + rest_cost;
int remaining_cost = max_total_cost - total_cost;
printf("Tc: %d\n", total_cost);
int vertex_height = -1;
if (remaining_cost >= 0)
{
vertex_height = remaining_cost + overlaps;
reachable_IDs.insert(vertex->m_id);
}
if (max_vertex_height < vertex_height)
{
max_vertex_height = vertex_height;
}
printf("Height: %d\n", vertex_height);
}
// printf("Total: %d (%d) Size: %d (%.3f)\n", min_total_cost, max_vertex_height, reachable_IDs.size(), (double)reachable_IDs.size() / m_environment.get_VertexCount());
return min_total_cost;
}
int sMultirobotInstance::build_HeightedEnvironments(int max_total_cost)
{
return build_HeightedEnvironments(max_total_cost, m_heighted_Environments);
}
int sMultirobotInstance::build_HeightedEnvironments(int max_total_cost, Environments_vector &heighted_Environments)
{
int min_total_cost = INT_MAX;
heighted_Environments.clear();
VertexIDs_vector source_IDs;
VertexIDs_vector goal_IDs;
collect_Endpoints(source_IDs, goal_IDs);
m_environment.calc_AllPairsShortestPaths(source_IDs, goal_IDs);
const sUndirectedGraph::Distances_2d_vector &all_pairs_Distances = m_environment.get_AllPairsShortestPaths();
for (sUndirectedGraph::Edges_list::const_iterator edge = m_environment.m_Edges.begin(); edge != m_environment.m_Edges.end(); ++edge)
{
int min_edge_robot_id = -1;
int min_edge_cost = INT_MAX;
int edge_vertex_u_id = edge->m_arc_uv.m_source->m_id;
int edge_vertex_v_id = edge->m_arc_uv.m_target->m_id;
int N_Robots = m_initial_arrangement.get_RobotCount();
for (int robot_id = 1; robot_id <= N_Robots; ++robot_id)
{
int robot_source_vertex_id = m_initial_arrangement.get_RobotLocation(robot_id);
int robot_sink_vertex_id;
switch (m_goal_type)
{
case GOAL_TYPE_ARRANGEMENT:
{
robot_sink_vertex_id = m_goal_arrangement.get_RobotLocation(robot_id);
break;
}
case GOAL_TYPE_SPECIFICATION:
{
const sRobotGoal::Vertices_set &goal_IDs = m_goal_specification.get_RobotGoal(robot_id);
sASSERT(goal_IDs.size() == 1);
robot_sink_vertex_id = *goal_IDs.begin();
break;
}
default:
{
break;
}
}
int edge_cost = sMIN(all_pairs_Distances[robot_source_vertex_id][edge_vertex_u_id] + all_pairs_Distances[edge_vertex_v_id][robot_sink_vertex_id],
all_pairs_Distances[robot_source_vertex_id][edge_vertex_v_id] + all_pairs_Distances[edge_vertex_u_id][robot_sink_vertex_id]);
if (edge_cost < min_edge_cost)
{
min_edge_cost = edge_cost;
min_edge_robot_id = robot_id;
}
}
int rest_cost = 0;
for (int robot_id = 1; robot_id <= N_Robots; ++robot_id)
{
if (robot_id != min_edge_robot_id)
{
int robot_source_vertex_id = m_initial_arrangement.get_RobotLocation(robot_id);
int robot_sink_vertex_id;
switch (m_goal_type)
{
case GOAL_TYPE_ARRANGEMENT:
{
robot_sink_vertex_id = m_goal_arrangement.get_RobotLocation(robot_id);
break;
}
case GOAL_TYPE_SPECIFICATION:
{
const sRobotGoal::Vertices_set &goal_IDs = m_goal_specification.get_RobotGoal(robot_id);
sASSERT(goal_IDs.size() == 1);
robot_sink_vertex_id = *goal_IDs.begin();
break;
}
default:
{
break;
}
}
rest_cost += all_pairs_Distances[robot_source_vertex_id][robot_sink_vertex_id];
}
}
int total_cost = min_edge_cost + rest_cost;
int edge_height = max_total_cost - total_cost;
printf("eh: %d\n", edge_height);
if (edge_height >= 0)
{
int environment_height = heighted_Environments.size();
while (environment_height++ <= edge_height)
{
heighted_Environments.push_back(sUndirectedGraph());
heighted_Environments.back().add_Vertices(m_environment.get_VertexCount());
}
for (int eh = 0; eh < edge_height; ++eh)
{
if (!heighted_Environments[eh].is_Adjacent(edge_vertex_u_id, edge_vertex_v_id))
{
heighted_Environments[eh].add_Edge(edge_vertex_u_id, edge_vertex_v_id);
}
}
}
if (min_total_cost > total_cost)
{
min_total_cost = total_cost;
}
}
printf("------>\n");
if (heighted_Environments.empty())
{
heighted_Environments.push_back(sUndirectedGraph());
heighted_Environments.back().add_Vertices(m_environment.get_VertexCount());
}
return min_total_cost;
}
int sMultirobotInstance::build_HeightedEnvironments_(int max_total_cost)
{
return build_HeightedEnvironments_(max_total_cost, m_heighted_Environments);
}
int sMultirobotInstance::build_HeightedEnvironments_(int max_total_cost, Environments_vector &heighted_Environments)
{
heighted_Environments.clear();
int max_vertex_height = 0;
sUndirectedGraph::VertexIDs_set reachable_IDs;
int min_total_cost = analyze_EdgeHeights_(max_total_cost, max_vertex_height, reachable_IDs);
sUndirectedGraph heighted_environment;
heighted_environment.add_Vertices(m_environment.get_VertexCount());
for (sUndirectedGraph::Edges_list::const_iterator edge = m_environment.m_Edges.begin(); edge != m_environment.m_Edges.end(); ++edge)
{
int edge_vertex_u_id = edge->m_arc_uv.m_source->m_id;
int edge_vertex_v_id = edge->m_arc_uv.m_target->m_id;
/*
sUndirectedGraph::VertexIDs_set::const_iterator reachable_u = reachable_IDs.find(edge_vertex_u_id);
sUndirectedGraph::VertexIDs_set::const_iterator reachable_v = reachable_IDs.find(edge_vertex_v_id);
*/
// if (reachable_u != reachable_IDs.end() && reachable_v != reachable_IDs.end())
{
heighted_environment.add_Edge(edge_vertex_u_id, edge_vertex_v_id);
}
}
for (int height = 0; height <= max_vertex_height; ++height)
{
heighted_Environments.push_back(heighted_environment);
}
return min_total_cost;
}
int sMultirobotInstance::estimate_TotalCost(int &max_individual_cost)
{
VertexIDs_vector source_IDs;
VertexIDs_vector goal_IDs;
collect_Endpoints(source_IDs, goal_IDs);
m_environment.calc_SourceGoalShortestPaths(source_IDs, goal_IDs);
const sUndirectedGraph::Distances_2d_vector &source_Distances = m_environment.get_SourceShortestPaths();
// const sUndirectedGraph::Distances_2d_vector &goal_Distances = m_environment.get_GoalShortestPaths();
int min_total_cost = 0;
max_individual_cost = 0;
int N_Robots = m_initial_arrangement.get_RobotCount();
for (int robot_id = 1; robot_id <= N_Robots; ++robot_id)
{
int robot_source_vertex_id = m_initial_arrangement.get_RobotLocation(robot_id);
int robot_sink_vertex_id;
switch (m_goal_type)
{
case GOAL_TYPE_ARRANGEMENT:
{
robot_sink_vertex_id = m_goal_arrangement.get_RobotLocation(robot_id);
break;
}
case GOAL_TYPE_SPECIFICATION:
{
const sRobotGoal::Vertices_set &goal_IDs = m_goal_specification.get_RobotGoal(robot_id);
sASSERT(goal_IDs.size() == 1);
robot_sink_vertex_id = *goal_IDs.begin();
break;
}
default:
{
break;
}
}
int robot_cost = source_Distances[robot_source_vertex_id][robot_sink_vertex_id];
min_total_cost += robot_cost;
if (robot_cost > max_individual_cost)
{
max_individual_cost = robot_cost;
}
}
return min_total_cost;
}
int sMultirobotInstance::estimate_TotalFuel(int &max_individual_fuel)
{
VertexIDs_vector source_IDs;
VertexIDs_vector goal_IDs;
collect_Endpoints(source_IDs, goal_IDs);
m_environment.calc_SourceGoalShortestPaths(source_IDs, goal_IDs);
const sUndirectedGraph::Distances_2d_vector &source_Distances = m_environment.get_SourceShortestPaths();
// const sUndirectedGraph::Distances_2d_vector &goal_Distances = m_environment.get_GoalShortestPaths();
int min_total_fuel = 0;
max_individual_fuel = 0;
int N_Robots = m_initial_arrangement.get_RobotCount();
for (int robot_id = 1; robot_id <= N_Robots; ++robot_id)
{
int robot_source_vertex_id = m_initial_arrangement.get_RobotLocation(robot_id);
int robot_sink_vertex_id;
switch (m_goal_type)
{
case GOAL_TYPE_ARRANGEMENT:
{
robot_sink_vertex_id = m_goal_arrangement.get_RobotLocation(robot_id);
break;
}
case GOAL_TYPE_SPECIFICATION:
{
const sRobotGoal::Vertices_set &goal_IDs = m_goal_specification.get_RobotGoal(robot_id);
sASSERT(goal_IDs.size() == 1);
robot_sink_vertex_id = *goal_IDs.begin();
break;
}
default:
{
break;
}
}
int robot_fuel = source_Distances[robot_source_vertex_id][robot_sink_vertex_id];
min_total_fuel += robot_fuel;
if (robot_fuel > max_individual_fuel)
{
max_individual_fuel = robot_fuel;
}
}
return min_total_fuel;
}
int sMultirobotInstance::construct_MDD(int max_total_cost, MDD_vector &MDD, int &extra_cost, MDD_vector &extra_MDD)
{
return construct_GraphMDD(m_environment, max_total_cost, MDD, extra_cost, extra_MDD);
}
int sMultirobotInstance::construct_FuelMDD(int max_total_fuel, int fuel_makespan, MDD_vector &MDD, int &extra_fuel, MDD_vector &extra_MDD)
{
return construct_GraphFuelMDD(m_environment, max_total_fuel, fuel_makespan, MDD, extra_fuel, extra_MDD);
}
int sMultirobotInstance::construct_DisplacementMDD(int max_total_cost, MDD_vector &MDD, int &extra_cost, MDD_vector &extra_MDD)
{
return construct_GraphDisplacementMDD(m_environment, max_total_cost, MDD, extra_cost, extra_MDD);
}
int sMultirobotInstance::construct_LimitedMDD(int max_total_cost, MDD_vector &MDD, int &extra_cost, MDD_vector &extra_MDD)
{
return construct_GraphLimitedMDD(m_environment, max_total_cost, MDD, extra_cost, extra_MDD);
}
int sMultirobotInstance::construct_SparseMDD(int max_total_cost, MDD_vector &MDD, int &extra_cost, MDD_vector &extra_MDD)
{
return construct_GraphMDD(m_sparse_environment, max_total_cost, MDD, extra_cost, extra_MDD);
}
int sMDD_Addition[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
// int sMDD_Addition[] = { 2, 1, 1, 0, 0, 0, 0, 0, 0, 0 }; 36.94
// int sMDD_Addition[] = { 2, 1, 0, 0, 0, 0, 0, 0, 0, 0 }; // 33.97
// int sMDD_Addition[] = { 2, 2, 1, 1, 1, 0, 0, 0, 0, 0 }; 51.21
// int sMDD_Addition[] = { 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 }; 54.29
// int sMDD_Addition[] = { 4, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; 43.99
// int sMDD_Addition[] = { 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; //30.00
// int sMDD_Addition[] = { 4, 2, 1, 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 }; 45.0
// int sMDD_Addition[] = { 2, 1, 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 }; 36.66
// int sMDD_Addition[] = { 3, 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 }; 49.0
// int sMDD_Addition[] = { 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
// int sMDD_Addition[] = { 1, 1, 1, 1, 1, 1, 1, 0, 0, 0 };
// int sMDD_Addition[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
typedef std::multimap<int, int> RobotIndices_mmap;
int sMultirobotInstance::construct_GraphMDD(sUndirectedGraph &graph, int max_total_cost, MDD_vector &MDD, int &extra_cost, MDD_vector &extra_MDD)
{
int max_individual_cost;
int N_Vertices = graph.get_VertexCount();
MDD.clear();
extra_MDD.clear();
VertexIDs_vector source_IDs;
VertexIDs_vector goal_IDs;
collect_Endpoints(source_IDs, goal_IDs);
graph.calc_SourceGoalShortestPaths(source_IDs, goal_IDs);
int min_total_cost = estimate_TotalCost(max_individual_cost);
const sUndirectedGraph::Distances_2d_vector &source_Distances = graph.get_SourceShortestPaths();
const sUndirectedGraph::Distances_2d_vector &goal_Distances = graph.get_GoalShortestPaths();
extra_cost = max_total_cost - min_total_cost;
int mdd_depth = max_individual_cost + extra_cost;
int N_Robots = m_initial_arrangement.get_RobotCount();
MDD.resize(N_Robots + 1);
extra_MDD.resize(N_Robots + 1);
RobotIndices_mmap sorted_mdd_Robots;
for (int mdd_robot_id = 1; mdd_robot_id <= N_Robots; ++mdd_robot_id)
{
MDD[mdd_robot_id].resize(mdd_depth + 1);
extra_MDD[mdd_robot_id].resize(mdd_depth + 1);
int robot_source_vertex_id = m_initial_arrangement.get_RobotLocation(mdd_robot_id);
int robot_sink_vertex_id;
switch (m_goal_type)
{
case GOAL_TYPE_ARRANGEMENT:
{
robot_sink_vertex_id = m_goal_arrangement.get_RobotLocation(mdd_robot_id);
break;
}
case GOAL_TYPE_SPECIFICATION:
{
const sRobotGoal::Vertices_set &goal_IDs = m_goal_specification.get_RobotGoal(mdd_robot_id);
sASSERT(goal_IDs.size() == 1);
robot_sink_vertex_id = *goal_IDs.begin();
break;
}
default:
{
break;
}
}
int robot_cost = source_Distances[robot_source_vertex_id][robot_sink_vertex_id];
sorted_mdd_Robots.insert(RobotIndices_mmap::value_type(robot_cost, mdd_robot_id));
}
int sort_index = 0;
for (RobotIndices_mmap::const_reverse_iterator sort_robot = sorted_mdd_Robots.rbegin(); sort_robot != sorted_mdd_Robots.rend(); ++sort_robot)
{
int add_index = (sort_index++ * (sizeof(sMDD_Addition) / sizeof(int))) / N_Robots;
int extra_addition = sMDD_Addition[add_index];
int mdd_robot_id = sort_robot->second;
MDD[mdd_robot_id].resize(mdd_depth + 1);
extra_MDD[mdd_robot_id].resize(mdd_depth + 1);
int robot_source_vertex_id = m_initial_arrangement.get_RobotLocation(mdd_robot_id);
int robot_sink_vertex_id;
switch (m_goal_type)
{
case GOAL_TYPE_ARRANGEMENT:
{
robot_sink_vertex_id = m_goal_arrangement.get_RobotLocation(mdd_robot_id);
break;
}
case GOAL_TYPE_SPECIFICATION:
{
const sRobotGoal::Vertices_set &goal_IDs = m_goal_specification.get_RobotGoal(mdd_robot_id);
sASSERT(goal_IDs.size() == 1);
robot_sink_vertex_id = *goal_IDs.begin();
break;
}
default:
{
break;
}
}
int robot_cost = source_Distances[robot_source_vertex_id][robot_sink_vertex_id];
/*
for (int mdd_level = 0; mdd_level <= mdd_depth; ++mdd_level)
{
for (int vertex_id = 0; vertex_id < N_Vertices; ++vertex_id)
{
if ( source_Distances[robot_source_vertex_id][vertex_id] <= mdd_level
&& goal_Distances[robot_sink_vertex_id][vertex_id] <= robot_cost + extra_cost - mdd_level)
{
MDD[mdd_robot_id][mdd_level].push_back(vertex_id);
printf("mdd_level:%d\n", mdd_level);
}
}
}
*/
for (int vertex_id = 0; vertex_id < N_Vertices; ++vertex_id)
{
for (int mdd_level = source_Distances[robot_source_vertex_id][vertex_id];
mdd_level <= sMIN(robot_cost + (extra_cost + extra_addition) - goal_Distances[robot_sink_vertex_id][vertex_id], mdd_depth);
++mdd_level)
{
MDD[mdd_robot_id][mdd_level].push_back(vertex_id);
}
}
for (int mdd_level = 0; mdd_level <= mdd_depth; ++mdd_level)
{
if (MDD[mdd_robot_id][mdd_level].empty())
{
MDD[mdd_robot_id][mdd_level].push_back(robot_sink_vertex_id);
}
if ( mdd_level >= source_Distances[robot_source_vertex_id][robot_sink_vertex_id]
&& mdd_level < source_Distances[robot_source_vertex_id][robot_sink_vertex_id] + (extra_cost + extra_addition))
{
extra_MDD[mdd_robot_id][mdd_level].push_back(robot_sink_vertex_id);
}
}
}
/*
printf("Distance printout\n");
for (int mdd_robot = 1; mdd_robot <= N_Robots; ++mdd_robot)
{
int robot_source_vertex_id = m_initial_arrangement.get_RobotLocation(mdd_robot);
int robot_sink_vertex_id;
switch (m_goal_type)
{
case GOAL_TYPE_ARRANGEMENT:
{
robot_sink_vertex_id = m_goal_arrangement.get_RobotLocation(mdd_robot);
break;
}
case GOAL_TYPE_SPECIFICATION:
{
const sRobotGoal::Vertices_set &goal_IDs = m_goal_specification.get_RobotGoal(mdd_robot);
sASSERT(goal_IDs.size() == 1);
robot_sink_vertex_id = *goal_IDs.begin();
break;
}
default:
{
break;
}
}
printf("robot:%d (%d,%d)\n", mdd_robot, robot_source_vertex_id, robot_sink_vertex_id);
for (int vertex_id = 0; vertex_id < N_Vertices; ++vertex_id)
{
int source_dist = source_Distances[robot_source_vertex_id][vertex_id];
int goal_dist = goal_Distances[robot_sink_vertex_id][vertex_id];
printf(" %d:%d,%d\n", vertex_id, source_dist, goal_dist);
}
}
printf("<----\n");
*/
/*
printf("MDD printout\n");
for (int mdd_robot = 1; mdd_robot <= N_Robots; ++mdd_robot)
{
printf("robot:%d\n", mdd_robot);
for (int mdd_level = 0; mdd_level <= mdd_depth; ++mdd_level)
{
if (!extra_MDD[mdd_robot][mdd_level].empty())
{
printf("* ");
}
for (int i = 0; i < MDD[mdd_robot][mdd_level].size(); ++i)
{
printf("%d ", MDD[mdd_robot][mdd_level][i]);
}
printf("\n");
}
printf("\n");
}
printf("<----\n");
getchar();
*/
std::vector<int> distribution;
distribution.resize(N_Robots + 1);
for (int robot_id = 0; robot_id <= N_Robots; ++robot_id)
{
distribution[robot_id] = 0;
}
return mdd_depth;
}
int sMultirobotInstance::construct_GraphFuelMDD(sUndirectedGraph &graph, int max_total_fuel, int fuel_makespan, MDD_vector &MDD, int &extra_fuel, MDD_vector &extra_MDD)
{
int max_individual_fuel;
int N_Vertices = graph.get_VertexCount();
MDD.clear();
extra_MDD.clear();
VertexIDs_vector source_IDs;
VertexIDs_vector goal_IDs;
collect_Endpoints(source_IDs, goal_IDs);
graph.calc_SourceGoalShortestPaths(source_IDs, goal_IDs);
int min_total_fuel = estimate_TotalFuel(max_individual_fuel);
const sUndirectedGraph::Distances_2d_vector &source_Distances = graph.get_SourceShortestPaths();
const sUndirectedGraph::Distances_2d_vector &goal_Distances = graph.get_GoalShortestPaths();
extra_fuel = max_total_fuel - min_total_fuel;
int mdd_depth = fuel_makespan;
int N_Robots = m_initial_arrangement.get_RobotCount();
MDD.resize(N_Robots + 1);
extra_MDD.resize(N_Robots + 1);
RobotIndices_mmap sorted_mdd_Robots;
for (int mdd_robot_id = 1; mdd_robot_id <= N_Robots; ++mdd_robot_id)
{
MDD[mdd_robot_id].resize(mdd_depth + 1);
extra_MDD[mdd_robot_id].resize(mdd_depth + 1);
int robot_source_vertex_id = m_initial_arrangement.get_RobotLocation(mdd_robot_id);
int robot_sink_vertex_id;
switch (m_goal_type)
{
case GOAL_TYPE_ARRANGEMENT:
{
robot_sink_vertex_id = m_goal_arrangement.get_RobotLocation(mdd_robot_id);
break;
}
case GOAL_TYPE_SPECIFICATION:
{
const sRobotGoal::Vertices_set &goal_IDs = m_goal_specification.get_RobotGoal(mdd_robot_id);
sASSERT(goal_IDs.size() == 1);
robot_sink_vertex_id = *goal_IDs.begin();
break;
}
default:
{
break;
}
}
int robot_fuel = source_Distances[robot_source_vertex_id][robot_sink_vertex_id];
sorted_mdd_Robots.insert(RobotIndices_mmap::value_type(robot_fuel, mdd_robot_id));
}
//int sort_index = 0;
for (RobotIndices_mmap::const_reverse_iterator sort_robot = sorted_mdd_Robots.rbegin(); sort_robot != sorted_mdd_Robots.rend(); ++sort_robot)
{
//int add_index = (sort_index++ * (sizeof(sMDD_Addition) / sizeof(int))) / N_Robots;
//int extra_addition = sMDD_Addition[add_index];
int mdd_robot_id = sort_robot->second;
MDD[mdd_robot_id].resize(mdd_depth + 1);
extra_MDD[mdd_robot_id].resize(mdd_depth + 1);
int robot_source_vertex_id = m_initial_arrangement.get_RobotLocation(mdd_robot_id);
int robot_sink_vertex_id;
switch (m_goal_type)
{
case GOAL_TYPE_ARRANGEMENT:
{
robot_sink_vertex_id = m_goal_arrangement.get_RobotLocation(mdd_robot_id);
break;
}
case GOAL_TYPE_SPECIFICATION:
{
const sRobotGoal::Vertices_set &goal_IDs = m_goal_specification.get_RobotGoal(mdd_robot_id);
sASSERT(goal_IDs.size() == 1);
robot_sink_vertex_id = *goal_IDs.begin();
break;
}
default:
{
break;
}
}
int robot_fuel = source_Distances[robot_source_vertex_id][robot_sink_vertex_id];
for (int mdd_level = 0; mdd_level <= mdd_depth; ++mdd_level)
{
for (int vertex_id = 0; vertex_id < N_Vertices; ++vertex_id)
{
if ( source_Distances[robot_source_vertex_id][vertex_id] <= mdd_level
&& goal_Distances[robot_sink_vertex_id][vertex_id] <= mdd_depth - mdd_level
&& goal_Distances[robot_sink_vertex_id][vertex_id] <= robot_fuel + extra_fuel - source_Distances[robot_source_vertex_id][vertex_id])
{
MDD[mdd_robot_id][mdd_level].push_back(vertex_id);
}
}
}
/*
for (int vertex_id = 0; vertex_id < N_Vertices; ++vertex_id)
{
for (int mdd_level = source_Distances[robot_source_vertex_id][vertex_id];
mdd_level <= mdd_depth - goal_Distances[robot_sink_vertex_id][vertex_id];
++mdd_level)
{
MDD[mdd_robot_id][mdd_level].push_back(vertex_id);
}
}
*/
for (int mdd_level = 0; mdd_level <= mdd_depth; ++mdd_level)
{
if (MDD[mdd_robot_id][mdd_level].empty())
{
MDD[mdd_robot_id][mdd_level].push_back(robot_sink_vertex_id);
}
/*
if (mdd_level >= source_Distances[robot_source_vertex_id][robot_sink_vertex_id])
{
extra_MDD[mdd_robot_id][mdd_level].push_back(robot_sink_vertex_id);
}
*/
}
}
/*
printf("Distance printout\n");
for (int mdd_robot = 1; mdd_robot <= N_Robots; ++mdd_robot)
{
int robot_source_vertex_id = m_initial_arrangement.get_RobotLocation(mdd_robot);
int robot_sink_vertex_id;
switch (m_goal_type)
{
case GOAL_TYPE_ARRANGEMENT:
{
robot_sink_vertex_id = m_goal_arrangement.get_RobotLocation(mdd_robot);
break;
}
case GOAL_TYPE_SPECIFICATION:
{
const sRobotGoal::Vertices_set &goal_IDs = m_goal_specification.get_RobotGoal(mdd_robot);
sASSERT(goal_IDs.size() == 1);
robot_sink_vertex_id = *goal_IDs.begin();
break;
}
default:
{
break;
}
}
printf("robot:%d (%d,%d)\n", mdd_robot, robot_source_vertex_id, robot_sink_vertex_id);
for (int vertex_id = 0; vertex_id < N_Vertices; ++vertex_id)
{
int source_dist = source_Distances[robot_source_vertex_id][vertex_id];
int goal_dist = goal_Distances[robot_sink_vertex_id][vertex_id];
printf(" %d:%d,%d\n", vertex_id, source_dist, goal_dist);
}
}
printf("<----\n");
*/
/*
printf("MDD printout\n");
for (int mdd_robot = 1; mdd_robot <= N_Robots; ++mdd_robot)
{
printf("robot:%d\n", mdd_robot);
for (int mdd_level = 0; mdd_level <= mdd_depth; ++mdd_level)
{
if (!extra_MDD[mdd_robot][mdd_level].empty())
{
printf("* ");
}
for (int i = 0; i < MDD[mdd_robot][mdd_level].size(); ++i)
{
printf("%d ", MDD[mdd_robot][mdd_level][i]);
}
printf("\n");
}
printf("\n");
}
printf("<----\n");
getchar();
*/
std::vector<int> distribution;
distribution.resize(N_Robots + 1);
for (int robot_id = 0; robot_id <= N_Robots; ++robot_id)
{
distribution[robot_id] = 0;
}
return mdd_depth;
}
int sMultirobotInstance::construct_GraphDisplacementMDD(sUndirectedGraph &graph, int max_total_cost, MDD_vector &MDD, int &extra_cost, MDD_vector &extra_MDD)
{
int max_individual_cost;
int N_Vertices = graph.get_VertexCount();
MDD.clear();
extra_MDD.clear();
VertexIDs_vector source_IDs;
VertexIDs_vector goal_IDs;
collect_Endpoints(source_IDs, goal_IDs);
graph.calc_SourceGoalShortestPaths(source_IDs, goal_IDs);
int min_total_cost = estimate_TotalCost(max_individual_cost);
const sUndirectedGraph::Distances_2d_vector &source_Distances = graph.get_SourceShortestPaths();
const sUndirectedGraph::Distances_2d_vector &goal_Distances = graph.get_GoalShortestPaths();
extra_cost = max_total_cost - min_total_cost;
int mdd_depth = max_individual_cost + extra_cost;
int N_Robots = m_initial_arrangement.get_RobotCount();
MDD.resize(N_Robots + 1);
extra_MDD.resize(N_Robots + 1);
RobotIndices_mmap sorted_mdd_Robots;
for (int mdd_robot_id = 1; mdd_robot_id <= N_Robots; ++mdd_robot_id)
{
MDD[mdd_robot_id].resize(mdd_depth + 1);
extra_MDD[mdd_robot_id].resize(mdd_depth + 1);
int robot_source_vertex_id = m_initial_arrangement.get_RobotLocation(mdd_robot_id);
int robot_sink_vertex_id;
switch (m_goal_type)
{
case GOAL_TYPE_ARRANGEMENT:
{
robot_sink_vertex_id = m_goal_arrangement.get_RobotLocation(mdd_robot_id);
break;
}
case GOAL_TYPE_SPECIFICATION:
{
const sRobotGoal::Vertices_set &goal_IDs = m_goal_specification.get_RobotGoal(mdd_robot_id);
sASSERT(goal_IDs.size() == 1);
robot_sink_vertex_id = *goal_IDs.begin();
break;
}
default:
{
break;
}
}
int robot_cost = source_Distances[robot_source_vertex_id][robot_sink_vertex_id];
sorted_mdd_Robots.insert(RobotIndices_mmap::value_type(robot_cost, mdd_robot_id));
}
int sort_index = 0;
for (RobotIndices_mmap::const_reverse_iterator sort_robot = sorted_mdd_Robots.rbegin(); sort_robot != sorted_mdd_Robots.rend(); ++sort_robot)
{
int add_index = (sort_index++ * (sizeof(sMDD_Addition) / sizeof(int))) / N_Robots;
int extra_addition = sMDD_Addition[add_index];
int mdd_robot_id = sort_robot->second;
MDD[mdd_robot_id].resize(mdd_depth + 1);
extra_MDD[mdd_robot_id].resize(mdd_depth + 1);
int robot_source_vertex_id = m_initial_arrangement.get_RobotLocation(mdd_robot_id);
int robot_sink_vertex_id;
switch (m_goal_type)
{
case GOAL_TYPE_ARRANGEMENT:
{
robot_sink_vertex_id = m_goal_arrangement.get_RobotLocation(mdd_robot_id);
break;
}
case GOAL_TYPE_SPECIFICATION:
{
const sRobotGoal::Vertices_set &goal_IDs = m_goal_specification.get_RobotGoal(mdd_robot_id);
sASSERT(goal_IDs.size() == 1);
robot_sink_vertex_id = *goal_IDs.begin();
break;
}
default:
{
break;
}
}
int robot_cost = source_Distances[robot_source_vertex_id][robot_sink_vertex_id];
/*
for (int mdd_level = 0; mdd_level <= mdd_depth; ++mdd_level)
{
for (int vertex_id = 0; vertex_id < N_Vertices; ++vertex_id)
{
if ( source_Distances[robot_source_vertex_id][vertex_id] <= mdd_level
&& goal_Distances[robot_sink_vertex_id][vertex_id] <= robot_cost + extra_cost - mdd_level)
{
MDD[mdd_robot_id][mdd_level].push_back(vertex_id);
printf("mdd_level:%d\n", mdd_level);
}
}
}
*/
RobotMDD_set robot_MDD;
robot_MDD.resize(mdd_depth + 1);
for (int vertex_id = 0; vertex_id < N_Vertices; ++vertex_id)
{
for (int mdd_level = source_Distances[robot_source_vertex_id][vertex_id];
mdd_level <= sMIN(robot_cost + (extra_cost + extra_addition) - goal_Distances[robot_sink_vertex_id][vertex_id], mdd_depth);
++mdd_level)
{
if (m_initial_arrangement.m_robot_Sizes[mdd_robot_id] > 1)
{
for (int dr = 0; dr < m_initial_arrangement.m_robot_Sizes[mdd_robot_id]; ++dr)
{
for (int dc = 0; dc < m_initial_arrangement.m_robot_Sizes[mdd_robot_id]; ++dc)
{
int grid_vertex_id = graph.get_GridNeighborVertexID(vertex_id, dr, dc);
if (grid_vertex_id >= 0)
{
robot_MDD[mdd_level].insert(grid_vertex_id);
}
}
}
}
else
{
robot_MDD[mdd_level].insert(vertex_id);
}
}
}
for (int mdd_level = 0; mdd_level <= mdd_depth; ++mdd_level)
{
if (robot_MDD[mdd_level].empty())
{
if (m_initial_arrangement.m_robot_Sizes[mdd_robot_id] > 1)
{
for (int dr = 0; dr < m_initial_arrangement.m_robot_Sizes[mdd_robot_id]; ++dr)
{
for (int dc = 0; dc < m_initial_arrangement.m_robot_Sizes[mdd_robot_id]; ++dc)
{
int grid_vertex_id = graph.get_GridNeighborVertexID(robot_sink_vertex_id, dr, dc);
if (grid_vertex_id >= 0)
{
robot_MDD[mdd_level].insert(grid_vertex_id);
}
}
}
}
else
{
robot_MDD[mdd_level].insert(robot_sink_vertex_id);
}
}
if ( mdd_level >= source_Distances[robot_source_vertex_id][robot_sink_vertex_id]
&& mdd_level < source_Distances[robot_source_vertex_id][robot_sink_vertex_id] + (extra_cost + extra_addition))
{
extra_MDD[mdd_robot_id][mdd_level].push_back(robot_sink_vertex_id);
}
}
for (int mdd_level = 0; mdd_level <= mdd_depth; ++mdd_level)
{
for (VertexIDs_set::const_iterator vertex_ID = robot_MDD[mdd_level].begin(); vertex_ID != robot_MDD[mdd_level].end(); ++vertex_ID)
{
MDD[mdd_robot_id][mdd_level].push_back(*vertex_ID);
}
}
}
/*
printf("Distance printout\n");
for (int mdd_robot = 1; mdd_robot <= N_Robots; ++mdd_robot)
{
int robot_source_vertex_id = m_initial_arrangement.get_RobotLocation(mdd_robot);
int robot_sink_vertex_id;
switch (m_goal_type)
{
case GOAL_TYPE_ARRANGEMENT:
{
robot_sink_vertex_id = m_goal_arrangement.get_RobotLocation(mdd_robot);
break;
}
case GOAL_TYPE_SPECIFICATION:
{
const sRobotGoal::Vertices_set &goal_IDs = m_goal_specification.get_RobotGoal(mdd_robot);
sASSERT(goal_IDs.size() == 1);
robot_sink_vertex_id = *goal_IDs.begin();
break;
}
default:
{
break;
}
}
printf("robot:%d (%d,%d)\n", mdd_robot, robot_source_vertex_id, robot_sink_vertex_id);
for (int vertex_id = 0; vertex_id < N_Vertices; ++vertex_id)
{
int source_dist = source_Distances[robot_source_vertex_id][vertex_id];
int goal_dist = goal_Distances[robot_sink_vertex_id][vertex_id];
printf(" %d:%d,%d\n", vertex_id, source_dist, goal_dist);
}
}
printf("<----\n");
printf("MDD printout\n");
for (int mdd_robot = 1; mdd_robot <= N_Robots; ++mdd_robot)
{
printf("robot:%d\n", mdd_robot);
for (int mdd_level = 0; mdd_level <= mdd_depth; ++mdd_level)
{
for (int i = 0; i < MDD[mdd_robot][mdd_level].size(); ++i)
{
printf("%d ", MDD[mdd_robot][mdd_level][i]);
}
printf("\n");
}
printf("\n");
}
printf("<----\n");
*/
std::vector<int> distribution;
distribution.resize(N_Robots + 1);
for (int robot_id = 0; robot_id <= N_Robots; ++robot_id)
{
distribution[robot_id] = 0;
}
return mdd_depth;
}
int sMultirobotInstance::construct_GraphLimitedMDD(sUndirectedGraph &graph, int max_total_cost, MDD_vector &MDD, int &extra_cost, MDD_vector &extra_MDD)
{
int max_individual_cost;
int N_Vertices = graph.get_VertexCount();
MDD.clear();
extra_MDD.clear();
VertexIDs_vector source_IDs;
VertexIDs_vector goal_IDs;
collect_Endpoints(source_IDs, goal_IDs);
graph.calc_SourceGoalShortestPaths(source_IDs, goal_IDs);
int min_total_cost = estimate_TotalCost(max_individual_cost);
const sUndirectedGraph::Distances_2d_vector &source_Distances = graph.get_SourceShortestPaths();
const sUndirectedGraph::Distances_2d_vector &goal_Distances = graph.get_GoalShortestPaths();
extra_cost = max_total_cost - min_total_cost;
int mdd_depth = max_individual_cost + extra_cost;
int N_Robots = m_initial_arrangement.get_RobotCount();
MDD.resize(N_Robots + 1);
extra_MDD.resize(N_Robots + 1);
RobotIndices_mmap sorted_mdd_Robots;
for (int mdd_robot_id = 1; mdd_robot_id <= N_Robots; ++mdd_robot_id)
{
MDD[mdd_robot_id].resize(mdd_depth + 1);
extra_MDD[mdd_robot_id].resize(mdd_depth + 1);
int robot_source_vertex_id = m_initial_arrangement.get_RobotLocation(mdd_robot_id);
int robot_sink_vertex_id;
switch (m_goal_type)
{
case GOAL_TYPE_ARRANGEMENT:
{
robot_sink_vertex_id = m_goal_arrangement.get_RobotLocation(mdd_robot_id);
break;
}
case GOAL_TYPE_SPECIFICATION:
{
const sRobotGoal::Vertices_set &goal_IDs = m_goal_specification.get_RobotGoal(mdd_robot_id);
sASSERT(goal_IDs.size() == 1);
robot_sink_vertex_id = *goal_IDs.begin();
break;
}
default:
{
break;
}
}
int robot_cost = source_Distances[robot_source_vertex_id][robot_sink_vertex_id];
sorted_mdd_Robots.insert(RobotIndices_mmap::value_type(robot_cost, mdd_robot_id));
}
int sort_index = 0;
for (RobotIndices_mmap::const_reverse_iterator sort_robot = sorted_mdd_Robots.rbegin(); sort_robot != sorted_mdd_Robots.rend(); ++sort_robot)
{
int add_index = (sort_index++ * (sizeof(sMDD_Addition) / sizeof(int))) / N_Robots;
int extra_addition = sMDD_Addition[add_index];
int mdd_robot_id = sort_robot->second;
MDD[mdd_robot_id].resize(mdd_depth + 1);
extra_MDD[mdd_robot_id].resize(mdd_depth + 1);
int robot_source_vertex_id = m_initial_arrangement.get_RobotLocation(mdd_robot_id);
int robot_sink_vertex_id;
switch (m_goal_type)
{
case GOAL_TYPE_ARRANGEMENT:
{
robot_sink_vertex_id = m_goal_arrangement.get_RobotLocation(mdd_robot_id);
break;
}
case GOAL_TYPE_SPECIFICATION:
{
const sRobotGoal::Vertices_set &goal_IDs = m_goal_specification.get_RobotGoal(mdd_robot_id);
sASSERT(goal_IDs.size() == 1);
robot_sink_vertex_id = *goal_IDs.begin();
break;
}
default:
{
break;
}
}
int robot_cost = source_Distances[robot_source_vertex_id][robot_sink_vertex_id];
/*
for (int mdd_level = 0; mdd_level <= mdd_depth; ++mdd_level)
{
for (int vertex_id = 0; vertex_id < N_Vertices; ++vertex_id)
{
if ( source_Distances[robot_source_vertex_id][vertex_id] <= mdd_level
&& goal_Distances[robot_sink_vertex_id][vertex_id] <= robot_cost + extra_cost - mdd_level)
{
MDD[mdd_robot_id][mdd_level].push_back(vertex_id);
printf("mdd_level:%d\n", mdd_level);
}
}
}
*/
RobotMDD_set robot_MDD;
robot_MDD.resize(mdd_depth + 1);
for (int vertex_id = 0; vertex_id < N_Vertices; ++vertex_id)
{
for (int mdd_level = source_Distances[robot_source_vertex_id][vertex_id];
mdd_level <= sMIN(robot_cost + (extra_cost + extra_addition) - goal_Distances[robot_sink_vertex_id][vertex_id], mdd_depth);
++mdd_level)
{
if (m_initial_arrangement.m_robot_Sizes[mdd_robot_id] > 1)
{
if (is_Fitting(graph, mdd_robot_id, m_initial_arrangement.m_robot_Sizes[mdd_robot_id], m_initial_arrangement.m_robot_Sizes[mdd_robot_id], vertex_id))
{
robot_MDD[mdd_level].insert(vertex_id);
}
}
else
{
robot_MDD[mdd_level].insert(vertex_id);
}
}
}
for (int mdd_level = 0; mdd_level <= mdd_depth; ++mdd_level)
{
if (robot_MDD[mdd_level].empty())
{
if (m_initial_arrangement.m_robot_Sizes[mdd_robot_id] > 1)
{
if (is_Fitting(graph, mdd_robot_id, m_initial_arrangement.m_robot_Sizes[mdd_robot_id], m_initial_arrangement.m_robot_Sizes[mdd_robot_id], robot_sink_vertex_id))
{
robot_MDD[mdd_level].insert(robot_sink_vertex_id);
}
}
else
{
robot_MDD[mdd_level].insert(robot_sink_vertex_id);
}
}
if ( mdd_level >= source_Distances[robot_source_vertex_id][robot_sink_vertex_id]
&& mdd_level < source_Distances[robot_source_vertex_id][robot_sink_vertex_id] + (extra_cost + extra_addition))
{
extra_MDD[mdd_robot_id][mdd_level].push_back(robot_sink_vertex_id);
}
}
for (int mdd_level = 0; mdd_level <= mdd_depth; ++mdd_level)
{
for (VertexIDs_set::const_iterator vertex_ID = robot_MDD[mdd_level].begin(); vertex_ID != robot_MDD[mdd_level].end(); ++vertex_ID)
{
MDD[mdd_robot_id][mdd_level].push_back(*vertex_ID);
}
}
}
/*
printf("Distance printout\n");
for (int mdd_robot = 1; mdd_robot <= N_Robots; ++mdd_robot)
{
int robot_source_vertex_id = m_initial_arrangement.get_RobotLocation(mdd_robot);
int robot_sink_vertex_id;
switch (m_goal_type)
{
case GOAL_TYPE_ARRANGEMENT:
{
robot_sink_vertex_id = m_goal_arrangement.get_RobotLocation(mdd_robot);
break;
}
case GOAL_TYPE_SPECIFICATION:
{
const sRobotGoal::Vertices_set &goal_IDs = m_goal_specification.get_RobotGoal(mdd_robot);
sASSERT(goal_IDs.size() == 1);
robot_sink_vertex_id = *goal_IDs.begin();
break;
}
default:
{
break;
}
}
printf("robot:%d (%d,%d)\n", mdd_robot, robot_source_vertex_id, robot_sink_vertex_id);
for (int vertex_id = 0; vertex_id < N_Vertices; ++vertex_id)
{
int source_dist = source_Distances[robot_source_vertex_id][vertex_id];
int goal_dist = goal_Distances[robot_sink_vertex_id][vertex_id];
printf(" %d:%d,%d\n", vertex_id, source_dist, goal_dist);
}
}
printf("<----\n");
printf("MDD printout\n");
for (int mdd_robot = 1; mdd_robot <= N_Robots; ++mdd_robot)
{
printf("robot:%d\n", mdd_robot);
for (int mdd_level = 0; mdd_level <= mdd_depth; ++mdd_level)
{
for (int i = 0; i < MDD[mdd_robot][mdd_level].size(); ++i)
{
printf("%d ", MDD[mdd_robot][mdd_level][i]);
}
printf("\n");
}
printf("\n");
}
printf("<----\n");
*/
std::vector<int> distribution;
distribution.resize(N_Robots + 1);
for (int robot_id = 0; robot_id <= N_Robots; ++robot_id)
{
distribution[robot_id] = 0;
}
return mdd_depth;
}
bool sMultirobotInstance::is_Fitting(sUndirectedGraph &graph, int sUNUSED(robot_id), int robot_row_size, int robot_column_size, int vertex_id)
{
for (int dr = 0; dr < robot_row_size; ++dr)
{
for (int dc = 0; dc < robot_column_size; ++dc)
{
int grid_vertex_id = graph.get_GridNeighborVertexID(vertex_id, dr, dc);
if (grid_vertex_id < 0)
{
return false;
}
}
}
return true;
}
void sMultirobotInstance::reduce_MDD(const Arrangements_vector &unfolded_solution, const MDD_vector &MDD, MDD_vector &reduced_MDD)
{
reduced_MDD.clear();
int N_Robots = MDD.size() - 1;
sASSERT(!MDD.empty() && MDD.size() > 1);
int mdd_depth = MDD[1].size() - 1;
sASSERT(mdd_depth >= 1);
reduced_MDD.resize(MDD.size());
Arrangements_vector addup_unfolded_solution = unfolded_solution;
if (addup_unfolded_solution.size() <= mdd_depth)
{
int N_addups = mdd_depth - addup_unfolded_solution.size();
sRobotArrangement last_arrangement = addup_unfolded_solution[addup_unfolded_solution.size() - 1];
do
{
addup_unfolded_solution.push_back(last_arrangement);
}
while (N_addups-- > 0);
}
#ifdef sVERBOSE
{
printf("Reducing MDD\n");
}
#endif
for (int mdd_robot_id = 1; mdd_robot_id <= N_Robots; ++mdd_robot_id)
{
#ifdef sVERBOSE
{
printf("robot:%d (%ld)\n", mdd_robot_id, MDD[mdd_robot_id].size());
}
#endif
reduced_MDD[mdd_robot_id].resize(MDD[mdd_robot_id].size());
for (int u = 0; u < MDD[mdd_robot_id][0].size(); ++u)
{
if ( addup_unfolded_solution[0].is_VertexUnforced(MDD[mdd_robot_id][0][u])
&& addup_unfolded_solution[1].is_VertexUnforced(MDD[mdd_robot_id][0][u]))
{
#ifdef sVERBOSE
{
printf("+%d ", MDD[mdd_robot_id][0][u]);
}
#endif
reduced_MDD[mdd_robot_id][0].push_back(MDD[mdd_robot_id][0][u]);
}
else
{
#ifdef sVERBOSE
{
printf("-%d ", MDD[mdd_robot_id][0][u]);
}
#endif
}
}
for (int mdd_level = 1; mdd_level < mdd_depth; ++mdd_level)
{
#ifdef sVERBOSE
{
printf("level:%d\n", mdd_level);
}
#endif
for (int u = 0; u < MDD[mdd_robot_id][mdd_level].size(); ++u)
{
if ( addup_unfolded_solution[mdd_level + 1].is_VertexUnforced(MDD[mdd_robot_id][mdd_level][u])
&& addup_unfolded_solution[mdd_level].is_VertexUnforced(MDD[mdd_robot_id][mdd_level][u])
&& addup_unfolded_solution[mdd_level - 1].is_VertexUnforced(MDD[mdd_robot_id][mdd_level][u]))
{
#ifdef sVERBOSE
{
printf("+%d ", MDD[mdd_robot_id][mdd_level][u]);
}
#endif
reduced_MDD[mdd_robot_id][mdd_level].push_back(MDD[mdd_robot_id][mdd_level][u]);
}
else
{
#ifdef sVERBOSE
{
printf("-%d ", MDD[mdd_robot_id][mdd_level][u]);
}
#endif
}
}
}
for (int u = 0; u < MDD[mdd_robot_id][mdd_depth].size(); ++u)
{
if ( addup_unfolded_solution[mdd_depth - 1].is_VertexUnforced(MDD[mdd_robot_id][mdd_depth][u])
&& addup_unfolded_solution[mdd_depth].is_VertexUnforced(MDD[mdd_robot_id][mdd_depth][u]))
{
#ifdef sVERBOSE
{
printf("+%d ", MDD[mdd_robot_id][mdd_depth][u]);
}
#endif
reduced_MDD[mdd_robot_id][mdd_depth].push_back(MDD[mdd_robot_id][mdd_depth][u]);
}
else
{
#ifdef sVERBOSE
{
printf("-%d ", MDD[mdd_robot_id][mdd_depth][u]);
}
#endif
}
}
}
}
struct MDDPoint
{
MDDPoint(int level, int vertex_id)
{
m_level = level;
m_vertex_id = vertex_id;
}
int m_level;
int m_vertex_id;
};
typedef std::list<MDDPoint> Queue_vector;
bool sMultirobotInstance::check_Connectivity(const MDD_vector &MDD) const
{
int N_Robots = MDD.size() - 1;
sASSERT(!MDD.empty() && MDD.size() > 1);
int mdd_depth = MDD[1].size() - 1;
sASSERT(mdd_depth >= 1);
MDD_vector scheduled_MDD = MDD;
#ifdef sVERBOSE
{
printf("Checking MDD connectivity ...\n");
}
#endif
for (int mdd_robot_id = 1; mdd_robot_id <= N_Robots; ++mdd_robot_id)
{
if (MDD[mdd_robot_id][0].empty() || MDD[mdd_robot_id][mdd_depth].empty())
{
#ifdef sVERBOSE
{
printf(" Unaccessible source or destination\n");
}
#endif
return false;
}
#ifdef sVERBOSE
{
printf("Goal id: %d (at level %d)\n", MDD[mdd_robot_id][mdd_depth][0], mdd_depth);
}
#endif
scheduled_MDD[mdd_robot_id][0][0] = -1;
Queue_vector mdd_Queue;
mdd_Queue.push_back(MDDPoint(0, MDD[mdd_robot_id][0][0]));
while (!mdd_Queue.empty())
{
MDDPoint mdd_point = mdd_Queue.front();
mdd_Queue.pop_front();
#ifdef sVERBOSE
{
printf("mdd point:%d,%d\n", mdd_point.m_level, mdd_point.m_vertex_id);
}
#endif
if (mdd_point.m_level == mdd_depth && mdd_point.m_vertex_id == MDD[mdd_robot_id][mdd_depth][0])
{
#ifdef sVERBOSE
{
printf(" Connected\n");
}
#endif
return true;
}
if (mdd_point.m_level < mdd_depth)
{
for (int v = 0; v < MDD[mdd_robot_id][mdd_point.m_level + 1].size(); ++v)
{
if (scheduled_MDD[mdd_robot_id][mdd_point.m_level + 1][v] >= 0)
{
if (mdd_point.m_vertex_id == MDD[mdd_robot_id][mdd_point.m_level + 1][v] || m_environment.is_Adjacent(mdd_point.m_vertex_id, MDD[mdd_robot_id][mdd_point.m_level + 1][v]))
{
mdd_Queue.push_back(MDDPoint(mdd_point.m_level + 1, MDD[mdd_robot_id][mdd_point.m_level + 1][v]));
scheduled_MDD[mdd_robot_id][mdd_point.m_level + 1][v] = -1;
}
}
}
}
}
}
#ifdef sVERBOSE
{
printf(" Classically disconnected\n");
}
#endif
return false;
}
void sMultirobotInstance::unify_MDD(const MDD_vector &MDD, RobotMDD_vector &unified_MDD)
{
int N_Robots = MDD.size() - 1;
sASSERT(!MDD.empty());
int mdd_depth = MDD[1].size();
unified_MDD.resize(mdd_depth);
#ifdef sVERBOSE
{
printf("Unifying... (%ld,%ld)\n", MDD.size(), MDD[1].size());
}
#endif
for (int mdd_level = 0; mdd_level < mdd_depth; ++mdd_level)
{
VertexIDs_set vertex_IDs;
for (int mdd_robot_id = 1; mdd_robot_id <= N_Robots; ++mdd_robot_id)
{
const VertexIDs_vector &mdd_vertex_IDs = MDD[mdd_robot_id][mdd_level];
for (VertexIDs_vector::const_iterator vertex = mdd_vertex_IDs.begin(); vertex != mdd_vertex_IDs.end(); ++vertex)
{
vertex_IDs.insert(*vertex);
}
}
#ifdef sVERBOSE
{
printf(" unify level: %d: ", mdd_level);
}
#endif
for (VertexIDs_set::const_iterator vertex = vertex_IDs.begin(); vertex != vertex_IDs.end(); ++vertex)
{
#ifdef sVERBOSE
{
printf("%d ", *vertex);
}
#endif
unified_MDD[mdd_level].push_back(*vertex);
}
#ifdef sVERBOSE
{
printf("\n");
}
#endif
}
}
void sMultirobotInstance::construct_InverseMDD(int N_Vertices, const MDD_vector &MDD, InverseMDD_vector &inverse_MDD)
{
inverse_MDD.clear();
int N_Robots = MDD.size() - 1;
int mdd_depth = MDD[1].size();
inverse_MDD.resize(N_Robots + 1);
for (int mdd_robot_id = 1; mdd_robot_id <= N_Robots; ++mdd_robot_id)
{
inverse_MDD[mdd_robot_id].resize(mdd_depth);
for (int mdd_level = 0; mdd_level < mdd_depth; ++mdd_level)
{
inverse_MDD[mdd_robot_id][mdd_level].resize(N_Vertices, -1);
for (int mdd_vertex_index = 0; mdd_vertex_index < MDD[mdd_robot_id][mdd_level].size(); ++mdd_vertex_index)
{
inverse_MDD[mdd_robot_id][mdd_level][MDD[mdd_robot_id][mdd_level][mdd_vertex_index]] = mdd_vertex_index;
}
}
}
}
void sMultirobotInstance::construct_MDDIndices(const MDD_vector &MDD, MDDIndices_vector &MDD_Indices)
{
int N_Robots = MDD.size() - 1;
int mdd_depth = MDD[1].size();
MDD_Indices.resize(N_Robots + 1);
for (int mdd_robot_id = 1; mdd_robot_id <= N_Robots; ++mdd_robot_id)
{
MDD_Indices[mdd_robot_id].resize(mdd_depth);
for (int mdd_level = 0; mdd_level < mdd_depth; ++mdd_level)
{
for (int mdd_vertex_index = 0; mdd_vertex_index < MDD[mdd_robot_id][mdd_level].size(); ++mdd_vertex_index)
{
MDD_Indices[mdd_robot_id][mdd_level][MDD[mdd_robot_id][mdd_level][mdd_vertex_index]] = mdd_vertex_index;
}
}
}
}
void sMultirobotInstance::construct_MDDIndices(const RobotMDD_vector &unified_MDD, RobotMDDIndices_vector &unified_MDD_Indices)
{
int mdd_depth = unified_MDD.size();
unified_MDD_Indices.resize(mdd_depth);
for (int mdd_level = 0; mdd_level < mdd_depth; ++mdd_level)
{
for (int mdd_vertex_index = 0; mdd_vertex_index < unified_MDD[mdd_level].size(); ++mdd_vertex_index)
{
unified_MDD_Indices[mdd_level][unified_MDD[mdd_level][mdd_vertex_index]] = mdd_vertex_index;
}
}
}
int sMultirobotInstance::construct_NoMDD(int max_total_cost, MDD_vector &MDD, int &extra_cost, MDD_vector &extra_MDD)
{
return construct_GraphMDD(m_environment, max_total_cost, MDD, extra_cost, extra_MDD);
}
int sMultirobotInstance::construct_SparseNoMDD(int max_total_cost, MDD_vector &MDD, int &extra_cost, MDD_vector &extra_MDD)
{
return construct_GraphMDD(m_sparse_environment, max_total_cost, MDD, extra_cost, extra_MDD);
}
int sMultirobotInstance::construct_GraphNoMDD(sUndirectedGraph &graph, int max_total_cost, MDD_vector &MDD, int &extra_cost, MDD_vector &extra_MDD)
{
int max_individual_cost;
int min_total_cost = estimate_TotalCost(max_individual_cost);
VertexIDs_vector source_IDs;
VertexIDs_vector goal_IDs;
collect_Endpoints(source_IDs, goal_IDs);
graph.calc_SourceGoalShortestPaths(source_IDs, goal_IDs);
const sUndirectedGraph::Distances_2d_vector &source_Distances = graph.get_SourceShortestPaths();
// const sUndirectedGraph::Distances_2d_vector &goal_Distances = graph.get_GoalShortestPaths();
extra_cost = max_total_cost - min_total_cost;
int mdd_depth = max_individual_cost + extra_cost;
/*
printf("mdd_depth:%d\n", mdd_depth);
printf("extra_cost:%d\n", extra_cost);
*/
int N_Robots = m_initial_arrangement.get_RobotCount();
MDD.clear();
MDD.resize(N_Robots + 1);
extra_MDD.resize(N_Robots + 1);
for (int mdd_robot_id = 1; mdd_robot_id <= N_Robots; ++mdd_robot_id)
{
// printf("mdd_robot:%d\n", mdd_robot_id);
MDD[mdd_robot_id].resize(mdd_depth + 1);
extra_MDD[mdd_robot_id].resize(mdd_depth + 1);
int robot_source_vertex_id = m_initial_arrangement.get_RobotLocation(mdd_robot_id);
int robot_sink_vertex_id;
switch (m_goal_type)
{
case GOAL_TYPE_ARRANGEMENT:
{
robot_sink_vertex_id = m_goal_arrangement.get_RobotLocation(mdd_robot_id);
break;
}
case GOAL_TYPE_SPECIFICATION:
{
const sRobotGoal::Vertices_set &goal_IDs = m_goal_specification.get_RobotGoal(mdd_robot_id);
sASSERT(goal_IDs.size() == 1);
robot_sink_vertex_id = *goal_IDs.begin();
break;
}
default:
{
break;
}
}
for (int mdd_level = 0; mdd_level <= mdd_depth; ++mdd_level)
{
// printf("level %d (%d):", mdd_level, mdd_depth);
int N_Vertices = graph.get_VertexCount();
for (int vertex_id = 0; vertex_id < N_Vertices; ++vertex_id)
{
MDD[mdd_robot_id][mdd_level].push_back(vertex_id);
// printf("%d ", vertex_id);
}
if (mdd_level >= source_Distances[robot_source_vertex_id][robot_sink_vertex_id])
{
extra_MDD[mdd_robot_id][mdd_level].push_back(robot_sink_vertex_id);
// printf(" * ");
}
// extra_MDD[mdd_robot_id][mdd_level].push_back(robot_sink_vertex_id);
// printf("\n");
}
}
std::vector<int> distribution;
distribution.resize(N_Robots + 1);
for (int robot_id = 0; robot_id <= N_Robots; ++robot_id)
{
distribution[robot_id] = 0;
}
return mdd_depth;
}
void sMultirobotInstance::construct_MakespanMDD(int max_makespan, MDD_vector &MDD)
{
construct_GraphMakespanMDD(m_environment, max_makespan, MDD);
}
void sMultirobotInstance::construct_SparseMakespanMDD(int max_makespan, MDD_vector &MDD)
{
construct_GraphMakespanMDD(m_sparse_environment, max_makespan, MDD);
}
void sMultirobotInstance::construct_GraphMakespanMDD(sUndirectedGraph &graph, int max_makespan, MDD_vector &MDD)
{
VertexIDs_vector source_IDs;
VertexIDs_vector goal_IDs;
MDD.clear();
collect_Endpoints(source_IDs, goal_IDs);
graph.calc_SourceGoalShortestPaths(source_IDs, goal_IDs);
const sUndirectedGraph::Distances_2d_vector &source_Distances = graph.get_SourceShortestPaths();
const sUndirectedGraph::Distances_2d_vector &goal_Distances = graph.get_GoalShortestPaths();
int N_Robots = m_initial_arrangement.get_RobotCount();
MDD.resize(N_Robots + 1);
for (int mdd_robot_id = 1; mdd_robot_id <= N_Robots; ++mdd_robot_id)
{
MDD[mdd_robot_id].resize(max_makespan + 1);
int robot_source_vertex_id = m_initial_arrangement.get_RobotLocation(mdd_robot_id);
int robot_sink_vertex_id;
switch (m_goal_type)
{
case GOAL_TYPE_ARRANGEMENT:
{
robot_sink_vertex_id = m_goal_arrangement.get_RobotLocation(mdd_robot_id);
break;
}
case GOAL_TYPE_SPECIFICATION:
{
const sRobotGoal::Vertices_set &goal_IDs = m_goal_specification.get_RobotGoal(mdd_robot_id);
sASSERT(goal_IDs.size() == 1);
robot_sink_vertex_id = *goal_IDs.begin();
break;
}
default:
{
break;
}
}
#ifdef sVERBOSE
printf("Robot:%d\n", mdd_robot_id);
#endif
for (int mdd_level = 0; mdd_level <= max_makespan; ++mdd_level)
{
#ifdef sVERBOSE
printf("mdd level %d,%d: ", mdd_level, max_makespan);
#endif
int N_Vertices = graph.get_VertexCount();
for (int vertex_id = 0; vertex_id < N_Vertices; ++vertex_id)
{
if ( source_Distances[robot_source_vertex_id][vertex_id] <= mdd_level
&& goal_Distances[robot_sink_vertex_id][vertex_id] <= max_makespan - mdd_level)
{
#ifdef sVERBOSE
printf("%d ", vertex_id);
#endif
MDD[mdd_robot_id][mdd_level].push_back(vertex_id);
}
}
#ifdef sVERBOSE
printf("\n");
#endif
}
#ifdef sVERBOSE
printf("\n");
#endif
}
std::vector<int> distribution;
distribution.resize(N_Robots + 1);
for (int robot_id = 0; robot_id <= N_Robots; ++robot_id)
{
distribution[robot_id] = 0;
}
}
/*----------------------------------------------------------------------------*/
void sMultirobotInstance::to_Screen(const sString &indent) const
{
to_Stream(stdout, indent);
}
void sMultirobotInstance::to_Screen_multirobot(const sString &indent) const
{
to_Stream_multirobot(stdout, indent);
}
void sMultirobotInstance::to_Screen_capacitated_multirobot(const sString &indent) const
{
to_Stream_capacitated_multirobot(stdout, indent);
}
void sMultirobotInstance::to_Screen_domainPDDL(const sString &indent) const
{
to_Stream_domainPDDL(stdout, indent);
}
void sMultirobotInstance::to_Screen_problemPDDL(const sString &indent) const
{
to_Stream_problemPDDL(stdout, indent);
}
void sMultirobotInstance::to_Screen_bgu(const sString &indent, int instance_id) const
{
to_Stream_bgu(stdout, indent, instance_id);
}
sResult sMultirobotInstance::to_File(const sString &filename, const sString &indent) const
{
FILE *fw;
if ((fw = fopen(filename.c_str(), "w")) == NULL)
{
return sMULTIROBOT_OPEN_ERROR;
}
to_Stream(fw, indent);
fclose(fw);
return sRESULT_SUCCESS;
}
sResult sMultirobotInstance::to_File_multirobot(const sString &filename, const sString &indent) const
{
FILE *fw;
if ((fw = fopen(filename.c_str(), "w")) == NULL)
{
return sMULTIROBOT_OPEN_ERROR;
}
to_Stream_multirobot(fw, indent);
fclose(fw);
return sRESULT_SUCCESS;
}
sResult sMultirobotInstance::to_File_capacitated_multirobot(const sString &filename, const sString &indent) const
{
FILE *fw;
if ((fw = fopen(filename.c_str(), "w")) == NULL)
{
return sMULTIROBOT_OPEN_ERROR;
}
to_Stream_capacitated_multirobot(fw, indent);
fclose(fw);
return sRESULT_SUCCESS;
}
sResult sMultirobotInstance::to_File_domainPDDL(const sString &filename, const sString &indent) const
{
FILE *fw;
if ((fw = fopen(filename.c_str(), "w")) == NULL)
{
return sMULTIROBOT_PDDL_OPEN_ERROR;
}
to_Stream_domainPDDL(fw, indent);
fclose(fw);
return sRESULT_SUCCESS;
}
sResult sMultirobotInstance::to_File_problemPDDL(const sString &filename, const sString &indent) const
{
FILE *fw;
if ((fw = fopen(filename.c_str(), "w")) == NULL)
{
return sMULTIROBOT_PDDL_OPEN_ERROR;
}
to_Stream_problemPDDL(fw, indent);
fclose(fw);
return sRESULT_SUCCESS;
}
sResult sMultirobotInstance::to_File_bgu(const sString &filename, const sString &indent, int instance_id) const
{
FILE *fw;
if ((fw = fopen(filename.c_str(), "w")) == NULL)
{
return sMULTIROBOT_BGU_OPEN_ERROR;
}
to_Stream_bgu(fw, indent, instance_id);
fclose(fw);
return sRESULT_SUCCESS;
}
void sMultirobotInstance::to_Stream(FILE *fw, const sString &indent) const
{
fprintf(fw, "%sMultirobot instance: [\n", indent.c_str());
fprintf(fw, "%s%sEnvironment:\n", indent.c_str(), sRELOC_INDENT.c_str());
m_environment.to_Stream_vertices(fw, indent + sRELOC_INDENT + sRELOC_INDENT);
fprintf(fw, "%s%sInitial arrangement:\n", indent.c_str(), sRELOC_INDENT.c_str());
m_initial_arrangement.to_Stream(fw, indent + sRELOC_INDENT + sRELOC_INDENT);
switch (m_goal_type)
{
case GOAL_TYPE_ARRANGEMENT:
{
fprintf(fw, "%s%sGoal arrangement:\n", indent.c_str(), sRELOC_INDENT.c_str());
m_goal_arrangement.to_Stream(fw, indent + sRELOC_INDENT + sRELOC_INDENT);
break;
}
case GOAL_TYPE_SPECIFICATION:
{
fprintf(fw, "%s%sGoal specification:\n", indent.c_str(), sRELOC_INDENT.c_str());
m_goal_specification.to_Stream(fw, indent + sRELOC_INDENT + sRELOC_INDENT);
break;
}
default:
{
sASSERT(false);
break;
}
}
fprintf(fw, "%s]\n", indent.c_str());
}
void sMultirobotInstance::to_Stream_multirobot(FILE *fw, const sString &indent) const
{
fprintf(fw, "%sV =\n", indent.c_str());
int N_Vertices;
switch (m_goal_type)
{
case GOAL_TYPE_ARRANGEMENT:
{
N_Vertices = m_initial_arrangement.m_vertex_Occups.size();
break;
}
case GOAL_TYPE_SPECIFICATION:
{
N_Vertices = m_goal_specification.m_goal_Compats.size();
break;
}
default:
{
sASSERT(false);
break;
}
}
for (int i = 0; i < N_Vertices; ++i)
{
switch (m_goal_type)
{
case GOAL_TYPE_ARRANGEMENT:
{
fprintf(fw, "(%d:-1)[%d:%d:%d]", i,
m_initial_arrangement.m_vertex_Occups[i],
m_goal_arrangement.m_vertex_Occups[i],
m_goal_arrangement.m_vertex_Occups[i]);
break;
}
case GOAL_TYPE_SPECIFICATION:
{
if (m_goal_specification.m_goal_Compats[i].empty())
{
fprintf(fw, "(%d:-1)[%d:0:0]", i,
m_initial_arrangement.m_vertex_Occups[i]);
}
else if (m_goal_specification.m_goal_Compats[i].size() == 1)
{
fprintf(fw, "(%d:-1)[%d:%d:%d]", i,
m_initial_arrangement.m_vertex_Occups[i],
*m_goal_specification.m_goal_Compats[i].begin(),
*m_goal_specification.m_goal_Compats[i].begin());
}
else
{
fprintf(fw, "(%d:-1)[%d:", i, m_initial_arrangement.m_vertex_Occups[i]);
m_goal_specification.to_Stream_multirobot(fw, m_goal_specification.m_goal_Compats[i]);
fprintf(fw, ":");
m_goal_specification.to_Stream_multirobot(fw, m_goal_specification.m_goal_Compats[i]);
fprintf(fw, "]");
}
break;
}
default:
{
break;
}
}
if (m_environment.m_Vertices[i].m_Conflicts.empty())
{
fprintf(fw, "\n");
}
else
{
fprintf(fw, "< ");
for (int c = 0; c < m_environment.m_Vertices[i].m_Conflicts.size(); ++c)
{
fprintf(fw, "%d ", m_environment.m_Vertices[i].m_Conflicts[c]);
}
fprintf(fw, ">\n");
}
}
m_environment.to_Stream_multirobot(fw, indent);
}
void sMultirobotInstance::to_Stream_capacitated_multirobot(FILE *fw, const sString &indent) const
{
fprintf(fw, "%sV =\n", indent.c_str());
// TODO
int N_Vertices;
switch (m_goal_type)
{
case GOAL_TYPE_ARRANGEMENT:
{
N_Vertices = m_initial_arrangement.m_vertex_Occups.size();
break;
}
case GOAL_TYPE_SPECIFICATION:
{
N_Vertices = m_goal_specification.m_goal_Compats.size();
break;
}
default:
{
sASSERT(false);
break;
}
}
for (int i = 0; i < N_Vertices; ++i)
{
switch (m_goal_type)
{
case GOAL_TYPE_ARRANGEMENT:
{
fprintf(fw, "(%d:-1:%d)[%d:%d:%d]", i,
m_environment.m_Vertices[i].m_capacity,
m_initial_arrangement.m_vertex_Occups[i],
m_goal_arrangement.m_vertex_Occups[i],
m_goal_arrangement.m_vertex_Occups[i]);
break;
}
case GOAL_TYPE_SPECIFICATION:
{
if (m_goal_specification.m_goal_Compats[i].empty())
{
fprintf(fw, "(%d:-1:%d)[%d:0:0]", i,
m_environment.m_Vertices[i].m_capacity,
m_initial_arrangement.m_vertex_Occups[i]);
}
else if (m_goal_specification.m_goal_Compats[i].size() == 1)
{
fprintf(fw, "(%d:-1:%d)[%d:%d:%d]", i,
m_environment.m_Vertices[i].m_capacity,
m_initial_arrangement.m_vertex_Occups[i],
*m_goal_specification.m_goal_Compats[i].begin(),
*m_goal_specification.m_goal_Compats[i].begin());
}
else
{
fprintf(fw, "(%d:-1:%d)[%d:", i, m_environment.m_Vertices[i].m_capacity, m_initial_arrangement.m_vertex_Occups[i]);
m_goal_specification.to_Stream_multirobot(fw, m_goal_specification.m_goal_Compats[i]);
fprintf(fw, ":");
m_goal_specification.to_Stream_multirobot(fw, m_goal_specification.m_goal_Compats[i]);
fprintf(fw, "]");
}
break;
}
default:
{
break;
}
}
if (m_environment.m_Vertices[i].m_Conflicts.empty())
{
fprintf(fw, "\n");
}
else
{
fprintf(fw, "< ");
for (int c = 0; c < m_environment.m_Vertices[i].m_Conflicts.size(); ++c)
{
fprintf(fw, "%d ", m_environment.m_Vertices[i].m_Conflicts[c]);
}
fprintf(fw, ">\n");
}
}
m_environment.to_Stream_capacitated_multirobot(fw, indent);
}
void sMultirobotInstance::to_Stream_domainPDDL(FILE *fw, const sString &indent) const
{
fprintf(fw, "%s(define (domain multirobot)\n", indent.c_str());
fprintf(fw, "%s%s(:predicates\n", indent.c_str(), sRELOC_INDENT.c_str());
fprintf(fw, "%s%s%s(adjacent ?u ?v)\n", indent.c_str(), sRELOC_INDENT.c_str(), sRELOC_INDENT.c_str());
fprintf(fw, "%s%s%s(robot_location ?r ?v)\n", indent.c_str(), sRELOC_INDENT.c_str(), sRELOC_INDENT.c_str());
fprintf(fw, "%s%s%s(no_robot ?v)\n", indent.c_str(), sRELOC_INDENT.c_str(), sRELOC_INDENT.c_str());
fprintf(fw, "%s%s)\n", indent.c_str(), sRELOC_INDENT.c_str());
fprintf(fw, "%s%s(:action move\n", indent.c_str(), sRELOC_INDENT.c_str());
fprintf(fw, "%s%s%s:parameters (?r ?u ?v)\n", indent.c_str(), sRELOC_INDENT.c_str(), sRELOC_INDENT.c_str());
fprintf(fw, "%s%s%s:precondition (and\n", indent.c_str(), sRELOC_INDENT.c_str(), sRELOC_INDENT.c_str());
fprintf(fw, "%s%s%s%s(robot_location ?r ?u) (no_robot ?v) (adjacent ?u ?v)\n", indent.c_str(), sRELOC_INDENT.c_str(), sRELOC_INDENT.c_str(), sRELOC_INDENT.c_str());
fprintf(fw, "%s%s%s)\n", indent.c_str(), sRELOC_INDENT.c_str(), sRELOC_INDENT.c_str());
fprintf(fw, "%s%s%s:effect (and\n", indent.c_str(), sRELOC_INDENT.c_str(), sRELOC_INDENT.c_str());
fprintf(fw, "%s%s%s%s(robot_location ?r ?v) (no_robot ?u) (not (no_robot ?v))\n", indent.c_str(), sRELOC_INDENT.c_str(), sRELOC_INDENT.c_str(), sRELOC_INDENT.c_str());
fprintf(fw, "%s%s%s)\n", indent.c_str(), sRELOC_INDENT.c_str(), sRELOC_INDENT.c_str());
fprintf(fw, "%s%s)\n", indent.c_str(), sRELOC_INDENT.c_str());
fprintf(fw, "%s)\n", indent.c_str());
}
void sMultirobotInstance::to_Stream_problemPDDL(FILE *fw, const sString &indent) const
{
fprintf(fw, "%s(define (problem multirobot_instance)\n", indent.c_str());
fprintf(fw, "%s%s(:domain multirobot)\n", indent.c_str(), sRELOC_INDENT.c_str());
fprintf(fw, "%s%s(:objects\n", indent.c_str(), sRELOC_INDENT.c_str());
int N_Vertices = m_environment.get_VertexCount();
for (int vertex_id = 0; vertex_id < N_Vertices; ++vertex_id)
{
fprintf(fw, "%s%s%sv%d\n", indent.c_str(), sRELOC_INDENT.c_str(), sRELOC_INDENT.c_str(), vertex_id);
}
int N_Robots = m_initial_arrangement.get_RobotCount();
for (int robot_id = 1; robot_id <= N_Robots; ++robot_id)
{
fprintf(fw, "%s%s%sr%d\n", indent.c_str(), sRELOC_INDENT.c_str(), sRELOC_INDENT.c_str(), robot_id);
}
fprintf(fw, "%s%s)\n", indent.c_str(), sRELOC_INDENT.c_str());
fprintf(fw, "%s%s(:init\n", indent.c_str(), sRELOC_INDENT.c_str());
for (sUndirectedGraph::Edges_list::const_iterator edge = m_environment.m_Edges.begin(); edge != m_environment.m_Edges.end(); ++edge)
{
fprintf(fw, "%s%s%s(adjacent v%d v%d)\n", indent.c_str(), sRELOC_INDENT.c_str(), sRELOC_INDENT.c_str(), edge->m_arc_vu.m_target->m_id, edge->m_arc_uv.m_target->m_id);
fprintf(fw, "%s%s%s(adjacent v%d v%d)\n", indent.c_str(), sRELOC_INDENT.c_str(), sRELOC_INDENT.c_str(), edge->m_arc_uv.m_target->m_id, edge->m_arc_vu.m_target->m_id);
}
for (int robot_id = 1; robot_id <= N_Robots; ++robot_id)
{
fprintf(fw, "%s%s%s(robot_location r%d v%d)\n", indent.c_str(), sRELOC_INDENT.c_str(), sRELOC_INDENT.c_str(), robot_id, m_initial_arrangement.get_RobotLocation(robot_id));
}
for (int vertex_id = 0; vertex_id < N_Vertices; ++vertex_id)
{
int robot_id = m_initial_arrangement.get_VertexOccupancy(vertex_id);
if (robot_id == sRobotArrangement::VACANT_VERTEX)
{
fprintf(fw, "%s%s%s(no_robot v%d)\n", indent.c_str(), sRELOC_INDENT.c_str(), sRELOC_INDENT.c_str(), vertex_id);
}
}
fprintf(fw, "%s%s)\n", indent.c_str(), sRELOC_INDENT.c_str());
switch (m_goal_type)
{
case GOAL_TYPE_ARRANGEMENT:
{
fprintf(fw, "%s%s(:goal (and \n", indent.c_str(), sRELOC_INDENT.c_str());
for (int robot_id = 1; robot_id <= N_Robots; ++robot_id)
{
fprintf(fw, "%s%s%s(robot_location r%d v%d)\n", indent.c_str(), sRELOC_INDENT.c_str(), sRELOC_INDENT.c_str(), robot_id, m_goal_arrangement.get_RobotLocation(robot_id));
}
for (int vertex_id = 0; vertex_id < N_Vertices; ++vertex_id)
{
int robot_id = m_goal_arrangement.get_VertexOccupancy(vertex_id);
if (robot_id == sRobotArrangement::VACANT_VERTEX)
{
fprintf(fw, "%s%s%s(no_robot v%d)\n", indent.c_str(), sRELOC_INDENT.c_str(), sRELOC_INDENT.c_str(), vertex_id);
}
}
fprintf(fw, "%s%s))\n", indent.c_str(), sRELOC_INDENT.c_str());
break;
}
case GOAL_TYPE_SPECIFICATION:
{
fprintf(fw, "%s%s(:goal (and \n", indent.c_str(), sRELOC_INDENT.c_str());
for (int robot_id = 1; robot_id <= N_Robots; ++robot_id)
{
const sRobotGoal::Vertices_set &goal_IDs = m_goal_specification.get_RobotGoal(robot_id);
fprintf(fw, "%s%s%s(or ", indent.c_str(), sRELOC_INDENT.c_str(), sRELOC_INDENT.c_str());
for (sRobotGoal::Vertices_set::const_iterator goal_id = goal_IDs.begin(); goal_id != goal_IDs.end(); ++goal_id)
{
fprintf(fw, "(robot_location r%d v%d) ", robot_id, *goal_id);
}
fprintf(fw, ")\n");
}
for (int vertex_id = 0; vertex_id < N_Vertices; ++vertex_id)
{
const sRobotGoal::Robots_set &robot_IDs = m_goal_specification.get_GoalCompatibility(vertex_id);
if (robot_IDs.empty())
{
fprintf(fw, "%s%s%s(no_robot v%d)\n", indent.c_str(), sRELOC_INDENT.c_str(), sRELOC_INDENT.c_str(), vertex_id);
}
}
fprintf(fw, "%s%s))\n", indent.c_str(), sRELOC_INDENT.c_str());
break;
}
default:
{
sASSERT(false);
break;
}
}
fprintf(fw, "%s)\n", indent.c_str());
}
void sMultirobotInstance::to_Stream_bgu(FILE *fw, const sString &indent, int instance_id) const
{
sASSERT(m_environment.m_Matrix != NULL);
fprintf(fw, "%s%d\n", indent.c_str(), instance_id);
fprintf(fw, "%sGrid:\n", indent.c_str());
fprintf(fw, "%s%d,%d\n", indent.c_str(), m_environment.m_y_size, m_environment.m_x_size);
for (int j = 0; j < m_environment.m_y_size; ++j)
{
for (int i = 0; i < m_environment.m_x_size; ++i)
{
if (m_environment.m_Matrix[j * m_environment.m_x_size + i] >= 0)
{
fprintf(fw, ".");
}
else
{
fprintf(fw, "@");
}
}
fprintf(fw, "\n");
}
int N_Robots = m_initial_arrangement.get_RobotCount();
fprintf(fw, "%sAgents:\n", indent.c_str());
fprintf(fw, "%s%d\n", indent.c_str(), N_Robots);
switch (m_goal_type)
{
case GOAL_TYPE_ARRANGEMENT:
{
for (int robot_id = 1; robot_id <= N_Robots; ++robot_id)
{
fprintf(fw, "%s%d,", indent.c_str(), robot_id - 1);
int goal_vertex_id = m_goal_arrangement.get_RobotLocation(robot_id);
fprintf(fw, "%d,%d,", m_environment.calc_GridRow(goal_vertex_id), m_environment.calc_GridColumn(goal_vertex_id));
int init_vertex_id = m_initial_arrangement.get_RobotLocation(robot_id);
fprintf(fw, "%d,%d\n", m_environment.calc_GridRow(init_vertex_id), m_environment.calc_GridColumn(init_vertex_id));
}
break;
}
case GOAL_TYPE_SPECIFICATION:
{
for (int robot_id = 1; robot_id <= N_Robots; ++robot_id)
{
fprintf(fw, "%s%d,", indent.c_str(), robot_id - 1);
sASSERT(m_goal_specification.get_RobotGoal(robot_id).size() == 1);
int goal_vertex_id = *m_goal_specification.get_RobotGoal(robot_id).begin();
fprintf(fw, "%d,%d,", m_environment.calc_GridRow(goal_vertex_id), m_environment.calc_GridColumn(goal_vertex_id));
int init_vertex_id = m_initial_arrangement.get_RobotLocation(robot_id);
fprintf(fw, "%d,%d\n", m_environment.calc_GridRow(init_vertex_id), m_environment.calc_GridColumn(init_vertex_id));
}
break;
}
default:
{
sASSERT(false);
break;
}
}
}
sResult sMultirobotInstance::from_File_bgu(const sString &filename)
{
sResult result;
FILE *fr;
if ((fr = fopen(filename.c_str(), "r")) == NULL)
{
return sMULTIROBOT_BGU_OPEN_ERROR;
}
result = from_Stream_bgu(fr);
if (sFAILED(result))
{
fclose(fr);
return result;
}
fclose(fr);
return sRESULT_SUCCESS;
}
sResult sMultirobotInstance::from_Stream_bgu(FILE *fr)
{
sResult result;
int N_Robots;
if (sFAILED(result = m_environment.from_Stream_bgu(fr)))
{
return result;
}
fscanf(fr, "Agents:\n");
fscanf(fr, "%d\n", &N_Robots);
m_goal_type = GOAL_TYPE_ARRANGEMENT;
m_initial_arrangement = sRobotArrangement(m_environment.get_VertexCount(), N_Robots);
m_goal_arrangement = sRobotArrangement(m_environment.get_VertexCount(), N_Robots);
m_goal_specification = sRobotGoal(m_environment.get_VertexCount(), N_Robots);
for (int robot_id = 1; robot_id <= N_Robots; ++robot_id)
{
int r_id;
fscanf(fr, "%d,", &r_id);
int goal_row, goal_column;
fscanf(fr, "%d,%d,", &goal_row, &goal_column);
int goal_vertex_id = m_environment.calc_GridVertexID(goal_row, goal_column);
int init_row, init_column;
fscanf(fr, "%d,%d\n", &init_row, &init_column);
int init_vertex_id = m_environment.calc_GridVertexID(init_row, init_column);
m_initial_arrangement.place_Robot(robot_id, init_vertex_id);
m_goal_arrangement.place_Robot(robot_id, goal_vertex_id);
m_goal_specification.charge_Robot(robot_id, goal_vertex_id);
}
return sRESULT_SUCCESS;
}
sResult sMultirobotInstance::from_File_usc(const sString &map_filename, const sString &agents_filename)
{
sResult result;
FILE *fr_map, *fr_agents;
if ((fr_map = fopen(map_filename.c_str(), "r")) == NULL)
{
return sMULTIROBOT_USC_MAP_OPEN_ERROR;
}
if ((fr_agents = fopen(agents_filename.c_str(), "r")) == NULL)
{
return sMULTIROBOT_USC_AGNT_OPEN_ERROR;
}
result = from_Stream_usc(fr_map, fr_agents);
if (sFAILED(result))
{
fclose(fr_map);
fclose(fr_agents);
return result;
}
fclose(fr_map);
fclose(fr_agents);
return sRESULT_SUCCESS;
}
sResult sMultirobotInstance::from_Stream_usc(FILE *fr_map, FILE *fr_agents)
{
sResult result;
int N_Robots;
if (sFAILED(result = m_environment.from_Stream_usc(fr_map)))
{
return result;
}
fscanf(fr_agents, "%d\n", &N_Robots);
m_goal_type = GOAL_TYPE_ARRANGEMENT;
m_initial_arrangement = sRobotArrangement(m_environment.get_VertexCount(), N_Robots);
m_goal_arrangement = sRobotArrangement(m_environment.get_VertexCount(), N_Robots);
m_goal_specification = sRobotGoal(m_environment.get_VertexCount(), N_Robots);
for (int robot_id = 1; robot_id <= N_Robots; ++robot_id)
{
int goal_row, goal_column;
fscanf(fr_agents, "%d,%d,", &goal_row, &goal_column);
int goal_vertex_id = m_environment.calc_GridVertexID(goal_row, goal_column);
int init_row, init_column;
fscanf(fr_agents, "%d,%d,", &init_row, &init_column);
int init_vertex_id = m_environment.calc_GridVertexID(init_row, init_column);
float delay_ignore;
fscanf(fr_agents, "%f\n", &delay_ignore);
m_initial_arrangement.place_Robot(robot_id, init_vertex_id);
m_goal_arrangement.place_Robot(robot_id, goal_vertex_id);
m_goal_specification.charge_Robot(robot_id, goal_vertex_id);
}
return sRESULT_SUCCESS;
}
sResult sMultirobotInstance::from_File_lusc(const sString &map_filename, const sString &agents_filename)
{
sResult result;
FILE *fr_map, *fr_agents;
if ((fr_map = fopen(map_filename.c_str(), "r")) == NULL)
{
return sMULTIROBOT_USC_MAP_OPEN_ERROR;
}
if ((fr_agents = fopen(agents_filename.c_str(), "r")) == NULL)
{
return sMULTIROBOT_USC_AGNT_OPEN_ERROR;
}
result = from_Stream_lusc(fr_map, fr_agents);
if (sFAILED(result))
{
fclose(fr_map);
fclose(fr_agents);
return result;
}
fclose(fr_map);
fclose(fr_agents);
return sRESULT_SUCCESS;
}
sResult sMultirobotInstance::from_Stream_lusc(FILE *fr_map, FILE *fr_agents)
{
sResult result;
int N_Robots;
if (sFAILED(result = m_environment.from_Stream_lusc(fr_map)))
{
return result;
}
fscanf(fr_agents, "%d\n", &N_Robots);
m_goal_type = GOAL_TYPE_ARRANGEMENT;
m_initial_arrangement = sRobotArrangement(m_environment.get_VertexCount(), N_Robots);
m_goal_arrangement = sRobotArrangement(m_environment.get_VertexCount(), N_Robots);
m_goal_specification = sRobotGoal(m_environment.get_VertexCount(), N_Robots);
m_initial_arrangement.m_robot_Sizes.resize(N_Robots + 1);
for (int robot_id = 1; robot_id <= N_Robots; ++robot_id)
{
int init_row, init_column;
fscanf(fr_agents, "%d,%d,", &init_row, &init_column);
int init_vertex_id = m_environment.calc_GridVertexID(init_row, init_column);
int goal_row, goal_column;
fscanf(fr_agents, "%d,%d,", &goal_row, &goal_column);
int goal_vertex_id = m_environment.calc_GridVertexID(goal_row, goal_column);
int robot_size;
fscanf(fr_agents, "%d\n", &robot_size);
m_initial_arrangement.m_robot_Sizes[robot_id] = robot_size;
m_initial_arrangement.place_Robot(robot_id, init_vertex_id);
m_goal_arrangement.place_Robot(robot_id, goal_vertex_id);
m_goal_specification.charge_Robot(robot_id, goal_vertex_id);
}
return sRESULT_SUCCESS;
}
sResult sMultirobotInstance::to_File_dibox(const sString &filename)
{
sResult result;
FILE *fw;
if ((fw = fopen(filename.c_str(), "w")) == NULL)
{
return sMULTIROBOT_DIBOX_OPEN_ERROR;
}
result = to_Stream_dibox(fw);
if (sFAILED(result))
{
fclose(fw);
return result;
}
fclose(fw);
return sRESULT_SUCCESS;
}
sResult sMultirobotInstance::to_Stream_dibox(FILE *fw)
{
int N_Robots = m_initial_arrangement.get_RobotCount();
m_environment.to_Stream_dibox(fw);
fprintf(fw, "LIST OF AGENTS:%d\n", N_Robots);
m_goal_type = GOAL_TYPE_ARRANGEMENT;
for (int robot_id = 1; robot_id <= N_Robots; ++robot_id)
{
int init_vertex_id, goal_vertex_id;
init_vertex_id = m_initial_arrangement.get_RobotLocation(robot_id);
goal_vertex_id = m_goal_arrangement.get_RobotLocation(robot_id);
fprintf(fw, "(q%d,%d,%d)\n", robot_id, init_vertex_id + 1, goal_vertex_id + 1);
}
return sRESULT_SUCCESS;
}
sResult sMultirobotInstance::from_File_dibox(const sString &filename)
{
sResult result;
FILE *fr;
if ((fr = fopen(filename.c_str(), "r")) == NULL)
{
return sMULTIROBOT_DIBOX_OPEN_ERROR;
}
result = from_Stream_dibox(fr);
if (sFAILED(result))
{
fclose(fr);
return result;
}
fclose(fr);
return sRESULT_SUCCESS;
}
sResult sMultirobotInstance::from_Stream_dibox(FILE *fr)
{
sResult result;
int N_Robots;
if (sFAILED(result = m_environment.from_Stream_dibox(fr)))
{
return result;
}
fscanf(fr, "LIST OF AGENTS:%d\n", &N_Robots);
m_goal_type = GOAL_TYPE_ARRANGEMENT;
m_initial_arrangement = sRobotArrangement(m_environment.get_VertexCount(), N_Robots);
m_goal_arrangement = sRobotArrangement(m_environment.get_VertexCount(), N_Robots);
m_goal_specification = sRobotGoal(m_environment.get_VertexCount(), N_Robots);
for (int robot_id = 1; robot_id <= N_Robots; ++robot_id)
{
int init_vertex_id, goal_vertex_id;
while(fgetc(fr) != ',');
fscanf(fr, "%d,%d)\n", &init_vertex_id, &goal_vertex_id);
m_initial_arrangement.place_Robot(robot_id, init_vertex_id - 1);
m_goal_arrangement.place_Robot(robot_id, goal_vertex_id - 1);
m_goal_specification.charge_Robot(robot_id, goal_vertex_id - 1);
}
return sRESULT_SUCCESS;
}
/*----------------------------------------------------------------------------*/
// sMultirobotSolution
const sMultirobotSolution::Move sMultirobotSolution::UNDEFINED_MOVE = sMultirobotSolution::Move(0, 0, 0);
/*----------------------------------------------------------------------------*/
sMultirobotSolution::Move::Move(int robot_id, int src_vrtx_id, int dest_vrtx_id)
: m_robot_id(robot_id)
, m_src_vrtx_id(src_vrtx_id)
, m_dest_vrtx_id(dest_vrtx_id)
, m_crt_time(0)
{
// nothing
}
sMultirobotSolution::Move::Move(int robot_id, int src_vrtx_id, int dest_vrtx_id, int crt_time)
: m_robot_id(robot_id)
, m_src_vrtx_id(src_vrtx_id)
, m_dest_vrtx_id(dest_vrtx_id)
, m_crt_time(crt_time)
{
// nothing
}
bool sMultirobotSolution::Move::is_Undefined(void) const
{
return (m_robot_id <= 0);
}
bool sMultirobotSolution::Move::is_Dependent(const Move &move) const
{
return ( m_src_vrtx_id == move.m_src_vrtx_id
|| m_src_vrtx_id == move.m_dest_vrtx_id
|| m_dest_vrtx_id == move.m_src_vrtx_id
|| m_dest_vrtx_id == move.m_dest_vrtx_id);
}
/*----------------------------------------------------------------------------*/
sMultirobotSolution::Step::Step(int time)
: m_time(time)
{
// nothing
}
/*----------------------------------------------------------------------------*/
sMultirobotSolution::sMultirobotSolution()
: m_Moves_cnt(0)
, m_optimality_ratio(-1.0)
{
// nothing
}
sMultirobotSolution::sMultirobotSolution(int start_step, const sMultirobotSolution &sub_solution)
: m_Moves_cnt(0)
, m_optimality_ratio(-1.0)
{
int N_Steps = sub_solution.m_Steps.size();
for (int i = 0; i < N_Steps; ++i)
{
const Step &step = sub_solution.m_Steps[i];
for (Moves_list::const_iterator move = step.m_Moves.begin(); move != step.m_Moves.end(); ++move)
{
add_Move(i + start_step, *move);
}
}
}
sMultirobotSolution::sMultirobotSolution(const sMultirobotSolution &sub_solution_1, const sMultirobotSolution sub_solution_2)
: m_Moves_cnt(0)
, m_optimality_ratio(-1.0)
{
int N_Steps_1 = sub_solution_1.m_Steps.size();
for (int i = 0; i < N_Steps_1; ++i)
{
const Step &step = sub_solution_1.m_Steps[i];
for (Moves_list::const_iterator move = step.m_Moves.begin(); move != step.m_Moves.end(); ++move)
{
add_Move(i, *move);
}
}
int N_Steps_2 = sub_solution_2.m_Steps.size();
for (int i = 0; i < N_Steps_2; ++i)
{
const Step &step = sub_solution_2.m_Steps[i];
for (Moves_list::const_iterator move = step.m_Moves.begin(); move != step.m_Moves.end(); ++move)
{
add_Move(i, *move);
}
}
}
bool sMultirobotSolution::is_Null(void) const
{
return (m_Steps.empty());
}
int sMultirobotSolution::get_MoveCount(void) const
{
return m_Moves_cnt;
}
int sMultirobotSolution::get_StepCount(void) const
{
return m_Steps.size();
}
void sMultirobotSolution::add_Move(int time, const Move &move)
{
int push_cnt = time - m_Steps.size();
while (push_cnt-- >= 0)
{
m_Steps.push_back(Step(m_Steps.size()));
}
m_Steps[time].m_Moves.push_back(move);
++m_Moves_cnt;
}
int sMultirobotSolution::calc_EmptySteps(void) const
{
int N_empty_Steps = 0;
int N_Steps = m_Steps.size();
for (int i = 0; i < N_Steps; ++i)
{
const Step &step = m_Steps[i];
if (step.m_Moves.empty())
{
++N_empty_Steps;
}
}
return N_empty_Steps;
}
void sMultirobotSolution::remove_EmptySteps(void)
{
int time = 0;
Steps_vector clean_Steps;
int N_Steps = m_Steps.size();
for (int i = 0; i < N_Steps; ++i)
{
Step &step = m_Steps[i];
if (!step.m_Moves.empty())
{
step.m_time = time++;
clean_Steps.push_back(step);
}
}
m_Steps = clean_Steps;
}
sMultirobotSolution sMultirobotSolution::extract_Subsolution(int start_step, int final_step) const
{
sMultirobotSolution subsolution;
for (int i = start_step; i <= final_step; ++i)
{
const Step &step = m_Steps[i];
for (Moves_list::const_iterator move = step.m_Moves.begin(); move != step.m_Moves.end(); ++move)
{
subsolution.add_Move(i, *move);
}
}
return subsolution;
}
void sMultirobotSolution::execute_Solution(const sRobotArrangement &initial_arrangement,
sRobotArrangement &final_arrangement,
int N_Steps) const
{
final_arrangement = initial_arrangement;
if (N_Steps == N_STEPS_UNDEFINED)
{
for (sMultirobotSolution::Steps_vector::const_iterator step = m_Steps.begin(); step != m_Steps.end(); ++step)
{
for (sMultirobotSolution::Moves_list::const_iterator move = step->m_Moves.begin(); move != step->m_Moves.end(); ++move)
{
final_arrangement.move_Robot(move->m_robot_id, move->m_dest_vrtx_id);
}
}
}
else
{
for (sMultirobotSolution::Steps_vector::const_iterator step = m_Steps.begin(); step != m_Steps.end(); ++step)
{
for (sMultirobotSolution::Moves_list::const_iterator move = step->m_Moves.begin(); move != step->m_Moves.end(); ++move)
{
final_arrangement.move_Robot(move->m_robot_id, move->m_dest_vrtx_id);
}
if (--N_Steps <= 0)
{
return;
}
}
}
}
void sMultirobotSolution::execute_Step(const sRobotArrangement ¤t_arrangement,
sRobotArrangement &final_arrangement,
int step_idx) const
{
final_arrangement = current_arrangement;
const Step &step = m_Steps[step_idx];
for (sMultirobotSolution::Moves_list::const_iterator move = step.m_Moves.begin(); move != step.m_Moves.end(); ++move)
{
final_arrangement.move_Robot(move->m_robot_id, move->m_dest_vrtx_id);
}
}
void sMultirobotSolution::execute_Solution(sRobotArrangement &arrangement,
int N_Steps) const
{
if (N_Steps == N_STEPS_UNDEFINED)
{
for (sMultirobotSolution::Steps_vector::const_iterator step = m_Steps.begin(); step != m_Steps.end(); ++step)
{
for (sMultirobotSolution::Moves_list::const_iterator move = step->m_Moves.begin(); move != step->m_Moves.end(); ++move)
{
arrangement.move_Robot(move->m_robot_id, move->m_dest_vrtx_id);
}
}
}
else
{
for (sMultirobotSolution::Steps_vector::const_iterator step = m_Steps.begin(); step != m_Steps.end(); ++step)
{
for (sMultirobotSolution::Moves_list::const_iterator move = step->m_Moves.begin(); move != step->m_Moves.end(); ++move)
{
arrangement.move_Robot(move->m_robot_id, move->m_dest_vrtx_id);
}
if (--N_Steps <= 0)
{
return;
}
}
}
}
void sMultirobotSolution::execute_Step(sRobotArrangement &arrangement,
int step_idx) const
{
const Step &step = m_Steps[step_idx];
for (sMultirobotSolution::Moves_list::const_iterator move = step.m_Moves.begin(); move != step.m_Moves.end(); ++move)
{
arrangement.move_Robot(move->m_robot_id, move->m_dest_vrtx_id);
}
}
bool sMultirobotSolution::verify_Step(const sRobotArrangement &arrangement,
int step_idx) const
{
const Step &step = m_Steps[step_idx];
for (sMultirobotSolution::Moves_list::const_iterator move = step.m_Moves.begin(); move != step.m_Moves.end(); ++move)
{
if (!arrangement.verify_Move(move->m_robot_id, move->m_dest_vrtx_id))
{
return false;
}
}
return true;
}
bool sMultirobotSolution::check_Step(const sRobotArrangement &arrangement,
int step_idx) const
{
const Step &step = m_Steps[step_idx];
for (sMultirobotSolution::Moves_list::const_iterator move = step.m_Moves.begin(); move != step.m_Moves.end(); ++move)
{
if (!arrangement.check_Move(move->m_robot_id, move->m_dest_vrtx_id))
{
return false;
}
}
return true;
}
void sMultirobotSolution::filter_Solution(const sRobotArrangement &initial_arrangement,
const sRobotGoal &goal_arrangement,
sMultirobotSolution &filter_solution) const
{
sRobotArrangement robot_arrangement = initial_arrangement;
for (sMultirobotSolution::Steps_vector::const_iterator step = m_Steps.begin(); step != m_Steps.end(); ++step)
{
for (sMultirobotSolution::Moves_list::const_iterator move = step->m_Moves.begin(); move != step->m_Moves.end(); ++move)
{
robot_arrangement.move_Robot(move->m_robot_id, move->m_dest_vrtx_id);
filter_solution.add_Move(step->m_time, *move);
if (goal_arrangement.is_Satisfied(robot_arrangement))
{
break;
}
}
}
}
int sMultirobotSolution::calc_CriticalTimes(void)
{
int max_crt_time = 0;
for (sMultirobotSolution::Steps_vector::iterator step = m_Steps.begin(); step != m_Steps.end(); ++step)
{
for (sMultirobotSolution::Moves_list::iterator move = step->m_Moves.begin(); move != step->m_Moves.end(); ++move)
{
move->m_crt_time = 0;
for (sMultirobotSolution::Steps_vector::const_iterator prev_step = m_Steps.begin(); prev_step != step; ++prev_step)
{
for (sMultirobotSolution::Moves_list::const_iterator prev_move = prev_step->m_Moves.begin(); prev_move != prev_step->m_Moves.end(); ++prev_move)
{
if (move->is_Dependent(*prev_move))
{
if (prev_move->m_crt_time >= move->m_crt_time)
{
move->m_crt_time = prev_move->m_crt_time + 1;
max_crt_time = sMAX(max_crt_time, move->m_crt_time);
}
}
}
}
for (sMultirobotSolution::Moves_list::const_iterator prev_move = step->m_Moves.begin(); prev_move != move; ++prev_move)
{
if (move->is_Dependent(*prev_move))
{
if (prev_move->m_crt_time >= move->m_crt_time)
{
move->m_crt_time = prev_move->m_crt_time + 1;
max_crt_time = sMAX(max_crt_time, move->m_crt_time);
}
}
}
}
}
return max_crt_time;
}
void sMultirobotSolution::criticalize_Solution(sMultirobotSolution &critical_solution)
{
calc_CriticalTimes();
for (sMultirobotSolution::Steps_vector::iterator step = m_Steps.begin(); step != m_Steps.end(); ++step)
{
for (sMultirobotSolution::Moves_list::iterator move = step->m_Moves.begin(); move != step->m_Moves.end(); ++move)
{
critical_solution.add_Move(move->m_crt_time, *move);
}
}
}
/*----------------------------------------------------------------------------*/
void sMultirobotSolution::to_Screen(const sString &indent) const
{
to_Stream(stdout, indent);
}
void sMultirobotSolution::to_Stream(FILE *fw, const sString &indent) const
{
fprintf(fw, "%sMulirobot solution: (|moves| = %d, paralellism = %.3f) [\n", indent.c_str(), m_Moves_cnt, (double)m_Moves_cnt / m_Steps.size());
int N_Steps = m_Steps.size();
for (int i = 0; i < N_Steps; ++i)
{
const Step &step = m_Steps[i];
fprintf(fw, "%s%sStep %d: ", indent.c_str(), sRELOC_INDENT.c_str(), step.m_time);
for (Moves_list::const_iterator move = step.m_Moves.begin(); move != step.m_Moves.end(); ++move)
{
fprintf(fw, "%d#%d->%d ", move->m_robot_id, move->m_src_vrtx_id, move->m_dest_vrtx_id);
}
fprintf(fw, "\n");
}
fprintf(fw, "%s]\n", indent.c_str());
}
void sMultirobotSolution::to_Screen(const sUndirectedGraph &grid, const sString &indent) const
{
to_Stream(grid, stdout, indent);
}
void sMultirobotSolution::to_Stream(const sUndirectedGraph &grid, FILE *fw, const sString &indent) const
{
fprintf(fw, "%sMulirobot solution: (|moves| = %d, paralellism = %.3f) [\n", indent.c_str(), m_Moves_cnt, (double)m_Moves_cnt / m_Steps.size());
int N_Steps = m_Steps.size();
for (int i = 0; i < N_Steps; ++i)
{
const Step &step = m_Steps[i];
fprintf(fw, "%s%sStep %d: ", indent.c_str(), sRELOC_INDENT.c_str(), step.m_time);
for (Moves_list::const_iterator move = step.m_Moves.begin(); move != step.m_Moves.end(); ++move)
{
int src_row = grid.calc_GridRow(move->m_src_vrtx_id);
int src_column = grid.calc_GridColumn(move->m_src_vrtx_id);
int dest_row = grid.calc_GridRow(move->m_dest_vrtx_id);
int dest_column = grid.calc_GridColumn(move->m_dest_vrtx_id);
fprintf(fw, "%d#%d[%d,%d] --> %d[%d,%d] ", move->m_robot_id, move->m_src_vrtx_id, src_row, src_column, move->m_dest_vrtx_id, dest_row, dest_column);
}
fprintf(fw, "\n");
}
fprintf(fw, "%s]\n", indent.c_str());
}
sResult sMultirobotSolution::to_File(const sUndirectedGraph &grid, const sString &filename, const sString &indent) const
{
FILE *fw;
if ((fw = fopen(filename.c_str(), "w")) == NULL)
{
return sMULTIROBOT_OPEN_ERROR;
}
to_Stream(grid, fw, indent);
fclose(fw);
return sRESULT_SUCCESS;
}
sResult sMultirobotSolution::to_File_multirobot(const sString &filename, const sString &indent) const
{
FILE *fw;
if ((fw = fopen(filename.c_str(), "w")) == NULL)
{
return sMULTIROBOT_SOLUTION_OPEN_ERROR;
}
to_Stream_multirobot(fw, indent);
fclose(fw);
return sRESULT_SUCCESS;
}
void sMultirobotSolution::to_Stream_multirobot(FILE *fw, const sString &indent) const
{
fprintf(fw, "%sFine solution\n", indent.c_str());
fprintf(fw, "%sLength:%d\n", indent.c_str(), get_MoveCount());
int N_Steps = m_Steps.size();
for (int i = 0; i < N_Steps; ++i)
{
const Step &step = m_Steps[i];
for (Moves_list::const_iterator move = step.m_Moves.begin(); move != step.m_Moves.end(); ++move)
{
fprintf(fw, "%s%d # %d ---> %d (%d)\n", indent.c_str(), move->m_robot_id, move->m_src_vrtx_id, move->m_dest_vrtx_id, i);
}
}
}
sResult sMultirobotSolution::to_File_graphrec(const sString &filename, const sMultirobotInstance &instance, const sString &indent) const
{
FILE *fw;
if ((fw = fopen(filename.c_str(), "w")) == NULL)
{
return sMULTIROBOT_SOLUTION_OPEN_ERROR;
}
to_Stream_graphrec(fw, instance, indent);
fclose(fw);
return sRESULT_SUCCESS;
}
void sMultirobotSolution::to_Stream_graphrec(FILE *fw, const sMultirobotInstance &instance, const sString &indent) const
{
fprintf(fw, "id:-\n");
instance.to_Stream_multirobot(fw, indent);
fprintf(fw, "Solution\n");
int N_Steps = m_Steps.size();
for (int i = 0; i < N_Steps; ++i)
{
const Step &step = m_Steps[i];
for (Moves_list::const_iterator move = step.m_Moves.begin(); move != step.m_Moves.end(); ++move)
{
fprintf(fw, "%d ---> %d (%d)\n", move->m_src_vrtx_id, move->m_dest_vrtx_id, i);
}
}
fprintf(fw, "%sLength:%d\n", indent.c_str(), get_MoveCount());
}
sResult sMultirobotSolution::from_File_multirobot(const sString &filename)
{
sResult result;
FILE *fr;
if ((fr = fopen(filename.c_str(), "r")) == NULL)
{
return sMULTIROBOT_SOLUTION_OPEN_ERROR;
}
result = from_Stream_multirobot(fr);
if (sFAILED(result))
{
fclose(fr);
return result;
}
fclose(fr);
return sRESULT_SUCCESS;
}
sResult sMultirobotSolution::from_Stream_multirobot(FILE *fr)
{
int N_Moves;
int c = fgetc(fr);
while (c != 'F')
{
if (c != '\n')
{
while(fgetc(fr) != '\n');
}
c = fgetc(fr);
}
fscanf(fr, "ine solution\nLength:%d\n", &N_Moves);
#ifdef sDEBUG
printf("Length:%d\n", N_Moves);
#endif
for (int i = 0; i < N_Moves; ++i)
{
int robot_id, src_vertex_id, dest_vertex_id, step;
fscanf(fr, "%d # %d ---> %d (%d)\n", &robot_id, &src_vertex_id, &dest_vertex_id, &step);
#ifdef sDEBUG
printf("%d # %d ---> %d (%d)\n", robot_id, src_vertex_id, dest_vertex_id, step);
#endif
add_Move(step, Move(robot_id, src_vertex_id, dest_vertex_id));
}
return sRESULT_SUCCESS;
}
/*----------------------------------------------------------------------------*/
// sMultirobotFlowModel
sMultirobotFlowModel::sMultirobotFlowModel(const sMultirobotInstance &instance)
: m_instance(instance)
{
// nothing
}
void sMultirobotFlowModel::build_Network(int N_steps)
{
for (int step = 0; step < N_steps; ++step)
{
sString step_label = sInt_32_to_String(step);
for (sUndirectedGraph::Vertices_vector::const_iterator vertex = m_instance.m_environment.m_Vertices.begin(); vertex != m_instance.m_environment.m_Vertices.end(); ++vertex)
{
sString vertex_label = sInt_32_to_String(vertex->m_id);
m_flow_network.add_Vertex(vertex_label + "_" + step_label);
}
}
for (int step = 0; step < N_steps - 1; ++step)
{
sString step_label = sInt_32_to_String(step);
sString next_step_label = sInt_32_to_String(step + 1);
for (sUndirectedGraph::Vertices_vector::const_iterator vertex = m_instance.m_environment.m_Vertices.begin(); vertex != m_instance.m_environment.m_Vertices.end(); ++vertex)
{
sString vertex_label = sInt_32_to_String(vertex->m_id);
for (sVertex::Neighbors_list::const_iterator neighbor = vertex->m_Neighbors.begin(); neighbor != vertex->m_Neighbors.end(); ++neighbor)
{
sString next_vertex_label = sInt_32_to_String((*neighbor)->m_target->m_id);
m_flow_network.add_Arc(vertex_label + "_" + step_label, next_vertex_label + "_" + next_step_label, 1, 0);
}
m_flow_network.add_Arc(vertex_label + "_" + step_label, vertex_label + "_" + next_step_label, 1, 0);
}
}
m_network_source = m_flow_network.add_Vertex("source");
m_network_sink = m_flow_network.add_Vertex("sink");
sString first_step_label = sInt_32_to_String(0);
sString last_step_label = sInt_32_to_String(N_steps - 1);
int N_robots = m_instance.m_initial_arrangement.get_RobotCount();
sASSERT(N_robots == m_instance.m_goal_arrangement.get_RobotCount());
for (int r = 1; r <= N_robots; ++r)
{
sString init_vertex_label = sInt_32_to_String(m_instance.m_initial_arrangement.get_RobotLocation(r));
sString goal_vertex_label = sInt_32_to_String(m_instance.m_goal_arrangement.get_RobotLocation(r));
m_flow_network.add_Arc("source", init_vertex_label + "_" + first_step_label, 1, 0);
m_flow_network.add_Arc(goal_vertex_label + "_" + last_step_label, "sink", 1, 0);
}
}
void sMultirobotFlowModel::build_Network(const Robots_vector &robot_selection, int N_steps)
{
for (int step = 0; step < N_steps; ++step)
{
sString step_label = sInt_32_to_String(step);
for (sUndirectedGraph::Vertices_vector::const_iterator vertex = m_instance.m_environment.m_Vertices.begin(); vertex != m_instance.m_environment.m_Vertices.end(); ++vertex)
{
sString vertex_label = sInt_32_to_String(vertex->m_id);
m_flow_network.add_Vertex(vertex_label + "_" + step_label);
}
}
for (int step = 0; step < N_steps - 1; ++step)
{
sString step_label = sInt_32_to_String(step);
sString next_step_label = sInt_32_to_String(step + 1);
for (sUndirectedGraph::Vertices_vector::const_iterator vertex = m_instance.m_environment.m_Vertices.begin(); vertex != m_instance.m_environment.m_Vertices.end(); ++vertex)
{
sString vertex_label = sInt_32_to_String(vertex->m_id);
for (sVertex::Neighbors_list::const_iterator neighbor = vertex->m_Neighbors.begin(); neighbor != vertex->m_Neighbors.end(); ++neighbor)
{
sString next_vertex_label = sInt_32_to_String((*neighbor)->m_target->m_id);
m_flow_network.add_Arc(vertex_label + "_" + step_label, next_vertex_label + "_" + next_step_label, 1, 0);
}
m_flow_network.add_Arc(vertex_label + "_" + step_label, vertex_label + "_" + next_step_label, 1, 0);
}
}
m_network_source = m_flow_network.add_Vertex("source");
m_network_sink = m_flow_network.add_Vertex("sink");
sString first_step_label = sInt_32_to_String(0);
sString last_step_label = sInt_32_to_String(N_steps - 1);
#ifdef sDEBUG
{
int N_robots = m_instance.m_initial_arrangement.get_RobotCount();
sASSERT(N_robots == m_instance.m_goal_arrangement.get_RobotCount());
}
#endif
for (Robots_vector::const_iterator r = robot_selection.begin(); r != robot_selection.end(); ++r)
{
sString init_vertex_label = sInt_32_to_String(m_instance.m_initial_arrangement.get_RobotLocation(*r));
sString goal_vertex_label = sInt_32_to_String(m_instance.m_goal_arrangement.get_RobotLocation(*r));
m_flow_network.add_Arc("source", init_vertex_label + "_" + first_step_label, 1, 0);
m_flow_network.add_Arc(goal_vertex_label + "_" + last_step_label, "sink", 1, 0);
}
}
void sMultirobotFlowModel::destroy_Network(void)
{
m_flow_network.clean_Graph();
}
int sMultirobotFlowModel::compute_Relocation(void)
{
sGoldberg goldberg;
return goldberg.compute_Flow(&m_flow_network, &m_network_source->second, &m_network_sink->second);
}
int sMultirobotFlowModel::compute_Distance(void)
{
int N_robots = m_instance.m_initial_arrangement.get_RobotCount();
sASSERT(N_robots == m_instance.m_goal_arrangement.get_RobotCount());
int N_steps = 1;
while (true)
{
destroy_Network();
build_Network(N_steps);
int relocation = compute_Relocation();
if (relocation == N_robots)
{
return N_steps;
}
++N_steps;
}
return -1;
}
int sMultirobotFlowModel::compute_Distance(const Robots_vector &robot_selection)
{
int N_robots = robot_selection.size();
int N_steps = 1;
while (true)
{
destroy_Network();
build_Network(robot_selection, N_steps);
int relocation = compute_Relocation();
if (relocation == N_robots)
{
return N_steps;
}
++N_steps;
}
return -1;
}
int sMultirobotFlowModel::compute_Distance(int *N_tries)
{
int N_robots = m_instance.m_initial_arrangement.get_RobotCount();
sASSERT(N_robots == m_instance.m_goal_arrangement.get_RobotCount());
int max_N_steps = 1;
for (int N_r = 1; N_r <= N_robots; ++N_r)
{
for (int t = 0; t < N_tries[N_r-1]; ++t)
{
Robots_vector robot_selection;
for (int r = 1; r <= N_robots; ++r)
{
robot_selection.push_back(r);
}
int selection_size = N_robots;
while (selection_size > N_r)
{
int rnd_r = rand() % selection_size;
robot_selection[rnd_r] = robot_selection[selection_size - 1];
--selection_size;
}
robot_selection.resize(N_r);
#ifdef sVERBOSE
for (Robots_vector::const_iterator sr = robot_selection.begin(); sr != robot_selection.end(); ++sr)
{
printf("%d,", *sr);
}
printf("\n");
#endif
int N_steps = 1;
while (true)
{
destroy_Network();
build_Network(robot_selection, N_steps);
int relocation = compute_Relocation();
if (relocation == N_r)
{
break;
}
++N_steps;
}
if (N_steps > max_N_steps)
{
max_N_steps = N_steps;
}
printf("----> %d\n", N_steps);
}
}
return max_N_steps;
}
/*----------------------------------------------------------------------------*/
} // namespace sReloc
| [
"pavel.surynek@seznam.cz"
] | pavel.surynek@seznam.cz |
24d63a9f2b65ee4dc4163a0b8496d948870dd0fc | e92d75b7053ce957859eff8eed11122f2709a1aa | /initial_graph.cpp | 135457e5a11f4e8604b484b31695ae3704a2ba67 | [] | no_license | buptxwli/graph | 07163a7e157e98a88aed478ced0fcc9f4b59a0e3 | 2518b9f69ee1c63cd3ef31bb00c994ca2560da47 | refs/heads/master | 2021-01-13T03:10:00.976291 | 2017-03-07T12:59:58 | 2017-03-07T12:59:58 | 77,432,361 | 0 | 1 | null | 2017-01-11T12:04:12 | 2016-12-27T06:40:26 | C++ | UTF-8 | C++ | false | false | 6,577 | cpp | #include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <queue>
#include <cstdio>
using namespace std;
const int maxnum=100;
const int maxrow=100;
const int maxline=50;
const int maxtime=maxnum*maxrow*maxline;
bool graph_mark[1000];
bool mark_point[maxrow][maxline];
int step_total[maxnum];
int row,line,num; // whole situation
char in[100][100]; //graph
int graph_pre[1000];
int graph_dis[1000];
int graph_size;
struct P
{
int x,y;
bool operator ==(const P &A) const
{
return (x==A.x && y==A.y);
}
bool operator !=(const P &A) const
{
return (x!=A.x || y!=A.y);
}
};
P point[1000]; //graph
P startpoint[maxnum]; //whole situation
P endpoint[maxnum]; //whole situation
P shortest_path[maxnum][maxtime]; //whole situation
struct E //graph only
{
int nextx,nexty,cost;
E(int _nextx=0,int _nexty=0,int _cost=0):nextx(_nextx),nexty(_nexty),cost(_cost){}
};
vector <E> edge[1000]; //graph
struct node //graph only
{
int name,tmpdis;
int turn;
node(int _name=0,int _tmpdis=0,int _turn=0):name(_name),tmpdis(_tmpdis),turn(_turn){}
bool operator <(const node &r)const
{
if(tmpdis!=r.tmpdis)
return tmpdis>r.tmpdis;
else
return turn>r.turn;
}
};
priority_queue<node>que; //graph
void graph_input()
{
graph_size=0;
for(int i=0;i<row;i++)
{
getchar();
for(int j=0;j<line;j++)
{
scanf("%c",&in[i][j]);
point[graph_size].x=i;
point[graph_size].y=j;
graph_size++;
}
}
return;
}
void graph_build()
{
for(int i=0;i<graph_size;i++)
edge[i].clear();
for(int i=0;i<graph_size;i++)
{
if(point[i].x==0) //first line only down
{
edge[i].push_back(E(point[i].x+1,point[i].y,1));
}
if(point[i].x==row-1) //last line only up
{
edge[i].push_back(E(point[i].x-1,point[i].y,1));
}
if (in[point[i].x][point[i].y]=='>') //turn left
{
edge[i].push_back(E(point[i].x,point[i].y+1,1));
}
if(in[point[i].x][point[i].y]=='<') //turn right
{
edge[i].push_back(E(point[i].x,point[i].y-1,1));
}
if(point[i].x==1)
{
edge[i].push_back(E(point[i].x-1,point[i].y,1));
}
if(point[i].x==row-2)
{
edge[i].push_back(E(point[i].x+1,point[i].y,1));
}
if(in[point[i].x][point[i].y]=='X')
{
if(point[i].x!=line-1 && in[point[i].x][point[i].y+1]=='>')
{
edge[i].push_back(E(point[i].x,point[i].y+1,1));
}
if(point[i].x!=0 && in[point[i].x][point[i].y-1]=='<')
{
edge[i].push_back(E(point[i].x,point[i].y-1,1));
}
if(in[point[i].x+1][point[i].y]=='X')
{
edge[i].push_back(E(point[i].x+1,point[i].y,1));
}
if (in[point[i].x-1][point[i].y]=='X')
{
edge[i].push_back(E(point[i].x-1,point[i].y,1));
}
}
if(in[point[i].x][point[i].y]=='Y')
{
if(point[i].x!=line-1 && in[point[i].x][point[i].y+1]=='>')
{
edge[i].push_back(E(point[i].x,point[i].y+1,1));
}
if(point[i].x!=0 && in[point[i].x][point[i].y-1]=='<')
{
edge[i].push_back(E(point[i].x,point[i].y-1,1));
}
if(in[point[i].x+1][point[i].y]=='Y')
{
edge[i].push_back(E(point[i].x+1,point[i].y,1));
}
if (in[point[i].x-1][point[i].y]=='Y')
{
edge[i].push_back(E(point[i].x-1,point[i].y,1));
}
}
}
}
void graph_inital()
{
memset(graph_mark,false,sizeof(graph_mark));
memset(graph_pre,-1,sizeof(graph_pre));
for(int i=0;i<graph_size;i++) graph_dis[i]=123456789;
while(!que.empty()) que.pop();
}
void find_shortest(int i)
{
graph_dis[startpoint[i].x*line+startpoint[i].y]=0;
que.push(node(startpoint[i].x*line+startpoint[i].y,0,0));
node tmp;
while(!que.empty())
{
tmp=que.top();
que.pop();
int u=tmp.name;
if(graph_mark[u]) continue;
graph_mark[u]=true;
for(int j=0;j<edge[u].size();j++)
{
int m=edge[u][j].nextx;
int n=edge[u][j].nexty;
int c=edge[u][j].cost;
if(!graph_mark[m*line+n]&&graph_dis[m*line+n]>graph_dis[u]+c)
{
graph_dis[m*line+n]=graph_dis[u]+c;
graph_pre[m*line+n]=u;
que.push(node(m*line+n,graph_dis[m*line+n]));
}
}
}
if(graph_dis[endpoint[i].x*line+endpoint[i].y]==123456789)
step_total[i]=-1;
else
{
step_total[i]=graph_dis[endpoint[i].x*line+endpoint[i].y]+1;
int tmppre=graph_pre[endpoint[i].x*line+endpoint[i].y];
shortest_path[i][step_total[i]-1]=endpoint[i];
int j=1;
while(tmppre>=0)
{
int prex=tmppre/line;
int prey=tmppre%line;
shortest_path[i][step_total[i]-1-j].x=prex;
shortest_path[i][step_total[i]-1-j].y=prey;
tmppre=graph_pre[tmppre];
j++;
}
}
return;
}
void debug_graph(int x)
{
if(step_total[x]==-1)
{
printf("can't arrive");
return;
}
printf("step=%d:\n",step_total[x]-1);
for(int i=0;i<step_total[x]-1;i++)
{
printf("(%d,%d)->",shortest_path[x][i].x,shortest_path[x][i].y);
}
printf("(%d,%d)\n",shortest_path[x][step_total[x]-1].x,shortest_path[x][step_total[x]-1].y);
return;
}
void debug(int x)
{
char tmp[maxrow][maxline];
for(int i=0;i<row;i++)
{
for(int j=0;j<line;j++)
tmp[i][j]=in[i][j];
}
for(int i=0;i<=step_total[x]-1;i++)
tmp[shortest_path[x][i].x][shortest_path[x][i].y]='0'+x;
for(int i=0;i<row;i++)
{
for(int j=0;j<line;j++)
printf("%c",tmp[i][j]);
printf("\n");
}
return ;
}
int main()
{
freopen("input.txt","r",stdin);
while (scanf("%d%d",&row,&line)!=EOF)
{
graph_input();
graph_build();
scanf("%d",&num);
for(int i=0;i<num;i++)
{
graph_inital();
scanf("%d%d%d%d",&startpoint[i].x,&startpoint[i].y,&endpoint[i].x,&endpoint[i].y);
printf("car[%d]\n",i);
find_shortest(i);
debug_graph(i);
debug(i);
}
}
return 0;
}
| [
"buptlorraine@163.com"
] | buptlorraine@163.com |
a074f7262879f87879b5a9c1b403762f8464c564 | 0e7c1dc20191ac6a0ed00f219fc8ebb609654694 | /DeathEngine/GUI/Button.h | f2c5ac7a71912da923fe2af396cafce29f3f9e2f | [] | no_license | seblef/DeathChase | 99a061773b6541e20ab949451beb575e86d0ea7e | bb24f9adce681f3833c4c6a415c6b3beecd098b1 | refs/heads/master | 2021-08-24T11:57:19.064199 | 2017-12-09T15:57:31 | 2017-12-09T15:57:31 | 113,684,828 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,040 | h |
#ifndef _BUTTON_H_
#define _BUTTON_H_
#include "IEnvironment.h"
#include "IButton.h"
#include "../Dev/MemDebugger.h"
namespace GUI
{
class Button : public IButton
{
public:
Button(IEnvironment *pEnvironment, IElement *pParent, IEventReceiver *pUser,
uint32 dwID, Core::Rect rect, bool bNoClip=false);
virtual ~Button();
virtual void Reset(IEnvironment *pEnvironment, IElement *pParent,
IEventReceiver *pUser, uint32 dwID, Core::Rect rect);
virtual void Clear();
virtual bool OnEvent(const Event& _Event);
virtual void Draw();
virtual void SetOverrideFont(IFont *pFont=0);
virtual void SetImage(Core::HTexture hTex);
virtual void SetImage(Core::HTexture hTex, const Core::Rect& pos);
virtual void SetPressedImage(Core::HTexture hTex);
virtual void SetPressedImage(Core::HTexture hTex, const Core::Rect& pos);
virtual void SetSpriteBank(ISpriteBank *pBank);
virtual void SetSprite(BUTTONSTATE _State, int iIndex,
Core::Color32 cColor=Core::Color32(255,255,255,255), bool bLoop=false);
virtual void SetIsPushButton(bool bPush);
virtual bool IsPushButton() const;
virtual void SetPressed(bool bPressed);
virtual bool IsPressed() const;
virtual void SetUseAlphaChannel(bool bUseAlpha);
virtual bool IsAlphaChannelUsed() const;
virtual void SetDrawBorder(bool bBorder);
virtual bool IsDrawingBorder() const;
MEMDEBUG_IMPL
MEMDEBUG_CLASSNAME("Button")
MEMDEBUG_CLASSSIZE(sizeof(Button))
private:
struct ButtonSprite
{
int iIndex;
Core::Color32 cColor;
bool bLoop;
};
bool m_bPressed;
bool m_bIsPushButton;
bool m_bUseAlphaChannel;
bool m_bBorder;
uint32 m_dwMouseOverTime;
uint32 m_dwFocusTime;
uint32 m_dwClickTime;
ISpriteBank* m_pSpriteBank;
IFont* m_pOverrideFont;
ButtonSprite m_ButtonSprites[BS_COUNT];
Core::HTexture m_hTexture, m_hPressedTexture;
Core::Rect m_ImageRect,m_PressedImageRect;
};
}
#endif | [
"sebast.lefort@gmail.com"
] | sebast.lefort@gmail.com |
46d43beb4e4c95265c26c3c46fd073ad43d3ce1a | f1872a2fb82ceb88814ae73d8453b3b2921a2183 | /box_inspector/src/box_inspector.cpp | aa8c0001eb2adedf7e7e6c317774ed8f1979d4d9 | [] | no_license | axd481/EECS376_PS6 | 718747ef8e9fef5469810fbecd9a228296dd7c84 | 6ccdf936fa1eb40671025ce2ad4a56ae4c05561d | refs/heads/master | 2020-03-11T21:50:23.661658 | 2018-04-19T21:51:02 | 2018-04-19T21:51:02 | 130,276,104 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,287 | cpp | //box_inspector.cpp implementation of class/library
#include <box_inspector/box_inspector.h>
//#include "box_inspector_fncs.cpp" //more code, outside this file
#include "box_inspector_fncs.cpp" //more code, outside this file
BoxInspector::BoxInspector(ros::NodeHandle* nodehandle) : nh_(*nodehandle) { //constructor
//set up camera subscriber:
box_camera_subscriber_ = nh_.subscribe("/ariac/box_camera_1", 1, &BoxInspector::box_camera_callback, this);
got_new_snapshot_=false; //trigger to get new snapshots
}
//to request a new snapshot, set need_new_snapshot_ = true, and make sure to give a ros::spinOnce()
void BoxInspector::box_camera_callback(const osrf_gear::LogicalCameraImage::ConstPtr & image_msg) {
if (!got_new_snapshot_) {
box_inspector_image_ = *image_msg; //copy the current message to a member data var, i.e. freeze the snapshot
got_new_snapshot_ = true;
ROS_INFO_STREAM("received box-camera image of: "<<box_inspector_image_<<endl);
int n_models = box_inspector_image_.models.size();
ROS_INFO("%d models seen ",n_models);
}
}
//method to request a new snapshot from logical camera; blocks until snapshot is ready,
// then result will be in box_inspector_image_
void BoxInspector::get_new_snapshot_from_box_cam() {
got_new_snapshot_= false;
ROS_INFO("waiting for snapshot from camera");
while (!got_new_snapshot_) {
ros::spinOnce();
ros::Duration(0.1).sleep();
}
ROS_INFO("got new snapshot");
}
//here is the main fnc; provide a list of models, expressed as desired parts w/ poses w/rt box;
//get a box-camera logical image and parse it
//populate the vectors as follows:
// satisfied_models_wrt_world: vector of models that match shipment specs, including precision location in box
// misplaced_models_wrt_world: vector of models that belong in the shipment, but are imprecisely located in box
// missing_models_wrt_world: vector of models that are requested in the shipment, but not yet present in the box
// orphan_models_wrt_world: vector of models that are seen in the box, but DO NOT belong in the box
void BoxInspector::update_inspection(vector<osrf_gear::Model> desired_models_wrt_world,
vector<osrf_gear::Model> &satisfied_models_wrt_world,
vector<osrf_gear::Model> &misplaced_models_actual_coords_wrt_world,
vector<osrf_gear::Model> &misplaced_models_desired_coords_wrt_world,
vector<osrf_gear::Model> &missing_models_wrt_world,
vector<osrf_gear::Model> &orphan_models_wrt_world) {
//WRITE ME!!!
ROS_WARN("NEED TO WRITE update_inspection() ");
got_new_snapshot_=false;
while(!got_new_snapshot_) {
ros::spinOnce(); // refresh camera image
ros::Duration(0.5).sleep();
ROS_INFO("waiting for logical camera image");
}
ROS_INFO("got new image");
int num_parts_seen = box_inspector_image_.models.size();
ROS_INFO("update_inspection: box camera saw %d objects",num_parts_seen);
orphan_models_wrt_world.clear(); //this will be empty, unless something very odd happens
satisfied_models_wrt_world.clear(); //shipment will be complete when this matches parts/poses specified in shipment
misplaced_models_actual_coords_wrt_world.clear();
misplaced_models_desired_coords_wrt_world.clear();
missing_models_wrt_world.clear();
//for(int i = 0; i < num_parts_seen; i++){
//go through the parts and add all of the good ones to the list
//if (box_inspector_image_models[i]
//Above if will check if the parts on the list are within the tolerance
//if they are then add them to a list of good parts using a for loop with number of good parts
////then in the same for loop check if the parts are missing and then add those to a list
//check again for extra parts
//pushback these lists to update inspection.
//
//}
//THIS IS WRONG...but an example of how to get models from image and sort into category vectors
for (int i=0;i<num_parts_seen;i++) {
orphan_models_wrt_world.push_back(box_inspector_image_.models[i]);
}
}
//intent of this function is, get a snapshot from the box-inspection camera;
//parse the image data to see if a shipping box is present
//if not, return false
//if seen, transform box pose to box pose w/rt world frame,
// copy data to reference arg box_pose_wrt_world
// and return "true"
bool BoxInspector::get_box_pose_wrt_world(geometry_msgs::PoseStamped &box_pose_wrt_world) {
geometry_msgs::Pose cam_pose, box_pose; //cam_pose is w/rt world, but box_pose is w/rt camera
//get a new snapshot of the box-inspection camera:
get_new_snapshot_from_box_cam();
//ROS_INFO("got box-inspection camera snapshot");
//look for box in model list:
int num_models = box_inspector_image_.models.size(); //how many models did the camera see?
if (num_models == 0) return false;
string box_name("shipping_box"); //does a model match this name?
osrf_gear::Model model;
cam_pose = box_inspector_image_.pose;
ROS_INFO("box cam sees %d models", num_models);
for (int imodel = 0; imodel < num_models; imodel++) {
model = box_inspector_image_.models[imodel];
string model_name(model.type);
if (model_name == box_name) {
box_pose = model.pose;
ROS_INFO_STREAM("get_box_pose_wrt_world(): found box at pose " << box_pose << endl);
//ROS_WARN("USE THIS INFO TO COMPUTE BOX POSE WRT WORLD AND POPULATE box_pose_wrt_world");
box_pose_wrt_world = compute_stPose(cam_pose, box_pose);
ROS_INFO_STREAM("box_pose_wrt_world: " << box_pose_wrt_world << endl);
return true;
}
}
//if reach here, did not find shipping_box
ROS_WARN("get_box_pose_wrt_world(): shipping-box not seen!");
return false;
}
//helper function:
//given a camera pose and a part-pose (or box-pose) w/rt camera, compute part pose w/rt world
//xform_utils library should help here
geometry_msgs::PoseStamped BoxInspector::compute_stPose(geometry_msgs::Pose cam_pose, geometry_msgs::Pose part_pose) {
geometry_msgs::PoseStamped stPose_part_wrt_world;
//compute part-pose w/rt world and return as a pose-stamped message object
Eigen::Affine3d cam_wrt_world, part_wrt_cam, part_wrt_world;
cam_wrt_world = xformUtils_.transformPoseToEigenAffine3d(cam_pose);
part_wrt_cam = xformUtils_.transformPoseToEigenAffine3d(part_pose);
part_wrt_world = cam_wrt_world*part_wrt_cam;
geometry_msgs::Pose pose_part_wrt_world = xformUtils_.transformEigenAffine3dToPose(part_wrt_world);
geometry_msgs::PoseStamped part_pose_stamped;
part_pose_stamped.header.stamp = ros::Time::now();
part_pose_stamped.header.frame_id = "world";
part_pose_stamped.pose = pose_part_wrt_world;
return part_pose_stamped;
}
//rosmsg show osrf_gear/LogicalCameraImage:
/*
osrf_gear/Model[] models
string type
geometry_msgs/Pose pose
geometry_msgs/Point position
float64 x
float64 y
float64 z
geometry_msgs/Quaternion orientation
float64 x
float64 y
float64 z
float64 w
geometry_msgs/Pose pose
geometry_msgs/Point position
float64 x
float64 y
float64 z
geometry_msgs/Quaternion orientation
float64 x
float64 y
float64 z
float64 w
*/
| [
"axd481@case.edu"
] | axd481@case.edu |
04d8456391725d85880a9d1b3778e2246ae75f09 | d07b896b228b7ff06732c960bd64793af74446a7 | /headers/Bank.h | 881bae7cde3528b326ddb881667b4f2ff4f80faf | [] | no_license | ChristopherOriolt/Bank | 94e44994b46554ae9d11d0a0744d9533e6371d26 | 5582d8c9185a35f7a87d5bfb0dd4005f8c88cff0 | refs/heads/master | 2020-04-24T07:25:00.626579 | 2019-02-22T02:21:19 | 2019-02-22T02:21:19 | 171,798,593 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,507 | h | /////////////////////////////////////
// Data Structures Project 1
// Author: Christopher Oriolt
// 2/20/2019
/////////////////////////////////
#include "Senior.h"
#include "Adult.h"
#include "Student.h"
#include "Account.h"
#include "CheckingAccount.h"
#include "SavingsAccount.h"
#include <vector>
using namespace std;
#ifndef Bank_H_
#define Bank_H_
class Bank {
private:
vector<Account*> Accounts;
Account* iterator(int a){
for(int i = 0; i < Accounts.size(); i++){
cout << Accounts.at(i) -> getCustomer() -> getCustomerNumber() << " " << a << endl;
if(a == (Accounts.at(i) -> getCustomer() -> getCustomerNumber())){
cout << "intorator got here";
return Accounts.at(i);
}
}
cout << "Account not found" << endl;
return NULL;
}
public:
Bank(){
Customer * person1 = new Senior("Bob", "Address", 71, 8053363, 111);
Customer * person2 = new Senior("Jack", "Address", 83, 1674655, 112);
Customer * person3 = new Student("kyle", "Address", 18, 3607784, 113);
Customer * person4 = new Student("Karen", "Address", 19, 3345589, 114);
Customer * person5 = new Adult("Ashley", "Address", 26, 3209951, 115);
Customer * person6 = new Adult("Mike", "Address", 33, 5506378, 116);
Account* sa1 = new SavingsAccount(person1, 200.10);
Account* ch1 = new CheckingAccount(person2, 100);
Account* sa2 = new SavingsAccount(person3, 1500.50);
Account* ch2 = new CheckingAccount(person4, 550.20);
Account* sa3 = new SavingsAccount(person5, 2000.25);
Account* ch3 = new CheckingAccount(person6, 330);
Accounts.push_back(sa1);
Accounts.push_back(sa2);
Accounts.push_back(sa3);
Accounts.push_back(ch1);
Accounts.push_back(ch2);
Accounts.push_back(ch3);
}
void addAccount(Account*) {
}
void makeDeposit(int a, double amount) {
Account* acc = iterator(a);
acc -> deposit(amount);
}
void makeWithdrawal(int a, double amount) {
Account* acc = iterator(a);
acc -> withdrawal(amount);
}
Account* getAccount(int i) {
return Accounts.at(i);
}
int accountsSize() {
return Accounts.size();
}
void printAccounts() {
for(int i = 0; i< Accounts.size(); i++) {
cout << Accounts.at(i) -> toString() << endl;
}
}
};
#endif | [
"coriolt21@my.whitworth.edu"
] | coriolt21@my.whitworth.edu |
34f137ad7fa87e4d3a3e36141388b31ec2e65cd4 | 50bfeea8da2447419dcb6bb212d2d103d2dcc4fc | /completed/c++/euler15.cpp | 4ebd743635f87a7c1dba15304ea3f838196f024a | [] | no_license | spkane31/projectEuler | 89cb3024f47ec077d06814f70496f38ae1541ab1 | e92f2449099e59cf1943fdbbd1308d7c9ceba9cb | refs/heads/master | 2021-01-01T03:35:35.149634 | 2019-07-17T19:25:57 | 2019-07-17T19:25:57 | 56,004,828 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 696 | cpp | // Sean Kane
// Euler Problem 15
// Started: April 19, 2016
// Finished:
#include <iostream>
#include <cmath>
#include "universalFxns.h"
using namespace std;
int main(){
unsigned long long int grid[21][21] = {0};
grid[0][0] = 1;
for(int a = 1; a < 21; a++){
grid[0][a] = 1;
grid[a][0] = 1;
}
for(int b = 1; b < 21; b++){
for(int c = 1; c < 21; c++){
grid[b][c] += grid[b-1][c] + grid[b][c-1];
}
}
cout << grid[2][1] << endl;
cout << grid[3][2] << endl;
cout << grid[4][4] << endl;
cout << grid[20][20] << endl;
for(int b = 0; b < 21; b++){
for(int c = 0; c < 21; c++){
cout << grid[b][c] << " ";
}
cout << "\n";
}
return 0;
}
| [
"spkane31@gmail.com"
] | spkane31@gmail.com |
51aab5cc68aee15665db20874abfba1f9e2144d1 | ced00d9419e231b7053d3461039273198238deab | /vongxoaytunhapso.cpp | 1eff1b09d18a2cce8d4efada3acecf401a8161f2 | [] | no_license | Minato1803/My_Bullshit_Code | f9b4e951c4c6c76d023c427e83633b36087767c2 | e44dba88cb2c683674d1e9a21626c53e2fe5cb89 | refs/heads/master | 2021-06-18T14:39:12.114194 | 2021-01-20T11:48:44 | 2021-01-20T11:48:44 | 161,520,184 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,128 | cpp | #include <iostream>
using namespace std;
void vongxoay(int a[],int hang,int cot )
{ int b[hang][cot], h=hang,c=cot;
int vth=0, vtc=0, j=0;
while(vth<=(h-1)/2||vth<=2){
for(int i=vtc; i<c; i++){
b[vth][i]=a[j];
j++;//a[0][0] den a[0][6]
} //chay hang phia tren
for(int i=vth+1; i<h; i++){
b[i][c-1]=a[j];
j++;//a[1][6] den a[6][6]
}//chay hang ben phai
for(int i=c-2; i>=vtc; i--){
b[h-1][i]=a[j];
j++;//a[6][5] den a[6][0]
}//chay hang duoi
for(int i=h-2; i>=vth+1; i--){
b[i][vtc]=a[j];
j++;//a[5][0] den a[1][0]
} //chay hang ben trai
vth++; vtc++; h--; c--;}//di vao trong}
cout<<"day xoay oc xuat ra: "<<endl;
for(int i=0; i<hang; i++){
for(int j=0; j<cot; j++){
cout<< b[i][j]<< " ";}
cout << endl;}
}
int main()
{int hang, cot, n;
cout<<"nhap do lon canh cua mang xoay oc: "; cin>>n;
hang=cot=n;
int a[n*n];
cout<<"nhap vao day so: "<<endl;
for(int i=0; i<(n*n);i++){
cin>>a[i];
}
cout<<"day so vua nhap: "<<endl;
for(int i=0; i<(n*n);i++){
cout<<a[i]<<" ";
}
cout<<endl;
vongxoay(a,hang,cot);
return 0;
}
| [
"nguyenduckhai.otaku@gmail.com"
] | nguyenduckhai.otaku@gmail.com |
6ccd6befeacb4f3acf77a7c792a8a004a29146d6 | 4185c1099535893911ff0325dfd41136f03a80f0 | /11抽象工厂模式/AbstractFactory.h | 9be51fefbfd408ed2239202d75f268686a84bcfa | [] | no_license | ruan875417/DesignPattern | ec3076185f7088f279fc3b4ac1db76a365631b34 | cc2a0a9e38ee067f27e89043339eea1d248ba170 | refs/heads/master | 2021-01-23T14:05:23.700334 | 2014-11-30T02:44:15 | 2014-11-30T02:44:15 | 25,769,676 | 2 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,304 | h | #ifndef ABSTTACTFACTORY_H
#define ABSTTACTFACTORY_H
#include<iostream>
using namespace std;
//////////////////////////////////////////
//抽象产品类A,
//定义了具体产品类A统一的接口
class Linux{
public:
virtual void create()=0;
};
//抽象产品类B
//定义了具体产品类B统一的接口
class Windows{
public:
virtual void create()=0;
};
///////////////////////////////////////////
//具体产品
class LinuxMobile:public Linux{
public:
void create();
};
class LinuxPC:public Linux{
public:
void create();
};
class WindowsMobile:public Windows{
public:
void create();
};
class WindowsPC:public Windows{
public:
void create();
};
//////////////////////////////////////////////////
//抽象工厂,它里面应该包含
//所有产品创建的抽象方法
class AbstractFactory{
public:
virtual Linux* createLinux()=0;
virtual Windows* createWindows()=0;
};
//具体工厂,创建具有特定
//实现的产品对象
class MobileFactory:public AbstractFactory{
public:
Linux* createLinux();
Windows* createWindows();
};
class PCFactory:public AbstractFactory{
public:
Linux* createLinux();
Windows* createWindows();
};
#endif
| [
"ruan875417@qq.com"
] | ruan875417@qq.com |
f8af0244c80ad7d3056f4ae29bb799ca955d2c75 | e63c1e59b2d1bfb5c03d7bf9178cf3b8302ce551 | /uri/uri_cpp/paradigmas/p1084.cpp | c6e6ab3ac8569054b1f64b3ec02da8bee90f2104 | [] | no_license | GabrielEstevam/icpc_contest_training | b8d97184ace8a0e13e1c0bf442baa36c853a6837 | 012796c2ceb901cf7aa25d44a93614696a7d9c58 | refs/heads/master | 2020-04-24T06:15:16.826669 | 2019-10-08T23:13:15 | 2019-10-08T23:13:15 | 171,758,893 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,001 | cpp | #include <iostream>
#include <sstream>
#include <string>
#include <stdlib.h>
#include <stdio.h>
#include <vector>
using namespace std;
int main() {
int n, d, i, j;
unsigned k;
string entry;
vector <char> input;
cin >> n;
cin >> d;
while (n != 0) {
cin >> entry;
for (k = 0; k < entry.size(); k++)
input.push_back(entry[k]);
i = 0;
j = 1;
while (i < d) {
if (input[j] > input[j-1]) {
input.erase(input.begin()+j-1);
i++;
if (j > 1)
j--;
} else if (j+1 < input.size()) {
j++;
} else {
while (i < d) {
input.pop_back();
i++;
}
}
}
for (k = 0; k < input.size(); k++)
cout << input[k];
cout << endl;
input.clear();
cin >> n;
cin >> d;
}
return 0;
}
| [
"gabrielestevam@hotmail.com"
] | gabrielestevam@hotmail.com |
b54ad031f023bce744f0fd657b6284eb763ca6ab | 493ac26ce835200f4844e78d8319156eae5b21f4 | /flow_simulation/ideal_flow/processor3/0.74/nut | e0825757aa6e833589042bf2308f88d9de66cbfd | [] | no_license | mohan-padmanabha/worm_project | 46f65090b06a2659a49b77cbde3844410c978954 | 7a39f9384034e381d5f71191122457a740de3ff0 | refs/heads/master | 2022-12-14T14:41:21.237400 | 2020-08-21T13:33:10 | 2020-08-21T13:33:10 | 289,277,792 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,814 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: v1912 |
| \\ / A nd | Website: www.openfoam.com |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0.74";
object nut;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 2 -1 0 0 0 0];
internalField nonuniform List<scalar>
1431
(
0.00436885
0.0115136
0.000882688
0.000971078
0.00151103
0.00856951
0.00209371
0.0094519
0.00706619
0.00121656
0.00417052
0.0125391
0.0151268
0.00224894
0.00165117
0.00179473
0.00202077
0.001182
0.0020786
0.00162322
0.00554473
0.00532232
0.0056374
0.0150819
0.00592671
0.0116571
0.00370096
0.001619
0.000886314
0.000703739
0.00203205
0.00256479
0.00191608
0.00124844
0.0128361
0.00154725
0.011806
0.000945299
0.000580113
0.00231683
0.00563217
0.00768015
0.0135563
0.00120682
0.00387843
0.00192385
0.0035747
0.0035054
0.0023403
0.00140578
0.0124801
0.00115826
0.0139
0.0127186
0.00893091
0.00754553
0.000908169
0.0134969
0.00176171
0.00100526
0.00146467
0.000492737
0.000464178
0.000426655
0.000274921
0.000365704
0.000787403
0.000611859
0.000819033
0.00124507
0.00368834
0.0011686
0.000495935
0.000856873
0.00149331
0.00097619
0.00058448
0.000318034
0.000620536
0.00106243
0.00171416
0.00063996
0.012206
0.00413101
0.00648227
0.00218356
0.00168483
0.00307392
0.0102397
0.0128208
0.00153619
0.00147229
0.00182716
0.00167436
0.00802708
0.00066294
0.0118996
0.0196143
0.00108324
0.00122128
0.0106624
0.000791096
0.00267256
0.00108501
0.00043025
0.00235136
0.00296682
0.0032715
0.00428437
0.00226335
0.00111574
0.0157095
0.0057247
0.0047311
0.0109922
0.00125387
0.00138731
0.000601012
0.000571021
0.000371424
0.00130676
0.00158213
0.00246229
0.00125348
0.00255918
0.000457696
0.000599294
0.00267111
0.00102761
0.00366694
0.00132986
0.00109131
0.00410977
0.00156694
0.0017573
0.00163355
0.000901627
0.00117757
0.013332
0.000424433
0.000349325
0.00192492
0.00148676
0.000658768
0.00548275
0.00180466
0.000561647
0.0126129
0.00152426
0.000983816
0.00102198
0.00103063
0.00245158
0.000621232
0.00330723
0.00168999
0.00995707
0.0165462
0.0131138
0.00324868
0.0183201
0.0158546
0.00071735
0.00228567
0.00276214
0.00421909
0.00402739
0.00972119
0.00130276
0.0169691
0.0176126
0.0143468
0.00219579
0.0134031
0.0139789
0.00935246
0.00371325
0.00626618
0.0139222
0.0138451
0.000434536
0.000950045
0.00839983
0.0180677
0.00681291
0.00131764
0.0015189
0.016394
0.00239753
0.00734088
0.00225363
0.00242855
0.00255547
0.0036521
0.000566876
0.0180538
0.0201412
0.0126391
0.000947627
0.00154467
0.00971973
0.000916579
0.00418308
0.00234994
0.0156977
0.00237207
0.00231874
0.000729874
0.0146076
0.00223017
0.00198128
0.000569125
0.00293927
0.00237341
0.0120517
0.00152564
0.00273516
0.0129268
0.00910741
0.0040354
0.00313474
0.00789341
0.00260392
0.0014766
0.00343849
0.0162676
0.00441137
0.0183393
0.00278159
0.00304778
0.00613353
0.00202731
0.00237434
0.00248613
0.00267861
0.0189834
0.00291952
0.00263796
0.00216517
0.00624643
0.0038894
0.0136178
0.0153965
0.00253284
0.00244593
0.0041724
0.0026663
0.00391566
0.0033056
0.0012966
0.00261926
0.0139493
0.00284
0.00123822
0.00233261
0.00731403
0.00238181
0.017049
0.0205975
0.0026061
0.00169587
0.0130643
0.0086726
0.00342247
0.00366299
0.00475295
0.0111707
0.00449538
0.00345442
0.000639224
0.00448935
0.00289368
0.00931136
0.00377781
0.017016
0.00203601
0.016036
0.00320194
0.000997528
0.00150406
0.0152733
0.0127769
0.00179538
0.00955137
0.00567022
0.0184356
0.00716898
0.0205274
0.00565916
0.0118059
0.00058243
0.00927781
0.0191459
0.0148182
0.002641
0.00256777
0.00183475
0.00147946
0.00222264
0.00104257
0.0138802
0.000668082
0.00734083
0.0148263
0.00295823
0.0019273
0.0143147
0.00243354
0.00870381
0.0153146
0.0180381
0.00038495
0.000431547
0.00133933
0.00840057
0.0198961
0.0128475
0.00713237
0.00156524
0.0137821
0.0144305
0.0191311
0.000777381
0.0125717
0.0107518
0.00099882
0.000825088
0.00724895
0.0129858
0.00108793
0.00115616
0.00180623
0.00757072
0.00605849
0.00378632
0.0147884
0.0071819
0.0191831
0.00999823
0.00129995
0.000374894
0.0146508
0.0151257
0.00522534
0.00758906
0.00231965
0.00979306
0.0155329
0.0169742
0.0150101
0.00723224
0.00132655
0.012586
0.0157129
0.00163142
0.00610401
0.00773887
0.00184574
0.011995
0.00644602
0.00555572
0.00131486
0.00108879
0.00555494
0.00167952
0.00515377
0.00654551
0.017659
0.00262157
0.0020005
0.00394859
0.00226348
0.0115393
0.0123909
0.00548049
0.0183745
0.0161145
0.00238884
0.0126765
0.0186135
0.0160081
0.00869009
0.00315752
0.0015423
0.0169383
0.00826949
0.0147412
0.00728905
0.0107742
0.0128836
0.0039446
0.0148818
0.0148868
0.00154134
0.0201989
0.0134438
0.0144206
0.0140027
0.00606255
0.00978283
0.0162583
0.00558591
0.020626
0.00735838
0.00534628
0.0139785
0.00795139
0.000532677
0.00468073
0.0142611
0.0171292
0.0120027
0.0145291
0.0146716
0.00730595
0.000871814
0.0148759
0.000521662
0.010215
0.0147662
0.00368718
0.0152092
0.00970724
0.0152834
0.0150017
0.00206533
0.00179812
0.00374704
0.005633
0.0140879
0.0152578
0.0149081
0.0146877
0.0146962
0.0146995
0.0149543
0.015355
0.0145478
0.0155144
0.0148607
0.00176514
0.0135343
0.00170338
0.00148075
0.00110353
0.00131185
0.00157718
0.00160712
0.00444232
0.00461221
0.00416788
0.00163998
0.0021417
0.00117989
0.00207405
0.00216053
0.005608
0.016162
0.00118229
0.00171164
0.00509205
0.00123688
0.0154869
0.0018782
0.00209222
0.00142659
0.00116164
0.0148572
0.00166896
0.0141389
0.0014975
0.00137385
0.00122329
0.00623149
0.0134004
0.0134277
0.00192458
0.00111681
0.00141636
0.00147605
0.00636609
0.00148154
0.0134445
0.00146144
0.0013369
0.0060204
0.00145828
0.00121109
0.00121489
0.00256275
0.0131631
0.00142432
0.00207833
0.00535066
0.00488303
0.00171735
0.00309977
0.0125706
0.00158462
0.00215772
0.00920458
0.00890872
0.00136183
0.00124704
0.0122516
0.0137563
0.00192027
0.00236491
0.00279084
0.00195688
0.00647123
0.00514559
0.00142928
0.00440832
0.00114684
0.00179017
0.00949078
0.0078189
0.00531888
0.0133878
0.00402767
0.00475654
0.00290605
0.00127597
0.0105134
0.00225964
0.0114966
0.00228117
0.00168036
0.000555843
0.0113122
0.00974122
0.0129597
0.00600532
0.0140582
0.00814432
0.00346936
0.00173309
0.0108677
0.00174835
0.0152864
0.00162443
0.00505022
0.00740452
0.00355568
0.00373256
0.0106537
0.00158731
0.0148816
0.0130498
0.0144223
0.00133554
0.00568676
0.014694
0.00147768
0.00367532
0.00268183
0.00935707
0.00163163
0.00641442
0.0132298
0.0119341
0.019102
0.0130785
0.00919126
0.00857766
0.00585988
0.00186363
0.0138653
0.00761885
0.0156592
0.0114671
0.0158871
0.00454969
0.00119547
0.0108455
0.00157141
0.00164917
0.0161161
0.0150607
0.0156031
0.00935433
0.00434578
0.0146822
0.0154135
0.0031309
0.00241846
0.00913169
0.00140933
0.00278781
0.0157331
0.00163107
0.012221
0.0120149
0.00354979
0.0147524
0.00517292
0.0146601
0.0180732
0.0139455
0.00170645
0.0131569
0.0137537
0.0083732
0.0124025
0.0081982
0.00183959
0.0157944
0.00121081
0.00163354
0.00186977
0.0109604
0.0148254
0.0163156
0.0052333
0.0071629
0.00483553
0.00357574
0.0134964
0.0140058
0.013218
0.0127053
0.00109131
0.0146089
0.0135684
0.00723526
0.0138381
0.00229935
0.0138183
0.00523676
0.0148971
0.0116351
0.000315404
0.0161959
0.0156663
0.0135913
0.0103655
0.00434615
0.00436308
0.00891556
0.00562426
0.0200012
0.00356687
0.0140891
0.00164637
0.0132677
0.0113844
0.0109101
0.00422751
0.0145786
0.0137919
0.00992569
0.00148296
0.0145849
0.00201247
0.00931811
0.00661755
0.00783747
0.0113033
0.0150263
0.019704
0.0134449
0.0137023
0.014901
0.0097576
0.00437542
0.00226834
0.00936742
0.0130111
0.0011373
0.015222
0.0115192
0.00170406
0.0151796
0.0137409
0.00333247
0.00172764
0.00632985
0.00503574
0.00576298
0.00800021
0.00615005
0.0145391
0.00169901
0.00063129
0.000837221
0.0158462
0.00482196
0.00198284
0.000886089
0.00529128
0.00278849
0.00494736
0.000774583
0.000553764
0.0140406
0.00143322
0.00438969
0.000469428
0.0151932
0.00119491
0.0141515
0.0155192
0.000665775
0.00170553
0.00178919
0.00138097
0.00131062
0.01198
0.0102521
0.00614583
0.00333603
0.00273188
0.00333912
0.00176772
0.00477235
0.0140773
0.00310779
0.00256643
0.00483029
0.0052463
0.00238845
0.0134601
0.0157113
0.00248185
0.00763292
0.00351846
0.0137233
0.00342085
0.00454867
0.00123547
0.0160127
0.0138958
0.00332889
0.006721
0.00298671
0.00500789
0.00157098
0.00167991
0.00308199
0.000761326
0.00701835
0.00389901
0.00468331
0.0154725
0.00794893
0.00524657
0.00118238
0.00518757
0.00135095
0.0108184
0.00703258
0.00652612
0.00146765
0.0156507
0.00520155
0.00628082
0.00144419
0.00756695
0.000592953
0.0175441
0.00625459
0.00333122
0.00183335
0.00127266
0.00299901
0.00177671
0.00207838
0.0133849
0.00418797
0.0116449
0.00236269
0.00477792
0.00526281
0.00584562
0.0125518
0.000428832
0.00775772
0.0110939
0.00183815
0.0145566
0.000686134
0.0156954
0.0018581
0.00100066
0.0129139
0.0068512
0.014203
0.00230838
0.0135487
0.00608792
0.0015837
0.00245708
0.0122492
0.00241742
0.000422049
0.00298591
0.00233968
0.00241034
0.015637
0.00241687
0.00608703
0.00116046
0.0152352
0.0157702
0.0116868
0.00250492
0.00861875
0.00808917
0.00650348
0.0167974
0.00260011
0.00954015
0.0112402
0.00964419
0.0168902
0.0155314
0.00202832
0.0132696
0.00538932
0.00141223
0.00476635
0.0151182
0.0151011
0.00109897
0.000774043
0.00746751
0.00191878
0.00214709
0.00124845
0.0139022
0.0016914
0.00161006
0.00234244
0.0134208
0.0133147
0.00298677
0.0138906
0.0154446
0.00704872
0.0157203
0.00374533
0.00147364
0.00243644
0.0150854
0.018401
0.00122057
0.017024
0.007497
0.0196191
0.00288746
0.00194862
0.0131912
0.0059965
0.000845249
0.000637612
0.00437157
0.00562661
0.000912176
0.000708791
0.00589414
0.0144449
0.00652317
0.0112086
0.0161215
0.0107542
0.0162257
0.00137551
0.0148058
0.0117014
0.0156387
0.0106602
0.0107622
0.00118282
0.0039648
0.00120001
0.0022964
0.00194089
0.00995299
0.00366831
0.0132831
0.00232253
0.00420482
0.00412678
0.0118901
0.0145177
0.00726758
0.000820963
0.000861132
0.000828553
0.000721447
0.000766158
0.000954453
0.000847375
0.00058306
0.000701336
0.000624876
0.000632568
0.000691278
0.00105043
0.00071217
0.000632623
0.000637201
0.000746295
0.000797328
0.00075123
0.000739062
0.000714938
0.000721001
0.000710422
0.00074525
0.0159415
0.016522
0.00134284
0.0102968
0.00782457
0.00488946
0.00269591
0.00842523
0.00239554
0.00205257
0.00369697
0.00129418
0.00302447
0.016075
0.00538688
0.00166198
0.0179455
0.00481584
0.0163852
0.00394423
0.00200318
0.0176723
0.00125396
0.000753113
0.0123527
0.0138443
0.000609842
0.0041523
0.0107882
0.00176529
0.00475095
0.0155191
0.0058763
0.012744
0.0150471
0.0116126
0.00169592
0.000949368
0.00209119
0.00192569
0.0156588
0.000984421
0.000706492
0.0106542
0.0140855
0.00763216
0.0046873
0.0011244
0.00682818
0.000920003
0.0105246
0.0155474
0.014708
0.00197943
0.0012415
0.00549486
0.00370009
0.000687759
0.00245736
0.000407391
0.0143872
0.00237646
0.00143033
0.00142812
0.00360432
0.00124539
0.0152596
0.001848
0.0151969
0.013029
0.00265928
0.00103724
0.0107401
0.0124742
0.019061
0.00187173
0.00127857
0.00341119
0.00255703
0.00168004
0.015394
0.00239075
0.00678424
0.0130598
0.00072052
0.0126856
0.00179166
0.00230134
0.00554377
0.00350083
0.00244658
0.00284369
0.00366564
0.00381909
0.0151096
0.00115262
0.00957516
0.00320191
0.00171395
0.00465709
0.00249892
0.00196611
0.000821447
0.0140849
0.0131741
0.0143564
0.00106434
0.0146407
0.0141344
0.00813991
0.00696978
0.00190716
0.000788795
0.000673718
0.00269778
0.0125604
0.0146165
0.000705293
0.00737503
0.00200422
0.0181212
0.0121851
0.00299803
0.00338142
0.00276099
0.0139631
0.00178344
0.00676994
0.00980379
0.0143443
0.00037343
0.0041251
0.000307822
0.0089361
0.0101528
0.00210772
0.0121064
0.0115023
0.0146205
0.00903907
0.00556201
0.0126546
0.00309198
0.00372136
0.000920225
0.0036275
0.00116195
0.0145665
0.0118381
0.00909403
0.0147018
0.0115821
0.0177528
0.000635194
0.000853585
0.0163386
0.00196727
0.0112299
0.00222553
0.0135491
0.0156285
0.00192534
0.000727337
0.0017854
0.00167946
0.00164146
0.00221282
0.00196014
0.00187048
0.00178287
0.00189008
0.000222287
0.000218881
0.000189015
0.000195538
0.000143503
0.000180912
0.0156396
0.00318145
0.0133239
0.00254539
0.00871474
0.00069568
0.00114284
0.0147483
0.00156647
0.00242484
0.0147798
0.00131876
0.00289962
0.0055285
0.000439141
0.0015591
0.00191955
0.00956874
0.0150065
0.00312394
0.0114196
0.00316642
0.00190038
0.0143749
0.0155406
0.00303127
0.0016234
0.00339071
0.0132303
0.0030495
0.00959503
0.0072263
0.0013236
0.00961242
0.000678783
0.00258443
0.00271197
0.000627489
0.00489411
0.00115926
0.000786287
0.00431021
0.00156491
0.00140461
0.014687
0.0105202
0.00185153
0.00458126
0.0115327
0.00352185
0.00134296
0.00605481
0.0105398
0.00529975
0.00792878
0.00351615
0.00114549
0.00493379
0.00708667
0.00115135
0.0136176
0.00374362
0.00372651
0.0111443
0.000653481
0.00264048
0.00269413
0.00152777
0.0095307
0.00711058
0.0155897
0.00734147
0.00188729
0.00936024
0.0173266
0.0022834
0.0110573
0.00160479
0.000821331
0.00158492
0.00113348
0.00300048
0.00123028
0.0136502
0.0157515
0.00185686
0.00565446
0.0146138
0.00413967
0.0122463
0.00237017
0.00374514
0.00631723
0.00336322
0.0124576
0.00110842
0.00428389
0.0063722
0.00533343
0.0119793
0.001401
0.000738075
0.00175876
0.00354267
0.00925508
0.0128676
0.00489344
0.0106492
0.00797892
0.00150752
0.0165975
0.00159438
0.00469423
0.00594782
0.00278953
0.00158777
0.0101889
0.00169774
0.00118925
0.00288038
0.0109599
0.00259913
0.0152661
0.0109162
0.00583914
0.00140821
0.00152076
0.000454469
0.0113707
0.00364883
0.0124663
0.00835393
0.0136397
0.015719
0.0147445
0.00187284
0.00164605
0.00210954
0.00158332
0.0107215
0.00184686
0.014378
0.0186738
0.00225558
0.00372801
0.0143509
0.0112124
0.0138477
0.00100502
0.00520684
0.0064367
0.0020636
0.00779548
0.0046589
0.00437367
0.006443
0.00209178
0.0115317
0.00368819
0.00211813
0.0124083
0.00720952
0.00859041
0.00588284
0.00793467
0.0116773
0.012492
0.0144379
0.00446077
0.00114627
0.00372476
0.00393974
0.00187272
0.0143068
0.00829465
0.0139181
0.0144674
0.00108595
0.00155621
0.00228475
0.0139149
0.00200326
0.00184177
0.0107621
0.0141747
0.0113548
0.00227449
0.0147509
0.0122009
0.0156101
0.006458
0.00342308
0.000720368
0.000634795
0.0014983
0.00288739
0.00216581
0.00240042
0.00322574
0.0155349
0.0148769
0.00123411
0.00570674
0.0134694
0.00380216
0.00227867
0.00290478
0.00179672
0.0139859
0.00926657
0.00105397
0.000929003
0.0182151
0.0102601
0.0123317
0.00144146
0.00224449
0.00392795
0.00457011
0.0105137
0.00101536
0.00245967
0.00241346
0.0175415
0.000259614
0.00772094
0.0130981
0.00465095
0.0037295
0.00698003
0.0116556
0.0128376
0.0019158
0.00302483
0.00126747
0.00657701
0.00165722
0.00185261
0.010686
0.00141287
0.00868902
0.00108966
0.0130927
0.000960368
0.000968981
0.000343773
0.0070192
0.00335235
0.00319445
0.00117694
0.0135751
0.0025218
0.0025076
0.00678004
0.0104629
0.00249414
0.00233198
0.00247537
0.00158958
0.00258089
0.0104448
0.0173619
0.00254031
0.0106989
0.00243871
0.00157107
0.00185728
0.00244783
0.00264116
0.00978178
0.00180506
0.00186703
0.00201086
0.00247567
0.0122239
0.0024361
0.000501313
0.00255975
0.00252596
0.00138041
0.00333097
0.00988113
0.00464135
0.00204262
0.00193514
0.00220029
0.00296203
0.000719656
0.000316231
0.0113783
0.00957823
0.00238495
0.00445142
0.00192408
0.00104779
0.000948037
0.00292485
0.00113735
0.00113056
0.00150252
0.0014021
0.00108557
0.0018044
0.0165622
0.00233617
0.00209804
0.0156935
0.00353703
0.0109358
0.0136827
0.00165459
0.00271369
0.00129719
0.000982874
0.00416064
0.0010919
0.00556232
0.0012546
0.00105669
0.000485449
0.00177332
0.000408368
0.00184785
0.000390943
0.00243426
0.00289313
0.00180664
0.0019031
0.000739102
0.00126318
0.000933647
0.00113934
0.00150114
0.000665038
0.000799963
0.00166927
0.00159525
0.000574503
0.000332257
0.00144153
0.00161226
0.00097659
0.000787611
)
;
boundaryField
{
frontAndBack
{
type empty;
}
wallOuter
{
type nutkWallFunction;
Cmu 0.09;
kappa 0.41;
E 9.8;
value nonuniform List<scalar>
96
(
0.000105453
8.47549e-05
7.99333e-05
0.000195052
0.000197544
0.000194524
0.000106529
9.39466e-05
6.83926e-05
0.000166326
5.82475e-05
0.000140561
8.13189e-05
0.000204047
0.00015312
0.000181052
0.000192509
9.12091e-05
5.34154e-05
0.000119284
5.24196e-05
0.000130097
9.26629e-05
0.000193829
0.000185096
9.86751e-05
0.000102532
9.88361e-05
8.65357e-05
9.16929e-05
0.000113925
0.000100957
7.0423e-05
8.42803e-05
7.53473e-05
7.62837e-05
8.35519e-05
0.000124727
8.56036e-05
7.65172e-05
7.71073e-05
8.95785e-05
9.52374e-05
8.99368e-05
8.87638e-05
8.57411e-05
8.646e-05
8.54605e-05
8.92776e-05
9.01984e-05
0.000116513
8.50557e-05
8.26444e-05
5.08354e-05
0.000165849
8.64324e-05
0.00013609
9.4324e-05
8.12676e-05
8.49034e-05
0.000203538
4.65934e-05
3.84016e-05
0.000237403
0.000222812
0.000249569
0.000218431
8.72533e-05
0.000203755
0.000192545
0.000188515
0.00024826
0.000222055
0.000212676
0.000203476
0.000214726
2.54168e-05
2.63516e-05
2.18412e-05
2.19464e-05
1.4782e-05
2.02093e-05
8.37735e-05
5.47959e-05
7.5776e-05
7.88318e-05
0.000162724
5.66664e-05
0.000210206
0.000209677
8.64222e-05
7.67148e-05
3.23079e-05
0.000217367
0.000128615
4.28973e-05
)
;
}
inlet
{
type calculated;
value nonuniform 0();
}
outlet
{
type calculated;
value nonuniform List<scalar> 9(0.017659 0.0169383 0.00183959 0.0156507 0.0116868 0.00696978 0.00210772 0.00352185 0.0105398);
}
wallInner
{
type nutkWallFunction;
Cmu 0.09;
kappa 0.41;
E 9.8;
value nonuniform List<scalar>
126
(
0.000201855
0.000119572
0.000170911
6.04909e-05
5.65935e-05
5.18724e-05
3.28478e-05
4.48201e-05
9.52391e-05
7.4827e-05
9.97176e-05
0.000145977
0.000397525
0.000137295
6.18878e-05
0.000102397
0.000172734
0.000117119
7.16843e-05
3.87647e-05
7.54881e-05
0.000125002
0.000196838
7.72279e-05
0.000141501
0.000148059
0.00016122
7.46852e-05
7.04237e-05
4.49523e-05
0.000152911
0.00018297
0.000272963
0.000146797
0.000284313
5.57806e-05
7.35775e-05
0.000155556
0.000128699
5.0212e-05
4.1984e-05
0.000172499
7.96098e-05
6.88739e-05
0.000118709
0.000124227
7.64083e-05
0.00030434
5.31783e-05
0.000153205
0.000175647
7.01208e-05
0.000223789
7.77048e-05
0.000117957
0.000173217
7.15238e-05
0.000209273
0.000170676
0.000123011
7.14574e-05
4.65915e-05
5.31222e-05
0.00015656
0.000119163
9.72727e-05
0.000135673
0.000151932
4.01705e-05
0.000210106
0.000152877
0.000128191
6.29419e-05
6.01328e-05
0.000147007
0.000136038
6.61291e-05
0.000198542
0.000187453
0.000182958
0.000156436
0.000187756
0.000137869
0.00018944
0.000160948
0.000186466
0.000195427
0.000126361
3.81478e-05
0.000188072
0.000171772
0.000194364
0.000160864
6.79154e-05
0.000139268
0.000219145
0.000107513
0.000214909
0.000114119
0.000115594
0.000151943
0.000115898
0.000128401
0.000147923
0.000121101
5.72566e-05
4.8236e-05
4.80223e-05
0.000270468
0.000318093
0.000205823
0.000216495
8.90901e-05
0.000111067
0.000133609
0.000173644
8.04033e-05
9.55426e-05
0.00019107
0.000182301
7.03469e-05
4.05723e-05
0.000167629
0.000185926
0.000115623
9.52693e-05
)
;
}
procBoundary3to1
{
type processor;
value nonuniform List<scalar>
48
(
0.0112735
0.00459712
0.00579667
0.00944536
0.00363861
0.00346038
0.00459712
0.0115219
0.0146536
0.00123504
0.00123504
0.00118742
0.00118742
0.00171431
0.00228576
0.00119396
0.00137158
0.00122609
0.00137158
0.00156847
0.00141465
0.00286287
0.00156847
0.00193043
0.00115896
0.00136545
0.0051544
0.00286287
0.00718182
0.00127548
0.00127548
0.00991321
0.00991321
0.0146536
0.00152409
0.00303367
0.0131426
0.00115896
0.0131509
0.00319242
0.00171431
0.0143794
0.0149297
0.00156847
0.00249056
0.00105588
0.00362841
0.00131633
)
;
}
procBoundary3to2
{
type processor;
value nonuniform List<scalar>
29
(
0.0018879
0.0018879
0.000454313
0.000505857
0.000671673
0.000604512
0.000413963
0.0016837
0.00258334
0.00210929
0.00113315
0.0012498
0.00106237
0.00180401
0.00139472
0.00145753
0.00192078
0.00244816
0.00208905
0.00179629
0.00162523
0.00192078
0.000238186
0.00244816
0.000903478
0.000965788
0.00244816
0.00224382
0.00224382
)
;
}
}
// ************************************************************************* //
| [
"mohan.2611@gmail.com"
] | mohan.2611@gmail.com | |
028f0ca8dccf3123d23b43f7563a5c7d04931e2b | 7cc38b60e2429bbbf92f8bb6e4b55d91860ca227 | /models/PaymentsModel.cpp | 2b710f49aef45147e1a1ccddbc51a0511b47e402 | [] | no_license | topten2018/untitled | 565e880e71aa2e7d028c09a1565e84ceec967036 | d9e607bf024f2484401fa0e797f3994ab672cb7a | refs/heads/master | 2020-03-06T16:12:20.237389 | 2018-04-14T10:42:00 | 2018-04-14T10:42:00 | 126,969,412 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,320 | cpp | #include "models/PaymentsModel.h"
#include "Utils/AutoSaver.h"
#include "Utils/StringUtils.h"
#include "dialogs/DlgAddress.h"
#include <QMessageBox>
#include <QFile>
#include <QTextStream>
#include <QMutexLocker>
PaymentsModel::PaymentsModel(const QString filename, QObject *parent)
: QAbstractTableModel(parent)
, m_strFileName(filename)
, m_mtx(QMutex::Recursive)
{
m_spAutoSaver = new AutoSaver(this);
load();
}
PaymentsModel::~PaymentsModel()
{
m_spAutoSaver->saveIfNeccessary();
qDeleteAll(m_lstItems);
}
QVariant PaymentsModel::headerData(int section, Qt::Orientation , int role) const
{
QVariant result;
switch (role)
{
case Qt::SizeHintRole:
switch (section)
{
case H_DATE:
return QSize(100, 28);
break;
case H_LABEL:
return QSize(220, 28);
break;
case H_AMOUNT:
return QSize(150, 28);
break;
}
break;
case Qt::DisplayRole:
switch (section)
{
case H_DATE:
result = tr("Date");
break;
case H_LABEL:
result = tr("Label");
break;
case H_MESSAGE:
result = tr("Message");
break;
case H_AMOUNT:
result = tr("Amount (APR)");
break;
};
break;
}
return result;
}
QVariant PaymentsModel::data(const QModelIndex & index,int role) const
{
if (!index.isValid())
return QVariant();
const TransactionItem * item = m_lstItems.at(index.row());
switch (role)
{
case Qt::TextAlignmentRole:
if (index.column() == H_AMOUNT)
{
return Qt::AlignRight + Qt::AlignVCenter;
}
break;
case Qt::DisplayRole:
{
switch (index.column())
{
case H_DATE:
return item->date().toString("dd.MM.yyyy hh:mm");
break;
case H_LABEL:
return item->label();
break;
case H_MESSAGE:
return item->message();
break;
case H_AMOUNT:
return item->amount();
break;
};
break;
}
}
return QVariant();
}
TransactionItem * PaymentsModel::item(int row)
{
return m_lstItems.at(row);
}
void PaymentsModel::onAddItem()
{
/* DlgAddress dlg(nullptr, dynamic_cast<QWidget *>(parent()));
if (dlg.exec() == QDialog::Accepted)
{
addItem(new TransactionItem(dlg.address()));
m_spAutoSaver->changeOccurred();
}*/
}
void PaymentsModel::append(TransactionItem * p)
{
addItem(p);
m_spAutoSaver->changeOccurred();
}
void PaymentsModel::onEditItem(int row)
{
TransactionItem * p = m_lstItems.at(row);
if (!p)
return;
/* DlgAddress dlg(p, dynamic_cast<QWidget *>(parent()));
if (dlg.exec() == QDialog::Accepted)
{
QMutexLocker locker(&m_mtx);
*m_lstItems.at(row) = dlg.address();
m_spAutoSaver->changeOccurred();
}*/
}
void PaymentsModel::onDeleteItem(int row)
{
QMessageBox mb(QMessageBox::Icon::Warning, tr("Warning"), tr("Delete this payment?")
, QMessageBox::StandardButton::Ok | QMessageBox::StandardButton::Cancel, dynamic_cast<QWidget *>(parent()));
if (mb.exec() == QMessageBox::StandardButton::Ok)
{
QMutexLocker locker(&m_mtx);
m_spAutoSaver->changeOccurred();
beginRemoveRows(QModelIndex(), row, row);
m_lstItems.removeAt(row);
endRemoveRows();
}
}
void PaymentsModel::addItem(TransactionItem * p)
{
QMutexLocker locker(&m_mtx);
beginInsertRows(QModelIndex(), 0, 0);
m_lstItems.insert(0, p);
endInsertRows();
}
void PaymentsModel::load()
{
QMutexLocker locker(&m_mtx);
/* qDeleteAll(m_lstItems);
m_lstItems.clear();
QFile file(m_strFileName);
if (file.open(QIODevice::ReadOnly))
{
QTextStream in(&file);
QStringList row;
while (!in.atEnd())
{
QString line = in.readLine();
if (Utils::parseCsvLine(line, row) && row.size() >= 2)
{
m_lstItems.append(new AddressItem(row[0], row[1]));
}
}
file.close();
}*/
}
void PaymentsModel::save() const
{
saveToFile(m_strFileName, false);
}
void PaymentsModel::exportToFile(const QString & filename) const
{
saveToFile(filename, true);
}
void PaymentsModel::saveToFile(const QString & filename, bool bWriteHeader) const
{
QMutexLocker locker(&m_mtx);
QFile file(filename);
if (file.open(QIODevice::WriteOnly))
{
QTextStream out(&file);
if (bWriteHeader)
{
QString line = QString("\"%1\",\"%2\"\r\n").arg("Label").arg("Address");
out << line;
}
foreach (TransactionItem * item, m_lstItems)
{
QString line = QString("\"%1\",\"%2\"\r\n").arg(item->label().replace("\"", "\"\"")).arg(item->address().replace("\"", "\"\""));
out << line;
}
file.close();
}
} | [
"zV3KT0R@gmail.com"
] | zV3KT0R@gmail.com |
a4467bbaf6b442d9cfe6ad3d0a210267d801577c | bbc61fe39037810826b481d965f295ef5a21dd36 | /src/masternode-payments.cpp | 1681b530e7bb9f67c8b236414bd44977f81061e8 | [
"MIT"
] | permissive | matthewchincy92/unionew | df7d58f39b752b1b31deb3a0917f7528e3771ef0 | 91951af8a98fb85eefa556d52cff5c1bd52a2e33 | refs/heads/master | 2021-04-03T02:53:01.283946 | 2018-10-23T04:53:45 | 2018-10-23T04:53:45 | 124,864,764 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 42,192 | cpp | // Copyright (c) 2014-2017 The Unio Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "activemasternode.h"
#include "governance-classes.h"
#include "masternode-payments.h"
#include "masternode-sync.h"
#include "masternodeman.h"
#include "messagesigner.h"
#include "netfulfilledman.h"
#include "spork.h"
#include "util.h"
#include <boost/lexical_cast.hpp>
/** Object for who's going to get paid on which blocks */
CMasternodePayments mnpayments;
CCriticalSection cs_vecPayees;
CCriticalSection cs_mapMasternodeBlocks;
CCriticalSection cs_mapMasternodePaymentVotes;
/**
* IsBlockValueValid
*
* Determine if coinbase outgoing created money is the correct value
*
* Why is this needed?
* - In Unio some blocks are superblocks, which output much higher amounts of coins
* - Otherblocks are 10% lower in outgoing value, so in total, no extra coins are created
* - When non-superblocks are detected, the normal schedule should be maintained
*/
bool IsBlockValueValid(const CBlock& block, int nBlockHeight, CAmount blockReward, std::string &strErrorRet)
{
strErrorRet = "";
bool isBlockRewardValueMet = (block.vtx[0].GetValueOut() <= blockReward);
if(fDebug) LogPrintf("block.vtx[0].GetValueOut() %lld <= blockReward %lld\n", block.vtx[0].GetValueOut(), blockReward);
// we are still using budgets, but we have no data about them anymore,
// all we know is predefined budget cycle and window
const Consensus::Params& consensusParams = Params().GetConsensus();
if(nBlockHeight < consensusParams.nSuperblockStartBlock) {
int nOffset = nBlockHeight % consensusParams.nBudgetPaymentsCycleBlocks;
if(nBlockHeight >= consensusParams.nBudgetPaymentsStartBlock &&
nOffset < consensusParams.nBudgetPaymentsWindowBlocks) {
// NOTE: make sure SPORK_13_OLD_SUPERBLOCK_FLAG is disabled when 12.1 starts to go live
if(masternodeSync.IsSynced() && !sporkManager.IsSporkActive(SPORK_13_OLD_SUPERBLOCK_FLAG)) {
// no budget blocks should be accepted here, if SPORK_13_OLD_SUPERBLOCK_FLAG is disabled
LogPrint("gobject", "IsBlockValueValid -- Client synced but budget spork is disabled, checking block value against block reward\n");
if(!isBlockRewardValueMet) {
strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, budgets are disabled",
nBlockHeight, block.vtx[0].GetValueOut(), blockReward);
}
return isBlockRewardValueMet;
}
LogPrint("gobject", "IsBlockValueValid -- WARNING: Skipping budget block value checks, accepting block\n");
// TODO: reprocess blocks to make sure they are legit?
return true;
}
// LogPrint("gobject", "IsBlockValueValid -- Block is not in budget cycle window, checking block value against block reward\n");
if(!isBlockRewardValueMet) {
strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, block is not in budget cycle window",
nBlockHeight, block.vtx[0].GetValueOut(), blockReward);
}
return isBlockRewardValueMet;
}
// superblocks started
CAmount nSuperblockMaxValue = blockReward + CSuperblock::GetPaymentsLimit(nBlockHeight);
bool isSuperblockMaxValueMet = (block.vtx[0].GetValueOut() <= nSuperblockMaxValue);
LogPrint("gobject", "block.vtx[0].GetValueOut() %lld <= nSuperblockMaxValue %lld\n", block.vtx[0].GetValueOut(), nSuperblockMaxValue);
if(!masternodeSync.IsSynced()) {
// not enough data but at least it must NOT exceed superblock max value
if(CSuperblock::IsValidBlockHeight(nBlockHeight)) {
if(fDebug) LogPrintf("IsBlockPayeeValid -- WARNING: Client not synced, checking superblock max bounds only\n");
if(!isSuperblockMaxValueMet) {
strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded superblock max value",
nBlockHeight, block.vtx[0].GetValueOut(), nSuperblockMaxValue);
}
return isSuperblockMaxValueMet;
}
if(!isBlockRewardValueMet) {
strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, only regular blocks are allowed at this height",
nBlockHeight, block.vtx[0].GetValueOut(), blockReward);
}
// it MUST be a regular block otherwise
return isBlockRewardValueMet;
}
// we are synced, let's try to check as much data as we can
if(sporkManager.IsSporkActive(SPORK_9_SUPERBLOCKS_ENABLED)) {
if(CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) {
if(CSuperblockManager::IsValid(block.vtx[0], nBlockHeight, blockReward)) {
LogPrint("gobject", "IsBlockValueValid -- Valid superblock at height %d: %s", nBlockHeight, block.vtx[0].ToString());
// all checks are done in CSuperblock::IsValid, nothing to do here
return true;
}
// triggered but invalid? that's weird
LogPrintf("IsBlockValueValid -- ERROR: Invalid superblock detected at height %d: %s", nBlockHeight, block.vtx[0].ToString());
// should NOT allow invalid superblocks, when superblocks are enabled
strErrorRet = strprintf("invalid superblock detected at height %d", nBlockHeight);
return false;
}
LogPrint("gobject", "IsBlockValueValid -- No triggered superblock detected at height %d\n", nBlockHeight);
if(!isBlockRewardValueMet) {
strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, no triggered superblock detected",
nBlockHeight, block.vtx[0].GetValueOut(), blockReward);
}
} else {
// should NOT allow superblocks at all, when superblocks are disabled
LogPrint("gobject", "IsBlockValueValid -- Superblocks are disabled, no superblocks allowed\n");
if(!isBlockRewardValueMet) {
strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, superblocks are disabled",
nBlockHeight, block.vtx[0].GetValueOut(), blockReward);
}
}
// it MUST be a regular block
return isBlockRewardValueMet;
}
bool IsBlockPayeeValid(const CTransaction& txNew, int nBlockHeight, CAmount blockReward)
{
if(!masternodeSync.IsSynced()) {
//there is no budget data to use to check anything, let's just accept the longest chain
if(fDebug) LogPrintf("IsBlockPayeeValid -- WARNING: Client not synced, skipping block payee checks\n");
return true;
}
// we are still using budgets, but we have no data about them anymore,
// we can only check masternode payments
const Consensus::Params& consensusParams = Params().GetConsensus();
if(nBlockHeight < consensusParams.nSuperblockStartBlock) {
if(mnpayments.IsTransactionValid(txNew, nBlockHeight)) {
LogPrint("mnpayments", "IsBlockPayeeValid -- Valid masternode payment at height %d: %s", nBlockHeight, txNew.ToString());
return true;
}
int nOffset = nBlockHeight % consensusParams.nBudgetPaymentsCycleBlocks;
if(nBlockHeight >= consensusParams.nBudgetPaymentsStartBlock &&
nOffset < consensusParams.nBudgetPaymentsWindowBlocks) {
if(!sporkManager.IsSporkActive(SPORK_13_OLD_SUPERBLOCK_FLAG)) {
// no budget blocks should be accepted here, if SPORK_13_OLD_SUPERBLOCK_FLAG is disabled
LogPrint("gobject", "IsBlockPayeeValid -- ERROR: Client synced but budget spork is disabled and masternode payment is invalid\n");
return false;
}
// NOTE: this should never happen in real, SPORK_13_OLD_SUPERBLOCK_FLAG MUST be disabled when 12.1 starts to go live
LogPrint("gobject", "IsBlockPayeeValid -- WARNING: Probably valid budget block, have no data, accepting\n");
// TODO: reprocess blocks to make sure they are legit?
return true;
}
if(sporkManager.IsSporkActive(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT)) {
LogPrintf("IsBlockPayeeValid -- ERROR: Invalid masternode payment detected at height %d: %s", nBlockHeight, txNew.ToString());
return false;
}
LogPrintf("IsBlockPayeeValid -- WARNING: Masternode payment enforcement is disabled, accepting any payee\n");
return true;
}
// superblocks started
// SEE IF THIS IS A VALID SUPERBLOCK
if(sporkManager.IsSporkActive(SPORK_9_SUPERBLOCKS_ENABLED)) {
if(CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) {
if(CSuperblockManager::IsValid(txNew, nBlockHeight, blockReward)) {
LogPrint("gobject", "IsBlockPayeeValid -- Valid superblock at height %d: %s", nBlockHeight, txNew.ToString());
return true;
}
LogPrintf("IsBlockPayeeValid -- ERROR: Invalid superblock detected at height %d: %s", nBlockHeight, txNew.ToString());
// should NOT allow such superblocks, when superblocks are enabled
return false;
}
// continue validation, should pay MN
LogPrint("gobject", "IsBlockPayeeValid -- No triggered superblock detected at height %d\n", nBlockHeight);
} else {
// should NOT allow superblocks at all, when superblocks are disabled
LogPrint("gobject", "IsBlockPayeeValid -- Superblocks are disabled, no superblocks allowed\n");
}
// IF THIS ISN'T A SUPERBLOCK OR SUPERBLOCK IS INVALID, IT SHOULD PAY A MASTERNODE DIRECTLY
if(mnpayments.IsTransactionValid(txNew, nBlockHeight)) {
LogPrint("mnpayments", "IsBlockPayeeValid -- Valid masternode payment at height %d: %s", nBlockHeight, txNew.ToString());
return true;
}
if(sporkManager.IsSporkActive(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT)) {
LogPrintf("IsBlockPayeeValid -- ERROR: Invalid masternode payment detected at height %d: %s", nBlockHeight, txNew.ToString());
return false;
}
LogPrintf("IsBlockPayeeValid -- WARNING: Masternode payment enforcement is disabled, accepting any payee\n");
return true;
}
void FillBlockPayments(CMutableTransaction& txNew, int nBlockHeight, CAmount blockReward, CTxOut& txoutMasternodeRet, std::vector<CTxOut>& voutSuperblockRet)
{
// only create superblocks if spork is enabled AND if superblock is actually triggered
// (height should be validated inside)
if(sporkManager.IsSporkActive(SPORK_9_SUPERBLOCKS_ENABLED) &&
CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) {
LogPrint("gobject", "FillBlockPayments -- triggered superblock creation at height %d\n", nBlockHeight);
CSuperblockManager::CreateSuperblock(txNew, nBlockHeight, voutSuperblockRet);
return;
}
// FILL BLOCK PAYEE WITH MASTERNODE PAYMENT OTHERWISE
mnpayments.FillBlockPayee(txNew, nBlockHeight, blockReward, txoutMasternodeRet);
LogPrint("mnpayments", "FillBlockPayments -- nBlockHeight %d blockReward %lld txoutMasternodeRet %s txNew %s",
nBlockHeight, blockReward, txoutMasternodeRet.ToString(), txNew.ToString());
}
std::string GetRequiredPaymentsString(int nBlockHeight)
{
// IF WE HAVE A ACTIVATED TRIGGER FOR THIS HEIGHT - IT IS A SUPERBLOCK, GET THE REQUIRED PAYEES
if(CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) {
return CSuperblockManager::GetRequiredPaymentsString(nBlockHeight);
}
// OTHERWISE, PAY MASTERNODE
return mnpayments.GetRequiredPaymentsString(nBlockHeight);
}
void CMasternodePayments::Clear()
{
LOCK2(cs_mapMasternodeBlocks, cs_mapMasternodePaymentVotes);
mapMasternodeBlocks.clear();
mapMasternodePaymentVotes.clear();
}
bool CMasternodePayments::CanVote(COutPoint outMasternode, int nBlockHeight)
{
LOCK(cs_mapMasternodePaymentVotes);
if (mapMasternodesLastVote.count(outMasternode) && mapMasternodesLastVote[outMasternode] == nBlockHeight) {
return false;
}
//record this masternode voted
mapMasternodesLastVote[outMasternode] = nBlockHeight;
return true;
}
/**
* FillBlockPayee
*
* Fill Masternode ONLY payment block
*/
void CMasternodePayments::FillBlockPayee(CMutableTransaction& txNew, int nBlockHeight, CAmount blockReward, CTxOut& txoutMasternodeRet)
{
// make sure it's not filled yet
txoutMasternodeRet = CTxOut();
CScript payee;
if(!mnpayments.GetBlockPayee(nBlockHeight, payee)) {
// no masternode detected...
int nCount = 0;
masternode_info_t mnInfo;
if(!mnodeman.GetNextMasternodeInQueueForPayment(nBlockHeight, true, nCount, mnInfo)) {
// ...and we can't calculate it on our own
LogPrintf("CMasternodePayments::FillBlockPayee -- Failed to detect masternode to pay\n");
return;
}
// fill payee with locally calculated winner and hope for the best
payee = GetScriptForDestination(mnInfo.pubKeyCollateralAddress.GetID());
}
// GET MASTERNODE PAYMENT VARIABLES SETUP
CAmount masternodePayment = GetMasternodePayment(nBlockHeight, blockReward);
// split reward between miner ...
txNew.vout[0].nValue -= masternodePayment;
// ... and masternode
txoutMasternodeRet = CTxOut(masternodePayment, payee);
txNew.vout.push_back(txoutMasternodeRet);
CTxDestination address1;
ExtractDestination(payee, address1);
CBitcoinAddress address2(address1);
LogPrintf("CMasternodePayments::FillBlockPayee -- Masternode payment %lld to %s\n", masternodePayment, address2.ToString());
}
int CMasternodePayments::GetMinMasternodePaymentsProto() {
return sporkManager.IsSporkActive(SPORK_10_MASTERNODE_PAY_UPDATED_NODES)
? MIN_MASTERNODE_PAYMENT_PROTO_VERSION_2
: MIN_MASTERNODE_PAYMENT_PROTO_VERSION_1;
}
void CMasternodePayments::ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv, CConnman& connman)
{
if(fLiteMode) return; // disable all Unio specific functionality
if (strCommand == NetMsgType::MASTERNODEPAYMENTSYNC) { //Masternode Payments Request Sync
// Ignore such requests until we are fully synced.
// We could start processing this after masternode list is synced
// but this is a heavy one so it's better to finish sync first.
if (!masternodeSync.IsSynced()) return;
int nCountNeeded;
vRecv >> nCountNeeded;
if(netfulfilledman.HasFulfilledRequest(pfrom->addr, NetMsgType::MASTERNODEPAYMENTSYNC)) {
// Asking for the payments list multiple times in a short period of time is no good
LogPrintf("MASTERNODEPAYMENTSYNC -- peer already asked me for the list, peer=%d\n", pfrom->id);
Misbehaving(pfrom->GetId(), 20);
return;
}
netfulfilledman.AddFulfilledRequest(pfrom->addr, NetMsgType::MASTERNODEPAYMENTSYNC);
Sync(pfrom, connman);
LogPrintf("MASTERNODEPAYMENTSYNC -- Sent Masternode payment votes to peer %d\n", pfrom->id);
} else if (strCommand == NetMsgType::MASTERNODEPAYMENTVOTE) { // Masternode Payments Vote for the Winner
CMasternodePaymentVote vote;
vRecv >> vote;
if(pfrom->nVersion < GetMinMasternodePaymentsProto()) return;
uint256 nHash = vote.GetHash();
pfrom->setAskFor.erase(nHash);
// TODO: clear setAskFor for MSG_MASTERNODE_PAYMENT_BLOCK too
// Ignore any payments messages until masternode list is synced
if(!masternodeSync.IsMasternodeListSynced()) return;
{
LOCK(cs_mapMasternodePaymentVotes);
if(mapMasternodePaymentVotes.count(nHash)) {
LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- hash=%s, nHeight=%d seen\n", nHash.ToString(), nCachedBlockHeight);
return;
}
// Avoid processing same vote multiple times
mapMasternodePaymentVotes[nHash] = vote;
// but first mark vote as non-verified,
// AddPaymentVote() below should take care of it if vote is actually ok
mapMasternodePaymentVotes[nHash].MarkAsNotVerified();
}
int nFirstBlock = nCachedBlockHeight - GetStorageLimit();
if(vote.nBlockHeight < nFirstBlock || vote.nBlockHeight > nCachedBlockHeight+20) {
LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- vote out of range: nFirstBlock=%d, nBlockHeight=%d, nHeight=%d\n", nFirstBlock, vote.nBlockHeight, nCachedBlockHeight);
return;
}
std::string strError = "";
if(!vote.IsValid(pfrom, nCachedBlockHeight, strError, connman)) {
LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- invalid message, error: %s\n", strError);
return;
}
if(!CanVote(vote.vinMasternode.prevout, vote.nBlockHeight)) {
LogPrintf("MASTERNODEPAYMENTVOTE -- masternode already voted, masternode=%s\n", vote.vinMasternode.prevout.ToStringShort());
return;
}
masternode_info_t mnInfo;
if(!mnodeman.GetMasternodeInfo(vote.vinMasternode.prevout, mnInfo)) {
// mn was not found, so we can't check vote, some info is probably missing
LogPrintf("MASTERNODEPAYMENTVOTE -- masternode is missing %s\n", vote.vinMasternode.prevout.ToStringShort());
mnodeman.AskForMN(pfrom, vote.vinMasternode.prevout, connman);
return;
}
int nDos = 0;
if(!vote.CheckSignature(mnInfo.pubKeyMasternode, nCachedBlockHeight, nDos)) {
if(nDos) {
LogPrintf("MASTERNODEPAYMENTVOTE -- ERROR: invalid signature\n");
Misbehaving(pfrom->GetId(), nDos);
} else {
// only warn about anything non-critical (i.e. nDos == 0) in debug mode
LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- WARNING: invalid signature\n");
}
// Either our info or vote info could be outdated.
// In case our info is outdated, ask for an update,
mnodeman.AskForMN(pfrom, vote.vinMasternode.prevout, connman);
// but there is nothing we can do if vote info itself is outdated
// (i.e. it was signed by a mn which changed its key),
// so just quit here.
return;
}
CTxDestination address1;
ExtractDestination(vote.payee, address1);
CBitcoinAddress address2(address1);
LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- vote: address=%s, nBlockHeight=%d, nHeight=%d, prevout=%s, hash=%s new\n",
address2.ToString(), vote.nBlockHeight, nCachedBlockHeight, vote.vinMasternode.prevout.ToStringShort(), nHash.ToString());
if(AddPaymentVote(vote)){
vote.Relay(connman);
masternodeSync.BumpAssetLastTime("MASTERNODEPAYMENTVOTE");
}
}
}
bool CMasternodePaymentVote::Sign()
{
std::string strError;
std::string strMessage = vinMasternode.prevout.ToStringShort() +
boost::lexical_cast<std::string>(nBlockHeight) +
ScriptToAsmStr(payee);
if(!CMessageSigner::SignMessage(strMessage, vchSig, activeMasternode.keyMasternode)) {
LogPrintf("CMasternodePaymentVote::Sign -- SignMessage() failed\n");
return false;
}
if(!CMessageSigner::VerifyMessage(activeMasternode.pubKeyMasternode, vchSig, strMessage, strError)) {
LogPrintf("CMasternodePaymentVote::Sign -- VerifyMessage() failed, error: %s\n", strError);
return false;
}
return true;
}
bool CMasternodePayments::GetBlockPayee(int nBlockHeight, CScript& payee)
{
if(mapMasternodeBlocks.count(nBlockHeight)){
return mapMasternodeBlocks[nBlockHeight].GetBestPayee(payee);
}
return false;
}
// Is this masternode scheduled to get paid soon?
// -- Only look ahead up to 8 blocks to allow for propagation of the latest 2 blocks of votes
bool CMasternodePayments::IsScheduled(CMasternode& mn, int nNotBlockHeight)
{
LOCK(cs_mapMasternodeBlocks);
if(!masternodeSync.IsMasternodeListSynced()) return false;
CScript mnpayee;
mnpayee = GetScriptForDestination(mn.pubKeyCollateralAddress.GetID());
CScript payee;
for(int64_t h = nCachedBlockHeight; h <= nCachedBlockHeight + 8; h++){
if(h == nNotBlockHeight) continue;
if(mapMasternodeBlocks.count(h) && mapMasternodeBlocks[h].GetBestPayee(payee) && mnpayee == payee) {
return true;
}
}
return false;
}
bool CMasternodePayments::AddPaymentVote(const CMasternodePaymentVote& vote)
{
uint256 blockHash = uint256();
if(!GetBlockHash(blockHash, vote.nBlockHeight - 101)) return false;
if(HasVerifiedPaymentVote(vote.GetHash())) return false;
LOCK2(cs_mapMasternodeBlocks, cs_mapMasternodePaymentVotes);
mapMasternodePaymentVotes[vote.GetHash()] = vote;
if(!mapMasternodeBlocks.count(vote.nBlockHeight)) {
CMasternodeBlockPayees blockPayees(vote.nBlockHeight);
mapMasternodeBlocks[vote.nBlockHeight] = blockPayees;
}
mapMasternodeBlocks[vote.nBlockHeight].AddPayee(vote);
return true;
}
bool CMasternodePayments::HasVerifiedPaymentVote(uint256 hashIn)
{
LOCK(cs_mapMasternodePaymentVotes);
std::map<uint256, CMasternodePaymentVote>::iterator it = mapMasternodePaymentVotes.find(hashIn);
return it != mapMasternodePaymentVotes.end() && it->second.IsVerified();
}
void CMasternodeBlockPayees::AddPayee(const CMasternodePaymentVote& vote)
{
LOCK(cs_vecPayees);
BOOST_FOREACH(CMasternodePayee& payee, vecPayees) {
if (payee.GetPayee() == vote.payee) {
payee.AddVoteHash(vote.GetHash());
return;
}
}
CMasternodePayee payeeNew(vote.payee, vote.GetHash());
vecPayees.push_back(payeeNew);
}
bool CMasternodeBlockPayees::GetBestPayee(CScript& payeeRet)
{
LOCK(cs_vecPayees);
if(!vecPayees.size()) {
LogPrint("mnpayments", "CMasternodeBlockPayees::GetBestPayee -- ERROR: couldn't find any payee\n");
return false;
}
int nVotes = -1;
BOOST_FOREACH(CMasternodePayee& payee, vecPayees) {
if (payee.GetVoteCount() > nVotes) {
payeeRet = payee.GetPayee();
nVotes = payee.GetVoteCount();
}
}
return (nVotes > -1);
}
bool CMasternodeBlockPayees::HasPayeeWithVotes(const CScript& payeeIn, int nVotesReq)
{
LOCK(cs_vecPayees);
BOOST_FOREACH(CMasternodePayee& payee, vecPayees) {
if (payee.GetVoteCount() >= nVotesReq && payee.GetPayee() == payeeIn) {
return true;
}
}
LogPrint("mnpayments", "CMasternodeBlockPayees::HasPayeeWithVotes -- ERROR: couldn't find any payee with %d+ votes\n", nVotesReq);
return false;
}
bool CMasternodeBlockPayees::IsTransactionValid(const CTransaction& txNew)
{
LOCK(cs_vecPayees);
int nMaxSignatures = 0;
std::string strPayeesPossible = "";
CAmount nMasternodePayment = GetMasternodePayment(nBlockHeight, txNew.GetValueOut());
//require at least MNPAYMENTS_SIGNATURES_REQUIRED signatures
BOOST_FOREACH(CMasternodePayee& payee, vecPayees) {
if (payee.GetVoteCount() >= nMaxSignatures) {
nMaxSignatures = payee.GetVoteCount();
}
}
// if we don't have at least MNPAYMENTS_SIGNATURES_REQUIRED signatures on a payee, approve whichever is the longest chain
if(nMaxSignatures < MNPAYMENTS_SIGNATURES_REQUIRED) return true;
BOOST_FOREACH(CMasternodePayee& payee, vecPayees) {
if (payee.GetVoteCount() >= MNPAYMENTS_SIGNATURES_REQUIRED) {
BOOST_FOREACH(CTxOut txout, txNew.vout) {
if (payee.GetPayee() == txout.scriptPubKey && nMasternodePayment == txout.nValue) {
LogPrint("mnpayments", "CMasternodeBlockPayees::IsTransactionValid -- Found required payment\n");
return true;
}
}
CTxDestination address1;
ExtractDestination(payee.GetPayee(), address1);
CBitcoinAddress address2(address1);
if(strPayeesPossible == "") {
strPayeesPossible = address2.ToString();
} else {
strPayeesPossible += "," + address2.ToString();
}
}
}
LogPrintf("CMasternodeBlockPayees::IsTransactionValid -- ERROR: Missing required payment, possible payees: '%s', amount: %f UNIO\n", strPayeesPossible, (float)nMasternodePayment/COIN);
return false;
}
std::string CMasternodeBlockPayees::GetRequiredPaymentsString()
{
LOCK(cs_vecPayees);
std::string strRequiredPayments = "Unknown";
BOOST_FOREACH(CMasternodePayee& payee, vecPayees)
{
CTxDestination address1;
ExtractDestination(payee.GetPayee(), address1);
CBitcoinAddress address2(address1);
if (strRequiredPayments != "Unknown") {
strRequiredPayments += ", " + address2.ToString() + ":" + boost::lexical_cast<std::string>(payee.GetVoteCount());
} else {
strRequiredPayments = address2.ToString() + ":" + boost::lexical_cast<std::string>(payee.GetVoteCount());
}
}
return strRequiredPayments;
}
std::string CMasternodePayments::GetRequiredPaymentsString(int nBlockHeight)
{
LOCK(cs_mapMasternodeBlocks);
if(mapMasternodeBlocks.count(nBlockHeight)){
return mapMasternodeBlocks[nBlockHeight].GetRequiredPaymentsString();
}
return "Unknown";
}
bool CMasternodePayments::IsTransactionValid(const CTransaction& txNew, int nBlockHeight)
{
LOCK(cs_mapMasternodeBlocks);
if(mapMasternodeBlocks.count(nBlockHeight)){
return mapMasternodeBlocks[nBlockHeight].IsTransactionValid(txNew);
}
return true;
}
void CMasternodePayments::CheckAndRemove()
{
if(!masternodeSync.IsBlockchainSynced()) return;
LOCK2(cs_mapMasternodeBlocks, cs_mapMasternodePaymentVotes);
int nLimit = GetStorageLimit();
std::map<uint256, CMasternodePaymentVote>::iterator it = mapMasternodePaymentVotes.begin();
while(it != mapMasternodePaymentVotes.end()) {
CMasternodePaymentVote vote = (*it).second;
if(nCachedBlockHeight - vote.nBlockHeight > nLimit) {
LogPrint("mnpayments", "CMasternodePayments::CheckAndRemove -- Removing old Masternode payment: nBlockHeight=%d\n", vote.nBlockHeight);
mapMasternodePaymentVotes.erase(it++);
mapMasternodeBlocks.erase(vote.nBlockHeight);
} else {
++it;
}
}
LogPrintf("CMasternodePayments::CheckAndRemove -- %s\n", ToString());
}
bool CMasternodePaymentVote::IsValid(CNode* pnode, int nValidationHeight, std::string& strError, CConnman& connman)
{
masternode_info_t mnInfo;
if(!mnodeman.GetMasternodeInfo(vinMasternode.prevout, mnInfo)) {
strError = strprintf("Unknown Masternode: prevout=%s", vinMasternode.prevout.ToStringShort());
// Only ask if we are already synced and still have no idea about that Masternode
if(masternodeSync.IsMasternodeListSynced()) {
mnodeman.AskForMN(pnode, vinMasternode.prevout, connman);
}
return false;
}
int nMinRequiredProtocol;
if(nBlockHeight >= nValidationHeight) {
// new votes must comply SPORK_10_MASTERNODE_PAY_UPDATED_NODES rules
nMinRequiredProtocol = mnpayments.GetMinMasternodePaymentsProto();
} else {
// allow non-updated masternodes for old blocks
nMinRequiredProtocol = MIN_MASTERNODE_PAYMENT_PROTO_VERSION_1;
}
if(mnInfo.nProtocolVersion < nMinRequiredProtocol) {
strError = strprintf("Masternode protocol is too old: nProtocolVersion=%d, nMinRequiredProtocol=%d", mnInfo.nProtocolVersion, nMinRequiredProtocol);
return false;
}
// Only masternodes should try to check masternode rank for old votes - they need to pick the right winner for future blocks.
// Regular clients (miners included) need to verify masternode rank for future block votes only.
if(!fMasterNode && nBlockHeight < nValidationHeight) return true;
int nRank;
if(!mnodeman.GetMasternodeRank(vinMasternode.prevout, nRank, nBlockHeight - 101, nMinRequiredProtocol)) {
LogPrint("mnpayments", "CMasternodePaymentVote::IsValid -- Can't calculate rank for masternode %s\n",
vinMasternode.prevout.ToStringShort());
return false;
}
if(nRank > MNPAYMENTS_SIGNATURES_TOTAL) {
// It's common to have masternodes mistakenly think they are in the top 10
// We don't want to print all of these messages in normal mode, debug mode should print though
strError = strprintf("Masternode is not in the top %d (%d)", MNPAYMENTS_SIGNATURES_TOTAL, nRank);
// Only ban for new mnw which is out of bounds, for old mnw MN list itself might be way too much off
if(nRank > MNPAYMENTS_SIGNATURES_TOTAL*2 && nBlockHeight > nValidationHeight) {
strError = strprintf("Masternode is not in the top %d (%d)", MNPAYMENTS_SIGNATURES_TOTAL*2, nRank);
LogPrintf("CMasternodePaymentVote::IsValid -- Error: %s\n", strError);
Misbehaving(pnode->GetId(), 20);
}
// Still invalid however
return false;
}
return true;
}
bool CMasternodePayments::ProcessBlock(int nBlockHeight, CConnman& connman)
{
// DETERMINE IF WE SHOULD BE VOTING FOR THE NEXT PAYEE
if(fLiteMode || !fMasterNode) return false;
// We have little chances to pick the right winner if winners list is out of sync
// but we have no choice, so we'll try. However it doesn't make sense to even try to do so
// if we have not enough data about masternodes.
if(!masternodeSync.IsMasternodeListSynced()) return false;
int nRank;
if (!mnodeman.GetMasternodeRank(activeMasternode.outpoint, nRank, nBlockHeight - 101, GetMinMasternodePaymentsProto())) {
LogPrint("mnpayments", "CMasternodePayments::ProcessBlock -- Unknown Masternode\n");
return false;
}
if (nRank > MNPAYMENTS_SIGNATURES_TOTAL) {
LogPrint("mnpayments", "CMasternodePayments::ProcessBlock -- Masternode not in the top %d (%d)\n", MNPAYMENTS_SIGNATURES_TOTAL, nRank);
return false;
}
// LOCATE THE NEXT MASTERNODE WHICH SHOULD BE PAID
LogPrintf("CMasternodePayments::ProcessBlock -- Start: nBlockHeight=%d, masternode=%s\n", nBlockHeight, activeMasternode.outpoint.ToStringShort());
// pay to the oldest MN that still had no payment but its input is old enough and it was active long enough
int nCount = 0;
masternode_info_t mnInfo;
if (!mnodeman.GetNextMasternodeInQueueForPayment(nBlockHeight, true, nCount, mnInfo)) {
LogPrintf("CMasternodePayments::ProcessBlock -- ERROR: Failed to find masternode to pay\n");
return false;
}
LogPrintf("CMasternodePayments::ProcessBlock -- Masternode found by GetNextMasternodeInQueueForPayment(): %s\n", mnInfo.vin.prevout.ToStringShort());
CScript payee = GetScriptForDestination(mnInfo.pubKeyCollateralAddress.GetID());
CMasternodePaymentVote voteNew(activeMasternode.outpoint, nBlockHeight, payee);
CTxDestination address1;
ExtractDestination(payee, address1);
CBitcoinAddress address2(address1);
LogPrintf("CMasternodePayments::ProcessBlock -- vote: payee=%s, nBlockHeight=%d\n", address2.ToString(), nBlockHeight);
// SIGN MESSAGE TO NETWORK WITH OUR MASTERNODE KEYS
LogPrintf("CMasternodePayments::ProcessBlock -- Signing vote\n");
if (voteNew.Sign()) {
LogPrintf("CMasternodePayments::ProcessBlock -- AddPaymentVote()\n");
if (AddPaymentVote(voteNew)) {
voteNew.Relay(connman);
return true;
}
}
return false;
}
void CMasternodePayments::CheckPreviousBlockVotes(int nPrevBlockHeight)
{
if (!masternodeSync.IsWinnersListSynced()) return;
std::string debugStr;
debugStr += strprintf("CMasternodePayments::CheckPreviousBlockVotes -- nPrevBlockHeight=%d, expected voting MNs:\n", nPrevBlockHeight);
CMasternodeMan::rank_pair_vec_t mns;
if (!mnodeman.GetMasternodeRanks(mns, nPrevBlockHeight - 101, GetMinMasternodePaymentsProto())) {
debugStr += "CMasternodePayments::CheckPreviousBlockVotes -- GetMasternodeRanks failed\n";
LogPrint("mnpayments", "%s", debugStr);
return;
}
LOCK2(cs_mapMasternodeBlocks, cs_mapMasternodePaymentVotes);
for (int i = 0; i < MNPAYMENTS_SIGNATURES_TOTAL && i < (int)mns.size(); i++) {
auto mn = mns[i];
CScript payee;
bool found = false;
if (mapMasternodeBlocks.count(nPrevBlockHeight)) {
for (auto &p : mapMasternodeBlocks[nPrevBlockHeight].vecPayees) {
for (auto &voteHash : p.GetVoteHashes()) {
if (!mapMasternodePaymentVotes.count(voteHash)) {
debugStr += strprintf("CMasternodePayments::CheckPreviousBlockVotes -- could not find vote %s\n",
voteHash.ToString());
continue;
}
auto vote = mapMasternodePaymentVotes[voteHash];
if (vote.vinMasternode.prevout == mn.second.vin.prevout) {
payee = vote.payee;
found = true;
break;
}
}
}
}
if (!found) {
debugStr += strprintf("CMasternodePayments::CheckPreviousBlockVotes -- %s - no vote received\n",
mn.second.vin.prevout.ToStringShort());
mapMasternodesDidNotVote[mn.second.vin.prevout]++;
continue;
}
CTxDestination address1;
ExtractDestination(payee, address1);
CBitcoinAddress address2(address1);
debugStr += strprintf("CMasternodePayments::CheckPreviousBlockVotes -- %s - voted for %s\n",
mn.second.vin.prevout.ToStringShort(), address2.ToString());
}
debugStr += "CMasternodePayments::CheckPreviousBlockVotes -- Masternodes which missed a vote in the past:\n";
for (auto it : mapMasternodesDidNotVote) {
debugStr += strprintf("CMasternodePayments::CheckPreviousBlockVotes -- %s: %d\n", it.first.ToStringShort(), it.second);
}
LogPrint("mnpayments", "%s", debugStr);
}
void CMasternodePaymentVote::Relay(CConnman& connman)
{
// Do not relay until fully synced
if(!masternodeSync.IsSynced()) {
LogPrint("mnpayments", "CMasternodePayments::Relay -- won't relay until fully synced\n");
return;
}
CInv inv(MSG_MASTERNODE_PAYMENT_VOTE, GetHash());
connman.RelayInv(inv);
}
bool CMasternodePaymentVote::CheckSignature(const CPubKey& pubKeyMasternode, int nValidationHeight, int &nDos)
{
// do not ban by default
nDos = 0;
std::string strMessage = vinMasternode.prevout.ToStringShort() +
boost::lexical_cast<std::string>(nBlockHeight) +
ScriptToAsmStr(payee);
std::string strError = "";
if (!CMessageSigner::VerifyMessage(pubKeyMasternode, vchSig, strMessage, strError)) {
// Only ban for future block vote when we are already synced.
// Otherwise it could be the case when MN which signed this vote is using another key now
// and we have no idea about the old one.
if(masternodeSync.IsMasternodeListSynced() && nBlockHeight > nValidationHeight) {
nDos = 20;
}
return error("CMasternodePaymentVote::CheckSignature -- Got bad Masternode payment signature, masternode=%s, error: %s", vinMasternode.prevout.ToStringShort().c_str(), strError);
}
return true;
}
std::string CMasternodePaymentVote::ToString() const
{
std::ostringstream info;
info << vinMasternode.prevout.ToStringShort() <<
", " << nBlockHeight <<
", " << ScriptToAsmStr(payee) <<
", " << (int)vchSig.size();
return info.str();
}
// Send only votes for future blocks, node should request every other missing payment block individually
void CMasternodePayments::Sync(CNode* pnode, CConnman& connman)
{
LOCK(cs_mapMasternodeBlocks);
if(!masternodeSync.IsWinnersListSynced()) return;
int nInvCount = 0;
for(int h = nCachedBlockHeight; h < nCachedBlockHeight + 20; h++) {
if(mapMasternodeBlocks.count(h)) {
BOOST_FOREACH(CMasternodePayee& payee, mapMasternodeBlocks[h].vecPayees) {
std::vector<uint256> vecVoteHashes = payee.GetVoteHashes();
BOOST_FOREACH(uint256& hash, vecVoteHashes) {
if(!HasVerifiedPaymentVote(hash)) continue;
pnode->PushInventory(CInv(MSG_MASTERNODE_PAYMENT_VOTE, hash));
nInvCount++;
}
}
}
}
LogPrintf("CMasternodePayments::Sync -- Sent %d votes to peer %d\n", nInvCount, pnode->id);
connman.PushMessage(pnode, NetMsgType::SYNCSTATUSCOUNT, MASTERNODE_SYNC_MNW, nInvCount);
}
// Request low data/unknown payment blocks in batches directly from some node instead of/after preliminary Sync.
void CMasternodePayments::RequestLowDataPaymentBlocks(CNode* pnode, CConnman& connman)
{
if(!masternodeSync.IsMasternodeListSynced()) return;
LOCK2(cs_main, cs_mapMasternodeBlocks);
std::vector<CInv> vToFetch;
int nLimit = GetStorageLimit();
const CBlockIndex *pindex = chainActive.Tip();
while(nCachedBlockHeight - pindex->nHeight < nLimit) {
if(!mapMasternodeBlocks.count(pindex->nHeight)) {
// We have no idea about this block height, let's ask
vToFetch.push_back(CInv(MSG_MASTERNODE_PAYMENT_BLOCK, pindex->GetBlockHash()));
// We should not violate GETDATA rules
if(vToFetch.size() == MAX_INV_SZ) {
LogPrintf("CMasternodePayments::SyncLowDataPaymentBlocks -- asking peer %d for %d blocks\n", pnode->id, MAX_INV_SZ);
connman.PushMessage(pnode, NetMsgType::GETDATA, vToFetch);
// Start filling new batch
vToFetch.clear();
}
}
if(!pindex->pprev) break;
pindex = pindex->pprev;
}
std::map<int, CMasternodeBlockPayees>::iterator it = mapMasternodeBlocks.begin();
while(it != mapMasternodeBlocks.end()) {
int nTotalVotes = 0;
bool fFound = false;
BOOST_FOREACH(CMasternodePayee& payee, it->second.vecPayees) {
if(payee.GetVoteCount() >= MNPAYMENTS_SIGNATURES_REQUIRED) {
fFound = true;
break;
}
nTotalVotes += payee.GetVoteCount();
}
// A clear winner (MNPAYMENTS_SIGNATURES_REQUIRED+ votes) was found
// or no clear winner was found but there are at least avg number of votes
if(fFound || nTotalVotes >= (MNPAYMENTS_SIGNATURES_TOTAL + MNPAYMENTS_SIGNATURES_REQUIRED)/2) {
// so just move to the next block
++it;
continue;
}
// DEBUG
DBG (
// Let's see why this failed
BOOST_FOREACH(CMasternodePayee& payee, it->second.vecPayees) {
CTxDestination address1;
ExtractDestination(payee.GetPayee(), address1);
CBitcoinAddress address2(address1);
printf("payee %s votes %d\n", address2.ToString().c_str(), payee.GetVoteCount());
}
printf("block %d votes total %d\n", it->first, nTotalVotes);
)
// END DEBUG
// Low data block found, let's try to sync it
uint256 hash;
if(GetBlockHash(hash, it->first)) {
vToFetch.push_back(CInv(MSG_MASTERNODE_PAYMENT_BLOCK, hash));
}
// We should not violate GETDATA rules
if(vToFetch.size() == MAX_INV_SZ) {
LogPrintf("CMasternodePayments::SyncLowDataPaymentBlocks -- asking peer %d for %d payment blocks\n", pnode->id, MAX_INV_SZ);
connman.PushMessage(pnode, NetMsgType::GETDATA, vToFetch);
// Start filling new batch
vToFetch.clear();
}
++it;
}
// Ask for the rest of it
if(!vToFetch.empty()) {
LogPrintf("CMasternodePayments::SyncLowDataPaymentBlocks -- asking peer %d for %d payment blocks\n", pnode->id, vToFetch.size());
connman.PushMessage(pnode, NetMsgType::GETDATA, vToFetch);
}
}
std::string CMasternodePayments::ToString() const
{
std::ostringstream info;
info << "Votes: " << (int)mapMasternodePaymentVotes.size() <<
", Blocks: " << (int)mapMasternodeBlocks.size();
return info.str();
}
bool CMasternodePayments::IsEnoughData()
{
float nAverageVotes = (MNPAYMENTS_SIGNATURES_TOTAL + MNPAYMENTS_SIGNATURES_REQUIRED) / 2;
int nStorageLimit = GetStorageLimit();
return GetBlockCount() > nStorageLimit && GetVoteCount() > nStorageLimit * nAverageVotes;
}
int CMasternodePayments::GetStorageLimit()
{
return std::max(int(mnodeman.size() * nStorageCoeff), nMinBlocksToStore);
}
void CMasternodePayments::UpdatedBlockTip(const CBlockIndex *pindex, CConnman& connman)
{
if(!pindex) return;
nCachedBlockHeight = pindex->nHeight;
LogPrint("mnpayments", "CMasternodePayments::UpdatedBlockTip -- nCachedBlockHeight=%d\n", nCachedBlockHeight);
int nFutureBlock = nCachedBlockHeight + 10;
CheckPreviousBlockVotes(nFutureBlock - 1);
ProcessBlock(nFutureBlock, connman);
}
| [
"matthew@wtech.software"
] | matthew@wtech.software |
9b89254c1be3dedee01e13f76cb3abaefa38a9fb | 012f0800c635f23d069f0c400768bc58cc1a0574 | /hhvm/hhvm-3.17/third-party/thrift/src/thrift/lib/cpp2/server/Cpp2Worker.h | 7663e7d30306e4fb776e4e1dbef0d533d5b746cd | [
"Apache-2.0",
"Zend-2.0",
"BSD-3-Clause",
"PHP-3.01"
] | permissive | chrispcx/es-hhvm | c127840387ee17789840ea788e308b711d3986a1 | 220fd9627b1b168271112d33747a233a91e8a268 | refs/heads/master | 2021-01-11T18:13:42.713724 | 2017-02-07T02:02:10 | 2017-02-07T02:02:10 | 79,519,670 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,382 | h | /*
* Copyright 2014 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef CPP2_WORKER_H_
#define CPP2_WORKER_H_ 1
#include <folly/io/async/AsyncServerSocket.h>
#include <thrift/lib/cpp/async/TAsyncSSLSocket.h>
#include <folly/io/async/HHWheelTimer.h>
#include <thrift/lib/cpp2/server/ThriftServer.h>
#include <thrift/lib/cpp2/server/TLSHelper.h>
#include <folly/io/async/EventBase.h>
#include <folly/io/async/EventHandler.h>
#include <thrift/lib/cpp/server/TServer.h>
#include <unordered_set>
#include <wangle/acceptor/ConnectionManager.h>
#include <wangle/acceptor/Acceptor.h>
#include <wangle/acceptor/PeekingAcceptorHandshakeHelper.h>
namespace apache { namespace thrift {
// Forward declaration of classes
class Cpp2Connection;
class ThriftServer;
/**
* Cpp2Worker drives the actual I/O for ThriftServer connections.
*
* The ThriftServer itself accepts incoming connections, then hands off each
* connection to a Cpp2Worker running in another thread. There should
* typically be around one Cpp2Worker thread per core.
*/
class Cpp2Worker
: public wangle::Acceptor,
private wangle::PeekingAcceptorHandshakeHelper::PeekCallback,
public std::enable_shared_from_this<Cpp2Worker> {
protected:
enum { kPeekCount = 9 };
struct DoNotUse {};
public:
/**
* Cpp2Worker is the actual server object for existing connections.
* One or more of these should be created by ThriftServer (one per
* CPU core is recommended).
*
* @param server the ThriftServer which created us.
* @param serverChannel existing server channel to use, only for duplex server
*/
static std::shared_ptr<Cpp2Worker>
create(ThriftServer* server,
const std::shared_ptr<HeaderServerChannel>& serverChannel = nullptr,
folly::EventBase* eventBase = nullptr) {
std::shared_ptr<Cpp2Worker> worker(new Cpp2Worker(server, {}));
worker->construct(server, serverChannel, eventBase);
return worker;
}
void init(
folly::AsyncServerSocket* serverSocket,
folly::EventBase* eventBase,
wangle::SSLStats* stats = nullptr) override {
securityProtocolCtxManager_.addPeeker(this);
Acceptor::init(serverSocket, eventBase, stats);
}
/**
* Get underlying server.
*
* @returns pointer to ThriftServer
*/
ThriftServer* getServer() const {
return server_;
}
/**
* Count the number of pending fds. Used for overload detection.
* Not thread-safe.
*/
int computePendingCount();
/**
* Cached pending count. Thread-safe.
*/
int getPendingCount() const;
/**
* SSL stats hook
*/
void updateSSLStats(
const folly::AsyncTransportWrapper* sock,
std::chrono::milliseconds acceptLatency,
wangle::SSLErrorEnum error,
wangle::SecureTransportType type = wangle::SecureTransportType::TLS)
noexcept override;
protected:
Cpp2Worker(ThriftServer* server,
DoNotUse /* ignored, never call constructor directly */) :
Acceptor(server->getServerSocketConfig()),
wangle::PeekingAcceptorHandshakeHelper::PeekCallback(kPeekCount),
server_(server),
activeRequests_(0),
pendingCount_(0),
pendingTime_(std::chrono::steady_clock::now()) {
}
void construct(ThriftServer* server,
const std::shared_ptr<HeaderServerChannel>& serverChannel,
folly::EventBase* eventBase) {
auto observer =
std::dynamic_pointer_cast<folly::EventBaseObserver>(
server_->getObserver());
if (serverChannel) {
eventBase = serverChannel->getEventBase();
} else if (!eventBase) {
eventBase = folly::EventBaseManager::get()->getEventBase();
}
init(nullptr, eventBase);
if (serverChannel) {
// duplex
useExistingChannel(serverChannel);
}
if (observer) {
eventBase->setObserver(observer);
}
}
void onNewConnection(folly::AsyncTransportWrapper::UniquePtr,
const folly::SocketAddress*,
const std::string&,
wangle::SecureTransportType,
const wangle::TransportInfo&) override;
SSLPolicy getSSLPolicy() {
return server_->getSSLPolicy();
}
void plaintextConnectionReady(
folly::AsyncTransportWrapper::UniquePtr sock,
const folly::SocketAddress& clientAddr,
const std::string& nextProtocolName,
wangle::SecureTransportType secureTransportType,
wangle::TransportInfo& tinfo) override;
private:
/// The mother ship.
ThriftServer* server_;
folly::AsyncSocket::UniquePtr makeNewAsyncSocket(folly::EventBase* base,
int fd) override {
return folly::AsyncSocket::UniquePtr(new apache::thrift::async::TAsyncSocket(base, fd));
}
folly::AsyncSSLSocket::UniquePtr makeNewAsyncSSLSocket(
const std::shared_ptr<folly::SSLContext>& ctx,
folly::EventBase* base,
int fd) override {
return folly::AsyncSSLSocket::UniquePtr(
new apache::thrift::async::TAsyncSSLSocket(
ctx,
base,
fd,
true, /* set server */
true /* defer the security negotiation until sslAccept. */));
}
/**
* For a duplex Thrift server, use an existing channel
*/
void useExistingChannel(
const std::shared_ptr<HeaderServerChannel>& serverChannel);
uint32_t activeRequests_;
int pendingCount_;
std::chrono::steady_clock::time_point pendingTime_;
wangle::AcceptorHandshakeHelper::UniquePtr getHelper(
const std::vector<uint8_t>& bytes,
wangle::Acceptor* acceptor,
const folly::SocketAddress& clientAddr,
std::chrono::steady_clock::time_point acceptTime,
wangle::TransportInfo& tinfo) override;
friend class Cpp2Connection;
friend class ThriftServer;
};
}} // apache::thrift
#endif // #ifndef CPP2_WORKER_H_
| [
"peiqiang@huawei.com"
] | peiqiang@huawei.com |
35cbefdcc55c48c74b15cbaf5a5d88c7438ef253 | be3c35d27245654e53c47619a485ef3d0e50901d | /C++/CPPDemos/vs code/advanceCPPconcept/advanceCPPconcept/dog.h | a661e11f34712febef6e112449852d8476c3b147 | [] | no_license | zzhan08/Exercises | 9aa6a439e36222806310eef50199250353291c4d | 1be3566206ead9cc329c809c7ad1a2f03c010056 | refs/heads/main | 2023-03-03T05:52:30.539181 | 2021-02-07T20:43:03 | 2021-02-07T20:43:03 | 336,820,822 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 262 | h | #ifndef DOG
#define DOG
#include <string>
#include<iostream>
class dog {
public:
dog(std::string name) { std::cout<< name <<"dog name"<< std::endl; };
//void destroyMe() { delete this; }
private:
~dog() { std::cout << "dog destory" << std::endl; };
};
#endif | [
"zhangz@innopharmalabs.com"
] | zhangz@innopharmalabs.com |
1fe29e17b5b819e0ef76d3332a6fb8e693a206d5 | d158af22290eed3794493d0a108b783b50fbe562 | /include/xdisplay.h | 5bc1ce78bdc82b37a3baa6c763cc6a8403a77006 | [] | no_license | kozal/dt_xdemo | deac70dfe10a8cc153ad600c7d188774f88b5477 | 625f460c00e92af0ec7252b47a1a5a27604c8196 | refs/heads/master | 2021-01-01T19:41:22.955719 | 2017-08-23T17:56:20 | 2017-08-23T17:56:20 | 98,651,217 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,505 | h | #ifndef XDISPLAY_H
#define XDISPLAY_H
#include "xconfigure.h"
#include "ximage.h"
#include "XDevice.h"
#define XDISPLAY_COLOR_GRAY 0
#define XDISPLAY_COLOR_SIN 1
#define XDISPLAY_COLOR_COS 2
#define XDISPLAY_COLOR_HOT 3
#define XDISPLAY_COLOR_JET 4
class XDDraw;
struct XWindow
{
float gama;
uint32_t start;
uint32_t end;
uint32_t max;
};
class XDLL_EXPORT XDisplay
{
public:
XDisplay(void);
~XDisplay(void);
bool Open(uint32_t width, uint32_t height, uint32_t pixel_depth, HWND hwnd, uint32_t color_mode = 0);
bool Open(XDevice* dev_, uint32_t line_num, HWND hwnd, uint32_t color_mode = 0);
void Close();
bool GetIsOpen();
bool GetIsDDrawEnable();
uint32_t GetLastError();
void SetGama(float gama_val);
float GetGama();
bool Display(XImage* image_);
//void Display(uint8_t* data_);
private:
XDisplay(const XDisplay&);
XDisplay& operator = (const XDisplay&);
void GetGrayImage();
void RotateGrayImage();
void DdrawDisplay();
void AutoSetWindow();
bool CreateBMI(uint32_t color_mode);
bool CreateLUT();
bool CreateGrayBuf();
//uint32_t GetPixelValue(uint32_t row, uint32_t col);
bool _is_open;
uint32_t _width;
uint32_t _height;
uint32_t _pixel_depth;
uint32_t _pixel_byte;
uint32_t _last_err;
XImage* _raw_data_;
uint8_t* _gray_data_;
uint8_t* _rot_gray_data_;
uint8_t* _lut_;
XDDraw* _ddraw_;
BITMAPINFO* _bmi_;
HWND _hwnd;
XWindow _window;
};
#endif //XDISPLAY_H
| [
"omer.kozal@metu.edu.tr"
] | omer.kozal@metu.edu.tr |
c920249bb24d45df93f0535776be6cc3c0cd678a | b0add032985c446093c20b0f00b57452a1b215b5 | /ReVA_AI/src/TP2/compute_histogram.cpp | f2d95e69dd6e3d0231dc25e10f1fa4c6b610f5be | [] | no_license | Alzahra/Tp_Analyse-Image | 95efdc01515a38553b44b13bb6f5f1e5b1548d12 | 685a220dc0a6f1d5756d1f62bf09c9da47d1a0b1 | refs/heads/master | 2020-04-01T09:27:09.816450 | 2018-10-15T08:07:22 | 2018-10-15T08:07:22 | 153,075,527 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,615 | cpp | #include "compute_histogram.h"
using namespace cv;
using namespace std;
/*contient les fonctions permettant
- de calculer
- d’afficher
l’histogramme d’une image en niveaux de gris*/
//void Compute_Histogram::setImage(Mat prec)
//{
// cout<<"setImage"<<endl;
// image =prec;
//
// cout<<"fin setImage"<<endl;
//
//}
Compute_Histogram::Compute_Histogram(Mat imagebase){
image = imagebase;
}
void Compute_Histogram::CalculHist()
{
/***HISTO IMAGE DE BASE****/
int nbpixel = image.rows * image.cols;
indmax =0;
//Initialisation
for (int i = 0; i <255; ++i){
histogram[i] = 0;
}
// calculate the number of pixels for each intensity values
for(int y = 0; y < image.rows; y++)
for(int x = 0; x < image.cols; x++)
histogram[(int)image.at<uchar>(y,x)]++;
// find the maximum intensity element from histogram
max = histogram[0];
for(int i = 0; i < 255; i++)
if(max < histogram[i]){
max = histogram[i];
indmax = i;
}
//Frequence
for(int i = 0; i<255;i++)
histd[i] = histogram[i]*100./(double)nbpixel;
//cout<<"indmax"<<indmax<<"histd[indmax] = "<<histd[indmax]<<endl;
/******HISTO IMAGE ETENDUE*****/
//Pour l'expansion on cherche les bornes
max = -1;
int i = 255;
while (max <0 && i>0){
if(histogram[i])
max = i;
i--;
}
//cout<<"max"<<max<<endl;
min = -1;
i =0;
while(min <0 && i<255){
if(histogram[i])
min = i;
i++;
}
//cout<<"min"<<min<<endl;
/* Calcul dans la classe image!expansion.cpp grâce aux bornes*/
/* Affichage de l'image reajuste */
}
void Compute_Histogram::Affiche()
{
//bins = intervals
int width = 512; int height = 100;
int bin_w = 2; //cvRound((double) hist_w/256);
Mat histImage(height, width, CV_8UC1, Scalar(255));
//Draw Histo de base
for(int i = 0; i < 255; i++)
line(histImage, Point(bin_w*i, height),
Point(bin_w*i, height - histd[i]*100/histd[indmax]),
Scalar(0));
//Affichage de l'image
namedWindow("Display window"); /* Create a window for display */
imshow( "Display window", image ); /* Show our image inside it */
// display histogram de base
namedWindow("Intensity Histogram", CV_WINDOW_AUTOSIZE);
imshow("Intensity Histogram", histImage);
}
double Compute_Histogram::getMax(){
return max;
}
double Compute_Histogram::getMin(){
return min;
}
| [
"h13003041@l-024110a018-20.local"
] | h13003041@l-024110a018-20.local |
a551659c8548d521bb5aca315f37dff820e35f3f | e2e993e83a4b766813f0f2d79acdfdd3680dafd5 | /CardGame2/CardGame2.cpp | b8a6b89840a13999a65746c2271132f87eb0135c | [] | no_license | jaconstantin/CardGames | ef97e1153fa0f47260b49b77ec4eeea1931a7472 | 6a9c527a7779b74fcefcbb75d8525c440ef2d95e | refs/heads/master | 2021-01-13T10:46:57.762438 | 2016-11-15T01:00:23 | 2016-11-15T01:00:23 | 72,382,690 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,140 | cpp | // CardGame2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "card.h"
int main()
{
CardDeck *deck0 = new CardDeck();
deck0->show();
deck0->shuffle();
deck0->show();
cout << endl << endl << endl;
OneCard a(deck0->draw());
cout << a.getHandString() << " " << a.getValue() << endl << endl;
//manual test for getting the value of a single card
for (int i = 0; i < 13; ++i) {
a.setCard(Card(clover,static_cast<cardNum_t>(i)));
cout << a.getHandString() << " " << a.getValue() << " " << a.isAllowed() << endl << endl;
}
for (int i = 0; i < 4; ++i) {
a.setCard(Card(static_cast<cardSuit_t>(i), three));
cout << a.getHandString() << " " << a.getValue() << endl << endl;
}
//manual test for pairCards, allowed and getValue
Card b[2] = { Card(clover,three),Card(heart,three) };
PairCard pc1(b);
cout << pc1.getHandString() << " " << pc1.getValue() << " " << pc1.isAllowed() << endl << endl;
b[0] = Card(diamond, four);
b[1] = Card(spade, four);
pc1.setCard(b);
cout << pc1.getHandString() << " " << pc1.getValue() << " " << pc1.isAllowed() << endl << endl;
b[0] = Card(clover, four);
b[1] = Card(spade, five);
pc1.setCard(b);
cout << pc1.getHandString() << " " << pc1.getValue() << " " << pc1.isAllowed() << endl << endl;
//manual test for FiveCards, constructor and sort
Card c[5] = { Card(clover,three), Card(heart,four), Card(spade,five), Card(diamond,six), Card(clover,ace) };
FiveCard fc1(c);
cout << fc1.getHandString() << " ";
cout << fc1.getHandString() << endl << endl;
for (int i = 0; i < 5; ++i) {
c[i] = deck0->draw();
}
fc1.setCard(c);
cout << fc1.getHandString() << " ";
fc1.sort();
cout << fc1.getHandString() << endl << endl;
//manual test for allowed straight/flush/full house
//need to make is##### functions public if you want to remove the comment parts
c[0] = Card(clover,ace);
c[1] = Card(clover,two);
c[2] = Card(heart,three);
c[3] = Card(spade,four);
c[4] = Card(diamond,five);
fc1.setCard(c);
//cout << fc1.getHandString() << " " << fc1.isStraight() << " " << fc1.isFlush() << " " << fc1.isFullHouse() << " " << fc1.isQuadro() << endl << endl;
cout << fc1.getHandString() << " " << fc1.getStringType() << " " << fc1.isAllowed() << " " << fc1.getValue() << endl;
c[0] = Card(clover, ace);
c[1] = Card(clover, two);
c[2] = Card(heart, jack);
c[3] = Card(spade, queen);
c[4] = Card(diamond, king);
fc1.setCard(c);
//cout << fc1.getHandString() << " " << fc1.isStraight() << " " << fc1.isFlush() << " " << fc1.isFullHouse() << " " << fc1.isQuadro() << endl << endl;
cout << fc1.getHandString() << " " << fc1.getStringType() << " " << fc1.isAllowed() << " " << fc1.getValue() << endl;
c[0] = Card(clover, three);
c[1] = Card(clover, four);
c[2] = Card(heart, six);
c[3] = Card(spade, seven);
c[4] = Card(diamond, five);
fc1.setCard(c);
//cout << fc1.getHandString() << " " << fc1.isStraight() << " " << fc1.isFlush() << " " << fc1.isFullHouse() << " " << fc1.isQuadro() << endl << endl;
cout << fc1.getHandString() << " " << fc1.getStringType() << " " << fc1.isAllowed() << " " << fc1.getValue() << endl;
c[0] = Card(clover, three);
c[1] = Card(clover, four);
c[2] = Card(heart, three);
c[3] = Card(spade, six);
c[4] = Card(diamond, five);
fc1.setCard(c);
//cout << fc1.getHandString() << " " << fc1.isStraight() << " " << fc1.isFlush() << " " << fc1.isFullHouse() << " " << fc1.isQuadro() << endl << endl;
cout << fc1.getHandString() << " " << fc1.getStringType() << " " << fc1.isAllowed() << " " << fc1.getValue() << endl;
c[0] = Card(clover, three);
c[1] = Card(clover, four);
c[2] = Card(clover, six);
c[3] = Card(clover, seven);
c[4] = Card(clover, five);
fc1.setCard(c);
//cout << fc1.getHandString() << " " << fc1.isStraight() << " " << fc1.isFlush() << " " << fc1.isFullHouse() << " " << fc1.isQuadro() << endl << endl;
cout << fc1.getHandString() << " " << fc1.getStringType() << " " << fc1.isAllowed() << " " << fc1.getValue() << endl;
c[0] = Card(spade, jack);
c[1] = Card(spade, queen);
c[2] = Card(spade, two);
c[3] = Card(spade, ten);
c[4] = Card(spade, eight);
fc1.setCard(c);
//cout << fc1.getHandString() << " " << fc1.isStraight() << " " << fc1.isFlush() << " " << fc1.isFullHouse() << " " << fc1.isQuadro() << endl << endl;
cout << fc1.getHandString() << " " << fc1.getStringType() << " " << fc1.isAllowed() << " " << fc1.getValue() << endl;
c[0] = Card(heart, three);
c[1] = Card(heart, four);
c[2] = Card(heart, three);
c[3] = Card(heart, six);
c[4] = Card(heart, five);
fc1.setCard(c);
//cout << fc1.getHandString() << " " << fc1.isStraight() << " " << fc1.isFlush() << " " << fc1.isFullHouse() << " " << fc1.isQuadro() << endl << endl;
cout << fc1.getHandString() << " " << fc1.getStringType() << " " << fc1.isAllowed() << " " << fc1.getValue() << endl;
c[0] = Card(spade, three);
c[1] = Card(heart, eight);
c[2] = Card(spade, eight);
c[3] = Card(clover, three);
c[4] = Card(diamond, eight);
fc1.setCard(c);
//cout << fc1.getHandString() << " " << fc1.isStraight() << " " << fc1.isFlush() << " " << fc1.isFullHouse() << " " << fc1.isQuadro() << endl << endl;
cout << fc1.getHandString() << " " << fc1.getStringType() << " " << fc1.isAllowed() << " " << fc1.getValue() << endl;
c[0] = Card(spade, two);
c[1] = Card(heart, eight);
c[2] = Card(spade, eight);
c[3] = Card(clover, two);
c[4] = Card(diamond, two);
fc1.setCard(c);
//cout << fc1.getHandString() << " " << fc1.isStraight() << " " << fc1.isFlush() << " " << fc1.isFullHouse() << " " << fc1.isQuadro() << endl << endl;
cout << fc1.getHandString() << " " << fc1.getStringType() << " " << fc1.isAllowed() << " " << fc1.getValue() << endl;
c[0] = Card(spade, two);
c[1] = Card(heart, king);
c[2] = Card(spade, eight);
c[3] = Card(clover, two);
c[4] = Card(diamond, two);
fc1.setCard(c);
//cout << fc1.getHandString() << " " << fc1.isStraight() << " " << fc1.isFlush() << " " << fc1.isFullHouse() << " " << fc1.isQuadro() << endl << endl;
cout << fc1.getHandString() << " " << fc1.getStringType() << " " << fc1.isAllowed() << " " << fc1.getValue() << endl;
c[0] = Card(spade, eight);
c[1] = Card(heart, eight);
c[2] = Card(diamond, eight);
c[3] = Card(clover, eight);
c[4] = Card(diamond, two);
fc1.setCard(c);
//cout << fc1.getHandString() << " " << fc1.isStraight() << " " << fc1.isFlush() << " " << fc1.isFullHouse() << " " << fc1.isQuadro() << endl << endl;
cout << fc1.getHandString() << " " << fc1.getStringType() << " " << fc1.isAllowed() << " " << fc1.getValue() << endl;
c[0] = Card(spade, ace);
c[1] = Card(heart, ace);
c[2] = Card(spade, eight);
c[3] = Card(clover, ace);
c[4] = Card(diamond, ace);
fc1.setCard(c);
//cout << fc1.getHandString() << " " << fc1.isStraight() << " " << fc1.isFlush() << " " << fc1.isFullHouse() << " " << fc1.isQuadro() << endl << endl;
cout << fc1.getHandString() << " " << fc1.getStringType() << " " << fc1.isAllowed() << " " << fc1.getValue() << endl;
delete deck0;
return 0;
}
| [
"oteph113@gmail.com"
] | oteph113@gmail.com |
802530f7f5b85133af1f469ecaff91adfe7b1fb1 | 1e31ca8eded98e4ec4de4d732710b9b5bdcd531a | /week_5_ParticleDraw/src/Particle.h | 6d372bb0bf34ffa1d62750eb5e3b1fc81634a9c7 | [] | no_license | josephrmoore/moore_algo2013 | 6ac4c8c48faeccd7d76edb5ca1005ab77cb38ce6 | 493e713c7f8ccc236188386ee2b1783dc5440955 | refs/heads/master | 2021-01-23T16:35:57.861000 | 2013-12-13T23:09:06 | 2013-12-13T23:09:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 548 | h | //
// Particle.h
// SingleParticle
//
// Created by Charlie Whitney on 9/23/13.
//
//
#pragma once
#include "ofMain.h"
class Particle {
public:
Particle();
void update();
void draw(float radius, ofColor color);
void setParams( float px, float py, float vx, float vy );
void addForce( ofVec2f force );
void addDampingForce();
void resetForces();
ofVec2f pos;
ofVec2f vel;
ofVec2f frc;
ofVec2f damping; // could also be a ofVec2f
ofVideoPlayer img;
ofColor color;
}; | [
"josephrmoore@gmail.com"
] | josephrmoore@gmail.com |
08c2e337822ff1cf0c6da76c47c35780842714e3 | f435486913aa9c997319146fa0b71479d4c09846 | /h/directlightDlg.h | bd2a16b7286a1a2203b9bf2a7b1592d53ce77767 | [] | no_license | SnowyOwl-KHY/3DStudio | a60051e211c88e7e0034ed581437ffe64c8d586f | 3323aa3db689a372d719fea3821628f9ce0fae7e | refs/heads/master | 2020-04-09T05:13:50.200929 | 2015-08-31T18:53:06 | 2015-08-31T18:53:06 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 826 | h | #pragma once
#include "afxwin.h"
// directlightDlg 对话框
class directlightDlg : public CDialog
{
DECLARE_DYNAMIC(directlightDlg)
DirectLight &light;
public:
directlightDlg(DirectLight& l, CWnd* pParent = NULL); // 标准构造函数
virtual ~directlightDlg();
// 对话框数据
enum { IDD = IDD_DIALOG_DIRECTLIGHT };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
DECLARE_MESSAGE_MAP()
public:
virtual BOOL OnInitDialog();
CEdit mEditX;
CEdit mEditY;
CEdit mEditZ;
CEdit mEditAR;
CEdit mEditAG;
CEdit mEditAB;
CEdit mEditAA;
CEdit mEditDR;
CEdit mEditDG;
CEdit mEditDB;
CEdit mEditDA;
CEdit mEditSR;
CEdit mEditSG;
CEdit mEditSB;
CEdit mEditSA;
CEdit mEditX2;
CEdit mEditY2;
CEdit mEditZ2;
CEdit mEditCutoff;
CEdit mEditExpo;
virtual void OnOK();
};
| [
"kehycs@foxmail.com"
] | kehycs@foxmail.com |
8b8d818bd9ed4f80e62ae6ed2cbb2a4cfea70eb2 | d732c881b57ef5e3c8f8d105b2f2e09b86bcc3fe | /src/module-ml/VType_Conv2d.cpp | 46671d36358badfeb93c31ea014748f302836d62 | [] | no_license | gura-lang/gurax | 9180861394848fd0be1f8e60322b65a92c4c604d | d9fedbc6e10f38af62c53c1bb8a4734118d14ce4 | refs/heads/master | 2023-09-01T09:15:36.548730 | 2023-09-01T08:49:33 | 2023-09-01T08:49:33 | 160,017,455 | 10 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,385 | cpp | //==============================================================================
// VType_Conv2d.cpp
//==============================================================================
#include "stdafx.h"
Gurax_BeginModuleScope(ml)
//------------------------------------------------------------------------------
// Help
//------------------------------------------------------------------------------
static const char* g_docHelp_en = u8R"""(
# Overview
# Predefined Variable
${help.ComposePropertyHelp(ml.Conv2d, `en)}
# Operator
# Cast Operation
${help.ComposeConstructorHelp(ml.Conv2d, `en)}
${help.ComposeMethodHelp(ml.Conv2d, `en)}
)""";
//------------------------------------------------------------------------------
// Implementation of constructor
//------------------------------------------------------------------------------
// ml.Conv2d(nFilters as Number, nRowsFilter as Number, nColsFilter as Number, stride? as Number, padding? as Number) {block?}
Gurax_DeclareConstructor(Conv2d)
{
Declare(VTYPE_Conv2d, Flag::None);
DeclareArg("nFilters", VTYPE_Number, ArgOccur::Once, ArgFlag::None);
DeclareArg("nRowsFilter", VTYPE_Number, ArgOccur::Once, ArgFlag::None);
DeclareArg("nColsFilter", VTYPE_Number, ArgOccur::Once, ArgFlag::None);
DeclareArg("stride", VTYPE_Number, ArgOccur::ZeroOrOnce, ArgFlag::None);
DeclareArg("padding", VTYPE_Number, ArgOccur::ZeroOrOnce, ArgFlag::None);
DeclareBlock(BlkOccur::ZeroOrOnce);
AddHelp(Gurax_Symbol(en), u8R"""(
Creates a `ml.Conv2d` instance.
)""");
}
Gurax_ImplementConstructor(Conv2d)
{
// Arguments
ArgPicker args(argument);
size_t nFilters = args.PickNumberPos<size_t>();
size_t nRowsFilter = args.PickNumberPos<size_t>();
size_t nColsFilter = args.PickNumberPos<size_t>();
size_t stride = args.IsValid()? args.PickNumberPos<size_t>() : 1;
size_t padding = args.IsValid()? args.PickNumberNonNeg<size_t>() : 0;
if (Error::IsIssued()) return Value::nil();
// Function body
RefPtr<Conv2d> pConv2d(new Conv2d(nFilters, nRowsFilter, nColsFilter, stride, padding));
return argument.ReturnValue(processor, new Value_Conv2d(pConv2d.release()));
}
//-----------------------------------------------------------------------------
// Implementation of class method
//-----------------------------------------------------------------------------
// Conv2d.Preset(filter as Array, bias? as Array, stride? as Number, padding? as Number) {block?}
Gurax_DeclareClassMethod(Conv2d, Preset)
{
Declare(VTYPE_Number, Flag::None);
DeclareArg("filter", VTYPE_Array, ArgOccur::Once, ArgFlag::None);
DeclareArg("bias", VTYPE_Array, ArgOccur::ZeroOrOnce, ArgFlag::None);
DeclareArg("stride", VTYPE_Number, ArgOccur::ZeroOrOnce, ArgFlag::None);
DeclareArg("padding", VTYPE_Number, ArgOccur::ZeroOrOnce, ArgFlag::None);
DeclareBlock(BlkOccur::ZeroOrOnce);
AddHelp(Gurax_Symbol(en), u8R"""(
)""");
}
Gurax_ImplementClassMethod(Conv2d, Preset)
{
// Arguments
ArgPicker args(argument);
const Array& arrayFilter = args.Pick<Value_Array>().GetArray();
RefPtr<Array> pArrayBias(args.IsValid()? args.Pick<Value_Array>().GetArray().Reference() : Array::none());
size_t stride = args.IsValid()? args.PickNumberPos<size_t>() : 1;
size_t padding = args.IsValid()? args.PickNumberNonNeg<size_t>() : 0;
if (Error::IsIssued()) return Value::nil();
if (arrayFilter.GetDimSizes().size() != 4) {
Error::Issue(ErrorType::SizeError, "filter must be an Array of four dimensions");
return Value::nil();
}
if (!pArrayBias->IsNone() && pArrayBias->GetDimSizes().size() != 3) {
Error::Issue(ErrorType::SizeError, "bias must be an Array of three dimensions");
return Value::nil();
}
// Function body
RefPtr<Conv2d> pConv2d(new Conv2d(arrayFilter.Reference(), pArrayBias.release(), stride, padding));
return argument.ReturnValue(processor, new Value_Conv2d(pConv2d.release()));
}
//-----------------------------------------------------------------------------
// Implementation of property
//-----------------------------------------------------------------------------
// ml.Conv2d#nFilters
Gurax_DeclareProperty_R(Conv2d, nFilters)
{
Declare(VTYPE_Number, Flag::None);
}
Gurax_ImplementPropertyGetter(Conv2d, nFilters)
{
auto& valueThis = GetValueThis(valueTarget);
return new Value_Number(valueThis.GetConv2d().GetNFilters());
}
// ml.Conv2d#nRowsFilter
Gurax_DeclareProperty_R(Conv2d, nRowsFilter)
{
Declare(VTYPE_Number, Flag::None);
}
Gurax_ImplementPropertyGetter(Conv2d, nRowsFilter)
{
auto& valueThis = GetValueThis(valueTarget);
return new Value_Number(valueThis.GetConv2d().GetNRowsFilter());
}
// ml.Conv2d#nColsFilter
Gurax_DeclareProperty_R(Conv2d, nColsFilter)
{
Declare(VTYPE_Number, Flag::None);
}
Gurax_ImplementPropertyGetter(Conv2d, nColsFilter)
{
auto& valueThis = GetValueThis(valueTarget);
return new Value_Number(valueThis.GetConv2d().GetNColsFilter());
}
// ml.Conv2d#stride
Gurax_DeclareProperty_R(Conv2d, stride)
{
Declare(VTYPE_Number, Flag::None);
}
Gurax_ImplementPropertyGetter(Conv2d, stride)
{
auto& valueThis = GetValueThis(valueTarget);
return new Value_Number(valueThis.GetConv2d().GetStride());
}
// ml.Conv2d#padding
Gurax_DeclareProperty_R(Conv2d, padding)
{
Declare(VTYPE_Number, Flag::None);
}
Gurax_ImplementPropertyGetter(Conv2d, padding)
{
auto& valueThis = GetValueThis(valueTarget);
return new Value_Number(valueThis.GetConv2d().GetPadding());
}
// ml.Conv2d#filter
Gurax_DeclareProperty_R(Conv2d, filter)
{
Declare(VTYPE_Array, Flag::None);
AddHelp(Gurax_Symbol(en), u8R"""(
Skeleton.
)""");
}
Gurax_ImplementPropertyGetter(Conv2d, filter)
{
Conv2d& conv2d = GetValueThis(valueTarget).GetConv2d();
return conv2d.HasArrayFilter()? conv2d.GetArrayFilter().ToValue() : Value::nil();
}
// ml.Conv2d#filterGrad
Gurax_DeclareProperty_R(Conv2d, filterGrad)
{
Declare(VTYPE_Array, Flag::None);
AddHelp(Gurax_Symbol(en), u8R"""(
Skeleton.
)""");
}
Gurax_ImplementPropertyGetter(Conv2d, filterGrad)
{
Conv2d& conv2d = GetValueThis(valueTarget).GetConv2d();
return conv2d.HasArrayFilterGrad()? conv2d.GetArrayFilterGrad().ToValue() : Value::nil();
}
// ml.Conv2d#bias
Gurax_DeclareProperty_R(Conv2d, bias)
{
Declare(VTYPE_Array, Flag::None);
AddHelp(Gurax_Symbol(en), u8R"""(
Skeleton.
)""");
}
Gurax_ImplementPropertyGetter(Conv2d, bias)
{
Conv2d& conv2d = GetValueThis(valueTarget).GetConv2d();
return conv2d.HasArrayBias()? conv2d.GetArrayBias().ToValue() : Value::nil();
}
// ml.Conv2d#biasGrad
Gurax_DeclareProperty_R(Conv2d, biasGrad)
{
Declare(VTYPE_Array, Flag::None);
AddHelp(Gurax_Symbol(en), u8R"""(
Skeleton.
)""");
}
Gurax_ImplementPropertyGetter(Conv2d, biasGrad)
{
Conv2d& conv2d = GetValueThis(valueTarget).GetConv2d();
return conv2d.HasArrayBiasGrad()? conv2d.GetArrayBiasGrad().ToValue() : Value::nil();
}
//------------------------------------------------------------------------------
// VType_Conv2d
//------------------------------------------------------------------------------
VType_Conv2d VTYPE_Conv2d("Conv2d");
void VType_Conv2d::DoPrepare(Frame& frameOuter)
{
// Add help
AddHelp(Gurax_Symbol(en), g_docHelp_en);
// Declaration of VType
Declare(VTYPE_Gear, Flag::Immutable, Gurax_CreateConstructor(Conv2d));
// Assignment of class method
Assign(Gurax_CreateClassMethod(Conv2d, Preset));
// Assignment of property
Assign(Gurax_CreateProperty(Conv2d, nFilters));
Assign(Gurax_CreateProperty(Conv2d, nRowsFilter));
Assign(Gurax_CreateProperty(Conv2d, nColsFilter));
Assign(Gurax_CreateProperty(Conv2d, stride));
Assign(Gurax_CreateProperty(Conv2d, padding));
Assign(Gurax_CreateProperty(Conv2d, filter));
Assign(Gurax_CreateProperty(Conv2d, filterGrad));
Assign(Gurax_CreateProperty(Conv2d, bias));
Assign(Gurax_CreateProperty(Conv2d, biasGrad));
}
//------------------------------------------------------------------------------c
// Value_Conv2d
//------------------------------------------------------------------------------
VType& Value_Conv2d::vtype = VTYPE_Conv2d;
String Value_Conv2d::ToString(const StringStyle& ss) const
{
return ToStringGeneric(ss, GetConv2d().ToString(ss));
}
bool Value_Conv2d::DoSerialize(Stream& stream) const
{
return GetConv2d().Serialize(stream);
}
Value* VType_Conv2d::DoDeserialize(Stream& stream) const
{
RefPtr<Conv2d> pConv2d(Conv2d::Deserialize(stream));
return pConv2d? new Value_Conv2d(pConv2d.release()) : nullptr;
}
Gurax_EndModuleScope(ml)
| [
"ypsitau@nifty.com"
] | ypsitau@nifty.com |
e67de3627a3b4812d90c1e8c9686c79431c8ac00 | 21c3202b44ed91bfe46adbecf4692ab3e0252a2e | /Project2_Baseball_sprint3/tripplannerwindow.cpp | b68de0871d4a91533b975182a0d9042968553f5c | [] | no_license | afrederick89/Projects | 3c2d7cbbd8973fc808c9cb371f23ca9929995ff3 | 7798e8ee07e836131a99e9022e527a0750a8f877 | refs/heads/master | 2022-03-10T17:25:50.913005 | 2019-11-02T00:44:02 | 2019-11-02T00:44:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,881 | cpp | #include "tripplannerwindow.h"
#include "ui_tripplannerwindow.h"
#include <QAbstractItemView>
#include <QMessageBox>
#include "draggablelistmodel.h"
#include <QQueue>
#include "mainmenu.h"
#include <QRegExp>
TripPlannerWindow::TripPlannerWindow(QWidget *parent) :
QWidget(parent),
ui(new Ui::TripPlannerWindow)
{
ui->setupUi(this);
ui->stackedWidget->setStyleSheet("background:url(\":/rc/bkgd.jpg\");");
dijkstrasShortestPath = false;
mostEfficientlyVisitAll = false;
ui->visitAllTeamsMostEfficiently->hide();
QList<Team> teams = SQLManager::getInstance()->getAllTeams();
// Dijkstras shortest path trip
totalDistanceTraveled = 0;
populateGraph();
for (int i=0; i < teams.size(); i++) {
ui->startingStadiumComboBox->addItem(teams.at(i).teamName, teams.at(i).teamName);
}
ui->souvenirsListView->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->shoppingCartListView->setModel(new QStringListModel(this));
ui->shoppingCartListView->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->shoppingCartListView->hide();
ui->shoppingCartLabel->hide();
this->teams = teams;
// User ordered trip:
QStringList teamList;
DraggableListModel* model = new DraggableListModel; // subclassed QStringListModel for drag-drop feature items
for (auto team : teams) {
ui->teamListComboBox->addItem(team.teamName);
}
ui->orderableListView->setModel(model);
ui->orderableListView->setDragDropMode(QAbstractItemView::InternalMove);
ui->orderableListView->setEditTriggers(QAbstractItemView::NoEditTriggers);
}
TripPlannerWindow::~TripPlannerWindow()
{
delete ui;
}
bool TripPlannerWindow::stadiumListContainsStadium(Team searchStadium, QList<Team> list) {
bool contains = false;
// Determines if list contains searchStadium
for (auto stadium : list) {
if (stadium.stadiumName == searchStadium.stadiumName) {
contains = true;
}
}
return contains;
}
void TripPlannerWindow::populateGraph() {
SQLManager* sqlManager = SQLManager::getInstance();
QList<Team> teams = sqlManager->getAllTeams();
QList<Vertex*> vertexList;
// First, allocate memory for all vertices in database, with empty edge lists for now
for (auto team : teams) {
Vertex* newVertex = new Vertex(team, QList<Edge*>());
vertexList.push_back(newVertex);
}
// NEXT, loop through the list of vertices that we JUST populated, and see if it has any adjacent teams
// We have to do it this way so that the pointers in each stadium's edgelist is the same address location as each vertex pointer in vertexList
for (int i=0; i < vertexList.size(); i++) {
Vertex* currVertex = vertexList.at(i);
QList<Team> trulyAdjacentStadiums = sqlManager->getAdjacentStadiums(currVertex);
QList<Edge*> edgeList;
for (auto potentiallyAdjacentStadium : vertexList) {
Team stadium = potentiallyAdjacentStadium->data;
if (stadiumListContainsStadium(stadium, trulyAdjacentStadiums)) {
int weightBetween = sqlManager->getWeightBetween(potentiallyAdjacentStadium, currVertex);
if (weightBetween == -1) {
qDebug() << "Error encountered, tripplannerwindow::populateGraph";
}
Edge* newEdge = new Edge(potentiallyAdjacentStadium, weightBetween);
edgeList.push_back(newEdge);
// qDebug() << currVertex->data.stadiumName << " has edge to " << newEdge->destination->data.stadiumName << " with weight << " << weightBetween;
}
}
currVertex->edges = edgeList;
}
Graph* newGraph = new Graph(vertexList);
this->graph = newGraph;
}
void TripPlannerWindow::on_startingStadiumComboBox_currentIndexChanged(int index)
{
QList<Team> teams = SQLManager::getInstance()->getAllTeams();
for (int i=0; i < teams.size(); i++) {
ui->destinationStadiumComboBox->addItem(teams.at(i).teamName, teams.at(i).teamName);
}
this->originStadium = SQLManager::getInstance()->getTeamByName(teams.at(index).teamName);
}
void TripPlannerWindow::on_mostEfficientTripButton_clicked()
{
dijkstrasShortestPath = true;
// ui->destinationTeamLabel->setText("Press the \"Take Trip\" button to take the shortest path from " + originStadium.teamName + " to " + destination->data.teamName);
ui->stackedWidget->setCurrentIndex(1);
}
// NOTE: The origin has to be the same origin that was used in the previously completed dijkstra's traversal
void TripPlannerWindow::determineDijkstraPath(Vertex* origin, Vertex* destination, QList<Vertex*>& path) {
if (origin == destination) {
return;
}
if (destination->parent != NULL && origin != destination) {
path.push_back(destination);
determineDijkstraPath(origin, destination->parent, path);
}
}
void TripPlannerWindow::populateStadiumInfo(Vertex* vertex) {
QStringList souvenirsList;
QStringListModel* souvenirListModel = new QStringListModel(this);
QList<Souvenir> souvenirs = SQLManager::getInstance()->getSouvenirsByStadium(vertex->data.stadiumName);
ui->currentTeamLabel->setText("Currently visiting: " + vertex->data.teamName);
ui->currentStadiumLabel->setText("Stadium name: " + vertex->data.stadiumName);
for (auto souvenir : souvenirs) {
souvenirsList << "Item name: " + souvenir.itemName + "\nItem Price: " + QString::number(souvenir.itemCost, 'f', 2) + "\n\n";
}
souvenirListModel->setStringList(souvenirsList);
ui->souvenirsListView->setModel(souvenirListModel);
this->currentTeamSouvenirList = souvenirs;
}
void TripPlannerWindow::on_beginTripButton_clicked() {
QStringList teamNameList;
// Get all of the vertices (stadiums) in the map
QList<Vertex*> vertexList = this->graph->GetAllVertices();
QMap<Vertex*, int> distances;
QString originTeamName = ui->startingStadiumComboBox->currentData().toString();
QString destinationTeamName = ui->destinationStadiumComboBox->currentData().toString();
Vertex* origin = graph->getVertexByTeamName(originTeamName);
this->destination = graph->getVertexByTeamName(destinationTeamName);
this->graph->Dijkstras(origin, distances);
qDebug() << "Calculating shortest path from " << origin->data.teamName << " to " << destination->data.teamName;
QList<Vertex*> path;
for (auto vertex : vertexList) {
if (vertex == destination) {
determineDijkstraPath(origin, destination, path);
}
}
QString pathString;
// unelegant reverse loop lol
for (int i = (path.size() - 1); i >= 0; i--) {
this->tripPathQueue.push_back(path[i]->parent);
}
this->tripPathQueue.push_back(destination);
for (auto path : tripPathQueue) {
qDebug() << "Pit stop: " << path->data.stadiumName;
}
this->tripPathQueue = tripPathQueue;
ui->stackedWidget->setCurrentIndex(2);
// begins the trip at the origin
populateStadiumInfo(this->tripPathQueue.front());
ui->totalDistanceTraveled->hide();
ui->totalDistanceTraveled->setText("Total Distance Traveled: " + QString::number(distances[destination]) + " mi");
}
void TripPlannerWindow::updateShoppingCart(CartItem newCartItem) {
QAbstractItemModel* model = ui->shoppingCartListView->model();
QStringList list = static_cast<QStringListModel*>(model)->stringList();
list << "► " + newCartItem.item.itemName + " | $" + QString::number(newCartItem.item.itemCost, 'f', 2) + "\n\n";
static_cast<QStringListModel*>(model)->setStringList(list);
ui->shoppingCartListView->setModel(static_cast<QStringListModel*>(model));
}
void TripPlannerWindow::on_souvenirsListView_doubleClicked(const QModelIndex &index)
{
// Show the shopping cart list view if this is the first item added to the cart
if (shoppingCart.isEmpty()) {
ui->shoppingCartListView->show();
ui->shoppingCartLabel->show();
}
Team stadiumPurchasedAt = SQLManager::getInstance()->getTeamByName(this->currentTeamSouvenirList[index.row()].stadiumName);
Souvenir souvenirPurchased = this->currentTeamSouvenirList.at(index.row());
CartItem newCartItem(souvenirPurchased, stadiumPurchasedAt);
shoppingCart.push_back(newCartItem);
updateShoppingCart(newCartItem);
}
void TripPlannerWindow::on_shoppingCartListView_doubleClicked(const QModelIndex &index)
{
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this, "", "Are you sure you want to remove " + shoppingCart.at(index.row()).item.itemName + " from your cart?",
QMessageBox::Yes|QMessageBox::No);
if (reply == QMessageBox::Yes) {
this->shoppingCart.at(index.row());
QAbstractItemModel* model = ui->shoppingCartListView->model();
model->removeRow(index.row());
ui->shoppingCartListView->setModel(static_cast<QStringListModel*>(model));
}
}
void TripPlannerWindow::on_takeTripButton_clicked()
{
// END OF TRIP
if (ui->takeTripButton->text() == "End Trip") {
if (!this->shoppingCart.isEmpty()) {
// TO DO: Souvenir order list and summary page
QList<CartItem> finalShoppingCart;
QStringListModel* model = new QStringListModel;
model = static_cast<QStringListModel*>(ui->shoppingCartListView->model());
QStringList list = model->stringList();
QStringList formattedSummaryPage;
Team currentTeam = shoppingCart.at(0).stadiumPurchasedAt;
formattedSummaryPage << currentTeam.teamName + " @ " + currentTeam.stadiumName + "\n"
"----------------------------------\n";
double stadiumGrandTotal = 0;
double grandTotal = 0;
for (auto cartItem : shoppingCart) {
if (cartItem.stadiumPurchasedAt.stadiumName != currentTeam.stadiumName) {
currentTeam = cartItem.stadiumPurchasedAt;
formattedSummaryPage << "Total: $" + QString::number(stadiumGrandTotal, 'f', 2) + "\n\n";
stadiumGrandTotal = 0;
formattedSummaryPage << cartItem.stadiumPurchasedAt.teamName + " @ " + cartItem.stadiumPurchasedAt.stadiumName + "\n"
"----------------------------------\n";
}
stadiumGrandTotal += cartItem.item.itemCost;
grandTotal += cartItem.item.itemCost;
formattedSummaryPage << "x1 " + cartItem.item.itemName + " - $" + QString::number(cartItem.item.itemCost) + "\n";
}
formattedSummaryPage << "Total: $" + QString::number(stadiumGrandTotal, 'f', 2) + "";
formattedSummaryPage << "---------------------\n\n";
formattedSummaryPage << "Grand total: $" + QString::number(grandTotal, 'f', 2);
ui->summaryListView->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->stackedWidget->setCurrentIndex(4);
QStringListModel* summaryModel = new QStringListModel;
summaryModel->setStringList(formattedSummaryPage);
ui->summaryListView->setModel(summaryModel);
} else {
ui->stackedWidget->setCurrentIndex(4);
ui->tripSummaryLabel->setText("No items purchased!");
ui->summaryListView->hide();
}
}
// DIJKSTRAS SHORTEST PATH FROM A --> B
if (dijkstrasShortestPath) {
// traverse to destination using shortest path generated from dijkstras algorithm
populateStadiumInfo(tripPathQueue.back());
ui->destinationTeamLabel->hide();
// set the distance label to be visible
ui->totalDistanceTraveled->show();
ui->takeTripButton->setText("End Trip");
} else {
// custom trip
qDebug() << "ordered teams to visit: " << orderedTeamsToVisit.size();
if (!orderedTeamsToVisit.isEmpty()) {
qDebug() << "size of orderedlist: " << orderedTeamsToVisit.size();
QString nextStadiumName = this->orderedTeamsToVisit.front().stadiumName;
Vertex* nextVertex = this->graph->getVertexByStadiumName(nextStadiumName);
if (orderedTeamsToVisit.size() == 1) {
ui->takeTripButton->setText("End Trip");
}
populateCustomTripIteration(orderedTeamsToVisit.front());
}
}
}
void TripPlannerWindow::on_customTripButton_clicked()
{
ui->visitAllTeamsMostEfficiently->setText("Add all teams");
ui->visitAllTeamsMostEfficiently->show();
ui->stackedWidget->setCurrentIndex(3);
}
bool TripPlannerWindow::teamsToVisitListContains(Team teamToAdd) {
bool contains = false;
for (auto team : teamsToVisit) {
if (team.teamName == teamToAdd.teamName) {
contains = true;
}
}
return contains;
}
void TripPlannerWindow::on_addTeamButton_clicked()
{
Team teamToAdd = this->teams.at(ui->teamListComboBox->currentIndex());
if (!teamsToVisitListContains(teamToAdd)) {
DraggableListModel* model = static_cast<DraggableListModel*>(ui->orderableListView->model());
QStringList teamsToVisitList = model->stringList();
// Append the new team to the listView
teamsToVisitList << teamToAdd.teamName + " at " + teamToAdd.stadiumName + "\n\n";
model->setStringList(teamsToVisitList);
ui->orderableListView->setModel(model);
this->teamsToVisit.push_back(teamToAdd);
} else {
QMessageBox::StandardButton reply;
reply = QMessageBox::critical(this, "", "There is already a team with that name on your list!",
QMessageBox::Ok);
}
}
void TripPlannerWindow::populateCustomTripIteration(Team teamToVisit) {
ui->currentTeamLabel->setText("Currently visiting: " + teamToVisit.teamName);
ui->currentStadiumLabel->setText("Stadium name: " + teamToVisit.stadiumName);
// Find the fastest route from the current team to the next team on the user's ordered list of teams to visit...
QStringList souvenirsList;
QStringListModel* souvenirListModel = new QStringListModel(this);
QList<Souvenir> souvenirs = SQLManager::getInstance()->getSouvenirsByStadium(teamToVisit.stadiumName);
for (auto souvenir : souvenirs) {
souvenirsList << "Item name: " + souvenir.itemName + "\nItem Price: " + QString::number(souvenir.itemCost, 'f', 2) + "\n\n";
}
souvenirListModel->setStringList(souvenirsList);
ui->souvenirsListView->setModel(souvenirListModel);
this->currentTeamSouvenirList = souvenirs;
ui->stackedWidget->setCurrentIndex(2);
totalDistanceTraveled += aggregatedTripDistances.front();
ui->totalDistanceTraveled->setText("Distance traveled: " + QString::number(totalDistanceTraveled) + " miles");
qDebug() << "Vertex: " << orderedTeamsToVisit.front().teamName;
orderedTeamsToVisit.pop_front();
aggregatedTripDistances.pop_front();
}
void TripPlannerWindow::on_beginCustomTripButton_clicked()
{
// Loads the teams and the order of the teams that the user has added to their list into QList for trip traversal
DraggableListModel* model = static_cast<DraggableListModel*> (ui->orderableListView->model());
QList<Team> orderedTeamsToVisit;
QString sep(" at ");
if (model->rowCount() > 1) {
if (!mostEfficientlyVisitAll) {
for (auto listItem : model->stringList()) {
QStringList parts = listItem.split(" at ", QString::SkipEmptyParts);
QString teamName = parts.at(0);
qDebug() << parts[0];
Team teamToVisit = SQLManager::getInstance()->getStadiumByName(teamName);
orderedTeamsToVisit.push_back(teamToVisit);
qDebug() << "New ordered team: " << orderedTeamsToVisit.back().stadiumName;
}
this->orderedTeamsToVisit = orderedTeamsToVisit;
int aggregatedTripDistance = 0;
aggregatedTripDistances.push_back(0);
for (int i=0; i < (orderedTeamsToVisit.size() - 1); i++) {
Vertex* origin = graph->getVertexByTeamName(orderedTeamsToVisit.at(i).teamName);
Vertex* destination = graph->getVertexByTeamName(orderedTeamsToVisit.at(i+1).teamName);
QMap<Vertex*, int> distances;
this->graph->Dijkstras(origin, distances);
qDebug() << "A[" << i << "]: " << QString::number(aggregatedTripDistance + distances[destination]);
QList<Vertex*> path;
determineDijkstraPath(origin, destination, path);
for (auto vertex : path) {
qDebug() << "Pit stop: " << vertex->data.stadiumName;
}
this->aggregatedTripDistances.push_back(aggregatedTripDistance + distances[destination]);
}
} else {
for (auto listItem : model->stringList()) {
QStringList parts = listItem.split(" at ", QString::SkipEmptyParts);
QString teamName = parts.at(0);
qDebug() << parts[0];
Team teamToVisit = SQLManager::getInstance()->getStadiumByName(teamName);
orderedTeamsToVisit.push_back(teamToVisit);
}
this->orderedTeamsToVisit = orderedTeamsToVisit;
// begin da recursion
QList<Vertex*> visitedList;
visitedList.push_back(graph->getVertexByTeamName(orderedTeamsToVisit.front().teamName));
VisitCustomMostEfficiently(graph->getVertexByTeamName(orderedTeamsToVisit.front().teamName), visitedList, 0);
this->orderedTeamsToVisit.clear();
// re order the list in most efficient way possible from dijkstras recursion
for (auto vertex : visitedList) {
this->orderedTeamsToVisit.push_back(vertex->data);
}
}
QStringList souvenirsList;
QStringListModel* souvenirListModel = new QStringListModel(this);
QList<Souvenir> souvenirs = SQLManager::getInstance()->getSouvenirsByStadium(orderedTeamsToVisit.front().stadiumName);
for (auto souvenir : souvenirs) {
souvenirsList << "Item name: " + souvenir.itemName + "\nItem Price: " + QString::number(souvenir.itemCost, 'f', 2) + "\n\n";
}
souvenirListModel->setStringList(souvenirsList);
ui->souvenirsListView->setModel(souvenirListModel);
this->currentTeamSouvenirList = souvenirs;
on_takeTripButton_clicked();
} else {
QMessageBox::StandardButton reply;
reply = QMessageBox::critical(this, "", "You need to add at least two teams to the list!",
QMessageBox::Ok);
}
}
void TripPlannerWindow::on_backButton2_clicked()
{
MainMenu* newMM = new MainMenu;
newMM->show();
this->close();
}
void TripPlannerWindow::on_backButton_clicked()
{
MainMenu* newMM = new MainMenu;
newMM->show();
this->close();
}
void TripPlannerWindow::on_pushButton_clicked()
{
MainMenu* newMM = new MainMenu;
newMM->show();
this->close();
}
void TripPlannerWindow::on_abortButton_clicked()
{
MainMenu* newMM = new MainMenu;
newMM->show();
this->close();
}
void TripPlannerWindow::on_backButton_2_clicked()
{
MainMenu* NewMM = new MainMenu;
this->close();
NewMM->show();
}
bool TripPlannerWindow::visitedListContains(QList<Vertex*> visitedList, Vertex* vertexSearch) {
bool contains = false;
for (auto vertex : visitedList) {
if (vertex->data.stadiumName == vertexSearch->data.stadiumName) {
contains = true;
}
}
return contains;
}
bool TripPlannerWindow::orderedListContains(QList<Team> list, Team searchTeam) {
bool contains = false;
for (auto team : list) {
if (searchTeam.stadiumName == team.stadiumName) {
contains = true;
}
}
return contains;
}
void TripPlannerWindow::VisitCustomMostEfficiently(Vertex* currVertex, QList<Vertex*>& visitedList, int aggregatedDistanceTraveled) {
static QList<int> aggregatedDistances;
if (visitedList.size() == orderedTeamsToVisit.size()) {
// we done
this->aggregatedTripDistances = aggregatedDistances;
return;
}
if (aggregatedDistances.size() == 0) {
aggregatedDistances.push_back(0);
}
QMap<Vertex*, int> distances;
this->graph->Dijkstras(currVertex, distances);
QList<int> distanceInts = distances.values();
std::sort(distanceInts.begin(), distanceInts.end());
distanceInts.pop_front(); // the front is always going to be zero (distance from a vertex to itself is always the shortest path)
Vertex* nextClosest = NULL;
while (!orderedListContains(orderedTeamsToVisit, distances.key(distanceInts.front())->data) || visitedListContains(visitedList, distances.key(distanceInts.front()))) {
distanceInts.pop_front();
}
nextClosest = distances.key(distanceInts.front());
visitedList.push_back(nextClosest);
aggregatedDistances.push_back(distanceInts.front()); // accumulate the total distance traveled
aggregatedDistanceTraveled += distanceInts.front();
VisitCustomMostEfficiently(nextClosest, visitedList, (aggregatedDistanceTraveled + distanceInts.front()));
qDebug() << "Next closest, specified stadium to visit from " << currVertex->data.stadiumName << " is " << nextClosest->data.stadiumName;
}
void TripPlannerWindow::VisitAllMostEfficiently(Vertex* currVertex, QList<Vertex*>& visitedList, int aggregatedDistanceTraveled, int backTrackNum) {
static QList<int> aggregatedDistances;
if (aggregatedDistances.size() == 0) {
aggregatedDistances.push_back(0);
}
if (visitedList.size() == graph->GetAllVertices().size()) {
// we done
this->aggregatedTripDistances = aggregatedDistances;
return;
}
qDebug() << "Visited list: " << visitedList.size();
Vertex* nextClosest = NULL;
int shortestWeight = 999999;
for (auto edge : currVertex->edges) {
if (edge->weight < shortestWeight && !visitedListContains(visitedList, edge->destination)) {
shortestWeight = edge->weight;
nextClosest = edge->destination;
}
}
if (nextClosest == NULL) {
// gotta back track until we have visited all stadiums
++backTrackNum;
qDebug() << "Back tracking to " << visitedList.at(visitedList.size() - backTrackNum)->data.stadiumName;
VisitAllMostEfficiently(visitedList.at(visitedList.size() - backTrackNum), visitedList, aggregatedDistanceTraveled, backTrackNum);
} else {
visitedList.push_back(nextClosest);
aggregatedDistances.push_back(shortestWeight); // accumulate the total distance traveled
aggregatedDistanceTraveled += shortestWeight;
qDebug() << "\nVisiting next closest neighbor: " << nextClosest->data.stadiumName << " with weight " << shortestWeight;
qDebug() << "Total distance now traveled: " << aggregatedDistances.last();
qDebug() << "\n";
VisitAllMostEfficiently(nextClosest, visitedList, aggregatedDistanceTraveled);
}
}
void TripPlannerWindow::populateMostEfficientFromComerica(Team teamToVisit) {
ui->currentTeamLabel->setText("Currently visiting: " + teamToVisit.teamName);
ui->currentStadiumLabel->setText("Stadium name: " + teamToVisit.stadiumName);
// Find the fastest route from the current team to the next team on the user's ordered list of teams to visit...
QStringList souvenirsList;
QStringListModel* souvenirListModel = new QStringListModel(this);
QList<Souvenir> souvenirs = SQLManager::getInstance()->getSouvenirsByStadium(teamToVisit.stadiumName);
for (auto souvenir : souvenirs) {
souvenirsList << "Item name: " + souvenir.itemName + "\nItem Price: " + QString::number(souvenir.itemCost, 'f', 2) + "\n\n";
}
souvenirListModel->setStringList(souvenirsList);
ui->souvenirsListView->setModel(souvenirListModel);
this->currentTeamSouvenirList = souvenirs;
ui->stackedWidget->setCurrentIndex(2);
totalDistanceTraveled += aggregatedTripDistances.front();
ui->totalDistanceTraveled->setText("Distance traveled: " + QString::number(totalDistanceTraveled) + " miles");
orderedTeamsToVisit.pop_front();
aggregatedTripDistances.pop_front();
}
void TripPlannerWindow::on_visitAllTeamsMostEfficiently_clicked() {
// if (mostEfficientlyVisitAll) {
for (auto vertex : this->graph->GetAllVertices()) {
if (!teamsToVisitListContains(vertex->data)) {
DraggableListModel* model = static_cast<DraggableListModel*>(ui->orderableListView->model());
QStringList list = model->stringList();
// Append the new team to the listView
list << vertex->data.teamName + " at " + vertex->data.stadiumName + "\n\n";
model->setStringList(list);
ui->orderableListView->setModel(model);
this->teamsToVisit.push_back(vertex->data);
}
}
// }
}
void TripPlannerWindow::on_customMostEfficientTripButton_clicked()
{
ui->stackedWidget->setCurrentIndex(3);
ui->visitAllTeamsMostEfficiently->show();
this->mostEfficientlyVisitAll = true;
}
| [
"flocka89@users.noreply.github.com"
] | flocka89@users.noreply.github.com |
acf10a90d2d5eadc89d7448b9b57324f7beac592 | 81d46ffe3d0489af96ef47e9ad253073ccfc0751 | /juce_patches/src/patches.cpp | bb688ee8a9c1be10af61573286c615011cff0339 | [] | no_license | jzrake/patches | fdadee9468fe1f843026db8d5c231cf5938f37df | 73110e5a797e816b2b3d79d1990b2bf4b50c5374 | refs/heads/master | 2020-04-10T11:02:53.075157 | 2019-02-05T21:54:30 | 2019-02-05T21:54:30 | 160,982,366 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,629 | cpp | #include <ostream>
#include <vector>
#include <map>
#include "patches.hpp"
using namespace patches2d;
// ============================================================================
std::string patches2d::to_string(MeshLocation location)
{
switch (location)
{
case MeshLocation::vert: return "vert";
case MeshLocation::cell: return "cell";
case MeshLocation::face_i: return "face_i";
case MeshLocation::face_j: return "face_j";
}
}
std::string patches2d::to_string(Field field)
{
switch (field)
{
case Field::cell_volume: return "cell_volume";
case Field::cell_coords: return "cell_coords";
case Field::vert_coords: return "vert_coords";
case Field::face_area_i: return "face_area_i";
case Field::face_area_j: return "face_area_j";
case Field::face_velocity_i: return "face_velocity_i";
case Field::face_velocity_j: return "face_velocity_j";
case Field::conserved: return "conserved";
case Field::primitive: return "primitive";
}
}
std::string patches2d::to_string(Database::Index index)
{
return to_string(index, to_string(std::get<3>(index)));
}
std::string patches2d::to_string(Database::Index index, std::string field_name)
{
auto i = std::get<0>(index);
auto j = std::get<1>(index);
auto p = std::get<2>(index);
return std::to_string(p) + "." + std::to_string(i) + "-" + std::to_string(j) + "/" + field_name;
}
MeshLocation patches2d::parse_location(std::string str)
{
if (str == "vert") return MeshLocation::vert;
if (str == "cell") return MeshLocation::cell;
if (str == "face_i") return MeshLocation::face_i;
if (str == "face_j") return MeshLocation::face_j;
throw std::invalid_argument("unknown location: " + str);
}
Field patches2d::parse_field(std::string str)
{
if (str == "cell_volume") return Field::cell_volume;
if (str == "cell_coords") return Field::cell_coords;
if (str == "vert_coords") return Field::vert_coords;
if (str == "face_area_i") return Field::face_area_i;
if (str == "face_area_j") return Field::face_area_j;
if (str == "face_velocity_i") return Field::face_velocity_i;
if (str == "face_velocity_j") return Field::face_velocity_j;
if (str == "conserved") return Field::conserved;
if (str == "primitive") return Field::primitive;
throw std::invalid_argument("unknown field: " + str);
}
Database::Index patches2d::parse_index(std::string str)
{
auto dot = str.find('.');
auto dash = str.find('-');
auto slash = str.find('/');
int level = std::stoi(str.substr(0, dot));
int i = std::stoi(str.substr(dot + 1, dash));
int j = std::stoi(str.substr(dash + 1, slash));
auto field = parse_field(str.substr(slash + 1));
return std::make_tuple(i, j, level, field);
}
// ============================================================================
FieldDescriptor::FieldDescriptor(int num_fields, MeshLocation location)
: num_fields(num_fields)
, location(location)
{
}
// ============================================================================
Database::Database(int ni, int nj, Header header)
: ni(ni)
, nj(nj)
, header(header)
{
}
void Database::set_boundary_value(BoundaryValue b)
{
boundary_value = b;
}
void Database::insert(Index index, Array data)
{
patches[index].become(check_shape(data, index).copy());
}
auto Database::erase(Index index)
{
return patches.erase(index);
}
void Database::clear()
{
patches.clear();
}
void Database::commit(Index index, Array data, double rk_factor)
{
auto target = patches.at(index);
if (rk_factor == 0.0)
{
target = data;
}
else
{
target = data * (1 - rk_factor) + target * rk_factor;
}
}
Database::Array Database::fetch(Index index, int guard) const
{
return fetch(index, guard, guard, guard, guard);
}
Database::Array Database::fetch(Index index, int ngil, int ngir, int ngjl, int ngjr) const
{
if (location(index) != MeshLocation::cell)
{
throw std::invalid_argument("can only fetch cell data (for now)");
}
auto _ = nd::axis::all();
auto mi = ni + ngil + ngir;
auto mj = nj + ngjl + ngjr;
auto shape = std::array<int, 3>{mi, mj, num_fields(index)};
auto res = nd::array<double, 3>(shape);
auto i = std::get<0>(index);
auto j = std::get<1>(index);
auto p = std::get<2>(index);
auto f = std::get<3>(index);
auto Ri = std::make_tuple(i + 1, j, p, f);
auto Li = std::make_tuple(i - 1, j, p, f);
auto Rj = std::make_tuple(i, j + 1, p, f);
auto Lj = std::make_tuple(i, j - 1, p, f);
res.select(_|ngil|ni+ngil, _|ngjl|nj+ngjl, _) = patches.at(index);
// i-left boundary
// ========================================================================
if (ngil > 0)
{
auto neighbor = locate(Li);
auto bv = neighbor.empty()
? boundary_value(index, PatchBoundary::il, ngil, patches.at(index))
: neighbor.select(_|ni-ngil|ni, _, _);
res.select(_|0|ngil, _|ngjl|nj+ngjl, _) = bv;
}
// i-right boundary
// ========================================================================
if (ngir > 0)
{
auto neighbor = locate(Ri);
auto bv = neighbor.empty()
? boundary_value(index, PatchBoundary::ir, ngir, patches.at(index))
: neighbor.select(_|0|ngir, _, _);
res.select(_|mi-ngir|mi, _|ngjl|nj+ngjl, _) = bv;
}
// j-left boundary
// ========================================================================
if (ngjl > 0)
{
auto neighbor = locate(Lj);
auto bv = neighbor.empty()
? boundary_value(index, PatchBoundary::jl, ngjl, patches.at(index))
: neighbor.select(_, _|nj-ngjl|nj, _);
res.select(_|ngil|ni+ngil, _|0|ngjl, _) = bv;
}
// j-right boundary
// ========================================================================
if (ngjr > 0)
{
auto neighbor = locate(Rj);
auto bv = neighbor.empty()
? boundary_value(index, PatchBoundary::jr, ngjr, patches.at(index))
: neighbor.select(_, _|0|ngjr, _);
res.select(_|ngil|ni+ngil, _|mj-ngjr|mj, _) = bv;
}
return res;
}
Database::Array Database::assemble(int i0, int i1, int j0, int j1, int level, Field field) const
{
auto _ = nd::axis::all();
int mi = 0, mj = 0;
switch (header.at(field).location)
{
case MeshLocation::cell : mi = (i1 - i0) * ni + 0; mj = (j1 - j0) * nj + 0; break;
case MeshLocation::vert : mi = (i1 - i0) * ni + 1; mj = (j1 - j0) * nj + 1; break;
case MeshLocation::face_i: mi = (i1 - i0) * ni + 1; mj = (j1 - j0) * nj + 0; break;
case MeshLocation::face_j: mi = (i1 - i0) * ni + 0; mj = (j1 - j0) * nj + 1; break;
}
auto res = Array(mi, mj, header.at(field).num_fields);
for (int i = i0; i < i1; ++i)
{
for (int j = j0; j < j1; ++j)
{
int di = 0, dj = 0;
switch (header.at(field).location)
{
case MeshLocation::cell : di = (i == i1 - 1) * 0; dj = (j == j1 - 1) * 0; break;
case MeshLocation::vert : di = (i == i1 - 1) * 1; dj = (j == j1 - 1) * 1; break;
case MeshLocation::face_i: di = (i == i1 - 1) * 1; dj = (j == j1 - 1) * 0; break;
case MeshLocation::face_j: di = (i == i1 - 1) * 0; dj = (j == j1 - 1) * 1; break;
}
const auto& patch = patches.at(std::make_tuple(i, j, level, field));
res.select(_|i*ni|(i+1)*ni+di, _|j*nj|(j+1)*nj+dj, _) = patch.select(_|0|ni+di, _|0|nj+dj, _);
}
}
return res;
}
const Database::Array& Database::at(Index index) const
{
return patches.at(index);
}
const Database::Array& Database::at(Index index, Field which) const
{
std::get<3>(index) = which;
return patches.at(index);
}
std::map<Database::Index, Database::Array> Database::all(Field which) const
{
auto res = std::map<Index, Array>();
for (const auto& patch : patches)
{
if (std::get<3>(patch.first) == which)
{
res.insert(patch);
}
}
return res;
}
std::size_t Database::count(Field which) const
{
std::size_t n = 0;
for (const auto& patch : patches)
{
if (std::get<3>(patch.first) == which)
{
++n;
}
}
return n;
}
std::size_t Database::num_cells(Field which) const
{
return count(which) * ni * nj;
}
void Database::print(std::ostream& os) const
{
os << std::string(52, '=') << "\n";
os << "Database:\n\n";
os << "block size: " << ni << " " << nj << "\n";
os << "mesh patches:\n\n";
for (const auto& patch : patches)
{
os << "\t" << to_string(patch.first) << "\n";
}
os << "\n";
}
void Database::dump(const Serializer& ser) const
{
ser.write_header(header);
ser.write_block_size({ni, nj});
for (const auto& patch : patches)
{
ser.write_array(to_string(patch.first), patch.second);
}
}
Database Database::load(const Serializer& ser, std::set<Field> fields, std::function<bool()> bailout)
{
auto header = ser.read_header();
auto blocks = ser.read_block_size();
auto database = Database(blocks[0], blocks[1], header);
for (auto patch : ser.list_patches())
{
for (auto field : ser.list_fields(patch))
{
if (fields.empty() || fields.count(parse_field (field)))
{
auto ind = patch + "/" + field;
database.insert(parse_index(ind), ser.read_array(ind));
if (bailout && bailout())
{
return database;
}
}
}
}
return database;
}
// ========================================================================
int Database::num_fields(Index index) const
{
return header.at(std::get<3>(index)).num_fields;
}
MeshLocation Database::location(Index index) const
{
return header.at(std::get<3>(index)).location;
}
Database::Array Database::check_shape(Array& array, Index index) const
{
if (array.shape() != expected_shape(index))
{
throw std::invalid_argument("input patch data has the wrong shape");
}
return array;
}
Database::Index Database::coarsen(Index index) const
{
std::get<0>(index) /= 2;
std::get<1>(index) /= 2;
std::get<2>(index) -= 1;
return index;
}
std::array<Database::Index, 4> Database::refine(Index index) const
{
auto i = std::get<0>(index);
auto j = std::get<1>(index);
auto p = std::get<2>(index);
auto f = std::get<3>(index);
return {
std::make_tuple(i * 2 + 0, j * 2 + 0, p + 1, f),
std::make_tuple(i * 2 + 0, j * 2 + 1, p + 1, f),
std::make_tuple(i * 2 + 1, j * 2 + 0, p + 1, f),
std::make_tuple(i * 2 + 1, j * 2 + 1, p + 1, f),
};
}
std::array<int, 3> Database::expected_shape(Index index) const
{
switch (location(index))
{
case MeshLocation::cell: return {ni + 0, nj + 0, num_fields(index)};
case MeshLocation::vert: return {ni + 1, nj + 1, num_fields(index)};
case MeshLocation::face_i: return {ni + 1, nj + 0, num_fields(index)};
case MeshLocation::face_j: return {ni + 0, nj + 1, num_fields(index)};
}
throw;
}
nd::array<double, 3> Database::locate(Index index) const
{
if (patches.count(index))
{
return patches.at(index);
}
if (patches.count(coarsen(index)))
{
auto i = std::get<0>(index);
auto j = std::get<1>(index);
return prolongation(quadrant(patches.at(coarsen(index)), i % 2, j % 2));
}
if (contains_all(refine(index)))
{
return restriction(tile(refine(index)));
}
return nd::array<double, 3>();
}
nd::array<double, 3> Database::quadrant(const nd::array<double, 3>& A, int I, int J) const
{
auto _ = nd::axis::all();
if (I == 0 && J == 0) return A.select(_|0 |ni/2, _|0 |nj/2, _);
if (I == 0 && J == 1) return A.select(_|0 |ni/2, _|nj/2|nj, _);
if (I == 1 && J == 0) return A.select(_|ni/2|ni, _|0 |nj/2, _);
if (I == 1 && J == 1) return A.select(_|ni/2|ni, _|nj/2|nj, _);
throw std::invalid_argument("quadrant: I and J must be 0 or 1");
}
nd::array<double, 3> Database::tile(std::array<Index, 4> indexes) const
{
auto _ = nd::axis::all();
nd::array<double, 3> res(ni * 2, nj * 2, num_fields(indexes[0]));
res.select(_|0 |ni*1, _|0 |nj*1, _) = patches.at(indexes[0]);
res.select(_|0 |ni*1, _|nj|nj*2, _) = patches.at(indexes[1]);
res.select(_|ni|ni*2, _|0 |nj*1, _) = patches.at(indexes[2]);
res.select(_|ni|ni*2, _|nj|nj*2, _) = patches.at(indexes[3]);
return res;
}
nd::array<double, 3> Database::prolongation(const nd::array<double, 3>& A) const
{
auto _ = nd::axis::all();
nd::array<double, 3> res(ni, nj, A.shape(2));
res.select(_|0|ni|2, _|0|nj|2, _) = A;
res.select(_|0|ni|2, _|1|nj|2, _) = A;
res.select(_|1|ni|2, _|0|nj|2, _) = A;
res.select(_|1|ni|2, _|1|nj|2, _) = A;
return res;
}
nd::array<double, 3> Database::restriction(const nd::array<double, 3>& A) const
{
auto _ = nd::axis::all();
auto mi = A.shape(0);
auto mj = A.shape(1);
auto B = std::array<nd::array<double, 3>, 4>
{
A.select(_|0|mi|2, _|0|mj|2, _),
A.select(_|0|mi|2, _|1|mj|2, _),
A.select(_|1|mi|2, _|0|mj|2, _),
A.select(_|1|mi|2, _|1|mj|2, _),
};
return (B[0] + B[1] + B[2] + B[3]) * 0.25;
}
| [
"jonathan.zrake@gmail.com"
] | jonathan.zrake@gmail.com |
90183ab7690fab869dab6725eff6cf1b7c40b14b | 64e4fabf9b43b6b02b14b9df7e1751732b30ad38 | /src/chromium/services/network/public/cpp/url_request_mojom_traits.h | f71832d291c6f053af02c93848dab294b0bb1f96 | [
"BSD-3-Clause"
] | permissive | ivan-kits/skia-opengl-emscripten | 8a5ee0eab0214c84df3cd7eef37c8ba54acb045e | 79573e1ee794061bdcfd88cacdb75243eff5f6f0 | refs/heads/master | 2023-02-03T16:39:20.556706 | 2020-12-25T14:00:49 | 2020-12-25T14:00:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,895 | h | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SERVICES_NETWORK_PUBLIC_CPP_URL_REQUEST_MOJOM_TRAITS_H_
#define SERVICES_NETWORK_PUBLIC_CPP_URL_REQUEST_MOJOM_TRAITS_H_
#include <string>
#include <utility>
#include "base/component_export.h"
#include "base/memory/scoped_refptr.h"
#include "mojo/public/cpp/base/file_mojom_traits.h"
#include "mojo/public/cpp/base/file_path_mojom_traits.h"
#include "mojo/public/cpp/base/time_mojom_traits.h"
#include "mojo/public/cpp/bindings/enum_traits.h"
#include "mojo/public/cpp/bindings/struct_traits.h"
#include "net/base/request_priority.h"
#include "services/network/public/cpp/data_element.h"
#include "services/network/public/cpp/resource_request.h"
#include "services/network/public/cpp/resource_request_body.h"
#include "services/network/public/mojom/chunked_data_pipe_getter.mojom-shared.h"
#include "services/network/public/mojom/data_pipe_getter.mojom.h"
#include "services/network/public/mojom/url_loader.mojom-shared.h"
namespace mojo {
template <>
struct COMPONENT_EXPORT(NETWORK_CPP_BASE)
EnumTraits<network::mojom::RequestPriority, net::RequestPriority> {
static network::mojom::RequestPriority ToMojom(net::RequestPriority priority);
static bool FromMojom(network::mojom::RequestPriority in,
net::RequestPriority* out);
};
template <>
struct COMPONENT_EXPORT(NETWORK_CPP_BASE)
EnumTraits<network::mojom::URLRequestReferrerPolicy,
net::URLRequest::ReferrerPolicy> {
static network::mojom::URLRequestReferrerPolicy ToMojom(
net::URLRequest::ReferrerPolicy policy);
static bool FromMojom(network::mojom::URLRequestReferrerPolicy in,
net::URLRequest::ReferrerPolicy* out);
};
template <>
struct COMPONENT_EXPORT(NETWORK_CPP_BASE)
StructTraits<network::mojom::URLRequestDataView, network::ResourceRequest> {
static const std::string& method(const network::ResourceRequest& request) {
return request.method;
}
static const GURL& url(const network::ResourceRequest& request) {
return request.url;
}
static const GURL& site_for_cookies(const network::ResourceRequest& request) {
return request.site_for_cookies;
}
static const base::Optional<url::Origin>& top_frame_origin(
const network::ResourceRequest& request) {
return request.top_frame_origin;
}
static bool attach_same_site_cookies(
const network::ResourceRequest& request) {
return request.attach_same_site_cookies;
}
static bool update_first_party_url_on_redirect(
const network::ResourceRequest& request) {
return request.update_first_party_url_on_redirect;
}
static const base::Optional<url::Origin>& request_initiator(
const network::ResourceRequest& request) {
return request.request_initiator;
}
static const GURL& referrer(const network::ResourceRequest& request) {
return request.referrer;
}
static net::URLRequest::ReferrerPolicy referrer_policy(
const network::ResourceRequest& request) {
return request.referrer_policy;
}
static bool is_prerendering(const network::ResourceRequest& request) {
return request.is_prerendering;
}
static const net::HttpRequestHeaders& headers(
const network::ResourceRequest& request) {
return request.headers;
}
static const net::HttpRequestHeaders& cors_exempt_headers(
const network::ResourceRequest& request) {
return request.cors_exempt_headers;
}
static int32_t load_flags(const network::ResourceRequest& request) {
return request.load_flags;
}
static bool allow_credentials(const network::ResourceRequest& request) {
return request.allow_credentials;
}
static int32_t plugin_child_id(const network::ResourceRequest& request) {
return request.plugin_child_id;
}
static int32_t resource_type(const network::ResourceRequest& request) {
return request.resource_type;
}
static net::RequestPriority priority(
const network::ResourceRequest& request) {
return request.priority;
}
static int32_t appcache_host_id(const network::ResourceRequest& request) {
return request.appcache_host_id;
}
static bool should_reset_appcache(const network::ResourceRequest& request) {
return request.should_reset_appcache;
}
static bool is_external_request(const network::ResourceRequest& request) {
return request.is_external_request;
}
static network::mojom::CorsPreflightPolicy cors_preflight_policy(
const network::ResourceRequest& request) {
return request.cors_preflight_policy;
}
static bool originated_from_service_worker(
const network::ResourceRequest& request) {
return request.originated_from_service_worker;
}
static bool skip_service_worker(const network::ResourceRequest& request) {
return request.skip_service_worker;
}
static bool corb_detachable(const network::ResourceRequest& request) {
return request.corb_detachable;
}
static bool corb_excluded(const network::ResourceRequest& request) {
return request.corb_excluded;
}
static network::mojom::FetchRequestMode fetch_request_mode(
const network::ResourceRequest& request) {
return request.fetch_request_mode;
}
static network::mojom::FetchCredentialsMode fetch_credentials_mode(
const network::ResourceRequest& request) {
return request.fetch_credentials_mode;
}
static network::mojom::FetchRedirectMode fetch_redirect_mode(
const network::ResourceRequest& request) {
return request.fetch_redirect_mode;
}
static const std::string& fetch_integrity(
const network::ResourceRequest& request) {
return request.fetch_integrity;
}
static int32_t fetch_request_context_type(
const network::ResourceRequest& request) {
return request.fetch_request_context_type;
}
static const scoped_refptr<network::ResourceRequestBody>& request_body(
const network::ResourceRequest& request) {
return request.request_body;
}
static bool keepalive(const network::ResourceRequest& request) {
return request.keepalive;
}
static bool has_user_gesture(const network::ResourceRequest& request) {
return request.has_user_gesture;
}
static bool enable_load_timing(const network::ResourceRequest& request) {
return request.enable_load_timing;
}
static bool enable_upload_progress(const network::ResourceRequest& request) {
return request.enable_upload_progress;
}
static bool do_not_prompt_for_login(const network::ResourceRequest& request) {
return request.do_not_prompt_for_login;
}
static int32_t render_frame_id(const network::ResourceRequest& request) {
return request.render_frame_id;
}
static bool is_main_frame(const network::ResourceRequest& request) {
return request.is_main_frame;
}
static int32_t transition_type(const network::ResourceRequest& request) {
return request.transition_type;
}
static bool allow_download(const network::ResourceRequest& request) {
return request.allow_download;
}
static bool report_raw_headers(const network::ResourceRequest& request) {
return request.report_raw_headers;
}
static int32_t previews_state(const network::ResourceRequest& request) {
return request.previews_state;
}
static bool initiated_in_secure_context(
const network::ResourceRequest& request) {
return request.initiated_in_secure_context;
}
static bool upgrade_if_insecure(const network::ResourceRequest& request) {
return request.upgrade_if_insecure;
}
static bool is_revalidating(const network::ResourceRequest& request) {
return request.is_revalidating;
}
static const base::Optional<base::UnguessableToken>& throttling_profile_id(
const network::ResourceRequest& request) {
return request.throttling_profile_id;
}
static const net::HttpRequestHeaders& custom_proxy_pre_cache_headers(
const network::ResourceRequest& request) {
return request.custom_proxy_pre_cache_headers;
}
static const net::HttpRequestHeaders& custom_proxy_post_cache_headers(
const network::ResourceRequest& request) {
return request.custom_proxy_post_cache_headers;
}
static bool custom_proxy_use_alternate_proxy_list(
const network::ResourceRequest& request) {
return request.custom_proxy_use_alternate_proxy_list;
}
static const base::Optional<base::UnguessableToken>& fetch_window_id(
const network::ResourceRequest& request) {
return request.fetch_window_id;
}
static const base::Optional<std::string>& devtools_request_id(
const network::ResourceRequest& request) {
return request.devtools_request_id;
}
static bool Read(network::mojom::URLRequestDataView data,
network::ResourceRequest* out);
};
template <>
struct COMPONENT_EXPORT(NETWORK_CPP_BASE)
StructTraits<network::mojom::URLRequestBodyDataView,
scoped_refptr<network::ResourceRequestBody>> {
static bool IsNull(const scoped_refptr<network::ResourceRequestBody>& r) {
return !r;
}
static void SetToNull(scoped_refptr<network::ResourceRequestBody>* output) {
output->reset();
}
static const std::vector<network::DataElement>& elements(
const scoped_refptr<network::ResourceRequestBody>& r) {
return *r->elements();
}
static uint64_t identifier(
const scoped_refptr<network::ResourceRequestBody>& r) {
return r->identifier_;
}
static bool contains_sensitive_info(
const scoped_refptr<network::ResourceRequestBody>& r) {
return r->contains_sensitive_info_;
}
static bool Read(network::mojom::URLRequestBodyDataView data,
scoped_refptr<network::ResourceRequestBody>* out);
};
template <>
struct COMPONENT_EXPORT(NETWORK_CPP_BASE)
StructTraits<network::mojom::DataElementDataView, network::DataElement> {
static const network::mojom::DataElementType& type(
const network::DataElement& element) {
return element.type_;
}
static base::span<const uint8_t> buf(const network::DataElement& element) {
if (element.bytes_) {
return base::make_span(reinterpret_cast<const uint8_t*>(element.bytes_),
element.length_);
}
return base::make_span(
reinterpret_cast<const uint8_t*>(element.buf_.data()),
element.buf_.size());
}
static const base::FilePath& path(const network::DataElement& element) {
return element.path_;
}
static base::File file(const network::DataElement& element) {
return std::move(const_cast<network::DataElement&>(element).file_);
}
static const std::string& blob_uuid(const network::DataElement& element) {
return element.blob_uuid_;
}
static network::mojom::DataPipeGetterPtrInfo data_pipe_getter(
const network::DataElement& element) {
if (element.type_ != network::mojom::DataElementType::kDataPipe)
return nullptr;
return element.CloneDataPipeGetter().PassInterface();
}
static network::mojom::ChunkedDataPipeGetterPtrInfo chunked_data_pipe_getter(
const network::DataElement& element) {
if (element.type_ != network::mojom::DataElementType::kChunkedDataPipe)
return nullptr;
return const_cast<network::DataElement&>(element)
.ReleaseChunkedDataPipeGetter();
}
static uint64_t offset(const network::DataElement& element) {
return element.offset_;
}
static uint64_t length(const network::DataElement& element) {
return element.length_;
}
static const base::Time& expected_modification_time(
const network::DataElement& element) {
return element.expected_modification_time_;
}
static bool Read(network::mojom::DataElementDataView data,
network::DataElement* out);
};
} // namespace mojo
#endif // SERVICES_NETWORK_PUBLIC_CPP_URL_REQUEST_MOJOM_TRAITS_H_
| [
"trofimov_d_a@magnit.ru"
] | trofimov_d_a@magnit.ru |
267ce17161a1c152af3e592f455728a66819364f | 006f035d65012b7c5af15d54716407a276a096a8 | /dependencies/include/cgal/CGAL/Number_types/internal_functions_comparison_root_of_2.h | 22f61afe64910ddce4cb07959b0011aa697e1c5f | [] | no_license | rosecodym/space-boundary-tool | 4ce5b67fd96ec9b66f45aca60e0e69f4f8936e93 | 300db4084cd19b092bdf2e8432da065daeaa7c55 | refs/heads/master | 2020-12-24T06:51:32.828579 | 2016-08-12T16:13:51 | 2016-08-12T16:13:51 | 65,566,229 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,371 | h | // Copyright (c) 2005,2006 INRIA Sophia-Antipolis (France)
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org); you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 3 of the License,
// or (at your option) any later version.
//
// Licensees holding a valid commercial license may use this file in
// accordance with the commercial license agreement provided with the software.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
//
// $URL: svn+ssh://scm.gforge.inria.fr/svn/cgal/branches/releases/CGAL-4.1-branch/Number_types/include/CGAL/Number_types/internal_functions_comparison_root_of_2.h $
// $Id: internal_functions_comparison_root_of_2.h 67093 2012-01-13 11:22:39Z lrineau $
//
//
// Author(s) : Sylvain Pion, Monique Teillaud, Athanasios Kakargias
// Olivier Devillers
#ifndef CGAL_NUMBER_TypeS_ROOT_OF_COMPARISON_FUNCTIONS_22_H
#define CGAL_NUMBER_TypeS_ROOT_OF_COMPARISON_FUNCTIONS_22_H
#include <CGAL/enum.h>
#include <CGAL/kernel_assertions.h>
namespace CGAL {
namespace internal {
// Maybe we can trash this
/*1 1*/template <class FT>
/*1 1*/Comparison_result
compare_11_11( const FT& A1, const FT& B1,
const FT& A2, const FT& B2 )
{
// Compares roots of (A1 X + B1) and (A2 X + B2).
CGAL_precondition( A1 > 0 & A2 > 0 );
return CGAL_NTS compare(B2*A1, B1*A2);
}
/*2 1*/template <class FT>
/*1 1*/Comparison_result
compare_21_11(const FT& A2, const FT& B2, const FT& C2,
const FT& A1, const FT& B1 )
{
// Compares roots of (A1 X + B1) and the smaller of (A2 X^2 + B2 X + C2).
CGAL_precondition(A2 > 0);
// First, we compare the root of P1 to the root of the derivative of P2.
int cmp = compare_11_11<FT>(A1, B1, A2*2, B2);
if (cmp > 0)
return LARGER;
// If it doesn't work, we evaluate the sign of P2 at the root of P1.
FT p2 = B1 * (A1*B2 - A2*B1) - C2 * CGAL_NTS square(A1);
return CGAL_NTS sign(p2);
}
/*2 2*/template <class FT>
/*2 1*/Comparison_result
compare_22_21( const FT& A1p, const FT& B1p, const FT& C1p,
const FT& A2p, const FT& B2p, const FT& C2p )
{
// Compares the larger root of (A1 X^2 + B1 X + C1)
// to the smaller root of (A2 X^2 + B2 X + C2)
// It boils down to the code from the DFMT paper
// by multiplying A* and C* by 2, and B* by -1.
CGAL_precondition(A1p > 0 & A2p > 0);
FT A1 = 2 * A1p;
FT C1 = 2 * C1p;
FT B1 = -B1p;
FT A2 = 2 * A2p;
FT C2 = 2 * C2p;
FT B2 = -B2p;
// Now compares the larger root of (A1 X^2 -2B1 X + C1)
// to the smaller root of (A2 X^2 -2B2 X + C2)
FT J = calcJ(A1,B1,A2,B2);
if ( J < 0 ) return LARGER; // r1 > l2
FT K = calcK(A1,B1,C1,A2,B2,C2);
if ( K < 0 ) return LARGER; // r1 > l2
FT Jp = calcJp(B1,C1,B2,C2);
if ( Jp < 0 ) return SMALLER; // r1 < l2
FT P4 = calcP4(J,Jp,A1,C1,A2,C2);
return - CGAL_NTS sign(P4);
// if ( P4< FT(0) ) return LARGER; // r1 > l2
// if ( P4> FT(0) ) return SMALLER; // r1 < l2
// return EQUAL;
}
/*2 2*/template <class FT> inline
/*1 2*/Comparison_result
compare_22_12( const FT& A1, const FT& B1, const FT& C1,
const FT& A2, const FT& B2, const FT& C2 )
{
// _22_12 boils down to _22_21 by :
// - swapping the two polynomials
// - changing the sign of the result
return - compare_22_21(A2, B2, C2, A1, B1, C1);
}
/*2 2*/template <class FT>
/*1 1*/Comparison_result
compare_22_11( const FT& A1p, const FT& B1p, const FT& C1p,
const FT& A2p, const FT& B2p, const FT& C2p )
{
// Compares the smaller root of (A1 X^2 + B1 X + C1)
// to the smaller root of (A2 X^2 + B2 X + C2)
// It boils down to the code from the DFMT paper
// by multiplying A* and C* by 2, and B* by -1.
CGAL_precondition(A1p > 0 & A2p > 0);
FT A1 = 2 * A1p;
FT C1 = 2 * C1p;
FT B1 = -B1p;
FT A2 = 2 * A2p;
FT C2 = 2 * C2p;
FT B2 = -B2p;
// Compares the smaller root of (A1 X^2 -2B1 X + C1)
// to the smaller root of (A2 X^2 -2B2 X + C2)
FT J = calcJ(A1,B1,A2,B2);
FT K = calcK(A1,B1,C1,A2,B2,C2);
if (J > 0)
{
if (K > 0) return SMALLER; // l1 < l2
FT I1= calcI(A1,B1,C1);
FT I2= calcI(A2,B2,C2);
FT D = calcD(A1,I1,A2,I2);
if (D > 0) return SMALLER; // l1 < l2
FT Jp = calcJp(B1,C1,B2,C2);
if (Jp < 0) return LARGER; // l1 > l2
FT P4 = calcP4(I1,I2,K);
return CGAL_NTS sign(P4);
}
// J <= 0
if (K > 0) return LARGER; // l1 > l2
FT I1= calcI(A1,B1,C1);
FT I2= calcI(A2,B2,C2);
FT D = calcD(A1,I1,A2,I2);
if (D < 0) return LARGER; // l1 > l2
FT Jp = calcJp(B1,C1,B2,C2);
if (Jp > 0) return SMALLER; // l1 < l2
FT P4 = calcP4(I1,I2,K);
return - CGAL_NTS sign(P4);
}
/*2 2*/template <class FT> inline
/*2 2*/Comparison_result
compare_22_22( const FT& A1, const FT& B1, const FT& C1,
const FT& A2, const FT& B2, const FT& C2 )
{
// _22_22 boils down to _22_11 by :
// - changing the sign of the two roots (X <-> -X in the polynomial)
// - swapping the two polynomials
return compare_22_11<FT>(A2, -B2, C2, A1, -B1, C1);
}
template <class FT>
inline FT calcI(const FT& A, const FT& B, const FT& C)
{ return CGAL_NTS square(B)-A*C; }
template <class FT>
inline FT calcJ(const FT& A1, const FT& B1, const FT& A2, const FT& B2)
{ return A1*B2-A2*B1; }
template <class FT>
inline FT calcK(const FT& A1, const FT& B1, const FT& C1,
const FT& A2, const FT& B2, const FT& C2)
{ return C1*A2+A1*C2-2*B1*B2; }
template <class FT>
inline FT calcJp(const FT& B1, const FT& C1, const FT& B2, const FT& C2)
{ return B1*C2-C1*B2; }
template <class FT>
inline FT calcP4(const FT& J, const FT& Jp,
const FT& A1, const FT& C1,
const FT& A2, const FT& C2)
{ return CGAL_NTS square(A1*C2-C1*A2)-4*J*Jp;}
template <class FT>
inline FT calcP4(const FT& I1, const FT& I2, const FT& K)
{ return CGAL_NTS square(K)-4*I1*I2;}
template <class FT>
inline FT calcD(const FT& A1, const FT& I1, const FT& A2, const FT& I2)
{ return I1*CGAL_NTS square(A2) - I2*CGAL_NTS square(A1);}
} // namespace internal
} // namespace CGAL
#endif // CGAL_NUMBER_TypeS_ROOT_OF_COMPARISON_FUNCTIONS_22_H
| [
"cmrose@lbl.gov"
] | cmrose@lbl.gov |
a94483da4c546adcb7b01e8aa2f0fa28b0526803 | 83705af196092b503a108cdaf4c622f436a3a853 | /Data Structure/ar_insert_deletion.cpp | 171985395c379264429faa71bbcc3fff4c306db9 | [] | no_license | Born0/Academic-Code-Practice-AIUB- | 01a806e83bd305f05befcafdc2023e53d30e8e75 | 8cab3d71c8704f7626c51a53dc94bf44171a4faa | refs/heads/master | 2023-02-14T23:19:23.450973 | 2021-01-02T07:36:41 | 2021-01-02T07:36:41 | 304,325,657 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,246 | cpp | #include <iostream>
void insert(int arr[],int count,int newPosition,int newValue){
int i;
for (i=count-1; i>=newPosition; i--) {
arr[i+1]=arr[i];
}
arr[newPosition]=newValue;
count++;
std::cout << "After insert" << '\n';
for ( i = 0; i < count; i++) {
std::cout<< arr[i]<<'\n';
}
}
void deleteAny(int arr[],int count,int delPosition, int newValue){
int i;
for ( i = delPosition; i < count; i++) {
arr[i]=arr[i+1];
}
std::cout << "After insert" << '\n';
for ( i = 0; i < count; i++) {
std::cout<< arr[i]<<'\n';
}
}
int main()
{
int arr[10] , count;
std::cout<<"Enter Array size:";
std::cin>>count;
std::cout << "Enter elements:" << '\n';
for (size_t i = 0; i < count; i++) {
std::cin >> arr[i];
}
std::cout << "Entered Array" << '\n';
for (size_t i = 0; i < count; i++) {
std::cout<< arr[i]<<'\n';
}
std::cout << "Enter the newPosition of new element:" << '\n';
int newPosition;
std::cin >> newPosition;
std::cout << "Enter new value:" << '\n';
int newValue;
std::cin >> newValue;
insert(arr, count,newPosition, newValue);
std::cout << "Enter delete delete Position" << '\n';
int delPosition;
std::cin >> delPosition;
deleteAny(arr, count,delPosition, newValue);
}
| [
"40140598+Born0@users.noreply.github.com"
] | 40140598+Born0@users.noreply.github.com |
81f0d57dffdeaa504556534ff705d68822defb12 | 14252979305feced12474a6ce9cc7b805777b6a4 | /CMSSW_9_2_13/src/DataFormats/L1Trigger/interface/BxBlock.h | 62a59306dd0ef784e225da5061c6651f01f7228e | [] | no_license | meshoaib/BtaggedJets_Efficiency | ac18305af6440caef26c479ea2f968fe926a69c2 | f004fc3e97eb84b38b5fd7a8ad13693d2a8b1d89 | refs/heads/master | 2021-05-05T04:20:54.016096 | 2018-01-24T08:22:49 | 2018-01-24T08:22:49 | 118,557,382 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,230 | h | #ifndef DataFormats_L1Trigger_BxBlock_h
#define DataFormats_L1Trigger_BxBlock_h
#include <memory>
#include <vector>
#include <cmath>
namespace l1t {
class BxBlockHeader {
public:
BxBlockHeader() : id_(0), totalBx_(0), flags_(0) {};
BxBlockHeader(unsigned int id, unsigned int totalBx, unsigned int flags=0) : id_(id), totalBx_(totalBx), flags_(flags) {};
// Create a BX header: everything is contained in the raw uint32
BxBlockHeader(const uint32_t raw) : id_(((raw >> id_shift) & id_mask) / n_words)
, totalBx_(((raw >> totalBx_shift) & totalBx_mask) / n_words)
, flags_((raw >> flags_shift) & flags_mask) {};
bool operator<(const BxBlockHeader& o) const { return getBx() < o.getBx(); };
inline int getBx() const { return (int)id_ - (int)std::floor(totalBx_/2.); };
inline unsigned int getId() const { return id_; };
inline unsigned int getTotalBx() const { return totalBx_; };
inline unsigned int getFlags() const { return flags_; };
inline uint32_t raw() const { return (((id_ & id_mask) << id_shift) * n_words)
| (((totalBx_ & totalBx_mask) << totalBx_shift) * n_words)
| ((flags_ & flags_mask) << flags_shift); };
private:
static const unsigned int n_words = 6; // every link transmits 6 32 bit words per bx
static const unsigned int id_shift = 24;
static const unsigned int id_mask = 0xff;
static const unsigned int totalBx_shift = 16;
static const unsigned int totalBx_mask = 0xff;
static const unsigned int flags_shift = 0;
static const unsigned int flags_mask = 0xffff;
unsigned int id_;
unsigned int totalBx_;
unsigned int flags_;
};
class BxBlock {
public:
BxBlock(std::vector<uint32_t>::const_iterator bx_start, std::vector<uint32_t>::const_iterator bx_end) :
header_(*bx_start), payload_(bx_start+1, bx_end) {};
BxBlock(const BxBlockHeader& h, std::vector<uint32_t>::const_iterator payload_start, std::vector<uint32_t>::const_iterator payload_end) :
header_(h), payload_(payload_start, payload_end) {};
BxBlock(unsigned int id, unsigned int totalBx, std::vector<uint32_t>::const_iterator payload_start, std::vector<uint32_t>::const_iterator payload_end, unsigned int flags=0) :
header_(id, totalBx, flags), payload_(payload_start, payload_end) {};
BxBlock(unsigned int id, unsigned int totalBx, const std::vector<uint32_t>& payload, unsigned int flags=0) :
header_(id, totalBx, flags), payload_(payload) {};
~BxBlock() {};
bool operator<(const BxBlock& o) const { return header() < o.header(); };
inline unsigned int getSize() const { return payload_.size(); };
BxBlockHeader header() const { return header_; };
std::vector<uint32_t> payload() const { return payload_; };
private:
BxBlockHeader header_;
std::vector<uint32_t> payload_;
};
typedef std::vector<BxBlock> BxBlocks;
}
#endif
| [
"Muhammad.Shoaib@cern.ch"
] | Muhammad.Shoaib@cern.ch |
de89148aa5c3885dbded09991c40fba38770306f | 3e995e5ffbf4b09c1ebdcac087fa2e2ac5d2ce5f | /main.cpp | c64bf254941d8b32e869b897ac92f83f1b32395d | [] | no_license | Feffote/P7E18_Arboles | f73dea82358820396ec7b74dd6b6e360acb78cf4 | a03ddfdd2dbf16435a5a7b78cd1605a039a717b5 | refs/heads/master | 2020-04-03T21:09:54.893939 | 2018-11-02T14:57:47 | 2018-11-02T14:57:47 | 155,565,045 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,217 | cpp | #include <iostream>
//#include<conio.h>
#include<stdlib.h>
#include "main.h"
#include <vector>
using namespace std;
Nodo *arbol = NULL;
int main(){
menu();
//getch();
return 0;
}
//funcion de menu
void menu(){
int dato, opcion, contador=0;
do{
cout<<"\t.:MENU:."<<endl;
cout<<"1. Insertar un nuevo nodo"<<endl;
cout<<"2. Mostrar el arbol completo"<<endl;
cout<<"3. Buscar elemento en el arbol"<<endl;
cout<<"4. Recorrer el arbol en preOrden"<<endl;
cout<<"5. Recorrer el arbol en inOrden"<<endl;
cout<<"6. Recorrer el arbol en inOrden"<<endl;
cout<<"7. Eliminar nodo del arbol"<<endl;
cout<<"8. Calcular peso del Arbol"<<endl;
cout<<"9. Calcular cantidad de hojas"<<endl;
cout<<"10. Elemento Repetido"<<endl;
cout<<"11. Cantidad de elementos por nivel"<<endl;
cout<<"12. Calcular altura del Arbol"<<endl;
cout<<"13. Sumar todos los elementos del Arbol"<<endl;
cout<<"14. Salir"<<endl;
cout<<"Opcion: ";
cin>>opcion;
switch(opcion){
case 1: cout<<"\nDigite un número: ";
cin>>dato;
insertarNodo(arbol, dato, NULL); //inserta nuevo nodo
cout<<"\n";
system("pause");
break;
case 2: cout<<"\nMostrando el arbol completo:\n\n";
mostrarArbol(arbol, contador);
cout<<"\n";
system("pause");
break;
case 3: cout<<"\nDigite el elemento a buscar: ";
cin>>dato;
if(busqueda(arbol, dato) == true){
cout<<"\nElemento"<<dato<<" a sido encontrado en el arbol\n";
}
else{
cout<<"\nElemento no encontrado\n";
}
cout<<"\n";
system("pause");
break;
case 4: cout<<"\nRecorrido en preOrden: ";
preOrden(arbol);
cout<<"\n\n";
system("pause");
break;
case 5: cout<<"\nRecorrido en inOrden: ";
inOrden(arbol);
cout<<"\n\n";
system("pause");
break;
case 6: cout<<"\nRecorrido en postOrden: ";
postOrden(arbol);
cout<<"\n\n";
system("pause");
break;
case 7: cout<<"\nDigite el nodo que quiere eliminar: ";
cin>>dato;
eliminar(arbol,dato);
cout<<"\n";
system("pause");
break;
case 8: cout<<"\nPeso del arbol: ";
calcularPeso(arbol);
cout<<"\n";
system("pause");
break;
case 9: ;
case 10: cout<< "Número que desea buscar: ";
cin>>dato;
cout << "El número aparece ";
nodoRepetido(arbol, dato);
cout<< " veces."<< endl;
cout << "\n";
break;
case 11: ;
case 12: cout<<"\nAltura del arbol: "<<calcularAltura(arbol);
cout<<"\n";
system("pause");
break;
case 13: cout<<"\nLa suma de todos los elementos del arbol: ";
sumarElementos(arbol);
cout<<"\n";
system("pause");
break;
}
system("cls");
}while(opcion !=14);
}
//funcion crear nuevo nodo para el arbol
Nodo *crearNodo(int n, Nodo *padre){
Nodo *nuevo_nodo = new Nodo();
nuevo_nodo->dato = n;
nuevo_nodo->der = NULL;
nuevo_nodo->izq = NULL;
nuevo_nodo->padre = padre;
return nuevo_nodo;
}
//funcion insertar nodo en el arbol
void insertarNodo(Nodo *&arbol, int n, Nodo *padre) {
if (arbol == NULL) {
Nodo *nuevo_nodo = crearNodo(n, padre);
arbol = nuevo_nodo;
} else {
int valorRaiz = arbol->dato; // obtener valor de la raiz
if (n < valorRaiz) { //si el elemento es menor a la raiz insertar lado izquierdo
insertarNodo(arbol->izq, n, arbol);
} else { //si el elemento es mayor a la raiz insertar lado derecho
insertarNodo(arbol->der, n, arbol);
}
}
}
//funcion mostrar arbol
void mostrarArbol(Nodo * arbol, int cont){
if(arbol == NULL){
return;
}
else{
mostrarArbol(arbol->der, cont+1);
for(int i = 0; i<cont; i++){
cout<<" ";
}
cout<<arbol->dato<<endl;
mostrarArbol(arbol->izq, cont+1);
}
}
//funcion buscar elemento en el arbol
bool busqueda(Nodo * arbol, int n){
if(arbol == NULL){
return false;
}
else if(arbol->dato == n){
return true;
}
else if(n<arbol->dato){
return busqueda(arbol->izq, n);
}
else{
return busqueda(arbol->der,n);
}
}
//funcion reccorer arbol en profundidad - PreOrden
void preOrden(Nodo * arbol) {
if (arbol == NULL) {
return;
} else {
cout << arbol->dato << " - ";
preOrden(arbol->izq);
preOrden(arbol->der);
}
}
//funcion recorrer arbol en profundidad - inOrden
void inOrden(Nodo * arbol) {
if (arbol == NULL) {
return;
} else {
inOrden(arbol->izq);
cout << arbol->dato << " - ";
inOrden(arbol->der);
}
}
//funcion recorrer arbol en profundidad - postOrden
void postOrden(Nodo * arbol) {
if (arbol == NULL) {
return;
} else {
postOrden(arbol->izq);
postOrden(arbol->der);
cout << arbol->dato << " - ";
}
}
//determinar el nodo mas izquierdo posible
Nodo *minimo(Nodo *arbol){
if(arbol == NULL){
return NULL;
}
if(arbol->izq){//si tiene hijo izquierdo
return minimo(arbol->izq);//buscamos la parte mas izq posible
}
else{ //si no tiene hijo izq
return arbol; //retorna mismo nodo
}
}
//funcion eliminar nodo
void eliminar(Nodo *arbol, int n){
if(arbol == NULL){
return;
}
else if(n < arbol->dato){ //si el valor es menor
eliminar(arbol->izq, n); //buscar por la izquierda
}
else if(n > arbol->dato){ //si el valor es mayor
eliminar(arbol->der, n); //busca por la derecha
}
else{ //si el valor es encontrado
eliminarNodo(arbol);
}
}
//funcion reemplazar dos nodos
void reemplazar(Nodo *arbol, Nodo *nuevoNodo){
if(arbol->padre){
//arbol padre asignarle nuevo hijo
if(arbol->dato == arbol->padre->izq->dato){//hijo izq
arbol->padre->izq = nuevoNodo;
}
else if(arbol->dato == arbol->padre->der->dato){//hijo der
arbol->padre->der = nuevoNodo;
}
}
if(nuevoNodo){
//asignarle su nuevo padre
nuevoNodo->padre = arbol->padre;
}
}
//funcion destruir nodo
void destruirNodo(Nodo *nodo){
nodo->izq = NULL;
nodo->der = NULL;
delete nodo;
}
//funcion para eliminar nodo encontrado
void eliminarNodo(Nodo *nodoEliminar) {
if (nodoEliminar->izq && nodoEliminar->der){ //si el nodo tiene hijo izquierdo y derecho
Nodo *menor = minimo(nodoEliminar->der);
nodoEliminar->dato = menor->dato;
eliminarNodo(menor);
}
else if(nodoEliminar->izq){
reemplazar(nodoEliminar, nodoEliminar->izq);
destruirNodo(nodoEliminar);
}
else if(nodoEliminar->der){
reemplazar(nodoEliminar, nodoEliminar->der);
destruirNodo(nodoEliminar);
}
else{ //nodo sin hijos, nodo hoja
reemplazar(nodoEliminar, NULL);
destruirNodo(nodoEliminar);
}
}
void vectorizar(Nodo *arbol, vector <int> &lista) {
if (arbol != nullptr) {
lista.push_back(arbol->dato); //agrega los números del árbol al vector “lista”
vectorizar(arbol->izq, lista);
vectorizar(arbol->der, lista);
}
}
void calcularPeso(Nodo *arbol){
vector <int> lista ;
vectorizar(arbol,lista);
cout << lista.size() <<endl;
}
void calcularHojas(Nodo *arbol, int c){
vector<int> lista;
vectorizar(arbol, lista);
int cont1 = 0;
if (arbol == nullptr){
cont1++;
}
}
//void elementoPorNivel(int);
//cantidad de veces que aparece un número dado en el árbol
void nodoRepetido(Nodo *arbol, int n){
vector <int> lista;
vectorizar(arbol, lista);
int cont = 0;
for (int i=0 ; i<lista.size(); i=i+1){//recorre el vector y cuando encuentra el número, cont+1
if (n == lista[i]){
cont++;
}
}
cout<<cont<<endl;
}
int calcularAltura(Nodo *arbol) {
// Base case: empty tree has height 0
if (arbol == nullptr)
return 0;
// recurse for left and right subtree and consider maximum depth
return max(calcularAltura(arbol->izq), calcularAltura(arbol->der)) + 1;
}
void sumarElementos (Nodo *arbol){
vector <int> lista ;
vectorizar(arbol,lista);
int sum = 0;
for (int i = 0; i<lista.size(); i++){
sum += lista[i];
}
cout<< sum<<endl;
}
| [
"zinnifederico@gmail.com"
] | zinnifederico@gmail.com |
e98812c2eae621350c957b3ab5f0bc612f937ac0 | 0c142b680a84756175cad0822289ab65c8242a52 | /LPD8806.cpp | ee0a2cb28dd0527bbdea0b34efe9a9adad8d029a | [] | no_license | LyleH/arduino_lights | 4193302543f670c3cc348875cc1b642ca1fc6521 | 788bd448b976e592f69abe4cb4e5294392e199b4 | refs/heads/master | 2021-06-03T07:04:34.785678 | 2016-09-21T18:08:03 | 2016-09-21T18:08:03 | 68,844,326 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,184 | cpp | #include "LPD8806.h"
#ifdef __AVR_ATtiny85__
// Teensy/Gemma-specific stuff for hardware-assisted SPI @ 2 MHz
#if(F_CPU > 8000000L)
#define SPI_DELAY asm volatile("rjmp .+0"); // Burn 2 cycles
#elif(F_CPU > 4000000L)
#define SPI_DELAY asm volatile("nop"); // Burn 1 cycle
#else
#define SPI_DELAY // Run max speed
#endif
#define SPIBIT \
USICR = ((1<<USIWM0)|(1<<USITC)); \
SPI_DELAY \
USICR = ((1<<USIWM0)|(1<<USITC)|(1<<USICLK)); \
SPI_DELAY
static void spi_out(uint8_t n) {
USIDR = n;
SPIBIT
SPIBIT
SPIBIT
SPIBIT
SPIBIT
SPIBIT
SPIBIT
SPIBIT
}
#else
// All other boards support Full and Proper Hardware SPI
#include <SPI.h>
#define spi_out(n) (void)SPI.transfer(n)
#endif
/*****************************************************************************/
// Constructor for use with hardware SPI (specific clock/data pins):
LPD8806::LPD8806(uint16_t n) {
pixels = NULL;
begun = false;
updateLength(n);
updatePins();
}
// Constructor for use with arbitrary clock/data pins:
LPD8806::LPD8806(uint16_t n, uint8_t dpin, uint8_t cpin) {
pixels = NULL;
begun = false;
updateLength(n);
updatePins(dpin, cpin);
}
// isn't known at compile-time; situations where program config might be
// read from internal flash memory or an SD card, or arrive via serial
// command. If using this constructor, MUST follow up with updateLength()
// and updatePins() to establish the strip length and output pins!
LPD8806::LPD8806(void) {
numLEDs = numBytes = 0;
pixels = NULL;
begun = false;
updatePins(); // Must assume hardware SPI until pins are set
}
// Activate hard/soft SPI as appropriate:
void LPD8806::begin(void) {
if(hardwareSPI == true) startSPI();
else startBitbang();
begun = true;
}
// Change pin assignments post-constructor, switching to hardware SPI:
void LPD8806::updatePins(void) {
pinMode(datapin, INPUT); // Restore data and clock pins to inputs
pinMode(clkpin , INPUT);
datapin = clkpin = 0;
hardwareSPI = true;
// If begin() was previously invoked, init the SPI hardware now:
if(begun == true) startSPI();
// Otherwise, SPI is NOT initted until begin() is explicitly called.
}
// Change pin assignments post-constructor, using arbitrary pins:
void LPD8806::updatePins(uint8_t dpin, uint8_t cpin) {
if(begun == true) { // If begin() was previously invoked...
// If previously using hardware SPI, turn that off:
if(hardwareSPI) {
#ifdef __AVR_ATtiny85__
DDRB &= ~(_BV(PORTB1) | _BV(PORTB2));
#else
SPI.end();
#endif
} else {
pinMode(datapin, INPUT); // Restore prior data and clock pins to inputs
pinMode(clkpin , INPUT);
}
}
datapin = dpin;
clkpin = cpin;
#ifdef __AVR__
clkport = portOutputRegister(digitalPinToPort(cpin));
clkpinmask = digitalPinToBitMask(cpin);
dataport = portOutputRegister(digitalPinToPort(dpin));
datapinmask = digitalPinToBitMask(dpin);
#endif
// If previously begun, enable 'soft' SPI outputs now
if(begun == true) startBitbang();
hardwareSPI = false;
}
// Enable SPI hardware and set up protocol details:
void LPD8806::startSPI(void) {
#ifdef __AVR_ATtiny85__
PORTB &= ~(_BV(PORTB1) | _BV(PORTB2)); // Outputs
DDRB |= _BV(PORTB1) | _BV(PORTB2); // DO (NOT MOSI) + SCK
#else
SPI.begin();
SPI.setBitOrder(MSBFIRST);
SPI.setDataMode(SPI_MODE0);
// SPI bus is run at 2MHz. Although the LPD8806 should, in theory,
// work up to 20MHz. Experiment and see what you get.
#if defined(__AVR__) || defined(CORE_TEENSY)
SPI.setClockDivider(SPI_CLOCK_DIV8);
#else
SPI.setClockDivider((F_CPU + 1000000L) / 2000000L);
#endif
#endif
// Issue initial latch/reset to strip:
for(uint16_t i=((numLEDs+31)/32); i>0; i--) spi_out(0);
}
// Enable software SPI pins and issue initial latch:
void LPD8806::startBitbang() {
pinMode(datapin, OUTPUT);
pinMode(clkpin , OUTPUT);
#ifdef __AVR__
*dataport &= ~datapinmask; // Data is held low throughout (latch = 0)
for(uint16_t i=((numLEDs+31)/32)*8; i>0; i--) {
*clkport |= clkpinmask;
*clkport &= ~clkpinmask;
}
#else
digitalWrite(datapin, LOW);
for(uint16_t i=((numLEDs+31)/32)*8; i>0; i--) {
digitalWrite(clkpin, HIGH);
digitalWrite(clkpin, LOW);
}
#endif
}
// Change strip length (see notes with empty constructor, above):
void LPD8806::updateLength(uint16_t n) {
uint8_t latchBytes;
uint16_t dataBytes, totalBytes;
numLEDs = numBytes = 0;
if(pixels) free(pixels); // Free existing data (if any)
dataBytes = n * 3;
latchBytes = (n + 31) / 32;
totalBytes = dataBytes + latchBytes;
if((pixels = (uint8_t *)malloc(totalBytes))) { // Alloc new data
numLEDs = n;
numBytes = totalBytes;
memset( pixels , 0x80, dataBytes); // Init to RGB 'off' state
memset(&pixels[dataBytes], 0 , latchBytes); // Clear latch bytes
}
// 'begun' state does not change -- pins retain prior modes
}
uint16_t LPD8806::numPixels(void) {
return numLEDs;
}
void LPD8806::show(void) {
uint8_t *ptr = pixels;
uint16_t i = numBytes;
// This doesn't need to distinguish among individual pixel color
// bytes vs. latch data, etc. Everything is laid out in one big
// flat buffer and issued the same regardless of purpose.
if(hardwareSPI) {
while(i--) spi_out(*ptr++);
} else {
uint8_t p, bit;
while(i--) {
p = *ptr++;
for(bit=0x80; bit; bit >>= 1) {
#ifdef __AVR__
if(p & bit) *dataport |= datapinmask;
else *dataport &= ~datapinmask;
*clkport |= clkpinmask;
*clkport &= ~clkpinmask;
#else
if(p & bit) digitalWrite(datapin, HIGH);
else digitalWrite(datapin, LOW);
digitalWrite(clkpin, HIGH);
digitalWrite(clkpin, LOW);
#endif
}
}
}
}
// Convert separate R,G,B into combined 32-bit GRB color:
uint32_t LPD8806::Color(byte r, byte g, byte b) {
return ((uint32_t)(g | 0x80) << 16) |
((uint32_t)(r | 0x80) << 8) |
b | 0x80 ;
}
// Set pixel color from separate 7-bit R, G, B components:
void LPD8806::setPixelColor(uint16_t n, uint8_t r, uint8_t g, uint8_t b) {
if(n < numLEDs) { // Arrays are 0-indexed, thus NOT '<='
uint8_t *p = &pixels[n * 3];
*p++ = g | 0x80; // Strip color order is GRB,
*p++ = r | 0x80; // not the more common RGB,
*p++ = b | 0x80; // so the order here is intentional; don't "fix"
}
}
// Set pixel color from 'packed' 32-bit GRB (not RGB) value:
void LPD8806::setPixelColor(uint16_t n, uint32_t c) {
if(n < numLEDs) { // Arrays are 0-indexed, thus NOT '<='
uint8_t *p = &pixels[n * 3];
*p++ = (c >> 16) | 0x80;
*p++ = (c >> 8) | 0x80;
*p++ = c | 0x80;
}
}
// Query color from previously-set pixel (returns packed 32-bit GRB value)
uint32_t LPD8806::getPixelColor(uint16_t n) {
if(n < numLEDs) {
uint16_t ofs = n * 3;
return ((uint32_t)(pixels[ofs ] & 0x7f) << 16) |
((uint32_t)(pixels[ofs + 1] & 0x7f) << 8) |
(uint32_t)(pixels[ofs + 2] & 0x7f);
}
return 0; // Pixel # is out of bounds
}
| [
"lyle.henkeman01@gmail.com"
] | lyle.henkeman01@gmail.com |
0c62a6cae0f9a506e4cad4a9d9f60f7b21887e60 | bf77f38c1d42ce97902bd5dc0e498d7d89ab4705 | /byalib/graph/二分木の最小共通祖先-LCA.cpp | 6bcf40d21e43fb3baeab95b278a8ea0b5b5bf6a7 | [] | no_license | byam/algorithms | 6c570c8d00ad5457346d6851f634d962b2ef744e | f3db7230655c945412774505254e2be4cbf23074 | refs/heads/master | 2022-05-12T16:24:39.831337 | 2022-04-08T13:59:07 | 2022-04-08T13:59:07 | 68,830,972 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,040 | cpp | #include <bits/stdc++.h>
using namespace std;
/* LCA(G, root): Lowest Common Ancestor を求める構造体
- 木 G に対する
- 根を root とする
計算時間
- 前処理:𝑂(𝑁log𝐾) 時間, 𝑂(𝑁log𝐾) 空間
- クエリ:𝑂(log𝐾)
I/F
- int query(int u, int v): LCA を返す
- get_dist(int u, int v): LCA で 任意の2頂点間の距離が分かる
- is_on_path(int u, int v, int a): パス上にある頂点があるか分かる
ref: https://algo-logic.info/lca/
*/
using Graph = vector<vector<int>>;
struct LCA {
vector<vector<int>> parent; // parent[k][u]:= u の 2^k 先の親
vector<int> dist; // root からの距離
LCA(const Graph &G, int root = 0) { init(G, root); }
// 初期化
void init(const Graph &G, int root = 0) {
int V = G.size();
int K = 1;
while ((1 << K) < V) K++;
parent.assign(K, vector<int>(V, -1));
dist.assign(V, -1);
dfs(G, root, -1, 0);
for (int k = 0; k + 1 < K; k++) {
for (int v = 0; v < V; v++) {
if (parent[k][v] < 0) {
parent[k + 1][v] = -1;
} else {
parent[k + 1][v] = parent[k][parent[k][v]];
}
}
}
}
// 根からの距離と1つ先の頂点を求める
void dfs(const Graph &G, int v, int p, int d) {
parent[0][v] = p;
dist[v] = d;
for (auto e : G[v]) {
if (e != p) dfs(G, e, v, d + 1);
}
}
int query(int u, int v) {
if (dist[u] < dist[v]) swap(u, v); // u の方が深いとする
int K = parent.size();
// LCA までの距離を同じにする
for (int k = 0; k < K; k++) {
if ((dist[u] - dist[v]) >> k & 1) {
u = parent[k][u];
}
}
// 二分探索で LCA を求める
if (u == v) return u;
for (int k = K - 1; k >= 0; k--) {
if (parent[k][u] != parent[k][v]) {
u = parent[k][u];
v = parent[k][v];
}
}
return parent[0][u];
}
// LCA で 任意の2頂点間の距離が分かる
int get_dist(int u, int v) {
return dist[u] + dist[v] - 2 * dist[query(u, v)];
}
// パス上にある頂点があるか分かる
bool is_on_path(int u, int v, int a) {
return get_dist(u, a) + get_dist(a, v) == get_dist(u, v);
}
};
int main() {
// グラフ入力
int n;
cin >> n;
Graph g(n);
for (int i = 0; i < n - 1; i++) {
int a, b;
cin >> a >> b;
a--;
b--;
g[a].push_back(b);
g[b].push_back(a);
}
// LCA 作成
LCA lca(g, 0);
// クエリ
int q;
cin >> q;
for (int i = 0; i < q; i++) {
int a, b;
cin >> a, b;
a--;
b--;
// 閉路サイズ
cout << lca.get_dist(a, b) + 1 << endl;
}
return 0;
}
| [
"bya_ganbaatar@r.recruit.co.jp"
] | bya_ganbaatar@r.recruit.co.jp |
01f2accbf3a5deff450bdeb0bdf4ab22da3db29e | 44293e98bd059b47a9bb79ede3402c6ffa471416 | /RemoveDuplicatesFromSortedList/RemoveDuplicatesFromSortedList.cpp | 0761480141205558e3af0e22c6a3712c0bdb8d7b | [] | no_license | ishaofeng/LeetCode | 17a30885286a2e93da53493bd07fc87c5cd505fb | eaf2e67343e3d913eb1a9b833e300b73baa407c6 | refs/heads/master | 2016-09-05T08:56:40.120656 | 2014-11-27T00:24:49 | 2014-11-27T00:24:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,795 | cpp | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
ListNode *deleteDuplicates(ListNode *head)
{
if (head == NULL || head->next == NULL)
{
return head;
}
ListNode *node = head->next, *prev = head;
while (node != NULL)
{
if (node->val == prev->val)
{
prev->next = node->next;
delete node;
node = prev->next;
}
else
{
prev = node;
node = node->next;
}
}
return head;
}
ListNode *reverseList(ListNode *head)
{
if (head == NULL || head->next == NULL)
{
return head;
}
ListNode *next = NULL, *node = NULL;
node = head->next;
head->next = NULL;
while (node)
{
next = node->next;
node->next = head;
head = node;
node = next;
}
return head;
}
void print(ListNode *head)
{
if ( head != NULL)
{
cout << head->val << " ";
print(head->next);
}
else
{
cout << endl;
}
}
};
int main()
{
int val[] = {5, 5, 4, 4, 3, 2, 1, 1};
int len = sizeof(val) / sizeof(val[0]);
ListNode head(0), *newnode;
for (int i = 0; i < len; ++i)
{
newnode = new ListNode(val[i]);
newnode->next = head.next;
head.next = newnode;
}
Solution s;
ListNode *h = s.deleteDuplicates(head.next);
s.print(h);
return 0;
}
| [
"ishaofeng@foxmail.com"
] | ishaofeng@foxmail.com |
6283cab79958f353b9193cfde4cf09707357f21d | 6a721fb3eecf92950e1f6007fb49c399f0b3cb7c | /SDK/PUBG_NewMessageBorderWidget_functions.cpp | 8c797f78e12bc6c65a54c0025b53b6ee74c3fe39 | [] | no_license | handsomeprince/PUBG-SDK-3 | 5474c48041b6fd4e4be975c222f76b6c02df9f31 | 5a922157f770a49c82ae597284d2a7cb60c86515 | refs/heads/master | 2021-04-15T09:46:11.411487 | 2018-02-22T06:13:30 | 2018-02-22T06:13:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,834 | cpp | // PlayerUnknown's Battlegrounds (2.6.23) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "PUBG_NewMessageBorderWidget_parameters.hpp"
namespace Classes
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function NewMessageBorderWidget.NewMessageBorderWidget_C.TickMove
// (Public, HasDefaults, BlueprintCallable, BlueprintEvent)
// Parameters:
// float Time (Parm, ZeroConstructor, IsPlainOldData)
void UNewMessageBorderWidget_C::TickMove(float Time)
{
static auto fn = UObject::FindObject<UFunction>("Function NewMessageBorderWidget.NewMessageBorderWidget_C.TickMove");
UNewMessageBorderWidget_C_TickMove_Params params;
params.Time = Time;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function NewMessageBorderWidget.NewMessageBorderWidget_C.UpdatePositionInfo
// (Public, HasDefaults, BlueprintCallable, BlueprintEvent)
void UNewMessageBorderWidget_C::UpdatePositionInfo()
{
static auto fn = UObject::FindObject<UFunction>("Function NewMessageBorderWidget.NewMessageBorderWidget_C.UpdatePositionInfo");
UNewMessageBorderWidget_C_UpdatePositionInfo_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function NewMessageBorderWidget.NewMessageBorderWidget_C.IsFull
// (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure)
// Parameters:
// bool Full (Parm, OutParm, ZeroConstructor, IsPlainOldData)
void UNewMessageBorderWidget_C::IsFull(bool* Full)
{
static auto fn = UObject::FindObject<UFunction>("Function NewMessageBorderWidget.NewMessageBorderWidget_C.IsFull");
UNewMessageBorderWidget_C_IsFull_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (Full != nullptr)
*Full = params.Full;
}
// Function NewMessageBorderWidget.NewMessageBorderWidget_C.SetSizeRule
// (Public, HasDefaults, BlueprintCallable, BlueprintEvent)
// Parameters:
// TEnumAsByte<ESlateSizeRule> TopSize (Parm, ZeroConstructor, IsPlainOldData)
// TEnumAsByte<ESlateSizeRule> BottomSize (Parm, ZeroConstructor, IsPlainOldData)
void UNewMessageBorderWidget_C::SetSizeRule(TEnumAsByte<ESlateSizeRule> TopSize, TEnumAsByte<ESlateSizeRule> BottomSize)
{
static auto fn = UObject::FindObject<UFunction>("Function NewMessageBorderWidget.NewMessageBorderWidget_C.SetSizeRule");
UNewMessageBorderWidget_C_SetSizeRule_Params params;
params.TopSize = TopSize;
params.BottomSize = BottomSize;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function NewMessageBorderWidget.NewMessageBorderWidget_C.OnRemoveMessage
// (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UNewSystemMessageWidget_C* SystemMessageWidget (Parm, ZeroConstructor, IsPlainOldData)
void UNewMessageBorderWidget_C::OnRemoveMessage(class UNewSystemMessageWidget_C* SystemMessageWidget)
{
static auto fn = UObject::FindObject<UFunction>("Function NewMessageBorderWidget.NewMessageBorderWidget_C.OnRemoveMessage");
UNewMessageBorderWidget_C_OnRemoveMessage_Params params;
params.SystemMessageWidget = SystemMessageWidget;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function NewMessageBorderWidget.NewMessageBorderWidget_C.AddMessage
// (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UNewSystemMessageWidget_C* Message (Parm, ZeroConstructor, IsPlainOldData)
void UNewMessageBorderWidget_C::AddMessage(class UNewSystemMessageWidget_C* Message)
{
static auto fn = UObject::FindObject<UFunction>("Function NewMessageBorderWidget.NewMessageBorderWidget_C.AddMessage");
UNewMessageBorderWidget_C_AddMessage_Params params;
params.Message = Message;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function NewMessageBorderWidget.NewMessageBorderWidget_C.DisplayKilledMessage
// (Public, HasDefaults, BlueprintCallable, BlueprintEvent)
// Parameters:
// struct FDeathMessage DeathMessage (Parm)
void UNewMessageBorderWidget_C::DisplayKilledMessage(const struct FDeathMessage& DeathMessage)
{
static auto fn = UObject::FindObject<UFunction>("Function NewMessageBorderWidget.NewMessageBorderWidget_C.DisplayKilledMessage");
UNewMessageBorderWidget_C_DisplayKilledMessage_Params params;
params.DeathMessage = DeathMessage;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function NewMessageBorderWidget.NewMessageBorderWidget_C.Construct
// (BlueprintCosmetic, Event, Public, BlueprintEvent)
void UNewMessageBorderWidget_C::Construct()
{
static auto fn = UObject::FindObject<UFunction>("Function NewMessageBorderWidget.NewMessageBorderWidget_C.Construct");
UNewMessageBorderWidget_C_Construct_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function NewMessageBorderWidget.NewMessageBorderWidget_C.Tick
// (BlueprintCosmetic, Event, Public, BlueprintEvent)
// Parameters:
// struct FGeometry* MyGeometry (Parm, IsPlainOldData)
// float* InDeltaTime (Parm, ZeroConstructor, IsPlainOldData)
void UNewMessageBorderWidget_C::Tick(struct FGeometry* MyGeometry, float* InDeltaTime)
{
static auto fn = UObject::FindObject<UFunction>("Function NewMessageBorderWidget.NewMessageBorderWidget_C.Tick");
UNewMessageBorderWidget_C_Tick_Params params;
params.MyGeometry = MyGeometry;
params.InDeltaTime = InDeltaTime;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function NewMessageBorderWidget.NewMessageBorderWidget_C.ExecuteUbergraph_NewMessageBorderWidget
// (HasDefaults)
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void UNewMessageBorderWidget_C::ExecuteUbergraph_NewMessageBorderWidget(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function NewMessageBorderWidget.NewMessageBorderWidget_C.ExecuteUbergraph_NewMessageBorderWidget");
UNewMessageBorderWidget_C_ExecuteUbergraph_NewMessageBorderWidget_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"number201724@me.com"
] | number201724@me.com |
4cc6df30c141352dc972f1f2f0f39d44d060175a | 92b377f464f61ed81afdcd89fa481d05c98f75e1 | /src/timer.cpp | 9b8c2df552a1fb24a527ed64a12e83a7ac75c5c1 | [
"MIT"
] | permissive | crockeo/hc | d87507ade5be85b1041bd42f25c9c1c0ab5ae57b | a5f9eaa1051e8825fa765d120d8ea76682909a5a | refs/heads/master | 2020-05-18T07:24:52.109471 | 2015-01-08T16:23:39 | 2015-01-08T16:23:39 | 28,546,458 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,065 | cpp | #include "timer.hpp"
//////////////
// Includes //
#include "delta.hpp"
//////////
// Code //
// Constructing a timer with a cap.
Timer::Timer(float cap) {
this->running = false;
this->accum = 0;
this->cap = cap;
}
// Constructing a default timer.
Timer::Timer() {
this->running = false;
this->accum = 0;
this->cap = 0;
}
// Starting the timer.
void Timer::start() {
if (!this->running)
this->running = true;
}
// Stopping the timer (such that if it's
void Timer::stop() {
if (this->running)
this->running = false;
}
// Resetting the accumulated time.
void Timer::reset() {
this->accum = 0;
}
// Updating the timer.
void Timer::update() {
if (this->cap != 0)
if (this->accum > this->cap)
this->accum -= this->cap;
if (this->running)
this->accum += this->delta.since();
}
// Getting the time since the timer was started.
float Timer::getTime() const { return this->accum; }
// Checking if the timer is running.
bool Timer::isRunning() const { return this->running; }
| [
"crockeo@gmail.com"
] | crockeo@gmail.com |
6ca6c3d860e2425a11f40638661ff3af8bb64700 | a7764174fb0351ea666faa9f3b5dfe304390a011 | /inc/OSD_FontMgr.hxx | 622f450b5bad75b6c1a29c96e3cba9f422ff2f9a | [] | no_license | uel-dataexchange/Opencascade_uel | f7123943e9d8124f4fa67579e3cd3f85cfe52d91 | 06ec93d238d3e3ea2881ff44ba8c21cf870435cd | refs/heads/master | 2022-11-16T07:40:30.837854 | 2020-07-08T01:56:37 | 2020-07-08T01:56:37 | 276,290,778 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,351 | hxx | // This file is generated by WOK (CPPExt).
// Please do not edit this file; modify original file instead.
// The copyright and license terms as defined for the original file apply to
// this header file considered to be the "object code" form of the original source.
#ifndef _OSD_FontMgr_HeaderFile
#define _OSD_FontMgr_HeaderFile
#ifndef _Standard_HeaderFile
#include <Standard.hxx>
#endif
#ifndef _Standard_DefineHandle_HeaderFile
#include <Standard_DefineHandle.hxx>
#endif
#ifndef _Handle_OSD_FontMgr_HeaderFile
#include <Handle_OSD_FontMgr.hxx>
#endif
#ifndef _OSD_NListOfSystemFont_HeaderFile
#include <OSD_NListOfSystemFont.hxx>
#endif
#ifndef _MMgt_TShared_HeaderFile
#include <MMgt_TShared.hxx>
#endif
//! Structure for store of Font System Information <br>
class OSD_FontMgr : public MMgt_TShared {
public:
Standard_EXPORT static Handle_OSD_FontMgr GetInstance() ;
Standard_EXPORT OSD_NListOfSystemFont GetAvalableFonts() const;
DEFINE_STANDARD_RTTI(OSD_FontMgr)
protected:
private:
//! Creates empty font object <br>
Standard_EXPORT OSD_FontMgr();
Standard_EXPORT void InitFontDataBase() ;
OSD_NListOfSystemFont MyListOfFonts;
};
// other Inline functions and methods (like "C++: function call" methods)
#endif
| [
"shoka.sho2@excel.co.jp"
] | shoka.sho2@excel.co.jp |
4b01bcd8da6d4c7b7b28203d33f75e496f407ec3 | b21b5ff3469f651c688ffc4d534f3f7183718496 | /PhotoStage/widgets/mapview/imagemarker.h | 404c773c67e1ffdf4e581c5c0dbe61c3ab6fed4f | [] | no_license | jaapgeurts/photostage | 8d88de7e9d6fe4a714cf0931284d57356006d9d7 | aabfe1b6fd607fab6b4f52089a2b691cebf274af | refs/heads/master | 2021-01-10T10:26:15.306997 | 2019-02-22T12:38:00 | 2019-02-22T12:38:00 | 43,422,797 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 474 | h | #ifndef MAPVIEW_IMAGEMARKER_H
#define MAPVIEW_IMAGEMARKER_H
#include <QObject>
#include <QImage>
#include "abstractmarker.h"
namespace MapView
{
class ImageMarker : public AbstractMarker
{
public:
ImageMarker(QObject* parent = 0);
ImageMarker(const QImage& img, QObject* parent);
QSize size() const;
void paint(QPainter& painter, const MarkerInfo&, const QVariant&);
private:
QImage mIcon;
};
}
#endif // IMAGEMARKER_H
| [
"jaapg@gmx.net"
] | jaapg@gmx.net |
0e874444195f88d1432616c21cdd2cbe277ccb3e | a6b87253faeace0c4e1aa9400d0dd1e80ee4c1bd | /Project 260/VehicleCompDisplaySrc/searchWindow.h | bdb31b182b19404189ad886e7e7e8df090138996 | [] | no_license | poliu2s/CPSC-260 | 972b4140dacdc2720f4260c35295e072b66449c5 | a60ecd8f50cd25f95faf62e4a95c2fc61a433abf | refs/heads/master | 2021-01-10T19:03:48.024948 | 2012-12-27T22:23:42 | 2012-12-27T22:23:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,722 | h | #pragma once
// Author: Po Liu, 13623079, x2f7
// Date: 28 July 2010
// Class invariant:
// A user defined window class that displays the main GUI functionality by visually displaying
// the char matrix and allows the user to input words to find
#include <iostream>
#include <string>
#include <sstream>
#include "Simple_window.h"
#include "data.h"
#include "inputFormatter.h"
#include "MyLinkedList.h"
#ifndef SEARCHWINDOW_H
#define SEARCHWINDOW_H
struct searchWindow:Window
{
// Constructor that takes in a pointer to the wordsearch matrix
// pre: none
// post: sets up the window and draws everything
searchWindow(Point xy, int w, int h, const string& title, data* rawMatrix );
// Use of virtual method in destructor -------> one of the project requirements
virtual ~searchWindow() { }
// For displaying and holding the char array
data* wordSearch;
Text* displayMatrix[10][10];
Text* sampleWord1;
Text* sampleWord2;
Text* sampleWord3;
Text* sampleWord4;
Text* sampleWord5;
Text* sampleWord6;
private:
Button find_button;
Button quit_button;
In_box next_x;
// Callback function for find
// pre: none
// post: executes the find()
static void cb_find(Address, Address);
// When the find key is pressed, take the word in the inbox and look for it
// If it is found, then change the color of the word in the GUI
// pre: find key is clicked
// post: Highlights a word in the matrix, if not found then does nothing
void find();
// Callback function for quit
// pre: none
// post: executes the quit()
static void cb_quit(Address, Address);
// Quits out of the program if quit button is pressed
// pre: quit button click
// post: program exists
void quit();
};
#endif | [
"po.liu.2s@gmail.com"
] | po.liu.2s@gmail.com |
93f99f9fc43fd7ff4d5bc79947d90cf765861e67 | 172e4895181dca01903565564bfe13679dadc38f | /src/application/repository/ClientRepository.cpp | 67469be05c34ea13d3c1d81a4c599b4f512cf357 | [] | no_license | Brunomcarvalho89/RentCar | f39e552622801e122d90e4f63afadaa483afef92 | 2299d2fc8ea8dbda13be436507d97f781de0b56f | refs/heads/main | 2023-03-23T08:13:41.351309 | 2021-03-05T00:43:15 | 2021-03-05T00:43:15 | 344,620,069 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 695 | cpp | /*
* File: CarClassificationRepository.cpp
* Author: brunomcarvalho89@gmail.com
*
* Created on 19 de fevereiro de 2021, 14:11
*/
#include <algorithm>
#include <vector>
#include "application/repository/ClientRepository.hpp"
#include "domain/Client.hpp"
ClientRepository::ClientRepository() {
}
ClientRepository::~ClientRepository() {
}
void ClientRepository::add(std::shared_ptr<Client> client) {
this->repository.insert(this->repository.begin(), client);
}
std::shared_ptr<Client> ClientRepository::getByID(int id) {
for (std::shared_ptr<Client> elem : this->repository) {
if (elem->getId() == id) {
return elem;
}
}
return NULL;
}
| [
"brunomcarvalho89@gmail.com"
] | brunomcarvalho89@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.