hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6c867e751e40f380c966fc5a26db8ed465978b89 | 2,075 | cpp | C++ | test/seatalk/Test_seatalk_message_30.cpp | ShadowTeolog/marnav | 094dd06a2b9e52591bc9c3879ea4b5cf34a92192 | [
"BSD-4-Clause"
] | null | null | null | test/seatalk/Test_seatalk_message_30.cpp | ShadowTeolog/marnav | 094dd06a2b9e52591bc9c3879ea4b5cf34a92192 | [
"BSD-4-Clause"
] | 1 | 2021-11-10T14:40:21.000Z | 2021-11-10T14:40:21.000Z | test/seatalk/Test_seatalk_message_30.cpp | ShadowTeolog/marnav | 094dd06a2b9e52591bc9c3879ea4b5cf34a92192 | [
"BSD-4-Clause"
] | 1 | 2020-12-21T16:38:02.000Z | 2020-12-21T16:38:02.000Z | #include <gtest/gtest.h>
#include <marnav/seatalk/message_30.hpp>
namespace
{
using namespace marnav::seatalk;
class Test_seatalk_message_30 : public ::testing::Test
{
};
TEST_F(Test_seatalk_message_30, construction)
{
message_30 m;
}
TEST_F(Test_seatalk_message_30, parse_invalid_data_size)
{
EXPECT_ANY_THROW(message_30::parse({2, 0x00}));
EXPECT_ANY_THROW(message_30::parse({4, 0x00}));
}
TEST_F(Test_seatalk_message_30, parse_invalid_length)
{
EXPECT_ANY_THROW(message_30::parse({0x30, 0x01, 0x00}));
EXPECT_ANY_THROW(message_30::parse({0x30, 0x02, 0x00}));
}
TEST_F(Test_seatalk_message_30, parse)
{
struct test_case {
raw data;
message_30::intensity value;
};
std::vector<test_case> cases{
{{0x30, 0x00, 0x00}, message_30::intensity::L0},
{{0x30, 0x00, 0x04}, message_30::intensity::L1},
{{0x30, 0x00, 0x08}, message_30::intensity::L2},
{{0x30, 0x00, 0x0c}, message_30::intensity::L3},
};
for (auto const & t : cases) {
auto generic_message = message_30::parse(t.data);
EXPECT_TRUE(generic_message != nullptr);
if (!generic_message)
continue;
auto m = message_cast<message_30>(generic_message);
EXPECT_TRUE(m != nullptr);
if (!m)
continue;
EXPECT_EQ(message_id::set_lamp_intensity, m->type());
EXPECT_EQ(t.value, m->get_intensity());
}
}
TEST_F(Test_seatalk_message_30, write_default)
{
const raw expected{0x30, 0x00, 0x00};
message_30 m;
EXPECT_EQ(expected, m.get_data());
}
TEST_F(Test_seatalk_message_30, set_intensity)
{
{
const raw expected{0x30, 0x00, 0x00};
message_30 m;
m.set_intensity(message_30::intensity::L0);
EXPECT_EQ(expected, m.get_data());
}
{
const raw expected{0x30, 0x00, 0x04};
message_30 m;
m.set_intensity(message_30::intensity::L1);
EXPECT_EQ(expected, m.get_data());
}
{
const raw expected{0x30, 0x00, 0x08};
message_30 m;
m.set_intensity(message_30::intensity::L2);
EXPECT_EQ(expected, m.get_data());
}
{
const raw expected{0x30, 0x00, 0x0c};
message_30 m;
m.set_intensity(message_30::intensity::L3);
EXPECT_EQ(expected, m.get_data());
}
}
}
| 22.074468 | 57 | 0.715663 | [
"vector"
] |
6c86c64b17ac9795a5f67da4b613d754e24de384 | 27,282 | cpp | C++ | 01_Develop/libXMFFmpeg/Source/libavformat/isom.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | 2 | 2017-08-03T07:15:00.000Z | 2018-06-18T10:32:53.000Z | 01_Develop/libXMFFmpeg/Source/libavformat/isom.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | null | null | null | 01_Develop/libXMFFmpeg/Source/libavformat/isom.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | 2 | 2019-03-04T22:57:42.000Z | 2020-03-06T01:32:26.000Z | /*
* ISO Media common code
* Copyright (c) 2001 Fabrice Bellard
* Copyright (c) 2002 Francois Revol <revol@free.fr>
* Copyright (c) 2006 Baptiste Coudurier <baptiste.coudurier@free.fr>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "internal.h"
#include "isom.h"
#include "riff.h"
#include "../libavcodec/mpeg4audio.h"
#include "../libavcodec/mpegaudiodata.h"
/* http://www.mp4ra.org */
/* ordered by muxing preference */
const AVCodecTag ff_mp4_obj_type[] = {
{ CODEC_ID_MOV_TEXT , 0x08 },
{ CODEC_ID_MPEG4 , 0x20 },
{ CODEC_ID_H264 , 0x21 },
{ CODEC_ID_AAC , 0x40 },
{ CODEC_ID_MP4ALS , 0x40 }, /* 14496-3 ALS */
{ CODEC_ID_MPEG2VIDEO, 0x61 }, /* MPEG2 Main */
{ CODEC_ID_MPEG2VIDEO, 0x60 }, /* MPEG2 Simple */
{ CODEC_ID_MPEG2VIDEO, 0x62 }, /* MPEG2 SNR */
{ CODEC_ID_MPEG2VIDEO, 0x63 }, /* MPEG2 Spatial */
{ CODEC_ID_MPEG2VIDEO, 0x64 }, /* MPEG2 High */
{ CODEC_ID_MPEG2VIDEO, 0x65 }, /* MPEG2 422 */
{ CODEC_ID_AAC , 0x66 }, /* MPEG2 AAC Main */
{ CODEC_ID_AAC , 0x67 }, /* MPEG2 AAC Low */
{ CODEC_ID_AAC , 0x68 }, /* MPEG2 AAC SSR */
{ CODEC_ID_MP3 , 0x69 }, /* 13818-3 */
{ CODEC_ID_MP2 , 0x69 }, /* 11172-3 */
{ CODEC_ID_MPEG1VIDEO, 0x6A }, /* 11172-2 */
{ CODEC_ID_MP3 , 0x6B }, /* 11172-3 */
{ CODEC_ID_MJPEG , 0x6C }, /* 10918-1 */
{ CODEC_ID_PNG , 0x6D },
{ CODEC_ID_JPEG2000 , 0x6E }, /* 15444-1 */
{ CODEC_ID_VC1 , 0xA3 },
{ CODEC_ID_DIRAC , 0xA4 },
{ CODEC_ID_AC3 , 0xA5 },
{ CODEC_ID_DTS , 0xA9 }, /* mp4ra.org */
{ CODEC_ID_VORBIS , 0xDD }, /* non standard, gpac uses it */
{ CODEC_ID_DVD_SUBTITLE, 0xE0 }, /* non standard, see unsupported-embedded-subs-2.mp4 */
{ CODEC_ID_QCELP , 0xE1 },
{ CODEC_ID_MPEG4SYSTEMS, 0x01 },
{ CODEC_ID_MPEG4SYSTEMS, 0x02 },
{ CODEC_ID_NONE , 0 },
};
const AVCodecTag codec_movvideo_tags[] = {
/* { CODEC_ID_, MKTAG('I', 'V', '5', '0') }, *//* Indeo 5.0 */
{ CODEC_ID_RAWVIDEO, MKTAG('r', 'a', 'w', ' ') }, /* Uncompressed RGB */
{ CODEC_ID_RAWVIDEO, MKTAG('y', 'u', 'v', '2') }, /* Uncompressed YUV422 */
{ CODEC_ID_RAWVIDEO, MKTAG('A', 'V', 'U', 'I') }, /* YUV with alpha-channel (AVID Uncompressed) */
{ CODEC_ID_RAWVIDEO, MKTAG('2', 'v', 'u', 'y') }, /* UNCOMPRESSED 8BIT 4:2:2 */
{ CODEC_ID_RAWVIDEO, MKTAG('y', 'u', 'v', 's') }, /* same as 2vuy but byte swapped */
{ CODEC_ID_RAWVIDEO, MKTAG('L', '5', '5', '5') },
{ CODEC_ID_RAWVIDEO, MKTAG('L', '5', '6', '5') },
{ CODEC_ID_RAWVIDEO, MKTAG('B', '5', '6', '5') },
{ CODEC_ID_RAWVIDEO, MKTAG('2', '4', 'B', 'G') },
{ CODEC_ID_RAWVIDEO, MKTAG('B', 'G', 'R', 'A') },
{ CODEC_ID_RAWVIDEO, MKTAG('R', 'G', 'B', 'A') },
{ CODEC_ID_RAWVIDEO, MKTAG('A', 'B', 'G', 'R') },
{ CODEC_ID_RAWVIDEO, MKTAG('b', '1', '6', 'g') },
{ CODEC_ID_RAWVIDEO, MKTAG('b', '4', '8', 'r') },
{ CODEC_ID_RAWVIDEO, MKTAG('D', 'V', 'O', 'O') }, /* Digital Voodoo SD 8 Bit */
{ CODEC_ID_R10K, MKTAG('R', '1', '0', 'k') }, /* UNCOMPRESSED 10BIT RGB */
{ CODEC_ID_R10K, MKTAG('R', '1', '0', 'g') }, /* UNCOMPRESSED 10BIT RGB */
{ CODEC_ID_R210, MKTAG('r', '2', '1', '0') }, /* UNCOMPRESSED 10BIT RGB */
{ CODEC_ID_AVRP, MKTAG('A', 'V', 'r', 'p') }, /* Avid 1:1 10-bit RGB Packer */
{ CODEC_ID_AVRP, MKTAG('S', 'U', 'D', 'S') }, /* Avid DS Uncompressed */
{ CODEC_ID_V210, MKTAG('v', '2', '1', '0') }, /* UNCOMPRESSED 10BIT 4:2:2 */
{ CODEC_ID_V308, MKTAG('v', '3', '0', '8') }, /* UNCOMPRESSED 4:4:4 */
{ CODEC_ID_V410, MKTAG('v', '4', '1', '0') }, /* UNCOMPRESSED 10BIT 4:4:4 */
{ CODEC_ID_Y41P, MKTAG('Y', '4', '1', 'P') }, /* UNCOMPRESSED 12BIT 4:1:1 */
{ CODEC_ID_YUV4, MKTAG('y', 'u', 'v', '4') }, /* libquicktime packed yuv420p */
{ CODEC_ID_MJPEG, MKTAG('j', 'p', 'e', 'g') }, /* PhotoJPEG */
{ CODEC_ID_MJPEG, MKTAG('m', 'j', 'p', 'a') }, /* Motion-JPEG (format A) */
{ CODEC_ID_MJPEG, MKTAG('A', 'V', 'D', 'J') }, /* MJPEG with alpha-channel (AVID JFIF meridien compressed) */
/* { CODEC_ID_MJPEG, MKTAG('A', 'V', 'R', 'n') }, *//* MJPEG with alpha-channel (AVID ABVB/Truevision NuVista) */
{ CODEC_ID_MJPEG, MKTAG('d', 'm', 'b', '1') }, /* Motion JPEG OpenDML */
{ CODEC_ID_MJPEGB, MKTAG('m', 'j', 'p', 'b') }, /* Motion-JPEG (format B) */
{ CODEC_ID_SVQ1, MKTAG('S', 'V', 'Q', '1') }, /* Sorenson Video v1 */
{ CODEC_ID_SVQ1, MKTAG('s', 'v', 'q', '1') }, /* Sorenson Video v1 */
{ CODEC_ID_SVQ1, MKTAG('s', 'v', 'q', 'i') }, /* Sorenson Video v1 (from QT specs)*/
{ CODEC_ID_SVQ3, MKTAG('S', 'V', 'Q', '3') }, /* Sorenson Video v3 */
{ CODEC_ID_MPEG4, MKTAG('m', 'p', '4', 'v') },
{ CODEC_ID_MPEG4, MKTAG('D', 'I', 'V', 'X') }, /* OpenDiVX *//* sample files at http://heroinewarrior.com/xmovie.php3 use this tag */
{ CODEC_ID_MPEG4, MKTAG('X', 'V', 'I', 'D') },
{ CODEC_ID_MPEG4, MKTAG('3', 'I', 'V', '2') }, /* experimental: 3IVX files before ivx D4 4.5.1 */
{ CODEC_ID_H263, MKTAG('h', '2', '6', '3') }, /* H263 */
{ CODEC_ID_H263, MKTAG('s', '2', '6', '3') }, /* H263 ?? works */
{ CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'c', 'p') }, /* DV PAL */
{ CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'c', ' ') }, /* DV NTSC */
{ CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'p', 'p') }, /* DVCPRO PAL produced by FCP */
{ CODEC_ID_DVVIDEO, MKTAG('d', 'v', '5', 'p') }, /* DVCPRO50 PAL produced by FCP */
{ CODEC_ID_DVVIDEO, MKTAG('d', 'v', '5', 'n') }, /* DVCPRO50 NTSC produced by FCP */
{ CODEC_ID_DVVIDEO, MKTAG('A', 'V', 'd', 'v') }, /* AVID DV */
{ CODEC_ID_DVVIDEO, MKTAG('A', 'V', 'd', '1') }, /* AVID DV100 */
{ CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'h', 'q') }, /* DVCPRO HD 720p50 */
{ CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'h', 'p') }, /* DVCPRO HD 720p60 */
{ CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'h', '1') },
{ CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'h', '2') },
{ CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'h', '4') },
{ CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'h', '5') }, /* DVCPRO HD 50i produced by FCP */
{ CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'h', '6') }, /* DVCPRO HD 60i produced by FCP */
{ CODEC_ID_DVVIDEO, MKTAG('d', 'v', 'h', '3') }, /* DVCPRO HD 30p produced by FCP */
{ CODEC_ID_VP3, MKTAG('V', 'P', '3', '1') }, /* On2 VP3 */
{ CODEC_ID_RPZA, MKTAG('r', 'p', 'z', 'a') }, /* Apple Video (RPZA) */
{ CODEC_ID_CINEPAK, MKTAG('c', 'v', 'i', 'd') }, /* Cinepak */
{ CODEC_ID_8BPS, MKTAG('8', 'B', 'P', 'S') }, /* Planar RGB (8BPS) */
{ CODEC_ID_SMC, MKTAG('s', 'm', 'c', ' ') }, /* Apple Graphics (SMC) */
{ CODEC_ID_QTRLE, MKTAG('r', 'l', 'e', ' ') }, /* Apple Animation (RLE) */
{ CODEC_ID_MSRLE, MKTAG('W', 'R', 'L', 'E') },
{ CODEC_ID_QDRAW, MKTAG('q', 'd', 'r', 'w') }, /* QuickDraw */
{ CODEC_ID_RAWVIDEO, MKTAG('W', 'R', 'A', 'W') },
{ CODEC_ID_H264, MKTAG('a', 'v', 'c', '1') }, /* AVC-1/H.264 */
{ CODEC_ID_H264, MKTAG('a', 'i', '5', 'p') }, /* AVC-Intra 50M 720p24/30/60 */
{ CODEC_ID_H264, MKTAG('a', 'i', '5', 'q') }, /* AVC-Intra 50M 720p25/50 */
{ CODEC_ID_H264, MKTAG('a', 'i', '5', '2') }, /* AVC-Intra 50M 1080p25/50 */
{ CODEC_ID_H264, MKTAG('a', 'i', '5', '3') }, /* AVC-Intra 50M 1080p24/30/60 */
{ CODEC_ID_H264, MKTAG('a', 'i', '5', '5') }, /* AVC-Intra 50M 1080i50 */
{ CODEC_ID_H264, MKTAG('a', 'i', '5', '6') }, /* AVC-Intra 50M 1080i60 */
{ CODEC_ID_H264, MKTAG('a', 'i', '1', 'p') }, /* AVC-Intra 100M 720p24/30/60 */
{ CODEC_ID_H264, MKTAG('a', 'i', '1', 'q') }, /* AVC-Intra 100M 720p25/50 */
{ CODEC_ID_H264, MKTAG('a', 'i', '1', '2') }, /* AVC-Intra 100M 1080p25/50 */
{ CODEC_ID_H264, MKTAG('a', 'i', '1', '3') }, /* AVC-Intra 100M 1080p24/30/60 */
{ CODEC_ID_H264, MKTAG('a', 'i', '1', '5') }, /* AVC-Intra 100M 1080i50 */
{ CODEC_ID_H264, MKTAG('a', 'i', '1', '6') }, /* AVC-Intra 100M 1080i60 */
{ CODEC_ID_MPEG1VIDEO, MKTAG('m', '1', 'v', '1') }, /* Apple MPEG-1 Camcorder */
{ CODEC_ID_MPEG1VIDEO, MKTAG('m', 'p', 'e', 'g') }, /* MPEG */
{ CODEC_ID_MPEG1VIDEO, MKTAG('m', '1', 'v', ' ') },
{ CODEC_ID_MPEG2VIDEO, MKTAG('m', '2', 'v', '1') }, /* Apple MPEG-2 Camcorder */
{ CODEC_ID_MPEG2VIDEO, MKTAG('h', 'd', 'v', '1') }, /* MPEG2 HDV 720p30 */
{ CODEC_ID_MPEG2VIDEO, MKTAG('h', 'd', 'v', '2') }, /* MPEG2 HDV 1080i60 */
{ CODEC_ID_MPEG2VIDEO, MKTAG('h', 'd', 'v', '3') }, /* MPEG2 HDV 1080i50 */
{ CODEC_ID_MPEG2VIDEO, MKTAG('h', 'd', 'v', '4') }, /* MPEG2 HDV 720p24 */
{ CODEC_ID_MPEG2VIDEO, MKTAG('h', 'd', 'v', '5') }, /* MPEG2 HDV 720p25 */
{ CODEC_ID_MPEG2VIDEO, MKTAG('h', 'd', 'v', '6') }, /* MPEG2 HDV 1080p24 */
{ CODEC_ID_MPEG2VIDEO, MKTAG('h', 'd', 'v', '7') }, /* MPEG2 HDV 1080p25 */
{ CODEC_ID_MPEG2VIDEO, MKTAG('h', 'd', 'v', '8') }, /* MPEG2 HDV 1080p30 */
{ CODEC_ID_MPEG2VIDEO, MKTAG('h', 'd', 'v', '9') }, /* MPEG2 HDV 720p60 JVC */
{ CODEC_ID_MPEG2VIDEO, MKTAG('h', 'd', 'v', 'a') }, /* MPEG2 HDV 720p50 */
{ CODEC_ID_MPEG2VIDEO, MKTAG('m', 'x', '5', 'n') }, /* MPEG2 IMX NTSC 525/60 50mb/s produced by FCP */
{ CODEC_ID_MPEG2VIDEO, MKTAG('m', 'x', '5', 'p') }, /* MPEG2 IMX PAL 625/50 50mb/s produced by FCP */
{ CODEC_ID_MPEG2VIDEO, MKTAG('m', 'x', '4', 'n') }, /* MPEG2 IMX NTSC 525/60 40mb/s produced by FCP */
{ CODEC_ID_MPEG2VIDEO, MKTAG('m', 'x', '4', 'p') }, /* MPEG2 IMX PAL 625/50 40mb/s produced by FCP */
{ CODEC_ID_MPEG2VIDEO, MKTAG('m', 'x', '3', 'n') }, /* MPEG2 IMX NTSC 525/60 30mb/s produced by FCP */
{ CODEC_ID_MPEG2VIDEO, MKTAG('m', 'x', '3', 'p') }, /* MPEG2 IMX PAL 625/50 30mb/s produced by FCP */
{ CODEC_ID_MPEG2VIDEO, MKTAG('x', 'd', '5', '4') }, /* XDCAM HD422 720p24 CBR */
{ CODEC_ID_MPEG2VIDEO, MKTAG('x', 'd', '5', '5') }, /* XDCAM HD422 720p25 CBR */
{ CODEC_ID_MPEG2VIDEO, MKTAG('x', 'd', '5', '9') }, /* XDCAM HD422 720p60 CBR */
{ CODEC_ID_MPEG2VIDEO, MKTAG('x', 'd', '5', 'a') }, /* XDCAM HD422 720p50 CBR */
{ CODEC_ID_MPEG2VIDEO, MKTAG('x', 'd', '5', 'b') }, /* XDCAM HD422 1080i60 CBR */
{ CODEC_ID_MPEG2VIDEO, MKTAG('x', 'd', '5', 'c') }, /* XDCAM HD422 1080i50 CBR */
{ CODEC_ID_MPEG2VIDEO, MKTAG('x', 'd', '5', 'd') }, /* XDCAM HD422 1080p24 CBR */
{ CODEC_ID_MPEG2VIDEO, MKTAG('x', 'd', '5', 'e') }, /* XDCAM HD422 1080p25 CBR */
{ CODEC_ID_MPEG2VIDEO, MKTAG('x', 'd', '5', 'f') }, /* XDCAM HD422 1080p30 CBR */
{ CODEC_ID_MPEG2VIDEO, MKTAG('x', 'd', 'v', '1') }, /* XDCAM EX 720p30 VBR */
{ CODEC_ID_MPEG2VIDEO, MKTAG('x', 'd', 'v', '2') }, /* XDCAM HD 1080i60 */
{ CODEC_ID_MPEG2VIDEO, MKTAG('x', 'd', 'v', '3') }, /* XDCAM HD 1080i50 VBR */
{ CODEC_ID_MPEG2VIDEO, MKTAG('x', 'd', 'v', '4') }, /* XDCAM EX 720p24 VBR */
{ CODEC_ID_MPEG2VIDEO, MKTAG('x', 'd', 'v', '5') }, /* XDCAM EX 720p25 VBR */
{ CODEC_ID_MPEG2VIDEO, MKTAG('x', 'd', 'v', '6') }, /* XDCAM HD 1080p24 VBR */
{ CODEC_ID_MPEG2VIDEO, MKTAG('x', 'd', 'v', '7') }, /* XDCAM HD 1080p25 VBR */
{ CODEC_ID_MPEG2VIDEO, MKTAG('x', 'd', 'v', '8') }, /* XDCAM HD 1080p30 VBR */
{ CODEC_ID_MPEG2VIDEO, MKTAG('x', 'd', 'v', '9') }, /* XDCAM EX 720p60 VBR */
{ CODEC_ID_MPEG2VIDEO, MKTAG('x', 'd', 'v', 'a') }, /* XDCAM EX 720p50 VBR */
{ CODEC_ID_MPEG2VIDEO, MKTAG('x', 'd', 'v', 'b') }, /* XDCAM EX 1080i60 VBR */
{ CODEC_ID_MPEG2VIDEO, MKTAG('x', 'd', 'v', 'c') }, /* XDCAM EX 1080i50 VBR */
{ CODEC_ID_MPEG2VIDEO, MKTAG('x', 'd', 'v', 'd') }, /* XDCAM EX 1080p24 VBR */
{ CODEC_ID_MPEG2VIDEO, MKTAG('x', 'd', 'v', 'e') }, /* XDCAM EX 1080p25 VBR */
{ CODEC_ID_MPEG2VIDEO, MKTAG('x', 'd', 'v', 'f') }, /* XDCAM EX 1080p30 VBR */
{ CODEC_ID_MPEG2VIDEO, MKTAG('x', 'd', 'h', 'd') }, /* XDCAM HD 540p */
{ CODEC_ID_MPEG2VIDEO, MKTAG('x', 'd', 'h', '2') }, /* XDCAM HD422 540p */
{ CODEC_ID_MPEG2VIDEO, MKTAG('A', 'V', 'm', 'p') }, /* AVID IMX PAL */
{ CODEC_ID_JPEG2000, MKTAG('m', 'j', 'p', '2') }, /* JPEG 2000 produced by FCP */
{ CODEC_ID_TARGA, MKTAG('t', 'g', 'a', ' ') }, /* Truevision Targa */
{ CODEC_ID_TIFF, MKTAG('t', 'i', 'f', 'f') }, /* TIFF embedded in MOV */
{ CODEC_ID_GIF, MKTAG('g', 'i', 'f', ' ') }, /* embedded gif files as frames (usually one "click to play movie" frame) */
{ CODEC_ID_PNG, MKTAG('p', 'n', 'g', ' ') },
{ CODEC_ID_VC1, MKTAG('v', 'c', '-', '1') }, /* SMPTE RP 2025 */
{ CODEC_ID_CAVS, MKTAG('a', 'v', 's', '2') },
{ CODEC_ID_DIRAC, MKTAG('d', 'r', 'a', 'c') },
{ CODEC_ID_DNXHD, MKTAG('A', 'V', 'd', 'n') }, /* AVID DNxHD */
// { CODEC_ID_FLV1, MKTAG('H', '2', '6', '3') }, /* Flash Media Server */
{ CODEC_ID_MSMPEG4V3, MKTAG('3', 'I', 'V', 'D') }, /* 3ivx DivX Doctor */
{ CODEC_ID_RAWVIDEO, MKTAG('A', 'V', '1', 'x') }, /* AVID 1:1x */
{ CODEC_ID_RAWVIDEO, MKTAG('A', 'V', 'u', 'p') },
{ CODEC_ID_SGI, MKTAG('s', 'g', 'i', ' ') }, /* SGI */
{ CODEC_ID_DPX, MKTAG('d', 'p', 'x', ' ') }, /* DPX */
{ CODEC_ID_PRORES, MKTAG('a', 'p', 'c', 'h') }, /* Apple ProRes 422 High Quality */
{ CODEC_ID_PRORES, MKTAG('a', 'p', 'c', 'n') }, /* Apple ProRes 422 Standard Definition */
{ CODEC_ID_PRORES, MKTAG('a', 'p', 'c', 's') }, /* Apple ProRes 422 LT */
{ CODEC_ID_PRORES, MKTAG('a', 'p', 'c', 'o') }, /* Apple ProRes 422 Proxy */
{ CODEC_ID_PRORES, MKTAG('a', 'p', '4', 'h') }, /* Apple ProRes 4444 */
{ CODEC_ID_NONE, 0 },
};
const AVCodecTag codec_movaudio_tags[] = {
{ CODEC_ID_AAC, MKTAG('m', 'p', '4', 'a') },
{ CODEC_ID_AC3, MKTAG('a', 'c', '-', '3') }, /* ETSI TS 102 366 Annex F */
{ CODEC_ID_AC3, MKTAG('s', 'a', 'c', '3') }, /* Nero Recode */
{ CODEC_ID_ADPCM_IMA_QT, MKTAG('i', 'm', 'a', '4') },
{ CODEC_ID_ALAC, MKTAG('a', 'l', 'a', 'c') },
{ CODEC_ID_AMR_NB, MKTAG('s', 'a', 'm', 'r') }, /* AMR-NB 3gp */
{ CODEC_ID_AMR_WB, MKTAG('s', 'a', 'w', 'b') }, /* AMR-WB 3gp */
{ CODEC_ID_DTS, MKTAG('d', 't', 's', 'c') }, /* mp4ra.org */
{ CODEC_ID_DTS, MKTAG('D', 'T', 'S', ' ') }, /* non-standard */
{ CODEC_ID_DVAUDIO, MKTAG('v', 'd', 'v', 'a') },
{ CODEC_ID_DVAUDIO, MKTAG('d', 'v', 'c', 'a') },
{ CODEC_ID_EAC3, MKTAG('e', 'c', '-', '3') }, /* ETSI TS 102 366 Annex F */
{ CODEC_ID_GSM, MKTAG('a', 'g', 's', 'm') },
{ CODEC_ID_MACE3, MKTAG('M', 'A', 'C', '3') },
{ CODEC_ID_MACE6, MKTAG('M', 'A', 'C', '6') },
{ CODEC_ID_MP1, MKTAG('.', 'm', 'p', '1') },
{ CODEC_ID_MP2, MKTAG('.', 'm', 'p', '2') },
{ CODEC_ID_MP3, MKTAG('.', 'm', 'p', '3') },
{ CODEC_ID_MP3, 0x6D730055 },
{ CODEC_ID_NELLYMOSER, MKTAG('n', 'm', 'o', 's') }, /* Flash Media Server */
{ CODEC_ID_PCM_ALAW, MKTAG('a', 'l', 'a', 'w') },
{ CODEC_ID_PCM_F32BE, MKTAG('f', 'l', '3', '2') },
{ CODEC_ID_PCM_F32LE, MKTAG('f', 'l', '3', '2') },
{ CODEC_ID_PCM_F64BE, MKTAG('f', 'l', '6', '4') },
{ CODEC_ID_PCM_F64LE, MKTAG('f', 'l', '6', '4') },
{ CODEC_ID_PCM_MULAW, MKTAG('u', 'l', 'a', 'w') },
{ CODEC_ID_PCM_S16BE, MKTAG('t', 'w', 'o', 's') },
{ CODEC_ID_PCM_S16LE, MKTAG('s', 'o', 'w', 't') },
{ CODEC_ID_PCM_S16LE, MKTAG('l', 'p', 'c', 'm') },
{ CODEC_ID_PCM_S24BE, MKTAG('i', 'n', '2', '4') },
{ CODEC_ID_PCM_S24LE, MKTAG('i', 'n', '2', '4') },
{ CODEC_ID_PCM_S32BE, MKTAG('i', 'n', '3', '2') },
{ CODEC_ID_PCM_S32LE, MKTAG('i', 'n', '3', '2') },
{ CODEC_ID_PCM_S8, MKTAG('s', 'o', 'w', 't') },
{ CODEC_ID_PCM_U8, MKTAG('r', 'a', 'w', ' ') },
{ CODEC_ID_PCM_U8, MKTAG('N', 'O', 'N', 'E') },
{ CODEC_ID_QCELP, MKTAG('Q', 'c', 'l', 'p') },
{ CODEC_ID_QCELP, MKTAG('Q', 'c', 'l', 'q') },
{ CODEC_ID_QCELP, MKTAG('s', 'q', 'c', 'p') }, /* ISO Media fourcc */
{ CODEC_ID_QDM2, MKTAG('Q', 'D', 'M', '2') },
{ CODEC_ID_QDMC, MKTAG('Q', 'D', 'M', 'C') },
{ CODEC_ID_SPEEX, MKTAG('s', 'p', 'e', 'x') }, /* Flash Media Server */
{ CODEC_ID_WMAV2, MKTAG('W', 'M', 'A', '2') },
{ CODEC_ID_NONE, 0 },
};
const AVCodecTag ff_codec_movsubtitle_tags[] = {
{ CODEC_ID_MOV_TEXT, MKTAG('t', 'e', 'x', 't') },
{ CODEC_ID_MOV_TEXT, MKTAG('t', 'x', '3', 'g') },
{ CODEC_ID_NONE, 0 },
};
/* map numeric codes from mdhd atom to ISO 639 */
/* cf. QTFileFormat.pdf p253, qtff.pdf p205 */
/* http://developer.apple.com/documentation/mac/Text/Text-368.html */
/* deprecated by putting the code as 3*5bit ascii */
static const char mov_mdhd_language_map[][4] = {
/* 0-9 */
"eng", "fra", "ger", "ita", "dut", "sve", "spa", "dan", "por", "nor",
"heb", "jpn", "ara", "fin", "gre", "ice", "mlt", "tur", "hr "/*scr*/, "chi"/*ace?*/,
"urd", "hin", "tha", "kor", "lit", "pol", "hun", "est", "lav", "",
"fo ", "", "rus", "chi", "", "iri", "alb", "ron", "ces", "slk",
"slv", "yid", "sr ", "mac", "bul", "ukr", "bel", "uzb", "kaz", "aze",
/*?*/
"aze", "arm", "geo", "mol", "kir", "tgk", "tuk", "mon", "", "pus",
"kur", "kas", "snd", "tib", "nep", "san", "mar", "ben", "asm", "guj",
"pa ", "ori", "mal", "kan", "tam", "tel", "", "bur", "khm", "lao",
/* roman? arabic? */
"vie", "ind", "tgl", "may", "may", "amh", "tir", "orm", "som", "swa",
/*==rundi?*/
"", "run", "", "mlg", "epo", "", "", "", "", "",
/* 100 */
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "wel", "baq",
"cat", "lat", "que", "grn", "aym", "tat", "uig", "dzo", "jav"
};
int ff_mov_iso639_to_lang(const char lang[4], int mp4)
{
int i, code = 0;
/* old way, only for QT? */
for (i = 0; lang[0] && !mp4 && i < FF_ARRAY_ELEMS(mov_mdhd_language_map); i++) {
if (!strcmp(lang, mov_mdhd_language_map[i]))
return i;
}
/* XXX:can we do that in mov too? */
if (!mp4)
return -1;
/* handle undefined as such */
if (lang[0] == '\0')
lang = "und";
/* 5bit ascii */
for (i = 0; i < 3; i++) {
uint8_t c = lang[i];
c -= 0x60;
if (c > 0x1f)
return -1;
code <<= 5;
code |= c;
}
return code;
}
int ff_mov_lang_to_iso639(unsigned code, char to[4])
{
int i;
memset(to, 0, 4);
/* is it the mangled iso code? */
/* see http://www.geocities.com/xhelmboyx/quicktime/formats/mp4-layout.txt */
if (code > 138) {
for (i = 2; i >= 0; i--) {
to[i] = 0x60 + (code & 0x1f);
code >>= 5;
}
return 1;
}
/* old fashion apple lang code */
if (code >= FF_ARRAY_ELEMS(mov_mdhd_language_map))
return 0;
if (!mov_mdhd_language_map[code][0])
return 0;
memcpy(to, mov_mdhd_language_map[code], 4);
return 1;
}
int ff_mp4_read_descr_len(AVIOContext *pb)
{
int len = 0;
int count = 4;
while (count--) {
int c = avio_r8(pb);
len = (len << 7) | (c & 0x7f);
if (!(c & 0x80))
break;
}
return len;
}
int ff_mp4_read_descr(AVFormatContext *fc, AVIOContext *pb, int *tag)
{
int len;
*tag = avio_r8(pb);
len = ff_mp4_read_descr_len(pb);
av_dlog(fc, "MPEG4 description: tag=0x%02x len=%d\n", *tag, len);
return len;
}
void ff_mp4_parse_es_descr(AVIOContext *pb, int *es_id)
{
int flags;
if (es_id) *es_id = avio_rb16(pb);
else avio_rb16(pb);
flags = avio_r8(pb);
if (flags & 0x80) //streamDependenceFlag
avio_rb16(pb);
if (flags & 0x40) { //URL_Flag
int len = avio_r8(pb);
avio_skip(pb, len);
}
if (flags & 0x20) //OCRstreamFlag
avio_rb16(pb);
}
static const AVCodecTag mp4_audio_types[] = {
{ CODEC_ID_MP3ON4, AOT_PS }, /* old mp3on4 draft */
{ CODEC_ID_MP3ON4, AOT_L1 }, /* layer 1 */
{ CODEC_ID_MP3ON4, AOT_L2 }, /* layer 2 */
{ CODEC_ID_MP3ON4, AOT_L3 }, /* layer 3 */
{ CODEC_ID_MP4ALS, AOT_ALS }, /* MPEG-4 ALS */
{ CODEC_ID_NONE, AOT_NULL },
};
int ff_mp4_read_dec_config_descr(AVFormatContext *fc, AVStream *st, AVIOContext *pb)
{
int len, tag;
int object_type_id = avio_r8(pb);
avio_r8(pb); /* stream type */
avio_rb24(pb); /* buffer size db */
avio_rb32(pb); /* max bitrate */
avio_rb32(pb); /* avg bitrate */
st->codec->codec_id= ff_codec_get_id(ff_mp4_obj_type, object_type_id);
av_dlog(fc, "esds object type id 0x%02x\n", object_type_id);
len = ff_mp4_read_descr(fc, pb, &tag);
if (tag == MP4DecSpecificDescrTag) {
av_dlog(fc, "Specific MPEG4 header len=%d\n", len);
if (!len || (uint64_t)len > (1<<30))
return -1;
av_free(st->codec->extradata);
st->codec->extradata = (uint8_t *)av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);
if (!st->codec->extradata)
return AVERROR(ENOMEM);
avio_read(pb, st->codec->extradata, len);
st->codec->extradata_size = len;
if (st->codec->codec_id == CODEC_ID_AAC) {
MPEG4AudioConfig cfg;
avpriv_mpeg4audio_get_config(&cfg, st->codec->extradata,
st->codec->extradata_size * 8, 1);
st->codec->channels = cfg.channels;
if (cfg.object_type == 29 && cfg.sampling_index < 3) // old mp3on4
st->codec->sample_rate = avpriv_mpa_freq_tab[cfg.sampling_index];
else if (cfg.ext_sample_rate)
st->codec->sample_rate = cfg.ext_sample_rate;
else
st->codec->sample_rate = cfg.sample_rate;
av_dlog(fc, "mp4a config channels %d obj %d ext obj %d "
"sample rate %d ext sample rate %d\n", st->codec->channels,
cfg.object_type, cfg.ext_object_type,
cfg.sample_rate, cfg.ext_sample_rate);
if (!(st->codec->codec_id = ff_codec_get_id(mp4_audio_types,
cfg.object_type)))
st->codec->codec_id = CODEC_ID_AAC;
}
}
return 0;
}
typedef struct MovChannelLayout {
int64_t channel_layout;
uint32_t layout_tag;
} MovChannelLayout;
static const MovChannelLayout mov_channel_layout[] = {
{ AV_CH_LAYOUT_MONO, (100<<16) | 1}, // kCAFChannelLayoutTag_Mono
{ AV_CH_LAYOUT_STEREO, (101<<16) | 2}, // kCAFChannelLayoutTag_Stereo
{ AV_CH_LAYOUT_STEREO, (102<<16) | 2}, // kCAFChannelLayoutTag_StereoHeadphones
{ AV_CH_LAYOUT_2_1, (131<<16) | 3}, // kCAFChannelLayoutTag_ITU_2_1
{ AV_CH_LAYOUT_QUAD, (132<<16) | 4}, // kCAFChannelLayoutTag_ITU_2_2
{ AV_CH_LAYOUT_2_2, (132<<16) | 4}, // kCAFChannelLayoutTag_ITU_2_2
{ AV_CH_LAYOUT_QUAD, (108<<16) | 4}, // kCAFChannelLayoutTag_Quadraphonic
{ AV_CH_LAYOUT_SURROUND, (113<<16) | 3}, // kCAFChannelLayoutTag_MPEG_3_0_A
{ AV_CH_LAYOUT_4POINT0, (115<<16) | 4}, // kCAFChannelLayoutTag_MPEG_4_0_A
{ AV_CH_LAYOUT_5POINT0_BACK, (117<<16) | 5}, // kCAFChannelLayoutTag_MPEG_5_0_A
{ AV_CH_LAYOUT_5POINT0, (117<<16) | 5}, // kCAFChannelLayoutTag_MPEG_5_0_A
{ AV_CH_LAYOUT_5POINT1_BACK, (121<<16) | 6}, // kCAFChannelLayoutTag_MPEG_5_1_A
{ AV_CH_LAYOUT_5POINT1, (121<<16) | 6}, // kCAFChannelLayoutTag_MPEG_5_1_A
{ AV_CH_LAYOUT_7POINT1, (128<<16) | 8}, // kCAFChannelLayoutTag_MPEG_7_1_C
{ AV_CH_LAYOUT_7POINT1_WIDE, (126<<16) | 8}, // kCAFChannelLayoutTag_MPEG_7_1_A
{ AV_CH_LAYOUT_5POINT1_BACK|AV_CH_LAYOUT_STEREO_DOWNMIX, (130<<16) | 8}, // kCAFChannelLayoutTag_SMPTE_DTV
{ AV_CH_LAYOUT_STEREO|AV_CH_LOW_FREQUENCY, (133<<16) | 3}, // kCAFChannelLayoutTag_DVD_4
{ AV_CH_LAYOUT_2_1|AV_CH_LOW_FREQUENCY, (134<<16) | 4}, // kCAFChannelLayoutTag_DVD_5
{ AV_CH_LAYOUT_QUAD|AV_CH_LOW_FREQUENCY, (135<<16) | 4}, // kCAFChannelLayoutTag_DVD_6
{ AV_CH_LAYOUT_2_2|AV_CH_LOW_FREQUENCY, (135<<16) | 4}, // kCAFChannelLayoutTag_DVD_6
{ AV_CH_LAYOUT_SURROUND|AV_CH_LOW_FREQUENCY, (136<<16) | 4}, // kCAFChannelLayoutTag_DVD_10
{ AV_CH_LAYOUT_4POINT0|AV_CH_LOW_FREQUENCY, (137<<16) | 5}, // kCAFChannelLayoutTag_DVD_11
{ 0, 0},
};
void ff_mov_read_chan(AVFormatContext *s, int64_t size, AVCodecContext *codec)
{
uint32_t layout_tag;
AVIOContext *pb = s->pb;
const MovChannelLayout *layouts = mov_channel_layout;
layout_tag = avio_rb32(pb);
size -= 4;
if (layout_tag == 0) { // kCAFChannelLayoutTag_UseChannelDescriptions
// Channel descriptions not implemented
av_log_ask_for_sample(s, "Unimplemented container channel layout.\n");
avio_skip(pb, size);
return;
}
if (layout_tag == 0x10000) { // kCAFChannelLayoutTag_UseChannelBitmap
codec->channel_layout = avio_rb32(pb);
size -= 4;
avio_skip(pb, size);
return;
}
while (layouts->channel_layout) {
if (layout_tag == layouts->layout_tag) {
codec->channel_layout = layouts->channel_layout;
break;
}
layouts++;
}
if (!codec->channel_layout)
av_log(s, AV_LOG_WARNING, "Unknown container channel layout.\n");
avio_skip(pb, size);
}
void ff_mov_write_chan(AVIOContext *pb, int64_t channel_layout)
{
const MovChannelLayout *layouts;
uint32_t layout_tag = 0;
for (layouts = mov_channel_layout; layouts->channel_layout; layouts++)
if (channel_layout == layouts->channel_layout) {
layout_tag = layouts->layout_tag;
break;
}
if (layout_tag) {
avio_wb32(pb, layout_tag); // mChannelLayoutTag
avio_wb32(pb, 0); // mChannelBitmap
} else {
avio_wb32(pb, 0x10000); // kCAFChannelLayoutTag_UseChannelBitmap
avio_wb32(pb, channel_layout);
}
avio_wb32(pb, 0); // mNumberChannelDescriptions
}
| 50.804469 | 137 | 0.533172 | [
"object"
] |
6c870737da6c1c3a0c4d7fa0298222f965276c3c | 17,632 | cpp | C++ | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/tests/auto/corelib/itemmodels/qabstractproxymodel/tst_qabstractproxymodel.cpp | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/tests/auto/corelib/itemmodels/qabstractproxymodel/tst_qabstractproxymodel.cpp | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/tests/auto/corelib/itemmodels/qabstractproxymodel/tst_qabstractproxymodel.cpp | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <qabstractproxymodel.h>
#include <QItemSelection>
#include <qstandarditemmodel.h>
class tst_QAbstractProxyModel : public QObject
{
Q_OBJECT
private slots:
void qabstractproxymodel();
void data_data();
void data();
void flags_data();
void flags();
void headerData_data();
void headerData();
void itemData_data();
void itemData();
void mapFromSource_data();
void mapFromSource();
void mapSelectionFromSource_data();
void mapSelectionFromSource();
void mapSelectionToSource_data();
void mapSelectionToSource();
void mapToSource_data();
void mapToSource();
void revert();
void setSourceModel();
void submit_data();
void submit();
void testRoleNames();
void testSwappingRowsProxy();
void testDragAndDrop();
};
// Subclass that exposes the protected functions.
class SubQAbstractProxyModel : public QAbstractProxyModel
{
public:
// QAbstractProxyModel::mapFromSource is a pure virtual function.
QModelIndex mapFromSource(QModelIndex const& sourceIndex) const
{ Q_UNUSED(sourceIndex); return QModelIndex(); }
// QAbstractProxyModel::mapToSource is a pure virtual function.
QModelIndex mapToSource(QModelIndex const& proxyIndex) const
{ Q_UNUSED(proxyIndex); return QModelIndex(); }
QModelIndex index(int, int, const QModelIndex&) const
{
return QModelIndex();
}
QModelIndex parent(const QModelIndex&) const
{
return QModelIndex();
}
int rowCount(const QModelIndex&) const
{
return 0;
}
int columnCount(const QModelIndex&) const
{
return 0;
}
};
void tst_QAbstractProxyModel::qabstractproxymodel()
{
SubQAbstractProxyModel model;
model.data(QModelIndex());
model.flags(QModelIndex());
model.headerData(0, Qt::Vertical, 0);
model.itemData(QModelIndex());
model.mapFromSource(QModelIndex());
model.mapSelectionFromSource(QItemSelection());
model.mapSelectionToSource(QItemSelection());
model.mapToSource(QModelIndex());
model.revert();
model.setSourceModel(0);
QCOMPARE(model.sourceModel(), (QAbstractItemModel*)0);
model.submit();
}
void tst_QAbstractProxyModel::data_data()
{
QTest::addColumn<QModelIndex>("proxyIndex");
QTest::addColumn<int>("role");
QTest::addColumn<QVariant>("data");
QTest::newRow("null") << QModelIndex() << 0 << QVariant();
}
// public QVariant data(QModelIndex const& proxyIndex, int role = Qt::DisplayRole) const
void tst_QAbstractProxyModel::data()
{
QFETCH(QModelIndex, proxyIndex);
QFETCH(int, role);
QFETCH(QVariant, data);
SubQAbstractProxyModel model;
QCOMPARE(model.data(proxyIndex, role), data);
}
Q_DECLARE_METATYPE(Qt::ItemFlags)
void tst_QAbstractProxyModel::flags_data()
{
QTest::addColumn<QModelIndex>("index");
QTest::addColumn<Qt::ItemFlags>("flags");
QTest::newRow("null") << QModelIndex() << (Qt::ItemFlags)0;
}
// public Qt::ItemFlags flags(QModelIndex const& index) const
void tst_QAbstractProxyModel::flags()
{
QFETCH(QModelIndex, index);
QFETCH(Qt::ItemFlags, flags);
SubQAbstractProxyModel model;
QCOMPARE(model.flags(index), flags);
}
Q_DECLARE_METATYPE(Qt::Orientation)
Q_DECLARE_METATYPE(Qt::ItemDataRole)
void tst_QAbstractProxyModel::headerData_data()
{
QTest::addColumn<int>("section");
QTest::addColumn<Qt::Orientation>("orientation");
QTest::addColumn<Qt::ItemDataRole>("role");
QTest::addColumn<QVariant>("headerData");
QTest::newRow("null") << 0 << Qt::Vertical << Qt::UserRole << QVariant();
}
// public QVariant headerData(int section, Qt::Orientation orientation, int role) const
void tst_QAbstractProxyModel::headerData()
{
QFETCH(int, section);
QFETCH(Qt::Orientation, orientation);
QFETCH(Qt::ItemDataRole, role);
QFETCH(QVariant, headerData);
SubQAbstractProxyModel model;
QCOMPARE(model.headerData(section, orientation, role), headerData);
}
void tst_QAbstractProxyModel::itemData_data()
{
QTest::addColumn<QModelIndex>("index");
QTest::addColumn<int>("count");
QTest::newRow("null") << QModelIndex() << 0;
}
// public QMap<int,QVariant> itemData(QModelIndex const& index) const
void tst_QAbstractProxyModel::itemData()
{
QFETCH(QModelIndex, index);
QFETCH(int, count);
SubQAbstractProxyModel model;
QCOMPARE(model.itemData(index).count(), count);
}
void tst_QAbstractProxyModel::mapFromSource_data()
{
QTest::addColumn<QModelIndex>("sourceIndex");
QTest::addColumn<QModelIndex>("mapFromSource");
QTest::newRow("null") << QModelIndex() << QModelIndex();
}
// public QModelIndex mapFromSource(QModelIndex const& sourceIndex) const
void tst_QAbstractProxyModel::mapFromSource()
{
QFETCH(QModelIndex, sourceIndex);
QFETCH(QModelIndex, mapFromSource);
SubQAbstractProxyModel model;
QCOMPARE(model.mapFromSource(sourceIndex), mapFromSource);
}
void tst_QAbstractProxyModel::mapSelectionFromSource_data()
{
QTest::addColumn<QItemSelection>("selection");
QTest::addColumn<QItemSelection>("mapSelectionFromSource");
QTest::newRow("null") << QItemSelection() << QItemSelection();
QTest::newRow("empty") << QItemSelection(QModelIndex(), QModelIndex()) << QItemSelection(QModelIndex(), QModelIndex());
}
// public QItemSelection mapSelectionFromSource(QItemSelection const& selection) const
void tst_QAbstractProxyModel::mapSelectionFromSource()
{
QFETCH(QItemSelection, selection);
QFETCH(QItemSelection, mapSelectionFromSource);
SubQAbstractProxyModel model;
QCOMPARE(model.mapSelectionFromSource(selection), mapSelectionFromSource);
}
void tst_QAbstractProxyModel::mapSelectionToSource_data()
{
QTest::addColumn<QItemSelection>("selection");
QTest::addColumn<QItemSelection>("mapSelectionToSource");
QTest::newRow("null") << QItemSelection() << QItemSelection();
QTest::newRow("empty") << QItemSelection(QModelIndex(), QModelIndex()) << QItemSelection(QModelIndex(), QModelIndex());
}
// public QItemSelection mapSelectionToSource(QItemSelection const& selection) const
void tst_QAbstractProxyModel::mapSelectionToSource()
{
QFETCH(QItemSelection, selection);
QFETCH(QItemSelection, mapSelectionToSource);
SubQAbstractProxyModel model;
QCOMPARE(model.mapSelectionToSource(selection), mapSelectionToSource);
}
void tst_QAbstractProxyModel::mapToSource_data()
{
QTest::addColumn<QModelIndex>("proxyIndex");
QTest::addColumn<QModelIndex>("mapToSource");
QTest::newRow("null") << QModelIndex() << QModelIndex();
}
// public QModelIndex mapToSource(QModelIndex const& proxyIndex) const
void tst_QAbstractProxyModel::mapToSource()
{
QFETCH(QModelIndex, proxyIndex);
QFETCH(QModelIndex, mapToSource);
SubQAbstractProxyModel model;
QCOMPARE(model.mapToSource(proxyIndex), mapToSource);
}
// public void revert()
void tst_QAbstractProxyModel::revert()
{
SubQAbstractProxyModel model;
model.revert();
}
// public void setSourceModel(QAbstractItemModel* sourceModel)
void tst_QAbstractProxyModel::setSourceModel()
{
SubQAbstractProxyModel model;
QCOMPARE(model.property("sourceModel"), QVariant::fromValue<QAbstractItemModel*>(0));
QStandardItemModel *sourceModel = new QStandardItemModel(&model);
model.setSourceModel(sourceModel);
QCOMPARE(model.sourceModel(), static_cast<QAbstractItemModel*>(sourceModel));
QCOMPARE(model.property("sourceModel").value<QObject*>(), static_cast<QObject*>(sourceModel));
QCOMPARE(model.property("sourceModel").value<QAbstractItemModel*>(), sourceModel);
QStandardItemModel *sourceModel2 = new QStandardItemModel(&model);
model.setSourceModel(sourceModel2);
QCOMPARE(model.sourceModel(), static_cast<QAbstractItemModel*>(sourceModel2));
QCOMPARE(model.property("sourceModel").value<QObject*>(), static_cast<QObject*>(sourceModel2));
QCOMPARE(model.property("sourceModel").value<QAbstractItemModel*>(), sourceModel2);
delete sourceModel2;
QCOMPARE(model.sourceModel(), static_cast<QAbstractItemModel*>(0));
}
void tst_QAbstractProxyModel::submit_data()
{
QTest::addColumn<bool>("submit");
QTest::newRow("null") << true;
}
// public bool submit()
void tst_QAbstractProxyModel::submit()
{
QFETCH(bool, submit);
SubQAbstractProxyModel model;
QCOMPARE(model.submit(), submit);
}
class StandardItemModelWithCustomRoleNames : public QStandardItemModel
{
public:
enum CustomRole {
CustomRole1 = Qt::UserRole,
CustomRole2
};
StandardItemModelWithCustomRoleNames() {
QHash<int, QByteArray> _roleNames = roleNames();
_roleNames.insert(CustomRole1, "custom1");
_roleNames.insert(CustomRole2, "custom2");
setRoleNames(_roleNames);
}
};
class AnotherStandardItemModelWithCustomRoleNames : public QStandardItemModel
{
public:
enum CustomRole {
AnotherCustomRole1 = Qt::UserRole + 10, // Different to StandardItemModelWithCustomRoleNames::CustomRole1
AnotherCustomRole2
};
AnotherStandardItemModelWithCustomRoleNames() {
QHash<int, QByteArray> _roleNames = roleNames();
_roleNames.insert(AnotherCustomRole1, "another_custom1");
_roleNames.insert(AnotherCustomRole2, "another_custom2");
setRoleNames(_roleNames);
}
};
/**
Verifies that @p subSet is a subset of @p superSet. That is, all keys in @p subSet exist in @p superSet and have the same values.
*/
static void verifySubSetOf(const QHash<int, QByteArray> &superSet, const QHash<int, QByteArray> &subSet)
{
QHash<int, QByteArray>::const_iterator it = subSet.constBegin();
const QHash<int, QByteArray>::const_iterator end = subSet.constEnd();
for ( ; it != end; ++it ) {
QVERIFY(superSet.contains(it.key()));
QCOMPARE(it.value(), superSet.value(it.key()));
}
}
void tst_QAbstractProxyModel::testRoleNames()
{
QStandardItemModel defaultModel;
StandardItemModelWithCustomRoleNames model;
QHash<int, QByteArray> rootModelRoleNames = model.roleNames();
QHash<int, QByteArray> defaultModelRoleNames = defaultModel.roleNames();
verifySubSetOf( rootModelRoleNames, defaultModelRoleNames);
QVERIFY( rootModelRoleNames.size() == defaultModelRoleNames.size() + 2 );
QVERIFY( rootModelRoleNames.contains(StandardItemModelWithCustomRoleNames::CustomRole1));
QVERIFY( rootModelRoleNames.contains(StandardItemModelWithCustomRoleNames::CustomRole2));
QVERIFY( rootModelRoleNames.value(StandardItemModelWithCustomRoleNames::CustomRole1) == "custom1" );
QVERIFY( rootModelRoleNames.value(StandardItemModelWithCustomRoleNames::CustomRole2) == "custom2" );
SubQAbstractProxyModel proxy1;
proxy1.setSourceModel(&model);
QHash<int, QByteArray> proxy1RoleNames = proxy1.roleNames();
verifySubSetOf( proxy1RoleNames, defaultModelRoleNames );
QVERIFY( proxy1RoleNames.size() == defaultModelRoleNames.size() + 2 );
QVERIFY( proxy1RoleNames.contains(StandardItemModelWithCustomRoleNames::CustomRole1));
QVERIFY( proxy1RoleNames.contains(StandardItemModelWithCustomRoleNames::CustomRole2));
QVERIFY( proxy1RoleNames.value(StandardItemModelWithCustomRoleNames::CustomRole1) == "custom1" );
QVERIFY( proxy1RoleNames.value(StandardItemModelWithCustomRoleNames::CustomRole2) == "custom2" );
SubQAbstractProxyModel proxy2;
proxy2.setSourceModel(&proxy1);
QHash<int, QByteArray> proxy2RoleNames = proxy2.roleNames();
verifySubSetOf( proxy2RoleNames, defaultModelRoleNames );
QVERIFY( proxy2RoleNames.size() == defaultModelRoleNames.size() + 2 );
QVERIFY( proxy2RoleNames.contains(StandardItemModelWithCustomRoleNames::CustomRole1));
QVERIFY( proxy2RoleNames.contains(StandardItemModelWithCustomRoleNames::CustomRole2));
QVERIFY( proxy2RoleNames.value(StandardItemModelWithCustomRoleNames::CustomRole1) == "custom1" );
QVERIFY( proxy2RoleNames.value(StandardItemModelWithCustomRoleNames::CustomRole2) == "custom2" );
}
// This class only supports very simple table models
class SwappingProxy : public QAbstractProxyModel
{
static int swapRow(const int row)
{
if (row == 2) {
return 3;
} else if (row == 3) {
return 2;
} else {
return row;
}
}
public:
virtual QModelIndex index(int row, int column, const QModelIndex &parentIdx) const
{
if (!sourceModel())
return QModelIndex();
if (row < 0 || column < 0)
return QModelIndex();
if (row >= sourceModel()->rowCount())
return QModelIndex();
if (column >= sourceModel()->columnCount())
return QModelIndex();
return createIndex(row, column, parentIdx.internalPointer());
}
virtual QModelIndex parent(const QModelIndex &parentIdx) const
{
// well, we're a 2D model
Q_UNUSED(parentIdx);
return QModelIndex();
}
virtual int rowCount(const QModelIndex &parentIdx) const
{
if (parentIdx.isValid() || !sourceModel())
return 0;
return sourceModel()->rowCount();
}
virtual int columnCount(const QModelIndex &parentIdx) const
{
if (parentIdx.isValid() || !sourceModel())
return 0;
return sourceModel()->rowCount();
}
virtual QModelIndex mapToSource(const QModelIndex &proxyIndex) const
{
if (!proxyIndex.isValid())
return QModelIndex();
if (!sourceModel())
return QModelIndex();
Q_ASSERT(!proxyIndex.parent().isValid());
return sourceModel()->index(swapRow(proxyIndex.row()), proxyIndex.column(), QModelIndex());
}
virtual QModelIndex mapFromSource(const QModelIndex &sourceIndex) const
{
if (!sourceIndex.isValid())
return QModelIndex();
if (!sourceModel())
return QModelIndex();
Q_ASSERT(!sourceIndex.parent().isValid());
return index(swapRow(sourceIndex.row()), sourceIndex.column(), QModelIndex());
}
};
void tst_QAbstractProxyModel::testSwappingRowsProxy()
{
QStandardItemModel defaultModel;
defaultModel.setRowCount(4);
defaultModel.setColumnCount(2);
for (int row = 0; row < defaultModel.rowCount(); ++row) {
defaultModel.setItem(row, 0, new QStandardItem(QString::number(row) + QLatin1Char('A')));
defaultModel.setItem(row, 1, new QStandardItem(QString::number(row) + QLatin1Char('B')));
}
SwappingProxy proxy;
proxy.setSourceModel(&defaultModel);
QCOMPARE(proxy.data(proxy.index(0, 0, QModelIndex())), QVariant("0A"));
QCOMPARE(proxy.data(proxy.index(0, 1, QModelIndex())), QVariant("0B"));
QCOMPARE(proxy.data(proxy.index(1, 0, QModelIndex())), QVariant("1A"));
QCOMPARE(proxy.data(proxy.index(1, 1, QModelIndex())), QVariant("1B"));
QCOMPARE(proxy.data(proxy.index(2, 0, QModelIndex())), QVariant("3A"));
QCOMPARE(proxy.data(proxy.index(2, 1, QModelIndex())), QVariant("3B"));
QCOMPARE(proxy.data(proxy.index(3, 0, QModelIndex())), QVariant("2A"));
QCOMPARE(proxy.data(proxy.index(3, 1, QModelIndex())), QVariant("2B"));
for (int row = 0; row < defaultModel.rowCount(); ++row) {
QModelIndex left = proxy.index(row, 0, QModelIndex());
QModelIndex right = proxy.index(row, 1, QModelIndex());
QCOMPARE(left.sibling(left.row(), 1), right);
QCOMPARE(right.sibling(right.row(), 0), left);
}
}
class StandardItemModelWithCustomDragAndDrop : public QStandardItemModel
{
public:
QStringList mimeTypes() const { return QStringList() << QStringLiteral("foo/mimetype"); }
Qt::DropActions supportedDragActions() const { return Qt::CopyAction | Qt::LinkAction; }
Qt::DropActions supportedDropActions() const { return Qt::MoveAction; }
};
void tst_QAbstractProxyModel::testDragAndDrop()
{
StandardItemModelWithCustomDragAndDrop sourceModel;
SubQAbstractProxyModel proxy;
proxy.setSourceModel(&sourceModel);
QCOMPARE(proxy.mimeTypes(), sourceModel.mimeTypes());
QCOMPARE(proxy.supportedDragActions(), sourceModel.supportedDragActions());
QCOMPARE(proxy.supportedDropActions(), sourceModel.supportedDropActions());
}
QTEST_MAIN(tst_QAbstractProxyModel)
#include "tst_qabstractproxymodel.moc"
| 34.77712 | 133 | 0.707974 | [
"model"
] |
6c88e1b88b7818279cb32e10b92b68f16e0cc791 | 7,203 | cpp | C++ | source/gloperate-glfw/source/WindowEventDispatcher.cpp | apopiak/gloperate | b4194a1c3b2dc4ea1102a2c5ae3ff3b5540f31cd | [
"MIT"
] | null | null | null | source/gloperate-glfw/source/WindowEventDispatcher.cpp | apopiak/gloperate | b4194a1c3b2dc4ea1102a2c5ae3ff3b5540f31cd | [
"MIT"
] | null | null | null | source/gloperate-glfw/source/WindowEventDispatcher.cpp | apopiak/gloperate | b4194a1c3b2dc4ea1102a2c5ae3ff3b5540f31cd | [
"MIT"
] | null | null | null | #include <gloperate-glfw/WindowEventDispatcher.h>
#include <cassert>
#include <cmath>
#include <glbinding/gl/enum.h>
#include <GLFW/glfw3.h>
#include <gloperate-glfw/Window.h>
#include <gloperate-glfw/events.h>
namespace gloperate_glfw
{
WindowEventDispatcher::Timer::Timer()
: interval(0)
, singleShot(false)
{
reset();
}
WindowEventDispatcher::Timer::Timer(int interval, bool singleShot)
: interval(interval)
, singleShot(singleShot)
{
reset();
}
bool WindowEventDispatcher::Timer::ready() const
{
return elapsed >= interval;
}
void WindowEventDispatcher::Timer::reset()
{
elapsed = Duration(0);
}
WindowEventDispatcher::WindowTimerMap WindowEventDispatcher::s_timers;
std::chrono::high_resolution_clock::time_point WindowEventDispatcher::s_time;
std::chrono::high_resolution_clock WindowEventDispatcher::s_clock;
void WindowEventDispatcher::registerWindow(Window* window)
{
assert(window != nullptr);
GLFWwindow * glfwWindow = window->internalWindow();
if (!glfwWindow)
return;
glfwSetWindowUserPointer(glfwWindow, window);
glfwSetWindowRefreshCallback(glfwWindow, handleRefresh);
glfwSetKeyCallback(glfwWindow, handleKey);
glfwSetCharCallback(glfwWindow, handleChar);
glfwSetMouseButtonCallback(glfwWindow, handleMouse);
glfwSetCursorPosCallback(glfwWindow, handleCursorPos);
glfwSetCursorEnterCallback(glfwWindow, handleCursorEnter);
glfwSetScrollCallback(glfwWindow, handleScroll);
glfwSetWindowSizeCallback(glfwWindow, handleResize);
glfwSetFramebufferSizeCallback(glfwWindow, handleFramebufferResize);
glfwSetWindowFocusCallback(glfwWindow, handleFocus);
glfwSetWindowPosCallback(glfwWindow, handleMove);
glfwSetWindowIconifyCallback(glfwWindow, handleIconify);
glfwSetWindowCloseCallback(glfwWindow, handleClose);
}
void WindowEventDispatcher::deregisterWindow(Window* window)
{
assert(window != nullptr);
GLFWwindow* glfwWindow = window->internalWindow();
if (!glfwWindow)
return;
glfwSetWindowRefreshCallback(glfwWindow, nullptr);
glfwSetKeyCallback(glfwWindow, nullptr);
glfwSetCharCallback(glfwWindow, nullptr);
glfwSetMouseButtonCallback(glfwWindow, nullptr);
glfwSetCursorPosCallback(glfwWindow, nullptr);
glfwSetCursorEnterCallback(glfwWindow, nullptr);
glfwSetScrollCallback(glfwWindow, nullptr);
glfwSetWindowSizeCallback(glfwWindow, nullptr);
glfwSetFramebufferSizeCallback(glfwWindow, nullptr);
glfwSetWindowFocusCallback(glfwWindow, nullptr);
glfwSetWindowPosCallback(glfwWindow, nullptr);
glfwSetWindowIconifyCallback(glfwWindow, nullptr);
glfwSetWindowCloseCallback(glfwWindow, nullptr);
removeTimers(window);
}
void WindowEventDispatcher::addTimer(Window* window, int id, int interval, bool singleShot)
{
s_timers[window][id] = Timer(interval, singleShot);
}
void WindowEventDispatcher::removeTimer(Window* window, int id)
{
s_timers[window].erase(id);
}
void WindowEventDispatcher::removeTimers(Window* window)
{
s_timers.erase(window);
}
void WindowEventDispatcher::initializeTime()
{
s_time = s_clock.now();
}
void WindowEventDispatcher::checkForTimerEvents()
{
auto now = s_clock.now();
Timer::Duration delta = std::chrono::duration_cast<Timer::Duration>(now - s_time);
s_time = now;
std::vector<std::pair<Window*, int>> discarded;
for (auto& timerMapPair : s_timers)
{
Window* window = timerMapPair.first;
for (auto& timerPair : timerMapPair.second)
{
int id = timerPair.first;
Timer& timer = timerPair.second;
timer.elapsed += delta;
if (timer.ready())
{
dispatchEvent(window, new TimerEvent(id, timer.elapsed));
if (timer.singleShot)
{
discarded.emplace_back(window, id);
}
else
{
timer.reset();
}
}
}
}
for (const auto& pair : discarded)
{
removeTimer(pair.first, pair.second);
}
}
Window *WindowEventDispatcher::fromGLFW(GLFWwindow* glfwWindow)
{
return glfwWindow ? static_cast<Window*>(glfwGetWindowUserPointer(glfwWindow)) : nullptr;
}
glm::ivec2 WindowEventDispatcher::mousePosition(GLFWwindow* glfwWindow)
{
if (glfwWindow)
{
double xd, yd;
glfwGetCursorPos(glfwWindow, &xd, &yd);
return glm::ivec2(std::floor(xd), std::floor(yd));
}
else
{
return glm::ivec2();
}
}
void WindowEventDispatcher::dispatchEvent(GLFWwindow* glfwWindow, WindowEvent* event)
{
dispatchEvent(fromGLFW(glfwWindow), event);
}
void WindowEventDispatcher::dispatchEvent(Window* window, WindowEvent* event)
{
if (!window)
{
delete event;
return;
}
window->queueEvent(event);
}
// events
void WindowEventDispatcher::handleRefresh(GLFWwindow* glfwWindow)
{
dispatchEvent(glfwWindow, new PaintEvent);
}
void WindowEventDispatcher::handleKey(GLFWwindow* glfwWindow, int key, int scanCode, int action, int modifiers)
{
dispatchEvent(glfwWindow, new KeyEvent(key, scanCode, action, modifiers));
}
void WindowEventDispatcher::handleChar(GLFWwindow* glfwWindow, unsigned int character)
{
dispatchEvent(glfwWindow, new KeyEvent(character));
}
void WindowEventDispatcher::handleMouse(GLFWwindow* glfwWindow, int button, int action, int modifiers)
{
dispatchEvent(glfwWindow, new MouseEvent(mousePosition(glfwWindow), button, action, modifiers));
}
void WindowEventDispatcher::handleCursorPos(GLFWwindow* glfwWindow, double xPos, double yPos)
{
dispatchEvent(glfwWindow, new MouseEvent(glm::ivec2(std::floor(xPos), std::floor(yPos))));
}
void WindowEventDispatcher::handleCursorEnter(GLFWwindow* glfwWindow, int entered)
{
if (entered == GL_TRUE)
{
dispatchEvent(glfwWindow, new MouseEnterEvent);
}
else
{
dispatchEvent(glfwWindow, new MouseLeaveEvent);
}
}
void WindowEventDispatcher::handleScroll(GLFWwindow* glfwWindow, double xOffset, double yOffset)
{
dispatchEvent(glfwWindow, new ScrollEvent(glm::vec2(xOffset, yOffset), mousePosition(glfwWindow)));
}
void WindowEventDispatcher::handleResize(GLFWwindow* glfwWindow, int width, int height)
{
dispatchEvent(glfwWindow, new ResizeEvent(glm::ivec2(width, height)));
}
void WindowEventDispatcher::handleFramebufferResize(GLFWwindow* glfwWindow, int width, int height)
{
dispatchEvent(glfwWindow, new ResizeEvent(glm::ivec2(width, height), true));
}
void WindowEventDispatcher::handleMove(GLFWwindow* glfwWindow, int x, int y)
{
dispatchEvent(glfwWindow, new MoveEvent(glm::ivec2(x, y)));
}
void WindowEventDispatcher::handleFocus(GLFWwindow* glfwWindow, int focused)
{
dispatchEvent(glfwWindow, new FocusEvent(focused == GL_TRUE));
}
void WindowEventDispatcher::handleIconify(GLFWwindow* glfwWindow, int iconified)
{
dispatchEvent(glfwWindow, new IconifyEvent(iconified == GL_TRUE));
}
void WindowEventDispatcher::handleClose(GLFWwindow* glfwWindow)
{
dispatchEvent(glfwWindow, new CloseEvent);
}
} // namespace gloperate_glfw
| 26.876866 | 111 | 0.721505 | [
"vector"
] |
6c898f2b86a108200c5b4df79c3c42169563f852 | 530 | cpp | C++ | math/spf_sieve.cpp | prince776/CodeBook | 874fc7f94011ad1d25a55bcd91fecd2a11eb5a9b | [
"CC0-1.0"
] | 17 | 2021-01-25T12:07:17.000Z | 2022-02-26T17:20:31.000Z | math/spf_sieve.cpp | NavneelSinghal/CodeBook | ff60ace9107dd19ef8ba81e175003f567d2a9070 | [
"CC0-1.0"
] | null | null | null | math/spf_sieve.cpp | NavneelSinghal/CodeBook | ff60ace9107dd19ef8ba81e175003f567d2a9070 | [
"CC0-1.0"
] | 4 | 2021-02-28T11:13:44.000Z | 2021-11-20T12:56:20.000Z | // memory - N + N/(log N)
template <int N = 1'000'000>
struct fast_sieve_spf {
vector<int> primes, spf;
fast_sieve_spf() {
spf.resize(N + 1);
for (int i = 2; i <= N; ++i) {
if (spf[i] == 0) spf[i] = i, primes.push_back(i);
int product, spfi = spf[i];
for (auto prime : primes) {
product = i * prime;
if (product > N) break;
spf[product] = prime;
if (spfi == prime) break;
}
}
}
};
| 26.5 | 61 | 0.430189 | [
"vector"
] |
6c8f7726a1b62535f2363c4d2ed59f6318c1179b | 2,973 | cpp | C++ | Uncategorized/chain.cpp | crackersamdjam/DMOJ-Solutions | 97992566595e2c7bf41b5da9217d8ef61bdd1d71 | [
"MIT"
] | null | null | null | Uncategorized/chain.cpp | crackersamdjam/DMOJ-Solutions | 97992566595e2c7bf41b5da9217d8ef61bdd1d71 | [
"MIT"
] | null | null | null | Uncategorized/chain.cpp | crackersamdjam/DMOJ-Solutions | 97992566595e2c7bf41b5da9217d8ef61bdd1d71 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define gc getchar_unlocked()
#define pc(x) putchar_unlocked(x)
template<typename T> void scan(T &x){x = 0;bool _=0;T c=gc;_=c==45;c=_?gc:c;while(c<48||c>57)c=gc;for(;c<48||c>57;c=gc);for(;c>47&&c<58;c=gc)x=(x<<3)+(x<<1)+(c&15);x=_?-x:x;}
template<typename T> void printn(T n){bool _=0;_=n<0;n=_?-n:n;char snum[65];int i=0;do{snum[i++]=n%10+48;n/= 10;}while(n);--i;if (_)pc(45);while(i>=0)pc(snum[i--]);}
template<typename First, typename ... Ints> void scan(First &arg, Ints&... rest){scan(arg);scan(rest...);}
template<typename T> void print(T n){printn(n);pc(10);}
template<typename First, typename ... Ints> void print(First arg, Ints... rest){printn(arg);pc(32);print(rest...);}
using namespace std;
int n, st, ans;
string a;
vector<int> g, s, p;
int main(){
cin >> n >> a;
for(int i = 1; i < n; i++){
if(a[i] != a[i-1])
st = i;
}
a = a.substr(st) + a.substr(0, st);
//cout << a << '\n';
for(int i = 0; i < n; i++){
if(a[i] == 'g')
g.push_back(i);
if(a[i] == 's')
s.push_back(i);
if(a[i] == 'p')
p.push_back(i);
}
//cout << a << '\n';
if(g.size() <= 1 || s.size() <= 1){
print(n);
return 0;
}
for(int i = 0; i < n; i++){
if(a[i] != 's' and a[i+1] != 'g' && (i == n or a[i] != a[i+1])){
//gggsss
int pre;
if(s[0] > i){
pre = s.back() - n;
}
else{
pre = *--lower_bound(s.begin(), s.end(), i);
}
int nx;
if(g.back() < i+1){
nx = n + g[0];
}
else{
nx = *lower_bound(g.begin(), g.end(), i+1);
}
nx--;
ans = max(ans, nx - pre);
//print(pre, i, nx);
}
}
reverse(a.begin(), a.end());
g.clear();s.clear();p.clear();
for(int i = 0; i < n; i++){
if(a[i] == 'g')
g.push_back(i);
if(a[i] == 's')
s.push_back(i);
if(a[i] == 'p')
p.push_back(i);
}
for(int i = 0; i < n; i++){
if(a[i] != 's' and a[i+1] != 'g' && (i == n or a[i] != a[i+1])){
//gggsss
int pre;
if(s[0] > i){
pre = s.back() - n;
}
else{
pre = *--lower_bound(s.begin(), s.end(), i);
}
int nx;
if(g.back() < i+1){
nx = n + g[0];
}
else{
nx = *lower_bound(g.begin(), g.end(), i+1);
}
nx--;
ans = max(ans, nx - pre);
//print(pre, i, nx);
}
}
print(min(ans, n));
return 0;
} | 28.586538 | 175 | 0.36596 | [
"vector"
] |
6c9158f6ca6cbaba765151631cdcbea8698f963a | 2,669 | cpp | C++ | frameReceiver/src/FrameReceiverZMQRxThread.cpp | stfc-aeg/odin-data | 6c6353a11e0b813fc9db866ba610649dbbec95da | [
"Apache-2.0"
] | 7 | 2018-06-12T15:48:52.000Z | 2021-06-01T03:50:42.000Z | frameReceiver/src/FrameReceiverZMQRxThread.cpp | stfc-aeg/odin-data | 6c6353a11e0b813fc9db866ba610649dbbec95da | [
"Apache-2.0"
] | 211 | 2017-05-18T13:38:02.000Z | 2022-03-03T11:05:47.000Z | frameReceiver/src/FrameReceiverZMQRxThread.cpp | dls-controls/odin-data | ddbfb90d361d0b397fcfd30df4a749faaa8c84d6 | [
"Apache-2.0"
] | 8 | 2017-05-15T08:05:05.000Z | 2022-03-13T18:31:41.000Z | /*!
* FrameReceiverZMQRxThread.cpp
*
* Created on: Feb 4, 2015
* Author: Tim Nicholls, STFC Application Engineering Group
*/
#include "FrameReceiverZMQRxThread.h"
using namespace FrameReceiver;
FrameReceiverZMQRxThread::FrameReceiverZMQRxThread(FrameReceiverConfig& config,
SharedBufferManagerPtr buffer_manager,
FrameDecoderPtr frame_decoder,
unsigned int tick_period_ms) :
FrameReceiverRxThread(config, buffer_manager, frame_decoder, tick_period_ms),
logger_(log4cxx::Logger::getLogger("FR.ZMQRxThread")),
skt_channel_(ZMQ_PULL)
{
LOG4CXX_DEBUG_LEVEL(1, logger_, "FrameReceiverZMQRxThread constructor entered....");
// Store the frame decoder as a UDP type frame decoder
frame_decoder_ = boost::dynamic_pointer_cast<FrameDecoderZMQ>(frame_decoder);
}
FrameReceiverZMQRxThread::~FrameReceiverZMQRxThread()
{
LOG4CXX_DEBUG_LEVEL(1, logger_, "Destroying FrameReceiverZMQRxThread....");
}
void FrameReceiverZMQRxThread::run_specific_service(void)
{
LOG4CXX_DEBUG_LEVEL(1, logger_, "Running ZMQ RX thread service");
for (std::vector<uint16_t>::iterator rx_port_itr = config_.rx_ports_.begin(); rx_port_itr != config_.rx_ports_.end(); rx_port_itr++)
{
uint16_t rx_port = *rx_port_itr;
std::stringstream ss;
ss << "tcp://" << config_.rx_address_ << ":" << rx_port;
skt_channel_.connect(ss.str().c_str());
// Register the IPC channel with the reactor
reactor_.register_channel(skt_channel_, boost::bind(&FrameReceiverZMQRxThread::handle_receive_socket, this));
}
}
void FrameReceiverZMQRxThread::cleanup_specific_service(void)
{
LOG4CXX_DEBUG_LEVEL(1, logger_, "Cleaning up ZMQ RX thread service");
// Remove the IPC channel from the reactor
reactor_.remove_channel(skt_channel_);
skt_channel_.close();
}
void FrameReceiverZMQRxThread::handle_receive_socket()
{
// Receive a message from the main thread channel and place it directly into the
// provided memory buffer
void* nextMessageBuffer = frame_decoder_->get_next_message_buffer();
size_t msg_len = skt_channel_.recv_raw(nextMessageBuffer);
LOG4CXX_DEBUG_LEVEL(3, logger_, "RX thread received " << msg_len << " bytes on IPC channel, "
"payload buffer address " << nextMessageBuffer);
FrameDecoder::FrameReceiveState frame_receive_state = frame_decoder_->process_message(msg_len);
// Now check for end of messsage
if (skt_channel_.eom()){
// Message complete, notify the decoder
frame_decoder_->frame_meta_data(1);
}
}
| 34.662338 | 134 | 0.70888 | [
"vector"
] |
6c937e3926ee5134e789ef700617c1912869400f | 63,607 | cpp | C++ | ScutSystem/LUA_Export/LuaScutSystem.cpp | ScutGame/Client-source | 7dd886bf128c857a957f5360fcc28bcd511bf654 | [
"MIT"
] | 23 | 2015-01-28T12:41:43.000Z | 2021-07-14T05:35:56.000Z | ScutSystem/LUA_Export/LuaScutSystem.cpp | HongXiao/Client-source | 7dd886bf128c857a957f5360fcc28bcd511bf654 | [
"MIT"
] | null | null | null | ScutSystem/LUA_Export/LuaScutSystem.cpp | HongXiao/Client-source | 7dd886bf128c857a957f5360fcc28bcd511bf654 | [
"MIT"
] | 35 | 2015-02-04T10:01:00.000Z | 2021-03-05T15:27:14.000Z | /*
** Lua binding: ScutSystem
** Generated automatically by tolua++-1.0.92 on 10/07/13 15:26:42.
*/
#ifndef __cplusplus
#include "stdlib.h"
#endif
#include "string.h"
#include "tolua++.h"
/* Exported function */
TOLUA_API int tolua_ScutSystem_open (lua_State* tolua_S);
#include"../md5.h"
#include"../ScutUtility.h"
#include"../Stream.h"
#include <string>
#include "../Defines.h"
/* function to release collected object via destructor */
#ifdef __cplusplus
static int tolua_collect_ScutSystem__CMemoryStream (lua_State* tolua_S)
{
ScutSystem::CMemoryStream* self = (ScutSystem::CMemoryStream*) tolua_tousertype(tolua_S,1,0);
Mtolua_delete(self);
return 0;
}
static int tolua_collect_intptr_t (lua_State* tolua_S)
{
intptr_t* self = (intptr_t*) tolua_tousertype(tolua_S,1,0);
Mtolua_delete(self);
return 0;
}
static int tolua_collect_md5 (lua_State* tolua_S)
{
md5* self = (md5*) tolua_tousertype(tolua_S,1,0);
Mtolua_delete(self);
return 0;
}
static int tolua_collect_ScutSystem__CBaseMemoryStream (lua_State* tolua_S)
{
ScutSystem::CBaseMemoryStream* self = (ScutSystem::CBaseMemoryStream*) tolua_tousertype(tolua_S,1,0);
Mtolua_delete(self);
return 0;
}
static int tolua_collect_ScutSystem__CHandleStream (lua_State* tolua_S)
{
ScutSystem::CHandleStream* self = (ScutSystem::CHandleStream*) tolua_tousertype(tolua_S,1,0);
Mtolua_delete(self);
return 0;
}
static int tolua_collect_ScutSystem__CFileStream (lua_State* tolua_S)
{
ScutSystem::CFileStream* self = (ScutSystem::CFileStream*) tolua_tousertype(tolua_S,1,0);
Mtolua_delete(self);
return 0;
}
static int tolua_collect_ScutSystem__CStream (lua_State* tolua_S)
{
ScutSystem::CStream* self = (ScutSystem::CStream*) tolua_tousertype(tolua_S,1,0);
Mtolua_delete(self);
return 0;
}
#endif
/* function to register type */
static void tolua_reg_types (lua_State* tolua_S)
{
#ifndef Mtolua_typeid
#define Mtolua_typeid(L,TI,T)
#endif
tolua_usertype(tolua_S,"ScutSystem::CScutUtility");
Mtolua_typeid(tolua_S,typeid(ScutSystem::CScutUtility), "ScutSystem::CScutUtility");
tolua_usertype(tolua_S,"ScutSystem::CMemoryStream");
Mtolua_typeid(tolua_S,typeid(ScutSystem::CMemoryStream), "ScutSystem::CMemoryStream");
tolua_usertype(tolua_S,"ScutSystem::CBaseMemoryStream");
Mtolua_typeid(tolua_S,typeid(ScutSystem::CBaseMemoryStream), "ScutSystem::CBaseMemoryStream");
tolua_usertype(tolua_S,"DWORD");
Mtolua_typeid(tolua_S,typeid(DWORD), "DWORD");
tolua_usertype(tolua_S,"intptr_t");
Mtolua_typeid(tolua_S,typeid(intptr_t), "intptr_t");
tolua_usertype(tolua_S,"md5");
Mtolua_typeid(tolua_S,typeid(md5), "md5");
tolua_usertype(tolua_S,"ScutSystem::CHandleStream");
Mtolua_typeid(tolua_S,typeid(ScutSystem::CHandleStream), "ScutSystem::CHandleStream");
tolua_usertype(tolua_S,"ScutSystem::CFileStream");
Mtolua_typeid(tolua_S,typeid(ScutSystem::CFileStream), "ScutSystem::CFileStream");
tolua_usertype(tolua_S,"ScutSystem::CStream");
Mtolua_typeid(tolua_S,typeid(ScutSystem::CStream), "ScutSystem::CStream");
}
/* function: PrintMD5 */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_PrintMD500
static int tolua_ScutSystem_PrintMD500(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_istable(tolua_S,1,0,&tolua_err) ||
!tolua_isnoobj(tolua_S,2,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
unsigned char md5Digest[16];
{
#ifndef TOLUA_RELEASE
if (!tolua_isnumberarray(tolua_S,1,16,0,&tolua_err))
goto tolua_lerror;
else
#endif
{
int i;
for(i=0; i<16;i++)
md5Digest[i] = ((char) tolua_tofieldnumber(tolua_S,1,i+1,0));
}
}
{
char* tolua_ret = (char*) PrintMD5(md5Digest);
tolua_pushstring(tolua_S,(const char*)tolua_ret);
}
{
int i;
for(i=0; i<16;i++)
tolua_pushfieldnumber(tolua_S,1,i+1,(lua_Number) md5Digest[i]);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'PrintMD5'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* function: MD5String */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_MD5String00
static int tolua_ScutSystem_MD5String00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isstring(tolua_S,1,0,&tolua_err) ||
!tolua_isnoobj(tolua_S,2,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
char* szString = ((char*) tolua_tostring(tolua_S,1,0));
{
char* tolua_ret = (char*) MD5String(szString);
tolua_pushstring(tolua_S,(const char*)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'MD5String'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* function: MD5File */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_MD5File00
static int tolua_ScutSystem_MD5File00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isstring(tolua_S,1,0,&tolua_err) ||
!tolua_isnoobj(tolua_S,2,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
char* szFilename = ((char*) tolua_tostring(tolua_S,1,0));
{
char* tolua_ret = (char*) MD5File(szFilename);
tolua_pushstring(tolua_S,(const char*)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'MD5File'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: new of class md5 */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_md5_new00
static int tolua_ScutSystem_md5_new00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertable(tolua_S,1,"md5",0,&tolua_err) ||
!tolua_isnoobj(tolua_S,2,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
{
md5* tolua_ret = (md5*) Mtolua_new((md5)());
tolua_pushusertype(tolua_S,(void*)tolua_ret,"md5");
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'new'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: new_local of class md5 */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_md5_new00_local
static int tolua_ScutSystem_md5_new00_local(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertable(tolua_S,1,"md5",0,&tolua_err) ||
!tolua_isnoobj(tolua_S,2,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
{
md5* tolua_ret = (md5*) Mtolua_new((md5)());
tolua_pushusertype(tolua_S,(void*)tolua_ret,"md5");
tolua_register_gc(tolua_S,lua_gettop(tolua_S));
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'new'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: Init of class md5 */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_md5_Init00
static int tolua_ScutSystem_md5_Init00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"md5",0,&tolua_err) ||
!tolua_isnoobj(tolua_S,2,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
md5* self = (md5*) tolua_tousertype(tolua_S,1,0);
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'Init'", NULL);
#endif
{
self->Init();
}
}
return 0;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'Init'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: Update of class md5 */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_md5_Update00
static int tolua_ScutSystem_md5_Update00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"md5",0,&tolua_err) ||
!tolua_isnumber(tolua_S,2,0,&tolua_err) ||
!tolua_isnumber(tolua_S,3,0,&tolua_err) ||
!tolua_isnoobj(tolua_S,4,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
md5* self = (md5*) tolua_tousertype(tolua_S,1,0);
unsigned char chInput = (( unsigned char) tolua_tonumber(tolua_S,2,0));
unsigned int nInputLen = (( unsigned int) tolua_tonumber(tolua_S,3,0));
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'Update'", NULL);
#endif
{
self->Update(&chInput,nInputLen);
tolua_pushnumber(tolua_S,(lua_Number)chInput);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'Update'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: Finalize of class md5 */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_md5_Finalize00
static int tolua_ScutSystem_md5_Finalize00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"md5",0,&tolua_err) ||
!tolua_isnoobj(tolua_S,2,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
md5* self = (md5*) tolua_tousertype(tolua_S,1,0);
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'Finalize'", NULL);
#endif
{
self->Finalize();
}
}
return 0;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'Finalize'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: Digest of class md5 */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_md5_Digest00
static int tolua_ScutSystem_md5_Digest00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"md5",0,&tolua_err) ||
!tolua_isnoobj(tolua_S,2,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
md5* self = (md5*) tolua_tousertype(tolua_S,1,0);
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'Digest'", NULL);
#endif
{
void* tolua_ret = (void*) self->Digest();
tolua_pushuserdata(tolua_S,(void*)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'Digest'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: DesEncrypt of class ScutSystem::CScutUtility */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CScutUtility_DesEncrypt00
static int tolua_ScutSystem_ScutSystem_CScutUtility_DesEncrypt00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertable(tolua_S,1,"ScutSystem::CScutUtility",0,&tolua_err) ||
!tolua_isstring(tolua_S,2,0,&tolua_err) ||
!tolua_isstring(tolua_S,3,0,&tolua_err) ||
!tolua_iscppstring(tolua_S,4,0,&tolua_err) ||
!tolua_isnoobj(tolua_S,5,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
const char* lpszKey = ((const char*) tolua_tostring(tolua_S,2,0));
const char* lpDataIn = ((const char*) tolua_tostring(tolua_S,3,0));
std::string strDataOut = ((std::string) tolua_tocppstring(tolua_S,4,0));
{
int tolua_ret = (int) ScutSystem::CScutUtility::DesEncrypt(lpszKey,lpDataIn,strDataOut);
tolua_pushnumber(tolua_S,(lua_Number)tolua_ret);
tolua_pushcppstring(tolua_S,(const char*)strDataOut);
}
}
return 2;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'DesEncrypt'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: StdDesEncrypt of class ScutSystem::CScutUtility */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CScutUtility_StdDesEncrypt00
static int tolua_ScutSystem_ScutSystem_CScutUtility_StdDesEncrypt00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertable(tolua_S,1,"ScutSystem::CScutUtility",0,&tolua_err) ||
!tolua_isstring(tolua_S,2,0,&tolua_err) ||
!tolua_isstring(tolua_S,3,0,&tolua_err) ||
!tolua_iscppstring(tolua_S,4,0,&tolua_err) ||
!tolua_isnoobj(tolua_S,5,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
const char* lpszKey = ((const char*) tolua_tostring(tolua_S,2,0));
const char* lpDataIn = ((const char*) tolua_tostring(tolua_S,3,0));
std::string strDataOut = ((std::string) tolua_tocppstring(tolua_S,4,0));
{
ScutSystem::CScutUtility::StdDesEncrypt(lpszKey,lpDataIn,strDataOut);
tolua_pushcppstring(tolua_S,(const char*)strDataOut);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'StdDesEncrypt'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: StdDesDecrypt of class ScutSystem::CScutUtility */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CScutUtility_StdDesDecrypt00
static int tolua_ScutSystem_ScutSystem_CScutUtility_StdDesDecrypt00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertable(tolua_S,1,"ScutSystem::CScutUtility",0,&tolua_err) ||
!tolua_isstring(tolua_S,2,0,&tolua_err) ||
!tolua_isstring(tolua_S,3,0,&tolua_err) ||
!tolua_iscppstring(tolua_S,4,0,&tolua_err) ||
!tolua_isnoobj(tolua_S,5,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
const char* lpszKey = ((const char*) tolua_tostring(tolua_S,2,0));
const char* lpDataIn = ((const char*) tolua_tostring(tolua_S,3,0));
std::string strDataOut = ((std::string) tolua_tocppstring(tolua_S,4,0));
{
ScutSystem::CScutUtility::StdDesDecrypt(lpszKey,lpDataIn,strDataOut);
tolua_pushcppstring(tolua_S,(const char*)strDataOut);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'StdDesDecrypt'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: GetTickCount of class ScutSystem::CScutUtility */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CScutUtility_GetTickCount00
static int tolua_ScutSystem_ScutSystem_CScutUtility_GetTickCount00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertable(tolua_S,1,"ScutSystem::CScutUtility",0,&tolua_err) ||
!tolua_isnoobj(tolua_S,2,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
{
unsigned long tolua_ret = (unsigned long) ScutSystem::CScutUtility::GetTickCount();
tolua_pushnumber(tolua_S,(lua_Number)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'GetTickCount'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: CScutUtility::GetNowTime of class ScutSystem::CScutUtility */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CScutUtility_CScutUtility__GetNowTime00
static int tolua_ScutSystem_ScutSystem_CScutUtility_CScutUtility__GetNowTime00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"ScutSystem::CScutUtility",0,&tolua_err) ||
!tolua_isnoobj(tolua_S,2,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
ScutSystem::CScutUtility* self = (ScutSystem::CScutUtility*) tolua_tousertype(tolua_S,1,0);
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'CScutUtility::GetNowTime'", NULL);
#endif
{
std::string tolua_ret = (std::string) self->CScutUtility::GetNowTime();
tolua_pushcppstring(tolua_S,(const char*)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'CScutUtility__GetNowTime'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: delete of class ScutSystem::CStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CStream_delete00
static int tolua_ScutSystem_ScutSystem_CStream_delete00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"ScutSystem::CStream",0,&tolua_err) ||
!tolua_isnoobj(tolua_S,2,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
ScutSystem::CStream* self = (ScutSystem::CStream*) tolua_tousertype(tolua_S,1,0);
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'delete'", NULL);
#endif
Mtolua_delete(self);
}
return 0;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'delete'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: GetPosition of class ScutSystem::CStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CStream_GetPosition00
static int tolua_ScutSystem_ScutSystem_CStream_GetPosition00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"ScutSystem::CStream",0,&tolua_err) ||
!tolua_isnoobj(tolua_S,2,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
ScutSystem::CStream* self = (ScutSystem::CStream*) tolua_tousertype(tolua_S,1,0);
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'GetPosition'", NULL);
#endif
{
int tolua_ret = (int) self->GetPosition();
tolua_pushnumber(tolua_S,(lua_Number)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'GetPosition'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: SetPosition of class ScutSystem::CStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CStream_SetPosition00
static int tolua_ScutSystem_ScutSystem_CStream_SetPosition00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"ScutSystem::CStream",0,&tolua_err) ||
!tolua_isnumber(tolua_S,2,0,&tolua_err) ||
!tolua_isnoobj(tolua_S,3,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
ScutSystem::CStream* self = (ScutSystem::CStream*) tolua_tousertype(tolua_S,1,0);
const int nPos = ((const int) tolua_tonumber(tolua_S,2,0));
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'SetPosition'", NULL);
#endif
{
self->SetPosition(nPos);
}
}
return 0;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'SetPosition'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: GetSize of class ScutSystem::CStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CStream_GetSize00
static int tolua_ScutSystem_ScutSystem_CStream_GetSize00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"ScutSystem::CStream",0,&tolua_err) ||
!tolua_isnoobj(tolua_S,2,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
ScutSystem::CStream* self = (ScutSystem::CStream*) tolua_tousertype(tolua_S,1,0);
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'GetSize'", NULL);
#endif
{
int tolua_ret = (int) self->GetSize();
tolua_pushnumber(tolua_S,(lua_Number)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'GetSize'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: SetSize of class ScutSystem::CStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CStream_SetSize00
static int tolua_ScutSystem_ScutSystem_CStream_SetSize00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"ScutSystem::CStream",0,&tolua_err) ||
!tolua_isnumber(tolua_S,2,0,&tolua_err) ||
!tolua_isnoobj(tolua_S,3,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
ScutSystem::CStream* self = (ScutSystem::CStream*) tolua_tousertype(tolua_S,1,0);
const int nSize = ((const int) tolua_tonumber(tolua_S,2,0));
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'SetSize'", NULL);
#endif
{
self->SetSize(nSize);
}
}
return 0;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'SetSize'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: Read of class ScutSystem::CStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CStream_Read00
static int tolua_ScutSystem_ScutSystem_CStream_Read00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"ScutSystem::CStream",0,&tolua_err) ||
!tolua_isstring(tolua_S,2,0,&tolua_err) ||
!tolua_isnumber(tolua_S,3,0,&tolua_err) ||
!tolua_isnoobj(tolua_S,4,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
ScutSystem::CStream* self = (ScutSystem::CStream*) tolua_tousertype(tolua_S,1,0);
char* pszBuffer = ((char*) tolua_tostring(tolua_S,2,0));
int nSize = ((int) tolua_tonumber(tolua_S,3,0));
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'Read'", NULL);
#endif
{
int tolua_ret = (int) self->Read(pszBuffer,nSize);
tolua_pushnumber(tolua_S,(lua_Number)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'Read'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: Write of class ScutSystem::CStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CStream_Write00
static int tolua_ScutSystem_ScutSystem_CStream_Write00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"ScutSystem::CStream",0,&tolua_err) ||
!tolua_isstring(tolua_S,2,0,&tolua_err) ||
!tolua_isnumber(tolua_S,3,0,&tolua_err) ||
!tolua_isnoobj(tolua_S,4,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
ScutSystem::CStream* self = (ScutSystem::CStream*) tolua_tousertype(tolua_S,1,0);
const char* pszBuffer = ((const char*) tolua_tostring(tolua_S,2,0));
int nSize = ((int) tolua_tonumber(tolua_S,3,0));
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'Write'", NULL);
#endif
{
int tolua_ret = (int) self->Write(pszBuffer,nSize);
tolua_pushnumber(tolua_S,(lua_Number)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'Write'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: Seek of class ScutSystem::CStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CStream_Seek00
static int tolua_ScutSystem_ScutSystem_CStream_Seek00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"ScutSystem::CStream",0,&tolua_err) ||
!tolua_isnumber(tolua_S,2,0,&tolua_err) ||
!tolua_isnumber(tolua_S,3,0,&tolua_err) ||
!tolua_isnoobj(tolua_S,4,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
ScutSystem::CStream* self = (ScutSystem::CStream*) tolua_tousertype(tolua_S,1,0);
int nOffset = ((int) tolua_tonumber(tolua_S,2,0));
ScutSystem::EStreamOrigin origin = ((ScutSystem::EStreamOrigin) (int) tolua_tonumber(tolua_S,3,0));
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'Seek'", NULL);
#endif
{
int tolua_ret = (int) self->Seek(nOffset,origin);
tolua_pushnumber(tolua_S,(lua_Number)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'Seek'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: ReadBuffer of class ScutSystem::CStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CStream_ReadBuffer00
static int tolua_ScutSystem_ScutSystem_CStream_ReadBuffer00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"ScutSystem::CStream",0,&tolua_err) ||
!tolua_isstring(tolua_S,2,0,&tolua_err) ||
!tolua_isnumber(tolua_S,3,0,&tolua_err) ||
!tolua_isnoobj(tolua_S,4,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
ScutSystem::CStream* self = (ScutSystem::CStream*) tolua_tousertype(tolua_S,1,0);
char* pszBuffer = ((char*) tolua_tostring(tolua_S,2,0));
int nSize = ((int) tolua_tonumber(tolua_S,3,0));
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'ReadBuffer'", NULL);
#endif
{
bool tolua_ret = (bool) self->ReadBuffer(pszBuffer,nSize);
tolua_pushboolean(tolua_S,(bool)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'ReadBuffer'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: WriteBuffer of class ScutSystem::CStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CStream_WriteBuffer00
static int tolua_ScutSystem_ScutSystem_CStream_WriteBuffer00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"ScutSystem::CStream",0,&tolua_err) ||
!tolua_isstring(tolua_S,2,0,&tolua_err) ||
!tolua_isnumber(tolua_S,3,0,&tolua_err) ||
!tolua_isnoobj(tolua_S,4,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
ScutSystem::CStream* self = (ScutSystem::CStream*) tolua_tousertype(tolua_S,1,0);
const char* pszBuffer = ((const char*) tolua_tostring(tolua_S,2,0));
int nSize = ((int) tolua_tonumber(tolua_S,3,0));
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'WriteBuffer'", NULL);
#endif
{
bool tolua_ret = (bool) self->WriteBuffer(pszBuffer,nSize);
tolua_pushboolean(tolua_S,(bool)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'WriteBuffer'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: CopyFrom of class ScutSystem::CStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CStream_CopyFrom00
static int tolua_ScutSystem_ScutSystem_CStream_CopyFrom00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"ScutSystem::CStream",0,&tolua_err) ||
!tolua_isusertype(tolua_S,2,"ScutSystem::CStream",0,&tolua_err) ||
!tolua_isnumber(tolua_S,3,1,&tolua_err) ||
!tolua_isnoobj(tolua_S,4,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
ScutSystem::CStream* self = (ScutSystem::CStream*) tolua_tousertype(tolua_S,1,0);
ScutSystem::CStream* pSource = ((ScutSystem::CStream*) tolua_tousertype(tolua_S,2,0));
int nSize = ((int) tolua_tonumber(tolua_S,3,0));
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'CopyFrom'", NULL);
#endif
{
int tolua_ret = (int) self->CopyFrom(pSource,nSize);
tolua_pushnumber(tolua_S,(lua_Number)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'CopyFrom'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: GetBuffer of class ScutSystem::CStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CStream_GetBuffer00
static int tolua_ScutSystem_ScutSystem_CStream_GetBuffer00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"ScutSystem::CStream",0,&tolua_err) ||
!tolua_isnumber(tolua_S,2,0,&tolua_err) ||
!tolua_isnoobj(tolua_S,3,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
ScutSystem::CStream* self = (ScutSystem::CStream*) tolua_tousertype(tolua_S,1,0);
int nSize = ((int) tolua_tonumber(tolua_S,2,0));
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'GetBuffer'", NULL);
#endif
{
char* tolua_ret = (char*) self->GetBuffer(nSize);
tolua_pushstring(tolua_S,(const char*)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'GetBuffer'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: new of class ScutSystem::CHandleStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CHandleStream_new00
static int tolua_ScutSystem_ScutSystem_CHandleStream_new00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertable(tolua_S,1,"ScutSystem::CHandleStream",0,&tolua_err) ||
!tolua_isnoobj(tolua_S,2,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
{
ScutSystem::CHandleStream* tolua_ret = (ScutSystem::CHandleStream*) Mtolua_new((ScutSystem::CHandleStream)());
tolua_pushusertype(tolua_S,(void*)tolua_ret,"ScutSystem::CHandleStream");
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'new'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: new_local of class ScutSystem::CHandleStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CHandleStream_new00_local
static int tolua_ScutSystem_ScutSystem_CHandleStream_new00_local(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertable(tolua_S,1,"ScutSystem::CHandleStream",0,&tolua_err) ||
!tolua_isnoobj(tolua_S,2,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
{
ScutSystem::CHandleStream* tolua_ret = (ScutSystem::CHandleStream*) Mtolua_new((ScutSystem::CHandleStream)());
tolua_pushusertype(tolua_S,(void*)tolua_ret,"ScutSystem::CHandleStream");
tolua_register_gc(tolua_S,lua_gettop(tolua_S));
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'new'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: SetSize of class ScutSystem::CHandleStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CHandleStream_SetSize00
static int tolua_ScutSystem_ScutSystem_CHandleStream_SetSize00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"ScutSystem::CHandleStream",0,&tolua_err) ||
!tolua_isnumber(tolua_S,2,0,&tolua_err) ||
!tolua_isnoobj(tolua_S,3,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
ScutSystem::CHandleStream* self = (ScutSystem::CHandleStream*) tolua_tousertype(tolua_S,1,0);
const int nSize = ((const int) tolua_tonumber(tolua_S,2,0));
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'SetSize'", NULL);
#endif
{
self->SetSize(nSize);
}
}
return 0;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'SetSize'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: Read of class ScutSystem::CHandleStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CHandleStream_Read00
static int tolua_ScutSystem_ScutSystem_CHandleStream_Read00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"ScutSystem::CHandleStream",0,&tolua_err) ||
!tolua_isstring(tolua_S,2,0,&tolua_err) ||
!tolua_isnumber(tolua_S,3,0,&tolua_err) ||
!tolua_isnoobj(tolua_S,4,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
ScutSystem::CHandleStream* self = (ScutSystem::CHandleStream*) tolua_tousertype(tolua_S,1,0);
char* pszBuffer = ((char*) tolua_tostring(tolua_S,2,0));
int nSize = ((int) tolua_tonumber(tolua_S,3,0));
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'Read'", NULL);
#endif
{
int tolua_ret = (int) self->Read(pszBuffer,nSize);
tolua_pushnumber(tolua_S,(lua_Number)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'Read'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: Write of class ScutSystem::CHandleStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CHandleStream_Write00
static int tolua_ScutSystem_ScutSystem_CHandleStream_Write00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"ScutSystem::CHandleStream",0,&tolua_err) ||
!tolua_isstring(tolua_S,2,0,&tolua_err) ||
!tolua_isnumber(tolua_S,3,0,&tolua_err) ||
!tolua_isnoobj(tolua_S,4,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
ScutSystem::CHandleStream* self = (ScutSystem::CHandleStream*) tolua_tousertype(tolua_S,1,0);
const char* pszBuffer = ((const char*) tolua_tostring(tolua_S,2,0));
int nSize = ((int) tolua_tonumber(tolua_S,3,0));
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'Write'", NULL);
#endif
{
int tolua_ret = (int) self->Write(pszBuffer,nSize);
tolua_pushnumber(tolua_S,(lua_Number)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'Write'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: Seek of class ScutSystem::CHandleStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CHandleStream_Seek00
static int tolua_ScutSystem_ScutSystem_CHandleStream_Seek00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"ScutSystem::CHandleStream",0,&tolua_err) ||
!tolua_isnumber(tolua_S,2,0,&tolua_err) ||
!tolua_isnumber(tolua_S,3,0,&tolua_err) ||
!tolua_isnoobj(tolua_S,4,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
ScutSystem::CHandleStream* self = (ScutSystem::CHandleStream*) tolua_tousertype(tolua_S,1,0);
int nOffset = ((int) tolua_tonumber(tolua_S,2,0));
ScutSystem::EStreamOrigin origin = ((ScutSystem::EStreamOrigin) (int) tolua_tonumber(tolua_S,3,0));
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'Seek'", NULL);
#endif
{
int tolua_ret = (int) self->Seek(nOffset,origin);
tolua_pushnumber(tolua_S,(lua_Number)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'Seek'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: GetHandle of class ScutSystem::CHandleStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CHandleStream_GetHandle00
static int tolua_ScutSystem_ScutSystem_CHandleStream_GetHandle00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"ScutSystem::CHandleStream",0,&tolua_err) ||
!tolua_isnoobj(tolua_S,2,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
ScutSystem::CHandleStream* self = (ScutSystem::CHandleStream*) tolua_tousertype(tolua_S,1,0);
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'GetHandle'", NULL);
#endif
{
intptr_t tolua_ret = (intptr_t) self->GetHandle();
{
#ifdef __cplusplus
void* tolua_obj = Mtolua_new((intptr_t)(tolua_ret));
tolua_pushusertype(tolua_S,tolua_obj,"intptr_t");
tolua_register_gc(tolua_S,lua_gettop(tolua_S));
#else
void* tolua_obj = tolua_copy(tolua_S,(void*)&tolua_ret,sizeof(intptr_t));
tolua_pushusertype(tolua_S,tolua_obj,"intptr_t");
tolua_register_gc(tolua_S,lua_gettop(tolua_S));
#endif
}
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'GetHandle'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: SetHandle of class ScutSystem::CHandleStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CHandleStream_SetHandle00
static int tolua_ScutSystem_ScutSystem_CHandleStream_SetHandle00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"ScutSystem::CHandleStream",0,&tolua_err) ||
(tolua_isvaluenil(tolua_S,2,&tolua_err) || !tolua_isusertype(tolua_S,2,"intptr_t",0,&tolua_err)) ||
!tolua_isnoobj(tolua_S,3,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
ScutSystem::CHandleStream* self = (ScutSystem::CHandleStream*) tolua_tousertype(tolua_S,1,0);
intptr_t hHandle = *((intptr_t*) tolua_tousertype(tolua_S,2,0));
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'SetHandle'", NULL);
#endif
{
self->SetHandle(hHandle);
}
}
return 0;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'SetHandle'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: new of class ScutSystem::CFileStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CFileStream_new00
static int tolua_ScutSystem_ScutSystem_CFileStream_new00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertable(tolua_S,1,"ScutSystem::CFileStream",0,&tolua_err) ||
!tolua_isnoobj(tolua_S,2,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
{
ScutSystem::CFileStream* tolua_ret = (ScutSystem::CFileStream*) Mtolua_new((ScutSystem::CFileStream)());
tolua_pushusertype(tolua_S,(void*)tolua_ret,"ScutSystem::CFileStream");
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'new'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: new_local of class ScutSystem::CFileStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CFileStream_new00_local
static int tolua_ScutSystem_ScutSystem_CFileStream_new00_local(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertable(tolua_S,1,"ScutSystem::CFileStream",0,&tolua_err) ||
!tolua_isnoobj(tolua_S,2,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
{
ScutSystem::CFileStream* tolua_ret = (ScutSystem::CFileStream*) Mtolua_new((ScutSystem::CFileStream)());
tolua_pushusertype(tolua_S,(void*)tolua_ret,"ScutSystem::CFileStream");
tolua_register_gc(tolua_S,lua_gettop(tolua_S));
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'new'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: Open of class ScutSystem::CFileStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CFileStream_Open00
static int tolua_ScutSystem_ScutSystem_CFileStream_Open00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"ScutSystem::CFileStream",0,&tolua_err) ||
!tolua_isstring(tolua_S,2,0,&tolua_err) ||
(tolua_isvaluenil(tolua_S,3,&tolua_err) || !tolua_isusertype(tolua_S,3,"DWORD",0,&tolua_err)) ||
(tolua_isvaluenil(tolua_S,4,&tolua_err) || !tolua_isusertype(tolua_S,4,"DWORD",0,&tolua_err)) ||
!tolua_isstring(tolua_S,5,1,&tolua_err) ||
!tolua_isnoobj(tolua_S,6,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
ScutSystem::CFileStream* self = (ScutSystem::CFileStream*) tolua_tousertype(tolua_S,1,0);
const char* lpszFileName = ((const char*) tolua_tostring(tolua_S,2,0));
DWORD dwFlag = *((DWORD*) tolua_tousertype(tolua_S,3,0));
DWORD dwMode = *((DWORD*) tolua_tousertype(tolua_S,4,0));
char* chMode = ((char*) tolua_tostring(tolua_S,5,NULL));
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'Open'", NULL);
#endif
{
int tolua_ret = (int) self->Open(lpszFileName,dwFlag,dwMode,chMode);
tolua_pushnumber(tolua_S,(lua_Number)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'Open'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: delete of class ScutSystem::CFileStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CFileStream_delete00
static int tolua_ScutSystem_ScutSystem_CFileStream_delete00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"ScutSystem::CFileStream",0,&tolua_err) ||
!tolua_isnoobj(tolua_S,2,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
ScutSystem::CFileStream* self = (ScutSystem::CFileStream*) tolua_tousertype(tolua_S,1,0);
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'delete'", NULL);
#endif
Mtolua_delete(self);
}
return 0;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'delete'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: SetSize of class ScutSystem::CBaseMemoryStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CBaseMemoryStream_SetSize00
static int tolua_ScutSystem_ScutSystem_CBaseMemoryStream_SetSize00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"ScutSystem::CBaseMemoryStream",0,&tolua_err) ||
!tolua_isnumber(tolua_S,2,0,&tolua_err) ||
!tolua_isnoobj(tolua_S,3,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
ScutSystem::CBaseMemoryStream* self = (ScutSystem::CBaseMemoryStream*) tolua_tousertype(tolua_S,1,0);
const int nSize = ((const int) tolua_tonumber(tolua_S,2,0));
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'SetSize'", NULL);
#endif
{
self->SetSize(nSize);
}
}
return 0;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'SetSize'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: Write of class ScutSystem::CBaseMemoryStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CBaseMemoryStream_Write00
static int tolua_ScutSystem_ScutSystem_CBaseMemoryStream_Write00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"ScutSystem::CBaseMemoryStream",0,&tolua_err) ||
!tolua_isstring(tolua_S,2,0,&tolua_err) ||
!tolua_isnumber(tolua_S,3,0,&tolua_err) ||
!tolua_isnoobj(tolua_S,4,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
ScutSystem::CBaseMemoryStream* self = (ScutSystem::CBaseMemoryStream*) tolua_tousertype(tolua_S,1,0);
const char* pszBuffer = ((const char*) tolua_tostring(tolua_S,2,0));
int nSize = ((int) tolua_tonumber(tolua_S,3,0));
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'Write'", NULL);
#endif
{
int tolua_ret = (int) self->Write(pszBuffer,nSize);
tolua_pushnumber(tolua_S,(lua_Number)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'Write'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: Read of class ScutSystem::CBaseMemoryStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CBaseMemoryStream_Read00
static int tolua_ScutSystem_ScutSystem_CBaseMemoryStream_Read00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"ScutSystem::CBaseMemoryStream",0,&tolua_err) ||
!tolua_isstring(tolua_S,2,0,&tolua_err) ||
!tolua_isnumber(tolua_S,3,0,&tolua_err) ||
!tolua_isnoobj(tolua_S,4,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
ScutSystem::CBaseMemoryStream* self = (ScutSystem::CBaseMemoryStream*) tolua_tousertype(tolua_S,1,0);
char* pszBuffer = ((char*) tolua_tostring(tolua_S,2,0));
int nSize = ((int) tolua_tonumber(tolua_S,3,0));
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'Read'", NULL);
#endif
{
int tolua_ret = (int) self->Read(pszBuffer,nSize);
tolua_pushnumber(tolua_S,(lua_Number)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'Read'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: Seek of class ScutSystem::CBaseMemoryStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CBaseMemoryStream_Seek00
static int tolua_ScutSystem_ScutSystem_CBaseMemoryStream_Seek00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"ScutSystem::CBaseMemoryStream",0,&tolua_err) ||
!tolua_isnumber(tolua_S,2,0,&tolua_err) ||
!tolua_isnumber(tolua_S,3,0,&tolua_err) ||
!tolua_isnoobj(tolua_S,4,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
ScutSystem::CBaseMemoryStream* self = (ScutSystem::CBaseMemoryStream*) tolua_tousertype(tolua_S,1,0);
int nOffset = ((int) tolua_tonumber(tolua_S,2,0));
ScutSystem::EStreamOrigin origin = ((ScutSystem::EStreamOrigin) (int) tolua_tonumber(tolua_S,3,0));
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'Seek'", NULL);
#endif
{
int tolua_ret = (int) self->Seek(nOffset,origin);
tolua_pushnumber(tolua_S,(lua_Number)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'Seek'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: SaveTo of class ScutSystem::CBaseMemoryStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CBaseMemoryStream_SaveTo00
static int tolua_ScutSystem_ScutSystem_CBaseMemoryStream_SaveTo00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"ScutSystem::CBaseMemoryStream",0,&tolua_err) ||
!tolua_isusertype(tolua_S,2,"ScutSystem::CStream",0,&tolua_err) ||
!tolua_isnoobj(tolua_S,3,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
ScutSystem::CBaseMemoryStream* self = (ScutSystem::CBaseMemoryStream*) tolua_tousertype(tolua_S,1,0);
ScutSystem::CStream* pDest = ((ScutSystem::CStream*) tolua_tousertype(tolua_S,2,0));
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'SaveTo'", NULL);
#endif
{
self->SaveTo(pDest);
}
}
return 0;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'SaveTo'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: SaveTo of class ScutSystem::CBaseMemoryStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CBaseMemoryStream_SaveTo01
static int tolua_ScutSystem_ScutSystem_CBaseMemoryStream_SaveTo01(lua_State* tolua_S)
{
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"ScutSystem::CBaseMemoryStream",0,&tolua_err) ||
!tolua_isstring(tolua_S,2,0,&tolua_err) ||
!tolua_isnoobj(tolua_S,3,&tolua_err)
)
goto tolua_lerror;
else
{
ScutSystem::CBaseMemoryStream* self = (ScutSystem::CBaseMemoryStream*) tolua_tousertype(tolua_S,1,0);
const char* lpszFileName = ((const char*) tolua_tostring(tolua_S,2,0));
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'SaveTo'", NULL);
#endif
{
self->SaveTo(lpszFileName);
}
}
return 0;
tolua_lerror:
return tolua_ScutSystem_ScutSystem_CBaseMemoryStream_SaveTo00(tolua_S);
}
#endif //#ifndef TOLUA_DISABLE
/* method: GetMemory of class ScutSystem::CBaseMemoryStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CBaseMemoryStream_GetMemory00
static int tolua_ScutSystem_ScutSystem_CBaseMemoryStream_GetMemory00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"ScutSystem::CBaseMemoryStream",0,&tolua_err) ||
!tolua_isnoobj(tolua_S,2,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
ScutSystem::CBaseMemoryStream* self = (ScutSystem::CBaseMemoryStream*) tolua_tousertype(tolua_S,1,0);
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'GetMemory'", NULL);
#endif
{
void* tolua_ret = (void*) self->GetMemory();
tolua_pushuserdata(tolua_S,(void*)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'GetMemory'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: new of class ScutSystem::CMemoryStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CMemoryStream_new00
static int tolua_ScutSystem_ScutSystem_CMemoryStream_new00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertable(tolua_S,1,"ScutSystem::CMemoryStream",0,&tolua_err) ||
!tolua_isnoobj(tolua_S,2,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
{
ScutSystem::CMemoryStream* tolua_ret = (ScutSystem::CMemoryStream*) Mtolua_new((ScutSystem::CMemoryStream)());
tolua_pushusertype(tolua_S,(void*)tolua_ret,"ScutSystem::CMemoryStream");
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'new'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: new_local of class ScutSystem::CMemoryStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CMemoryStream_new00_local
static int tolua_ScutSystem_ScutSystem_CMemoryStream_new00_local(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertable(tolua_S,1,"ScutSystem::CMemoryStream",0,&tolua_err) ||
!tolua_isnoobj(tolua_S,2,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
{
ScutSystem::CMemoryStream* tolua_ret = (ScutSystem::CMemoryStream*) Mtolua_new((ScutSystem::CMemoryStream)());
tolua_pushusertype(tolua_S,(void*)tolua_ret,"ScutSystem::CMemoryStream");
tolua_register_gc(tolua_S,lua_gettop(tolua_S));
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'new'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: delete of class ScutSystem::CMemoryStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CMemoryStream_delete00
static int tolua_ScutSystem_ScutSystem_CMemoryStream_delete00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"ScutSystem::CMemoryStream",0,&tolua_err) ||
!tolua_isnoobj(tolua_S,2,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
ScutSystem::CMemoryStream* self = (ScutSystem::CMemoryStream*) tolua_tousertype(tolua_S,1,0);
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'delete'", NULL);
#endif
Mtolua_delete(self);
}
return 0;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'delete'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: Clear of class ScutSystem::CMemoryStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CMemoryStream_Clear00
static int tolua_ScutSystem_ScutSystem_CMemoryStream_Clear00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"ScutSystem::CMemoryStream",0,&tolua_err) ||
!tolua_isnoobj(tolua_S,2,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
ScutSystem::CMemoryStream* self = (ScutSystem::CMemoryStream*) tolua_tousertype(tolua_S,1,0);
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'Clear'", NULL);
#endif
{
self->Clear();
}
}
return 0;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'Clear'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: LoadFrom of class ScutSystem::CMemoryStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CMemoryStream_LoadFrom00
static int tolua_ScutSystem_ScutSystem_CMemoryStream_LoadFrom00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"ScutSystem::CMemoryStream",0,&tolua_err) ||
!tolua_isusertype(tolua_S,2,"ScutSystem::CStream",0,&tolua_err) ||
!tolua_isnoobj(tolua_S,3,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
ScutSystem::CMemoryStream* self = (ScutSystem::CMemoryStream*) tolua_tousertype(tolua_S,1,0);
ScutSystem::CStream* pSource = ((ScutSystem::CStream*) tolua_tousertype(tolua_S,2,0));
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'LoadFrom'", NULL);
#endif
{
self->LoadFrom(pSource);
}
}
return 0;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'LoadFrom'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: LoadFrom of class ScutSystem::CMemoryStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CMemoryStream_LoadFrom01
static int tolua_ScutSystem_ScutSystem_CMemoryStream_LoadFrom01(lua_State* tolua_S)
{
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"ScutSystem::CMemoryStream",0,&tolua_err) ||
!tolua_isstring(tolua_S,2,0,&tolua_err) ||
!tolua_isnoobj(tolua_S,3,&tolua_err)
)
goto tolua_lerror;
else
{
ScutSystem::CMemoryStream* self = (ScutSystem::CMemoryStream*) tolua_tousertype(tolua_S,1,0);
const char* lpszFileName = ((const char*) tolua_tostring(tolua_S,2,0));
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'LoadFrom'", NULL);
#endif
{
self->LoadFrom(lpszFileName);
}
}
return 0;
tolua_lerror:
return tolua_ScutSystem_ScutSystem_CMemoryStream_LoadFrom00(tolua_S);
}
#endif //#ifndef TOLUA_DISABLE
/* method: SetSize of class ScutSystem::CMemoryStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CMemoryStream_SetSize00
static int tolua_ScutSystem_ScutSystem_CMemoryStream_SetSize00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"ScutSystem::CMemoryStream",0,&tolua_err) ||
!tolua_isnumber(tolua_S,2,0,&tolua_err) ||
!tolua_isnoobj(tolua_S,3,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
ScutSystem::CMemoryStream* self = (ScutSystem::CMemoryStream*) tolua_tousertype(tolua_S,1,0);
const int nSize = ((const int) tolua_tonumber(tolua_S,2,0));
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'SetSize'", NULL);
#endif
{
self->SetSize(nSize);
}
}
return 0;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'SetSize'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: Write of class ScutSystem::CMemoryStream */
#ifndef TOLUA_DISABLE_tolua_ScutSystem_ScutSystem_CMemoryStream_Write00
static int tolua_ScutSystem_ScutSystem_CMemoryStream_Write00(lua_State* tolua_S)
{
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (
!tolua_isusertype(tolua_S,1,"ScutSystem::CMemoryStream",0,&tolua_err) ||
!tolua_isstring(tolua_S,2,0,&tolua_err) ||
!tolua_isnumber(tolua_S,3,0,&tolua_err) ||
!tolua_isnoobj(tolua_S,4,&tolua_err)
)
goto tolua_lerror;
else
#endif
{
ScutSystem::CMemoryStream* self = (ScutSystem::CMemoryStream*) tolua_tousertype(tolua_S,1,0);
const char* pszBuffer = ((const char*) tolua_tostring(tolua_S,2,0));
int nSize = ((int) tolua_tonumber(tolua_S,3,0));
#ifndef TOLUA_RELEASE
if (!self) tolua_error(tolua_S,"invalid 'self' in function 'Write'", NULL);
#endif
{
int tolua_ret = (int) self->Write(pszBuffer,nSize);
tolua_pushnumber(tolua_S,(lua_Number)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,"#ferror in function 'Write'.",&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* Open function */
TOLUA_API int tolua_ScutSystem_open (lua_State* tolua_S)
{
tolua_open(tolua_S);
tolua_reg_types(tolua_S);
tolua_module(tolua_S,NULL,0);
tolua_beginmodule(tolua_S,NULL);
tolua_function(tolua_S,"PrintMD5",tolua_ScutSystem_PrintMD500);
tolua_function(tolua_S,"MD5String",tolua_ScutSystem_MD5String00);
tolua_function(tolua_S,"MD5File",tolua_ScutSystem_MD5File00);
#ifdef __cplusplus
tolua_cclass(tolua_S,"md5","md5","",tolua_collect_md5);
#else
tolua_cclass(tolua_S,"md5","md5","",NULL);
#endif
tolua_beginmodule(tolua_S,"md5");
tolua_function(tolua_S,"new",tolua_ScutSystem_md5_new00);
tolua_function(tolua_S,"new_local",tolua_ScutSystem_md5_new00_local);
tolua_function(tolua_S,".call",tolua_ScutSystem_md5_new00_local);
tolua_function(tolua_S,"Init",tolua_ScutSystem_md5_Init00);
tolua_function(tolua_S,"Update",tolua_ScutSystem_md5_Update00);
tolua_function(tolua_S,"Finalize",tolua_ScutSystem_md5_Finalize00);
tolua_function(tolua_S,"Digest",tolua_ScutSystem_md5_Digest00);
tolua_endmodule(tolua_S);
tolua_module(tolua_S,"ScutSystem",0);
tolua_beginmodule(tolua_S,"ScutSystem");
tolua_cclass(tolua_S,"CScutUtility","ScutSystem::CScutUtility","",NULL);
tolua_beginmodule(tolua_S,"CScutUtility");
tolua_function(tolua_S,"DesEncrypt",tolua_ScutSystem_ScutSystem_CScutUtility_DesEncrypt00);
tolua_function(tolua_S,"StdDesEncrypt",tolua_ScutSystem_ScutSystem_CScutUtility_StdDesEncrypt00);
tolua_function(tolua_S,"StdDesDecrypt",tolua_ScutSystem_ScutSystem_CScutUtility_StdDesDecrypt00);
tolua_function(tolua_S,"GetTickCount",tolua_ScutSystem_ScutSystem_CScutUtility_GetTickCount00);
tolua_function(tolua_S,"CScutUtility__GetNowTime",tolua_ScutSystem_ScutSystem_CScutUtility_CScutUtility__GetNowTime00);
tolua_endmodule(tolua_S);
tolua_endmodule(tolua_S);
tolua_module(tolua_S,"ScutSystem",0);
tolua_beginmodule(tolua_S,"ScutSystem");
tolua_constant(tolua_S,"soBegin",ScutSystem::soBegin);
tolua_constant(tolua_S,"soCurrent",ScutSystem::soCurrent);
tolua_constant(tolua_S,"soEnd",ScutSystem::soEnd);
#ifdef __cplusplus
tolua_cclass(tolua_S,"CStream","ScutSystem::CStream","",tolua_collect_ScutSystem__CStream);
#else
tolua_cclass(tolua_S,"CStream","ScutSystem::CStream","",NULL);
#endif
tolua_beginmodule(tolua_S,"CStream");
tolua_function(tolua_S,"delete",tolua_ScutSystem_ScutSystem_CStream_delete00);
tolua_function(tolua_S,"GetPosition",tolua_ScutSystem_ScutSystem_CStream_GetPosition00);
tolua_function(tolua_S,"SetPosition",tolua_ScutSystem_ScutSystem_CStream_SetPosition00);
tolua_function(tolua_S,"GetSize",tolua_ScutSystem_ScutSystem_CStream_GetSize00);
tolua_function(tolua_S,"SetSize",tolua_ScutSystem_ScutSystem_CStream_SetSize00);
tolua_function(tolua_S,"Read",tolua_ScutSystem_ScutSystem_CStream_Read00);
tolua_function(tolua_S,"Write",tolua_ScutSystem_ScutSystem_CStream_Write00);
tolua_function(tolua_S,"Seek",tolua_ScutSystem_ScutSystem_CStream_Seek00);
tolua_function(tolua_S,"ReadBuffer",tolua_ScutSystem_ScutSystem_CStream_ReadBuffer00);
tolua_function(tolua_S,"WriteBuffer",tolua_ScutSystem_ScutSystem_CStream_WriteBuffer00);
tolua_function(tolua_S,"CopyFrom",tolua_ScutSystem_ScutSystem_CStream_CopyFrom00);
tolua_function(tolua_S,"GetBuffer",tolua_ScutSystem_ScutSystem_CStream_GetBuffer00);
tolua_endmodule(tolua_S);
#ifdef __cplusplus
tolua_cclass(tolua_S,"CHandleStream","ScutSystem::CHandleStream","ScutSystem::CStream",tolua_collect_ScutSystem__CHandleStream);
#else
tolua_cclass(tolua_S,"CHandleStream","ScutSystem::CHandleStream","ScutSystem::CStream",NULL);
#endif
tolua_beginmodule(tolua_S,"CHandleStream");
tolua_function(tolua_S,"new",tolua_ScutSystem_ScutSystem_CHandleStream_new00);
tolua_function(tolua_S,"new_local",tolua_ScutSystem_ScutSystem_CHandleStream_new00_local);
tolua_function(tolua_S,".call",tolua_ScutSystem_ScutSystem_CHandleStream_new00_local);
tolua_function(tolua_S,"SetSize",tolua_ScutSystem_ScutSystem_CHandleStream_SetSize00);
tolua_function(tolua_S,"Read",tolua_ScutSystem_ScutSystem_CHandleStream_Read00);
tolua_function(tolua_S,"Write",tolua_ScutSystem_ScutSystem_CHandleStream_Write00);
tolua_function(tolua_S,"Seek",tolua_ScutSystem_ScutSystem_CHandleStream_Seek00);
tolua_function(tolua_S,"GetHandle",tolua_ScutSystem_ScutSystem_CHandleStream_GetHandle00);
tolua_function(tolua_S,"SetHandle",tolua_ScutSystem_ScutSystem_CHandleStream_SetHandle00);
tolua_endmodule(tolua_S);
#ifdef __cplusplus
tolua_cclass(tolua_S,"CFileStream","ScutSystem::CFileStream","ScutSystem::CHandleStream",tolua_collect_ScutSystem__CFileStream);
#else
tolua_cclass(tolua_S,"CFileStream","ScutSystem::CFileStream","ScutSystem::CHandleStream",NULL);
#endif
tolua_beginmodule(tolua_S,"CFileStream");
tolua_function(tolua_S,"new",tolua_ScutSystem_ScutSystem_CFileStream_new00);
tolua_function(tolua_S,"new_local",tolua_ScutSystem_ScutSystem_CFileStream_new00_local);
tolua_function(tolua_S,".call",tolua_ScutSystem_ScutSystem_CFileStream_new00_local);
tolua_function(tolua_S,"Open",tolua_ScutSystem_ScutSystem_CFileStream_Open00);
tolua_function(tolua_S,"delete",tolua_ScutSystem_ScutSystem_CFileStream_delete00);
tolua_endmodule(tolua_S);
#ifdef __cplusplus
tolua_cclass(tolua_S,"CBaseMemoryStream","ScutSystem::CBaseMemoryStream","ScutSystem::CStream",tolua_collect_ScutSystem__CBaseMemoryStream);
#else
tolua_cclass(tolua_S,"CBaseMemoryStream","ScutSystem::CBaseMemoryStream","ScutSystem::CStream",NULL);
#endif
tolua_beginmodule(tolua_S,"CBaseMemoryStream");
tolua_function(tolua_S,"SetSize",tolua_ScutSystem_ScutSystem_CBaseMemoryStream_SetSize00);
tolua_function(tolua_S,"Write",tolua_ScutSystem_ScutSystem_CBaseMemoryStream_Write00);
tolua_function(tolua_S,"Read",tolua_ScutSystem_ScutSystem_CBaseMemoryStream_Read00);
tolua_function(tolua_S,"Seek",tolua_ScutSystem_ScutSystem_CBaseMemoryStream_Seek00);
tolua_function(tolua_S,"SaveTo",tolua_ScutSystem_ScutSystem_CBaseMemoryStream_SaveTo00);
tolua_function(tolua_S,"SaveTo",tolua_ScutSystem_ScutSystem_CBaseMemoryStream_SaveTo01);
tolua_function(tolua_S,"GetMemory",tolua_ScutSystem_ScutSystem_CBaseMemoryStream_GetMemory00);
tolua_endmodule(tolua_S);
#ifdef __cplusplus
tolua_cclass(tolua_S,"CMemoryStream","ScutSystem::CMemoryStream","ScutSystem::CBaseMemoryStream",tolua_collect_ScutSystem__CMemoryStream);
#else
tolua_cclass(tolua_S,"CMemoryStream","ScutSystem::CMemoryStream","ScutSystem::CBaseMemoryStream",NULL);
#endif
tolua_beginmodule(tolua_S,"CMemoryStream");
tolua_function(tolua_S,"new",tolua_ScutSystem_ScutSystem_CMemoryStream_new00);
tolua_function(tolua_S,"new_local",tolua_ScutSystem_ScutSystem_CMemoryStream_new00_local);
tolua_function(tolua_S,".call",tolua_ScutSystem_ScutSystem_CMemoryStream_new00_local);
tolua_function(tolua_S,"delete",tolua_ScutSystem_ScutSystem_CMemoryStream_delete00);
tolua_function(tolua_S,"Clear",tolua_ScutSystem_ScutSystem_CMemoryStream_Clear00);
tolua_function(tolua_S,"LoadFrom",tolua_ScutSystem_ScutSystem_CMemoryStream_LoadFrom00);
tolua_function(tolua_S,"LoadFrom",tolua_ScutSystem_ScutSystem_CMemoryStream_LoadFrom01);
tolua_function(tolua_S,"SetSize",tolua_ScutSystem_ScutSystem_CMemoryStream_SetSize00);
tolua_function(tolua_S,"Write",tolua_ScutSystem_ScutSystem_CMemoryStream_Write00);
tolua_endmodule(tolua_S);
tolua_endmodule(tolua_S);
tolua_endmodule(tolua_S);
return 1;
}
#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 501
TOLUA_API int luaopen_ScutSystem (lua_State* tolua_S) {
return tolua_ScutSystem_open(tolua_S);
};
#endif
| 32.222391 | 144 | 0.736303 | [
"object"
] |
6c950bbf4acd291d94a1e3f5ca14b9e582e224d4 | 26,900 | cpp | C++ | easy_manipulation_deployment/workcell_builder/workcell_builder/gui/new_scene.cpp | quasi-robotics/easy_manipulation_deployment | 21704ab8f9a9b5f89022990ff0d02c1765fd4be1 | [
"Apache-2.0"
] | 38 | 2020-07-10T02:40:01.000Z | 2022-01-16T16:06:43.000Z | easy_manipulation_deployment/workcell_builder/workcell_builder/gui/new_scene.cpp | quasi-robotics/easy_manipulation_deployment | 21704ab8f9a9b5f89022990ff0d02c1765fd4be1 | [
"Apache-2.0"
] | 11 | 2021-01-13T16:27:28.000Z | 2022-03-03T12:39:56.000Z | easy_manipulation_deployment/workcell_builder/workcell_builder/gui/new_scene.cpp | quasi-robotics/easy_manipulation_deployment | 21704ab8f9a9b5f89022990ff0d02c1765fd4be1 | [
"Apache-2.0"
] | 9 | 2021-01-08T07:40:06.000Z | 2022-02-02T00:31:07.000Z | // Copyright 2020 Advanced Remanufacturing and Technology Centre
// Copyright 2020 ROS-Industrial Consortium Asia Pacific Team
//
// 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 "gui/new_scene.h"
#include <QFileDialog>
#include <boost/filesystem.hpp>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
#include "gui/addexternaljoint.h"
#include "gui/addobject.h"
#include "gui/ui_new_scene.h"
NewScene::NewScene(QWidget * parent)
: QDialog(parent),
ui(new Ui::NewScene)
{
ui->setupUi(this);
on_enable_robot_stateChanged(0);
on_enable_ee_stateChanged(0);
success = false;
}
NewScene::~NewScene()
{
delete ui;
}
void NewScene::on_add_object_clicked()
{
AddObject object_window;
object_window.setWindowTitle("Add New Environmental Object");
object_window.setModal(true);
object_window.exec();
if (object_window.success) {
ui->object_list->addItem(QString::fromStdString(object_window.object.name));
// visual_list.push_back(visual_window);
gui_environment.environment.object_vector.push_back(object_window.object);
gui_environment.object_names.push_back(object_window.object.name);
std::vector<std::string> link_vec;
for (int i = 0; i < static_cast<int>(object_window.object.link_vector.size()); i++) {
link_vec.push_back(object_window.object.link_vector[i].name);
}
if (link_vec.size() == 0) {
link_vec.push_back("");
}
gui_environment.object_links.push_back(link_vec);
std::vector<std::string> joint_vec;
for (int i = 0; i < static_cast<int>(object_window.object.joint_vector.size()); i++) {
joint_vec.push_back(object_window.object.joint_vector[i].name);
}
if (joint_vec.size() == 0) {
joint_vec.push_back("");
}
gui_environment.object_joints.push_back(joint_vec);
}
}
void NewScene::on_object_list_itemDoubleClicked(QListWidgetItem * item)
{
int pos = ui->object_list->row(item);
AddObject object_window;
object_window.setModal(true);
object_window.setWindowTitle("Edit Object");
object_window.LoadObject(gui_environment.environment.object_vector[pos]);
object_window.link_names = gui_environment.object_links[pos];
object_window.joint_names = gui_environment.object_joints[pos];
object_window.available_object_names = gui_environment.object_names;
object_window.object = gui_environment.environment.object_vector[pos];
object_window.exec();
gui_environment.environment.object_vector[pos] = object_window.object;
gui_environment.object_names[pos] = object_window.object.name;
std::vector<std::string> link_vec;
for (int i = 0; i < static_cast<int>(object_window.object.link_vector.size()); i++) {
link_vec.push_back(object_window.object.link_vector[i].name);
}
gui_environment.object_links[pos] = link_vec;
item->setText(QString::fromStdString(object_window.object.name));
}
std::vector<std::string> NewScene::GetLinks(std::string filename)
{
std::vector<std::string> links;
std::ifstream infile(filename);
std::string line;
while (std::getline(infile, line)) {
std::istringstream ss(line);
ss >> std::ws;
std::string temp_string;
temp_string.resize(11);
ss.read(&temp_string[0], 11);
if (std::strcmp(temp_string.c_str(), "<link name=") == 0) {
remove_if(line.begin(), line.end(), isspace);
line.erase(0, line.find("\"") + 1);
line.erase(line.begin() + line.find("\""), line.end());
line.erase(0, line.find("}") + 1);
links.push_back(line);
}
}
return links;
}
void NewScene::add_desc_links(QString OutputFolder, int ee_or_robot) // 0 for robot, 1 for ee
{
int error = 0;
boost::filesystem::current_path(OutputFolder.toStdString());
boost::filesystem::path urdf = "urdf";
std::string object_name;
for (auto it = OutputFolder.toStdString().crbegin(); it != OutputFolder.toStdString().crend();
++it)
{
if (*it != '/') {
object_name = std::string(1, *it) + object_name;
} else {
break;
}
}
if (object_name.find("_description") > object_name.length()) {
if (ee_or_robot == 0) {
ui->robot_desc_error->setText(
"<font color='red'>Folder error: Please provide the filepath to"
" the robot description folder</font>");
} else {
ui->ee_desc_error->setText(
"<font color='red'>Folder error: Please provide the filepath to"
" the End Effector description folder</font>");
}
return;
} else {
object_name.erase(object_name.find("_description"), 12);
}
if (!boost::filesystem::exists(urdf) ) {
if (ee_or_robot == 0) {
ui->robot_desc_error->setText("<font color='red'>Folder error: No urdf folder exists</font>");
} else {
ui->ee_desc_error->setText("<font color='red'>Folder error: No urdf folder exists</font>");
}
return;
} else {
boost::filesystem::current_path("urdf");
std::string urdf_filename = object_name + ".urdf.xacro";
if (!boost::filesystem::exists(urdf_filename) ) {
if (ee_or_robot == 0) {
ui->robot_desc_error->setText("<font color='red'>Error! no URDF XACRO file exists</font>");
} else {
ui->ee_desc_error->setText("<font color='red'>Error! no URDF XACRO file exists</font>");
}
return;
} else {
// robot_links = GetLinks(urdf_filename);
for (int i = 0; i < static_cast<int>(gui_environment.object_names.size()); i++) {
if (strcmp(gui_environment.object_names[i].c_str(), object_name.c_str()) == 0) {
error++;
}
}
if (error == 0) {
if (ee_or_robot == 0) {
gui_environment.environment.robot_vector.clear();
Robot temp_robot;
temp_robot.name = object_name;
gui_environment.environment.robot_vector.push_back(temp_robot);
gui_environment.robot_loaded = true;
ErrorCheckOrigin(0);
ui->robot_x->setDisabled(false);
ui->robot_x_label->setDisabled(false);
ui->robot_y->setDisabled(false);
ui->robot_y_label->setDisabled(false);
ui->robot_z->setDisabled(false);
ui->robot_z_label->setDisabled(false);
ui->robot_roll->setDisabled(false);
ui->robot_roll_label->setDisabled(false);
ui->robot_pitch->setDisabled(false);
ui->robot_pitch_label->setDisabled(false);
ui->robot_yaw->setDisabled(false);
ui->robot_yaw_label->setDisabled(false);
gui_environment.robot_names.push_back(object_name);
gui_environment.robot_links.push_back(GetLinks(urdf_filename));
} else {
gui_environment.environment.ee_vector.clear();
EndEffector temp_ee;
temp_ee.name = object_name;
gui_environment.environment.ee_vector.push_back(temp_ee);
gui_environment.ee_loaded = true;
ErrorCheckOrigin(1);
ui->ee_x->setDisabled(false);
ui->ee_x_label->setDisabled(false);
ui->ee_y->setDisabled(false);
ui->ee_y_label->setDisabled(false);
ui->ee_z->setDisabled(false);
ui->ee_z_label->setDisabled(false);
ui->ee_roll->setDisabled(false);
ui->ee_roll_label->setDisabled(false);
ui->ee_pitch->setDisabled(false);
ui->ee_pitch_label->setDisabled(false);
ui->ee_yaw->setDisabled(false);
ui->ee_yaw_label->setDisabled(false);
gui_environment.ee_names.push_back(object_name);
gui_environment.ee_links.push_back(GetLinks(urdf_filename));
}
}
}
}
}
void NewScene::on_load_robot_desc_clicked()
{
QString OutputFolder;
OutputFolder = QFileDialog::getExistingDirectory(
0, ("Select Robot Description Folder"),
QDir::currentPath());
if (!OutputFolder.isEmpty()) {
ui->robot_desc_filepath->setText(OutputFolder);
gui_environment.environment.ee_vector[0].filepath = OutputFolder.toStdString();
add_desc_links(OutputFolder, 0);
}
}
void NewScene::on_load_ee_desc_clicked()
{
QString OutputFolder =
QFileDialog::getExistingDirectory(
0, ("Select End Effector Description Folder"),
QDir::currentPath());
if (!OutputFolder.isEmpty()) {
ui->ee_desc_filepath->setText(OutputFolder);
gui_environment.environment.robot_vector[0].filepath = OutputFolder.toStdString();
add_desc_links(OutputFolder, 1);
}
}
void NewScene::on_add_ext_joint_clicked()
{
int total_objects = gui_environment.object_names.size() + gui_environment.robot_names.size() +
gui_environment.ee_names.size();
if (total_objects > 1) {
AddExternalJoint external_joint_window;
external_joint_window.setWindowTitle("Add New External Joint");
external_joint_window.setModal(true);
std::vector<std::string> combine_names;
combine_names.insert(
combine_names.end(),
gui_environment.robot_names.begin(), gui_environment.robot_names.end() );
combine_names.insert(
combine_names.end(),
gui_environment.ee_names.begin(), gui_environment.ee_names.end() );
combine_names.insert(
combine_names.end(),
gui_environment.object_names.begin(), gui_environment.object_names.end() );
std::vector<std::vector<std::string>> combine_links;
combine_links.insert(
combine_links.end(),
gui_environment.robot_links.begin(), gui_environment.robot_links.end());
combine_links.insert(
combine_links.end(),
gui_environment.ee_links.begin(), gui_environment.ee_links.end());
combine_links.insert(
combine_links.end(),
gui_environment.object_links.begin(), gui_environment.object_links.end());
external_joint_window.available_links = combine_links;
external_joint_window.available_objects = combine_names;
external_joint_window.available_joint_names = gui_environment.ext_joint_names;
external_joint_window.LoadObjects();
external_joint_window.exec();
if (external_joint_window.success) {
ui->parent_link_list->addItem(
QString::fromStdString(external_joint_window.joint.parent_link));
ui->parent_obj_list->addItem(QString::fromStdString(external_joint_window.parent_object_str));
ui->child_obj_list->addItem(QString::fromStdString(external_joint_window.child_object_str));
ui->child_link_list->addItem(QString::fromStdString(external_joint_window.joint.child_link));
ui->ext_joint_list->addItem(QString::fromStdString(external_joint_window.joint.name));
gui_environment.ext_joint_names.push_back(external_joint_window.joint.name);
gui_environment.environment.ext_joint_vector.push_back(external_joint_window.joint);
gui_environment.child_objects.push_back(external_joint_window.child_object_str);
gui_environment.parent_objects.push_back(external_joint_window.parent_object_str);
}
} else {
ui->ext_joint_error->setText(
" <font color='red'>Error: You need at least 2 Objects to create an external joint</font>");
}
}
void NewScene::on_delete_object_clicked()
{
auto list = ui->object_list->selectionModel()->selectedIndexes();
if (list.size() != 0) {
gui_environment.environment.object_vector.erase(
gui_environment.environment.object_vector.begin() + list[0].row());
QListWidgetItem * item = ui->object_list->selectedItems().first();
delete ui->object_list->takeItem(ui->object_list->row(item));
gui_environment.object_names.erase(gui_environment.object_names.begin() + list[0].row());
gui_environment.object_links.erase(gui_environment.object_links.begin() + list[0].row());
gui_environment.object_joints.erase(gui_environment.object_joints.begin() + list[0].row());
}
}
void NewScene::on_ext_joint_list_itemDoubleClicked(QListWidgetItem * item)
{
int pos = ui->ext_joint_list->row(item);
AddExternalJoint external_joint_window;
external_joint_window.setWindowTitle("Add New Environmental Object");
external_joint_window.setModal(true);
external_joint_window.available_links = gui_environment.object_links;
external_joint_window.available_objects = gui_environment.object_names;
external_joint_window.available_joint_names = gui_environment.ext_joint_names;
external_joint_window.LoadObjects();
external_joint_window.child_object_str = gui_environment.child_objects[pos];
external_joint_window.parent_object_str = gui_environment.parent_objects[pos];
external_joint_is_origin.LoadExternalJoint(gui_environment.environment.ext_joint_vector[pos]);
external_joint_window.exec();
ui->parent_link_list->item(pos)->setText(
QString::fromStdString(
external_joint_window.joint.
parent_link));
ui->parent_obj_list->item(pos)->setText(
QString::fromStdString(
external_joint_window.
parent_object_str));
ui->child_obj_list->item(pos)->setText(
QString::fromStdString(
external_joint_window.
child_object_str));
ui->child_link_list->item(pos)->setText(
QString::fromStdString(
external_joint_window.joint.
child_link));
ui->ext_joint_list->item(pos)->setText(QString::fromStdString(external_joint_window.joint.name));
gui_environment.ext_joint_names[pos] = external_joint_window.joint.name;
gui_environment.environment.ext_joint_vector[pos] = external_joint_window.joint;
}
void NewScene::on_del_ext_joint_clicked()
{
auto list = ui->ext_joint_list->selectionModel()->selectedIndexes();
if (list.size() != 0) {
gui_environment.environment.ext_joint_vector.erase(
gui_environment.environment.ext_joint_vector.begin() + list[0].row());
QListWidgetItem * item = ui->ext_joint_list->selectedItems().first();
delete ui->ext_joint_list->takeItem(ui->ext_joint_list->row(item));
QListWidgetItem * parent = ui->parent_obj_list->takeItem(list[0].row());
delete ui->parent_obj_list->takeItem(ui->parent_obj_list->row(parent));
QListWidgetItem * parent_link = ui->parent_link_list->takeItem(list[0].row());
delete ui->parent_link_list->takeItem(ui->parent_link_list->row(parent_link));
QListWidgetItem * child = ui->child_obj_list->takeItem(list[0].row());
delete ui->child_obj_list->takeItem(ui->child_obj_list->row(child));
QListWidgetItem * child_link = ui->child_link_list->takeItem(list[0].row());
delete ui->child_link_list->takeItem(ui->child_link_list->row(child_link));
gui_environment.ext_joint_names.erase(gui_environment.ext_joint_names.begin() + list[0].row());
gui_environment.parent_objects.erase(gui_environment.parent_objects.begin() + list[0].row());
gui_environment.child_objects.erase(gui_environment.child_objects.begin() + list[0].row());
}
}
int NewScene::ErrorCheckOrigin(int robot_or_ee)
{
int num_errors = 0;
if (robot_or_ee == 0) {
if (ui->robot_x->text().isEmpty() || ui->robot_y->text().isEmpty() ||
ui->robot_z->text().isEmpty() || ui->robot_roll->text().isEmpty() ||
ui->robot_pitch->text().isEmpty() || ui->robot_yaw->text().isEmpty())
{
ui->robot_desc_error->setText(
" <font color='red'>Error: XYZ or RPY values for Robot not completely filled.</font>");
num_errors++;
} else {
int i = 0;
auto float_validator = new QDoubleValidator();
QString input_x = ui->robot_x->text();
QString input_y = ui->robot_y->text();
QString input_z = ui->robot_z->text();
QString input_roll = ui->robot_roll->text();
QString input_pitch = ui->robot_pitch->text();
QString input_yaw = ui->robot_yaw->text();
if (float_validator->validate(
input_x,
i) != QValidator::Acceptable ||
float_validator->validate(
input_y,
i) != QValidator::Acceptable ||
float_validator->validate(
input_z,
i) != QValidator::Acceptable ||
float_validator->validate(
input_roll,
i) != QValidator::Acceptable ||
float_validator->validate(
input_pitch,
i) != QValidator::Acceptable ||
float_validator->validate(input_yaw, i) != QValidator::Acceptable)
{
ui->robot_desc_error->setText(
" <font color='red'>Type Error: Robot XYZ and RPY need to be floats</font>");
num_errors++;
} else {
gui_environment.environment.robot_vector[0].origin.is_origin = true;
gui_environment.environment.robot_vector[0].origin.x = input_x.toFloat();
gui_environment.environment.robot_vector[0].origin.y = input_y.toFloat();
gui_environment.environment.robot_vector[0].origin.z = input_z.toFloat();
gui_environment.environment.robot_vector[0].origin.roll = input_roll.toFloat();
gui_environment.environment.robot_vector[0].origin.pitch = input_pitch.toFloat();
gui_environment.environment.robot_vector[0].origin.yaw = input_yaw.toFloat();
}
}
if (num_errors == 0) {
ui->robot_desc_error->setText(" <font color='green'> No Errors </font>");
}
} else {
if (ui->ee_x->text().isEmpty() || ui->ee_y->text().isEmpty() || ui->ee_z->text().isEmpty() ||
ui->ee_roll->text().isEmpty() || ui->ee_pitch->text().isEmpty() ||
ui->ee_yaw->text().isEmpty())
{
ui->ee_desc_error->setText(
" <font color='red'>Error: XYZ or RPY values for"
" End Effector not completely filled.</font>");
num_errors++;
} else {
int i = 0;
auto float_validator = new QDoubleValidator();
QString input_x = ui->ee_x->text();
QString input_y = ui->ee_y->text();
QString input_z = ui->ee_z->text();
QString input_roll = ui->ee_roll->text();
QString input_pitch = ui->ee_pitch->text();
QString input_yaw = ui->ee_yaw->text();
if (float_validator->validate(
input_x,
i) != QValidator::Acceptable ||
float_validator->validate(
input_y,
i) != QValidator::Acceptable ||
float_validator->validate(
input_z,
i) != QValidator::Acceptable ||
float_validator->validate(
input_roll,
i) != QValidator::Acceptable ||
float_validator->validate(
input_pitch,
i) != QValidator::Acceptable ||
float_validator->validate(input_yaw, i) != QValidator::Acceptable)
{
ui->ee_desc_error->setText(
" <font color='red'>Type Error: End Effector XYZ and RPY need to be floats</font>");
num_errors++;
} else {
gui_environment.environment.ee_vector[0].origin.is_origin = true;
gui_environment.environment.ee_vector[0].origin.x = input_x.toFloat();
gui_environment.environment.ee_vector[0].origin.y = input_y.toFloat();
gui_environment.environment.ee_vector[0].origin.z = input_z.toFloat();
gui_environment.environment.ee_vector[0].origin.roll = input_roll.toFloat();
gui_environment.environment.ee_vector[0].origin.pitch = input_pitch.toFloat();
gui_environment.environment.ee_vector[0].origin.yaw = input_yaw.toFloat();
}
}
if (num_errors == 0) {
ui->ee_desc_error->setText(" <font color='green'> No Errors </font>");
}
}
return num_errors;
}
void NewScene::on_robot_x_textChanged(const QString & arg1)
{
ErrorCheckOrigin(0);
}
void NewScene::on_robot_y_textChanged(const QString & arg1)
{
ErrorCheckOrigin(0);
}
void NewScene::on_robot_z_textChanged(const QString & arg1)
{
ErrorCheckOrigin(0);
}
void NewScene::on_robot_roll_textChanged(const QString & arg1)
{
ErrorCheckOrigin(0);
}
void NewScene::on_robot_pitch_textChanged(const QString & arg1)
{
ErrorCheckOrigin(0);
}
void NewScene::on_robot_yaw_textChanged(const QString & arg1)
{
ErrorCheckOrigin(0);
}
void NewScene::on_ee_x_textChanged(const QString & arg1)
{
ErrorCheckOrigin(1);
}
void NewScene::on_ee_y_textChanged(const QString & arg1)
{
ErrorCheckOrigin(1);
}
void NewScene::on_ee_z_textChanged(const QString & arg1)
{
ErrorCheckOrigin(1);
}
void NewScene::on_ee_roll_textChanged(const QString & arg1)
{
ErrorCheckOrigin(1);
}
void NewScene::on_ee_pitch_textChanged(const QString & arg1)
{
ErrorCheckOrigin(1);
}
void NewScene::on_ee_yaw_textChanged(const QString & arg1)
{
ErrorCheckOrigin(1);
}
void NewScene::on_enable_robot_stateChanged(int arg1)
{
if (arg1 == 0) {
ui->robot_desc_label->setDisabled(true);
ui->load_robot_desc->setDisabled(true);
ui->robot_desc_error->setDisabled(true);
ui->robot_desc_error->setText("Robot Disabled");
ui->robot_desc_filepath->setDisabled(true);
ui->robot_desc_filepath->clear();
gui_environment.robot_loaded = false;
gui_environment.environment.robot_vector.clear();
ui->robot_x->setDisabled(true);
ui->robot_x_label->setDisabled(true);
ui->robot_y->setDisabled(true);
ui->robot_y_label->setDisabled(true);
ui->robot_z->setDisabled(true);
ui->robot_z_label->setDisabled(true);
ui->robot_roll->setDisabled(true);
ui->robot_roll_label->setDisabled(true);
ui->robot_pitch->setDisabled(true);
ui->robot_pitch_label->setDisabled(true);
ui->robot_yaw->setDisabled(true);
ui->robot_yaw_label->setDisabled(true);
} else {
ui->robot_desc_label->setDisabled(false);
ui->load_robot_desc->setDisabled(false);
ui->robot_desc_error->setDisabled(false);
ui->robot_desc_error->setText("Please Load the Robot Description Folder");
ui->robot_desc_filepath->setDisabled(false);
}
}
void NewScene::on_enable_ee_stateChanged(int arg1)
{
if (arg1 == 0) {
ui->ee_desc_error->setDisabled(true);
ui->ee_desc_error->setText("End Effector Disabled");
ui->ee_desc_filepath->setDisabled(true);
ui->ee_desc_filepath->clear();
ui->load_ee_desc->setDisabled(true);
ui->ee_desc_label->setDisabled(true);
gui_environment.ee_loaded = false;
gui_environment.environment.ee_vector.clear();
ui->ee_x->setDisabled(true);
ui->ee_x_label->setDisabled(true);
ui->ee_y->setDisabled(true);
ui->ee_y_label->setDisabled(true);
ui->ee_z->setDisabled(true);
ui->ee_z_label->setDisabled(true);
ui->ee_roll->setDisabled(true);
ui->ee_roll_label->setDisabled(true);
ui->ee_pitch->setDisabled(true);
ui->ee_pitch_label->setDisabled(true);
ui->ee_yaw->setDisabled(true);
ui->ee_yaw_label->setDisabled(true);
} else {
ui->ee_desc_error->setDisabled(false);
ui->ee_desc_error->setText("Please Load the End Effector Description Folder");
ui->ee_desc_filepath->setDisabled(false);
ui->load_ee_desc->setDisabled(false);
ui->ee_desc_label->setDisabled(false);
}
}
void NewScene::on_create_environment_clicked()
{
int errors = 0;
ui->errorlist->clear();
if (gui_environment.robot_loaded) {
if (ErrorCheckOrigin(0) != 0) {
ui->errorlist->append("Robot Origin error: Cannot Generate YAML file");
errors++;
}
}
if (gui_environment.ee_loaded) {
if (ErrorCheckOrigin(1) != 0) {
ui->errorlist->append("End Effector Origin error: Cannot Generate YAML file");
errors++;
}
}
if (errors == 0) {
success = true;
this->close();
}
}
void NewScene::LoadEnvironment(GUIEnvironment input_environment)
{
if (input_environment.robot_loaded) {
on_enable_robot_stateChanged(1);
if (input_environment.environment.robot_vector.size() != 0) {
ui->robot_desc_label->setText(
QString::fromStdString(
input_environment.environment.
robot_vector[0].filepath));
ui->robot_x->setText(QString::number(input_environment.environment.robot_vector[0].origin.x));
ui->robot_y->setText(QString::number(input_environment.environment.robot_vector[0].origin.y));
ui->robot_z->setText(QString::number(input_environment.environment.robot_vector[0].origin.z));
ui->robot_roll->setText(
QString::number(
input_environment.environment.robot_vector[0].origin.
roll));
ui->robot_pitch->setText(
QString::number(
input_environment.environment.robot_vector[0].origin.
pitch));
ui->robot_yaw->setText(
QString::number(
input_environment.environment.robot_vector[0].origin.
yaw));
}
} else {
on_enable_robot_stateChanged(0);
}
if (input_environment.ee_loaded) {
on_enable_ee_stateChanged(1);
if (input_environment.environment.ee_vector.size() != 0) {
ui->ee_desc_label->setText(
QString::fromStdString(
input_environment.environment.ee_vector[0].
filepath));
ui->ee_x->setText(QString::number(input_environment.environment.ee_vector[0].origin.x));
ui->ee_y->setText(QString::number(input_environment.environment.ee_vector[0].origin.y));
ui->ee_z->setText(QString::number(input_environment.environment.ee_vector[0].origin.z));
ui->ee_roll->setText(
QString::number(input_environment.environment.ee_vector[0].origin.roll));
ui->ee_pitch->setText(
QString::number(input_environment.environment.ee_vector[0].origin.pitch));
ui->ee_yaw->setText(QString::number(input_environment.environment.ee_vector[0].origin.yaw));
}
} else {
on_enable_ee_stateChanged(0);
}
if (input_environment.environment.object_vector.size() != 0) {
for (int i = 0; i < input_environment.object_names.size(); i++) {
ui->object_list->addItem(QString::fromStdString(input_environment.object_names[i]));
}
}
if (input_environment.environment.ext_joint_vector.size() != 0) {
if (input_environment.parent_objects.size() == input_environment.child_objects.size() &&
input_environment.parent_objects.size() == input_environment.ext_joint_names.size())
{
for (int j = 0; j < input_environment.ext_joint_names.size(); j++) {
ui->ext_joint_list->addItem(QString::fromStdString(input_environment.ext_joint_names[j]));
ui->child_obj_list->addItem(QString::fromStdString(input_environment.child_objects[j]));
ui->child_link_list->addItem(
QString::fromStdString(
input_environment.environment.
ext_joint_vector[j].child_link));
ui->parent_obj_list->addItem(QString::fromStdString(input_environment.parent_objects[j]));
ui->parent_link_list->addItem(
QString::fromStdString(
input_environment.environment.
ext_joint_vector[j].parent_link));
}
}
}
gui_environment = input_environment;
}
| 36.351351 | 100 | 0.691561 | [
"object",
"vector"
] |
6cac270342e2b0862a4e1b777489a2d3c9b683c6 | 1,430 | hpp | C++ | src/ui/widgets/IgnoreUndoRedo.hpp | vimofthevine/UnderBudget | 5711be8e5da3cb7a78da007fe43cf1ce1b796493 | [
"Apache-2.0"
] | 2 | 2016-07-17T02:12:44.000Z | 2016-11-22T14:04:55.000Z | src/ui/widgets/IgnoreUndoRedo.hpp | vimofthevine/UnderBudget | 5711be8e5da3cb7a78da007fe43cf1ce1b796493 | [
"Apache-2.0"
] | null | null | null | src/ui/widgets/IgnoreUndoRedo.hpp | vimofthevine/UnderBudget | 5711be8e5da3cb7a78da007fe43cf1ce1b796493 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2013 Kyle Treubig
*
* 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 IGNOREUNDOREDO_HPP
#define IGNOREUNDOREDO_HPP
// Qt include(s)
#include <QObject>
namespace ub {
/**
* Event filter that ignores undo and redo keyboard shortcut events,
* forwarding them to a given recipient object.
*
* @ingroup ui_widgets
*/
class IgnoreUndoRedo : public QObject
{
public:
/**
* Constructs an ignore-undo/redo event filter.
*
* @param[in] recipient undo/redo event recipient
* @param[in] parent parent object
*/
IgnoreUndoRedo(QObject* recipient, QObject* parent = 0);
/**
* Reimplemented event filter to remove/ignore the undo/redo
* actions on a widget so that the application undo/redo
* actions are executed.
*/
bool eventFilter(QObject* watched, QEvent* event);
private:
/** Object to receive undo/redo events */
QObject* recipient;
};
}
#endif //IGNOREUNDOREDO_HPP
| 25.087719 | 75 | 0.727273 | [
"object"
] |
6cad2c4d03d145fed269d50d5528df81d2c231f2 | 11,589 | cc | C++ | src/rib/rib.cc | simula/flexran | 372a6e3398d839f4f87961217dbf6c5610464fbc | [
"Apache-2.0"
] | 2 | 2020-12-01T02:02:24.000Z | 2021-01-13T03:05:02.000Z | src/rib/rib.cc | simula/flexran | 372a6e3398d839f4f87961217dbf6c5610464fbc | [
"Apache-2.0"
] | null | null | null | src/rib/rib.cc | simula/flexran | 372a6e3398d839f4f87961217dbf6c5610464fbc | [
"Apache-2.0"
] | 2 | 2020-12-03T12:31:26.000Z | 2021-09-29T02:56:43.000Z | /*
* Copyright 2016-2018 FlexRAN Authors, Eurecom and The University of Edinburgh
* 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.
*
* For more information about Mosaic5G: contact@mosaic-5g.io
*/
/*! \file rib.cc
* \brief Ran Information Base: the controller's view on all agents
* \authors Xenofon Foukas, Navid Nikaein, Robert Schmidt
* \company Eurecom
* \email x.foukas@sms.ed.ac.uk, navid.nikaein@eurecom.fr,
* robert.schmidt@eurecom.fr
*/
#include "rib.h"
#include <algorithm>
#include <stdexcept>
#include <iomanip>
#include <sstream>
bool flexran::rib::Rib::add_pending_agent(std::shared_ptr<agent_info> ai)
{
if (ai->bs_id == 0)
return false;
if (agent_is_pending(ai->agent_id))
return false;
if (ai->capabilities.size() < 1)
return false;
for (auto p: pending_agents_) {
/* check that there is no existing pending agent with the same ID and
* overlapping capabilities */
if (p->bs_id == ai->bs_id
&& !p->capabilities.orthogonal(ai->capabilities)) {
return false;
}
}
pending_agents_.emplace(ai);
return true;
}
bool flexran::rib::Rib::agent_is_pending(int agent_id) const
{
auto search = std::find_if(pending_agents_.begin(), pending_agents_.end(),
[agent_id] (std::shared_ptr<agent_info> ai)
{ return agent_id == ai->agent_id; }
);
return search != pending_agents_.end();
}
void flexran::rib::Rib::remove_pending_agent(int agent_id)
{
auto search = std::find_if(pending_agents_.begin(), pending_agents_.end(),
[agent_id] (std::shared_ptr<agent_info> ai)
{ return agent_id == ai->agent_id; }
);
if (search == pending_agents_.end()) return;
pending_agents_.erase(search);
}
void flexran::rib::Rib::remove_pending_agents(uint64_t bs_id)
{
std::set<std::shared_ptr<agent_info>>::const_iterator search;
while ((search = std::find_if(pending_agents_.begin(), pending_agents_.end(),
[bs_id] (std::shared_ptr<agent_info> ai)
{ return bs_id == ai->bs_id; }
)) != pending_agents_.end()) {
pending_agents_.erase(search);
}
}
bool flexran::rib::Rib::new_eNB_config_entry(uint64_t bs_id)
{
/* ignore if such a BS already exists */
if (get_bs(bs_id) != nullptr) return false;
std::set<std::shared_ptr<agent_info>> agents;
/* get all agents matching bs_id */
std::for_each(pending_agents_.begin(), pending_agents_.end(),
[bs_id,&agents] (std::shared_ptr<agent_info> ai)
{ if (bs_id == ai->bs_id) agents.insert(ai); }
);
if (agents.size() == 1 && (*agents.begin())->capabilities.is_complete()) {
/* create new bs with this agent, remove pending agent, create entry for
* known agents */
eNB_configs_.emplace(
(*agents.begin())->bs_id,
std::make_shared<enb_rib_info>((*agents.begin())->bs_id, agents)
);
pending_agents_.erase(*agents.begin());
agent_configs_.emplace((*agents.begin())->agent_id, *agents.begin());
return true;
}
if (agents.size() > 1) {
agent_capabilities caps((*agents.begin())->capabilities);
for (auto it = agents.begin(); it != agents.end(); ++it) {
if (it == agents.begin()) continue;
/* test that capabilities don't overlap, if yes, add */
if (caps.orthogonal((*it)->capabilities)) caps.merge_in((*it)->capabilities);
else throw std::runtime_error("overlapping capabilities detected");
}
if (caps.is_complete()) {
eNB_configs_.emplace(std::make_pair(
(*agents.begin())->bs_id,
std::make_shared<enb_rib_info>((*agents.begin())->bs_id, agents)
)
);
for (auto a : agents) {
pending_agents_.erase(a);
agent_configs_.emplace(a->agent_id, a);
}
return true;
}
}
return false;
}
bool flexran::rib::Rib::has_eNB_config_entry(uint64_t bs_id) const
{
return get_bs(bs_id) != nullptr;
}
bool flexran::rib::Rib::remove_eNB_config_entry(int agent_id)
{
const auto it = agent_configs_.find(agent_id);
if (it == agent_configs_.end()) return false;
const std::shared_ptr<agent_info> disconnected = it->second;
/* get all agents for this BS, remove corresponding enb_rib_info and
* agent_configs_ and put agents that are still connected into pending */
std::set<std::shared_ptr<agent_info>> all = eNB_configs_.find(disconnected->bs_id)->second->get_agents();
eNB_configs_.erase(disconnected->bs_id);
for (auto b: all)
agent_configs_.erase(b->agent_id);
all.erase(disconnected);
for (auto b: all)
pending_agents_.insert(b);
return true;
}
std::set<uint64_t> flexran::rib::Rib::get_available_base_stations() const
{
std::set<uint64_t> agents;
for (auto it : eNB_configs_) {
agents.insert(it.first);
}
return agents;
}
std::shared_ptr<flexran::rib::enb_rib_info>
flexran::rib::Rib::get_bs(uint64_t bs_id) const
{
auto it = eNB_configs_.find(bs_id);
if (it == eNB_configs_.end()) return nullptr;
return it->second;
}
std::shared_ptr<flexran::rib::enb_rib_info>
flexran::rib::Rib::get_bs_from_agent(int agent_id) const
{
uint64_t bs_id = get_bs_id(agent_id);
if (bs_id == 0) return nullptr;
return get_bs(bs_id);
}
std::shared_ptr<flexran::rib::agent_info>
flexran::rib::Rib::get_agent(int agent_id) const
{
auto it = agent_configs_.find(agent_id);
if (it == agent_configs_.end()) return nullptr;
return it->second;
}
void flexran::rib::Rib::dump_mac_stats() const {
for (auto enb_config : eNB_configs_) {
enb_config.second->dump_mac_stats();
}
}
std::string flexran::rib::Rib::dump_all_mac_stats_to_string() const {
std::string str;
for (auto enb_config : eNB_configs_) {
str += enb_config.second->dump_mac_stats_to_string();
str += "\n";
}
return str;
}
std::string flexran::rib::Rib::dump_all_mac_stats_to_json_string() const
{
std::vector<std::string> mac_stats;
mac_stats.reserve(eNB_configs_.size());
std::transform(eNB_configs_.begin(), eNB_configs_.end(), std::back_inserter(mac_stats),
[] (const std::pair<int, std::shared_ptr<enb_rib_info>>& enb_config)
{ return enb_config.second->dump_mac_stats_to_json_string(); }
);
return format_mac_stats_to_json(mac_stats);
}
bool flexran::rib::Rib::dump_mac_stats_by_bs_id_to_json_string(uint64_t bs_id,
std::string& out) const
{
auto it = eNB_configs_.find(bs_id);
if (it == eNB_configs_.end()) return false;
out = format_mac_stats_to_json(std::vector<std::string>{it->second->dump_mac_stats_to_json_string()});
return true;
}
std::string flexran::rib::Rib::format_mac_stats_to_json(
const std::vector<std::string>& mac_stats_json)
{
std::string str;
str += "[";
for (auto it = mac_stats_json.begin(); it != mac_stats_json.end(); it++) {
if (it != mac_stats_json.begin()) str += ",";
str += "{";
str += *it;
str += "}";
}
str += "]";
return str;
}
void flexran::rib::Rib::dump_enb_configurations() const {
for (auto eNB_config : eNB_configs_) {
eNB_config.second->dump_configs();
}
}
std::string flexran::rib::Rib::dump_all_enb_configurations_to_string() const {
std::string str;
for (auto eNB_config : eNB_configs_) {
str += eNB_config.second->dump_configs_to_string();
str += "\n";
}
return str;
}
std::string flexran::rib::Rib::dump_all_enb_configurations_to_json_string() const
{
std::vector<std::string> enb_configurations;
enb_configurations.reserve(eNB_configs_.size());
std::transform(eNB_configs_.begin(), eNB_configs_.end(), std::back_inserter(enb_configurations),
[] (const std::pair<int, std::shared_ptr<enb_rib_info>>& enb_config)
{ return enb_config.second->dump_configs_to_json_string(); }
);
return format_enb_configurations_to_json(enb_configurations);
}
bool flexran::rib::Rib::dump_enb_configurations_by_bs_id_to_json_string(
uint64_t bs_id, std::string& out) const
{
auto it = eNB_configs_.find(bs_id);
if (it == eNB_configs_.end()) return false;
out = format_enb_configurations_to_json(std::vector<std::string>{it->second->dump_configs_to_json_string()});
return true;
}
std::string flexran::rib::Rib::format_enb_configurations_to_json(
const std::vector<std::string>& enb_configurations_json)
{
std::string str;
str += "[";
for (auto it = enb_configurations_json.begin(); it != enb_configurations_json.end(); it++) {
if (it != enb_configurations_json.begin()) str += ",";
str += "{";
str += *it;
str += "}";
}
str += "]";
return str;
}
std::string flexran::rib::Rib::format_statistics_to_json(
std::chrono::time_point<std::chrono::system_clock> t,
const std::string& configurations,
const std::string& mac_stats)
{
std::string str = "{";
str += "\"date_time\":\"" + format_date_time(t) + "\",";
if (!configurations.empty())
str += "\"eNB_config\":" + configurations;
if (!configurations.empty() && !mac_stats.empty())
str += ",";
if (!mac_stats.empty())
str += "\"mac_stats\":" + mac_stats;
str += "}";
return str;
}
std::string flexran::rib::Rib::format_date_time(std::chrono::time_point<std::chrono::system_clock> t)
{
std::ostringstream oss;
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(t.time_since_epoch()) % 1000;
std::time_t time = std::chrono::system_clock::to_time_t(t);
oss << std::put_time(std::localtime(&time), "%Y-%m-%dT%H:%M:%S.")
<< std::setfill('0') << std::setw(3) << ms.count();
return oss.str();
}
bool flexran::rib::Rib::dump_ue_by_rnti_by_bs_id_to_json_string(
rnti_t rnti, std::string& out, uint64_t bs_id) const
{
auto it = eNB_configs_.find(bs_id);
if (it == eNB_configs_.end()) return false;
return it->second->dump_ue_spec_stats_by_rnti_to_json_string(rnti, out);
}
uint64_t flexran::rib::Rib::get_bs_id(int agent_id) const
{
auto it = agent_configs_.find(agent_id);
if (it == agent_configs_.end()) return 0;
return it->second->bs_id;
}
uint64_t flexran::rib::Rib::parse_enb_agent_id(const std::string& enb_agent_id_s) const
{
/* -> return last eNB_config entry */
if (enb_agent_id_s == "-1") {
return eNB_configs_.empty() ? 0 : std::prev(eNB_configs_.end())->first;
}
uint64_t enb_id;
try {
if (enb_agent_id_s.substr(0, 2) == "0x")
enb_id = std::stoll(enb_agent_id_s, 0, 16);
else
enb_id = std::stoll(enb_agent_id_s);
} catch (const std::invalid_argument& e) {
return 0;
}
/* shorter than length limit -> assume it is agent ID */
if (enb_agent_id_s.length() < AGENT_ID_LENGTH_LIMIT)
return get_bs_id(enb_id);
if (!get_bs(enb_id)) return 0;
return enb_id;
}
uint64_t flexran::rib::Rib::parse_bs_id(const std::string& bs_id_s) const
{
/* -> return last eNB_config entry */
if (bs_id_s == "-1") {
return eNB_configs_.empty() ? 0 : std::prev(eNB_configs_.end())->first;
}
uint64_t enb_id;
try {
if (bs_id_s.substr(0, 2) == "0x")
enb_id = std::stoll(bs_id_s, 0, 16);
else
enb_id = std::stoll(bs_id_s);
} catch (const std::invalid_argument& e) {
return 0;
}
if (!get_bs(enb_id)) return 0;
return enb_id;
}
| 30.101299 | 111 | 0.673742 | [
"vector",
"transform"
] |
6cb563704dd7ae626c6049b8ace9b335ddf4f80e | 19,287 | cpp | C++ | Arcade Game Engine/engine/core.cpp | lidin/Arcade-Game-Engine | 135d7005cb024562800905aafee3273cb3586ab9 | [
"MIT"
] | 1 | 2017-02-18T00:12:06.000Z | 2017-02-18T00:12:06.000Z | Arcade Game Engine/engine/core.cpp | lidin/Arcade-Game-Engine | 135d7005cb024562800905aafee3273cb3586ab9 | [
"MIT"
] | 6 | 2017-04-05T00:28:04.000Z | 2017-05-28T22:24:03.000Z | Arcade Game Engine/engine/core.cpp | lidin/Arcade-Game-Engine | 135d7005cb024562800905aafee3273cb3586ab9 | [
"MIT"
] | 1 | 2018-02-22T05:41:34.000Z | 2018-02-22T05:41:34.000Z | //
// core.cpp
// Game Engine
//
#include "core.hpp"
#include <stack>
#include <queue>
#ifdef __APPLE__
# include <CoreFoundation/CoreFoundation.h>
#endif
// MARK: Helper functions
void _buildEntityPriorityQueue(Entity & root, vector<Entity*> & result)
{
int root_order = root.order();
long low = 0;
long high = (long)(result.size()-1);
while (low <= high)
{
long middle = (high+low+1)/2;
Entity * middle_entity = result.at(middle);
int order = middle_entity->order();
if (root_order < order)
{
high = middle - 1;
}
else if (root_order >= order)
{
low = middle + 1;
}
}
result.insert(result.begin()+low, &root);
for (auto child : root.children())
{
if (child) _buildEntityPriorityQueue(*child, result);
}
}
//
// MARK: - Sprite
//
// MARK: Member functions
Sprite::Sprite(SDL_Renderer * renderer, SDL_Texture * texture)
: _renderer(renderer)
, _texture(texture)
{}
Sprite * Sprite::createSprite(SDL_Renderer * renderer, const char * filename)
{
SDL_Surface * loaded_surface = IMG_Load(filename);
if (!loaded_surface)
{
SDL_Log("IMG_Load: %s\n", IMG_GetError());
}
else
{
auto texture = SDL_CreateTextureFromSurface(renderer, loaded_surface);
SDL_FreeSurface(loaded_surface);
return new Sprite(renderer, texture);
}
return nullptr;
}
void Sprite::destroy()
{
SDL_DestroyTexture(_texture);
}
void Sprite::draw(int x, int y, int w, int h, int scale)
{
SDL_Rect rect {x*scale, y*scale, w*scale, h*scale};
SDL_RenderCopy(_renderer, _texture, nullptr, &rect);
}
//
// MARK: - SpriteCollection
//
SpriteCollection & SpriteCollection::main()
{
static SpriteCollection instance;
return instance;
}
void SpriteCollection::init(SDL_Renderer * renderer)
{
_renderer = renderer;
}
Sprite * SpriteCollection::create(string id, const char * filename)
{
return _sprites[id] = Sprite::createSprite(_renderer, filename);
}
void SpriteCollection::destroy(string id)
{
auto it = _sprites.find(id);
if (it != _sprites.end())
{
_sprites.at(id)->destroy();
_sprites.erase(it);
}
}
void SpriteCollection::destroyAll()
{
for (auto pair : _sprites)
{
pair.second->destroy();
}
_sprites.clear();
}
Sprite * SpriteCollection::retrieve(string id)
{
if (_sprites.find(id) != _sprites.end())
{
return _sprites.at(id);
}
return nullptr;
}
void SpriteCollection::draw(string id, int x, int y, int w, int h, int scale)
{
Sprite * sprite;
if ((sprite = retrieve(id))) sprite->draw(x, y, w, h, scale);
}
//
// MARK: - NotificationCenter
//
void NotificationCenter::notify(Event event, GameObject & sender)
{
for (auto pair : _instance()._blocks[event])
{
if (pair.second == nullptr || pair.second == &sender) pair.first(event);
}
}
ObserverID NotificationCenter::observe(function<void(Event)> block,
Event event,
GameObject * sender)
{
auto size = _instance()._blocks[event].size();
_instance()._blocks[event].push_back({block, sender});
return hash<string>{}(event.string_value() + to_string(size));
}
// TODO: fix so that elements are not erased, but the spot it occupied is made
// available for the next observer. This function is currently not in use.
void NotificationCenter::unobserve(ObserverID id,
Event event,
GameObject * sender)
{
auto blocks_for_event = _instance()._blocks[event];
for (auto i = 0; i < blocks_for_event.size(); i++)
{
auto sender_for_block = blocks_for_event[i].second;
if (sender_for_block == nullptr || sender == nullptr ||
sender_for_block == sender)
{
size_t h = hash<string>{}(event.string_value() + to_string(i));
if (h == id)
{
_instance()._blocks[event].erase(_instance()._blocks[event].begin()+i);
return;
}
}
}
}
// MARK: Private member functions
NotificationCenter & NotificationCenter::_instance()
{
static NotificationCenter instance;
return instance;
}
//
// MARK: - Core
//
// MARK: Member functions
Core::Core()
: sample_rate(44100)
, max_volume(0.05)
, scale(1)
{}
bool Core::init(Entity * root,
const char * title,
Dimension2 dimensions,
RGBAColor background_color)
{
#if defined(__APPLE__) && !defined(GAME_ENGINE_DEBUG)
// change directory
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(mainBundle);
char path[PATH_MAX];
if (!CFURLGetFileSystemRepresentation(resourcesURL,
TRUE,
(UInt8*)path,
PATH_MAX))
{
printf("Core: could not set working directory.\n");
return false;
}
CFRelease(resourcesURL);
chdir(path);
#endif
// initialize SDL
if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
{
SDL_Log("SDL_Init: %s\n", SDL_GetError());
return false;
}
// initialize SDL_image
if (IMG_Init(IMG_INIT_PNG) < 0)
{
SDL_Log("IMG_Init: %s\n", IMG_GetError());
return false;
}
// create window
const int w_pos_x = (int)(dimensions.x < 0
? SDL_WINDOWPOS_UNDEFINED
: dimensions.x);
const int w_pos_y = (int)(dimensions.y < 0
? SDL_WINDOWPOS_UNDEFINED
: dimensions.y);
view_dimensions({dimensions.x, dimensions.y});
window(SDL_CreateWindow(title,
w_pos_x,
w_pos_y,
(int)(dimensions.x*scale()),
(int)(dimensions.y*scale()),
SDL_WINDOW_SHOWN));
if (window() == nullptr)
{
SDL_Log("SDL_CreateWindow: %s\n", SDL_GetError());
return false;
}
// create renderer for window
renderer(SDL_CreateRenderer(window(), -1, SDL_RENDERER_ACCELERATED));
if (renderer() == nullptr)
{
SDL_Log("SDL_CreateRenderer: %s\n", SDL_GetError());
return false;
}
// clear screen
SDL_SetRenderDrawColor(renderer(),
background_color.r,
background_color.g,
background_color.b,
background_color.a);
SDL_RenderClear(renderer());
// initialize member properties
_key_status.up = _key_status.down = false;
_key_status.left = _key_status.right = false;
_reset = false;
_pause = false;
SpriteCollection::main().init(renderer());
// initialize entities
if (root)
{
this->root(root);
root->init(this);
root->reset();
}
else
{
SDL_Log("Error: root was null, no top entity specified\n");
return false;
}
// initialize audio
auto fill_stream = [](void * userdata, uint8_t * stream, int length)
{
Core * core = (Core*)userdata;
int16_t * stream_16b = (int16_t*)stream;
double max_volume = core->max_volume();
for (int i = 0; i < length/2; i++) stream_16b[i] = 0;
function<void(Entity*)> callbacks;
callbacks = [max_volume, stream_16b, length, &callbacks](Entity * entity)
{
AudioComponent * audio = entity->audio();
if (audio) audio->audioStreamCallback(max_volume, stream_16b, length/2);
for (auto child : entity->children())
{
callbacks(child);
}
};
callbacks(core->root());
};
SDL_AudioSpec desired_audio_spec;
desired_audio_spec.freq = sample_rate();
desired_audio_spec.format = AUDIO_S16SYS;
desired_audio_spec.channels = 1;
desired_audio_spec.samples = 2048;
desired_audio_spec.callback = fill_stream;
desired_audio_spec.userdata = this;
SDL_OpenAudio(&desired_audio_spec, nullptr);
SDL_PauseAudio(0);
return true;
}
void Core::destroy()
{
SpriteCollection::main().destroyAll();
if (root()) root()->destroy();
SDL_CloseAudio();
SDL_DestroyRenderer(renderer());
SDL_DestroyWindow(window());
SDL_Quit();
}
void Core::reset(double after_duration)
{
createAccumulativeTimer(after_duration, [this] { _reset = true; });
}
void Core::pause()
{
_pause = true;
effectiveElapsedTime();
}
void Core::resume()
{
_pause = false;
effectiveElapsedTime();
}
void Core::createEffectiveTimer(double duration, function<void()> block)
{
_timers.push_back
({
{effectiveElapsedTime() + duration, block},
_EFFECTIVE
});
}
void Core::createAccumulativeTimer(double duration, function<void()> block)
{
_timers.push_back
({
{elapsedTime() + duration, block},
_ACCUMULATIVE
});
}
bool Core::update()
{
static double prev_time;
// record time
double start_time = elapsedTime();
delta_time(start_time - prev_time);
prev_time = start_time;
#ifdef GAME_ENGINE_DEBUG
effectiveElapsedTime();
#endif
// check user input
SDL_Event event;
bool should_continue = true;
while (SDL_PollEvent(&event))
{
if (event.type == SDL_QUIT)
{
should_continue = false;
break;
}
if (event.type == SDL_KEYDOWN)
{
switch (event.key.keysym.sym)
{
case SDLK_UP:
_key_status.up = true;
break;
case SDLK_DOWN:
_key_status.down = true;
break;
case SDLK_LEFT:
_key_status.left = true;
break;
case SDLK_RIGHT:
_key_status.right = true;
break;
}
}
if (event.type == SDL_KEYUP)
{
switch (event.key.keysym.sym)
{
case SDLK_UP:
_key_status.up = false;
break;
case SDLK_DOWN:
_key_status.down = false;
break;
case SDLK_LEFT:
_key_status.left = false;
break;
case SDLK_RIGHT:
_key_status.right = false;
break;
#ifdef GAME_ENGINE_DEBUG
case SDLK_p:
if (!_pause) pause();
else resume();
break;
#endif
case SDLK_ESCAPE:
case SDLK_q:
should_continue = false;
break;
}
}
}
// update entities
auto entities = vector<Entity*>();
_buildEntityPriorityQueue(*root(), entities);
uint8_t mask = !_pause ? 0b11111 : 0b00001;
for (uint8_t i = 0b10000; i > 0; i = i >>= 1)
{
for (auto entity : entities)
{
entity->update(mask & i);
}
}
#ifdef GAME_ENGINE_DEBUG
// draw bounding boxes
RGBAColor prev_color;
SDL_GetRenderDrawColor(renderer(),
&prev_color.r,
&prev_color.g,
&prev_color.b,
&prev_color.a);
SDL_SetRenderDrawColor(renderer(), 0xFF, 0xFF, 0xFF, 0xFF);
stack<Entity*> entity_stack;
entity_stack.push(root());
while (entity_stack.size() > 0)
{
Entity * current_entity = entity_stack.top();
entity_stack.pop();
PhysicsComponent * current_physics_component;
if ((current_physics_component = current_entity->physics()))
{
SDL_Rect rect;
Rectangle bounds = current_physics_component->collision_bounds();
Vector2 world_position;
current_entity->calculateWorldPosition(world_position);
rect.x = (world_position.x + bounds.pos.x) * scale();
rect.y = (world_position.y + bounds.pos.y) * scale();
rect.w = bounds.dim.x * scale();
rect.h = bounds.dim.y * scale();
SDL_RenderDrawRect(renderer(), &rect);
}
for (auto child : current_entity->children())
{
entity_stack.push(child);
}
}
SDL_SetRenderDrawColor(renderer(),
prev_color.r,
prev_color.g,
prev_color.b,
prev_color.a);
#endif
// clear screen
SDL_RenderPresent(renderer());
SDL_RenderClear(renderer());
// possibly do a reset
if (_reset)
{
_timers.clear();
root()->reset();
_reset = false;
resume();
}
// go through timers
int i = 0;
while (i < _timers.size())
{
auto pair = _timers[i];
const double current_time = pair.second == _EFFECTIVE
? effectiveElapsedTime()
: elapsedTime();
if (current_time >= pair.first.end_time)
{
pair.first.block();
_timers.erase(_timers.begin() + i);
}
else i++;
}
return should_continue;
}
void Core::keyStatus(Core::KeyStatus & key_status)
{
key_status.up = _key_status.up;
key_status.down = _key_status.down;
key_status.left = _key_status.left;
key_status.right = _key_status.right;
}
double Core::elapsedTime()
{
return SDL_GetTicks() / 1000.f;
}
double Core::effectiveElapsedTime()
{
static double last_pause_time;
static double total_pause_duration;
static bool pause_toggle;
const double elapsed = elapsedTime();
if (_pause && !pause_toggle)
{
pause_toggle = true;
last_pause_time = elapsed;
#ifdef GAME_ENGINE_DEBUG
printf("/**************** PAUSED ****************/\n");
#endif
}
else if (!_pause && pause_toggle)
{
pause_toggle = false;
total_pause_duration += elapsed - last_pause_time;
#ifdef GAME_ENGINE_DEBUG
printf("/**************** RESUMED ***************/\n");
#endif
}
#ifdef GAME_ENGINE_DEBUG
static double last_print_time;
if (elapsed - last_print_time >= 0.1)
{
printf("Elapsed: %f\t\t", elapsed);
printf("Effective elapsed: %f\t\t",
!_pause
? elapsed - total_pause_duration
: last_pause_time - total_pause_duration);
printf("Pause time: %f\t\t", last_pause_time);
printf("Pause duration: %f\n",
!_pause
? total_pause_duration
: total_pause_duration + elapsed - last_pause_time);
last_print_time = elapsed;
}
#endif
return (!_pause ? elapsed : last_pause_time) - total_pause_duration;
}
//
// MARK: - Entity
//
// MARK: Property functions
string Entity::id()
{
return _id;
}
// MARK: Member functions
Entity::Entity(string id, int order)
: _id(id)
, core(nullptr)
, parent(nullptr)
, input(nullptr)
, animation(nullptr)
, physics(nullptr)
, audio(nullptr)
, graphics(nullptr)
, order(order)
, local_position({0, 0})
{}
void Entity::addInput(InputComponent * input)
{
this->input(input);
}
void Entity::addAnimation(AnimationComponent * animation)
{
this->animation(animation);
}
void Entity::addPhysics(PhysicsComponent * physics)
{
this->physics(physics);
}
void Entity::addAudio(AudioComponent * audio)
{
this->audio(audio);
}
void Entity::addGraphics(GraphicsComponent * graphics)
{
this->graphics(graphics);
}
void Entity::init(Core * core)
{
this->core(core);
this->enabled(true);
if (input()) input()->init(this);
if (animation()) animation()->init(this);
if (physics()) physics()->init(this);
if (audio()) audio()->init(this);
if (graphics()) graphics()->init(this);
for (auto child : children()) child->init(core);
}
void Entity::reset()
{
velocity({0, 0});
if (input()) input()->reset();
if (animation()) animation()->reset();
if (physics()) physics()->reset();
if (audio()) audio()->reset();
if (graphics()) graphics()->reset();
for (auto child : children()) child->reset();
}
void Entity::destroy()
{
for (auto child : children())
{
child->destroy();
}
children().clear();
if (input()) delete input();
if (animation()) delete animation();
if (physics()) delete physics();
if (audio()) delete audio();
if (graphics()) delete graphics();
}
Dimension2 Entity::dimensions()
{
return graphics() ? graphics()->bounds().dim : Dimension2 {};
}
void Entity::addChild(Entity * child, int order)
{
if (order >= 0)
{
if (order > children().size()) order = (int)children().size();
children().insert(children().begin()+order, child);
}
else
{
children().push_back(child);
}
child->parent(this);
}
Entity * Entity::findChild(string id)
{
for (auto child : children())
{
if (child->id().compare(id) == 0) return child;
auto possible_find = child->findChild(id);
if (possible_find) return possible_find;
}
return nullptr;
}
void Entity::removeChild(string id)
{
for (int i = 0; i < children().size(); i++)
{
auto child = children()[i];
if (child->id() == id)
{
child->parent(nullptr);
children().erase(children().begin()+i);
}
}
}
void Entity::calculateWorldPosition(Vector2 & result)
{
Vector2 world_position = local_position();
Entity * current_entity = this;
while ((current_entity = current_entity->parent()))
{
world_position += current_entity->local_position();
}
result.x = world_position.x;
result.y = world_position.y;
}
void Entity::moveTo(double x, double y)
{
local_position().x = x;
local_position().y = y;
}
void Entity::moveHorizontallyTo(double x)
{
local_position().x = x;
}
void Entity::moveVerticallyTo(double y)
{
local_position().y = y;
}
void Entity::moveBy(double dx, double dy)
{
local_position().x += dx;
local_position().y += dy;
}
void Entity::changeVelocityTo(double vx, double vy)
{
velocity().x = vx;
velocity().y = vy;
}
void Entity::changeHorizontalVelocityTo(double vx)
{
velocity().x = vx;
}
void Entity::changeVerticalVelocityTo(double vy)
{
velocity().y = vy;
}
void Entity::changeVelocityBy(double dvx, double dvy)
{
velocity().x += dvx;
velocity().y += dvy;
}
void Entity::update(uint8_t component_mask)
{
if (enabled())
{
if (component_mask & 0b10000 && input()) input()->update(*core());
if (component_mask & 0b01000 && animation()) animation()->update(*core());
if (component_mask & 0b00100 && physics()) physics()->update(*core());
if (component_mask & 0b00010 && audio()) audio()->update(*core());
if (component_mask & 0b00001 && graphics()) graphics()->update(*core());
}
}
//
// MARK: - Component
//
// MARK: Property functions
string Component::id()
{
string id = trait() + "_component";
if (entity()) id = entity()->id() + "_" + id;
return id;
}
// MARK: Member functions
void Component::init(Entity * entity)
{
this->entity(entity);
}
//
// MARK: - InputComponent
//
// MARK: Property functions
string InputComponent::trait() { return "input"; }
//
// MARK: - GraphicsComponent
//
// MARK: Property functions
string GraphicsComponent::trait() { return "graphics"; }
// MARK: Member functions
void GraphicsComponent::offsetTo(int x, int y)
{
bounds().pos.x = x;
bounds().pos.y = y;
}
void GraphicsComponent::offsetBy(int dx, int dy)
{
bounds().pos.x += dx;
bounds().pos.y += dy;
}
void GraphicsComponent::resizeTo(int w, int h)
{
bounds().dim.x = w;
bounds().dim.y = h;
}
void GraphicsComponent::resizeBy(int dw, int dh)
{
bounds().dim.x += dw;
bounds().dim.y += dh;
}
void GraphicsComponent::update(Core & world)
{
if (current_sprite())
{
Vector2 entity_pos;
entity()->calculateWorldPosition(entity_pos);
current_sprite()->draw((int)(entity_pos.x + bounds().pos.x),
(int)(entity_pos.y + bounds().pos.y),
(int)bounds().dim.x,
(int)bounds().dim.y,
world.scale());
}
}
| 21.917045 | 79 | 0.610152 | [
"vector"
] |
6cc90dc850e84f8bd6a42938f1ffa48cc8ebd5f5 | 3,641 | cpp | C++ | UVa 12386 - Smallest Polygon/sample/12386 - Smallest Polygon.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | 1 | 2020-11-24T03:17:21.000Z | 2020-11-24T03:17:21.000Z | UVa 12386 - Smallest Polygon/sample/12386 - Smallest Polygon.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | null | null | null | UVa 12386 - Smallest Polygon/sample/12386 - Smallest Polygon.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | 1 | 2021-04-11T16:22:31.000Z | 2021-04-11T16:22:31.000Z | #include <stdio.h>
#include <math.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <string.h>
#include <assert.h>
using namespace std;
#define eps 1e-9
struct Pt {
double x, y;
Pt(double a = 0, double b = 0):
x(a), y(b) {}
bool operator<(const Pt &a) const {
if(fabs(x-a.x) > eps) return x < a.x;
return y < a.y;
}
bool operator==(const Pt &a) const {
return fabs(x-a.x) < eps && fabs(y-a.y) < eps;
}
Pt operator+(const Pt &a) const {
return Pt(x + a.x, y + a.y);
}
Pt operator-(const Pt &a) const {
return Pt(x - a.x, y - a.y);
}
Pt operator/(const double val) const {
return Pt(x / val, y / val);
}
Pt operator*(const double val) const {
return Pt(x * val, y * val);
}
};
typedef Pt Vector;
double dist(Pt a, Pt b) {
return hypot(a.x - b.x, a.y - b.y);
}
double dot(Pt a, Pt b) {
return a.x * b.x + a.y * b.y;
}
double cross2(Pt a, Pt b) {
return a.x * b.y - a.y * b.x;
}
double cross(Pt o, Pt a, Pt b) {
return (a.x-o.x)*(b.y-o.y)-(a.y-o.y)*(b.x-o.x);
}
int between(Pt a, Pt b, Pt c) {
return dot(c - a, b - a) > 0 && dot(c - b, a - b) > 0;
}
int onSeg(Pt a, Pt b, Pt c) {
return between(a, b, c) && fabs(cross(a, b, c)) < eps;
}
struct Seg {
Pt s, e;
};
int intersection(Pt as, Pt at, Pt bs, Pt bt) {
if(cross(as, at, bs) * cross(as, at, bt) < -eps &&
cross(at, as, bs) * cross(at, as, bt) < -eps &&
cross(bs, bt, as) * cross(bs, bt, at) < -eps &&
cross(bt, bs, as) * cross(bt, bs, at) < -eps)
return 1;
return 0;
}
double calcArea(Pt p[], int n) {
if(n < 3) return 0.0;
double ret = 0;
int i;
p[n] = p[0];
for(i = 0; i < n; i++)
ret += p[i].x * p[i+1].y - p[i].y * p[i+1].x;
return fabs(ret)/2;
}
double calcPer(Pt p[], int n) {
double ret = 0;
int i;
p[n] = p[0];
for(i = 0; i < n; i++)
ret += dist(p[i], p[i+1]);
return ret;
}
#define INF 1e+8
Pt p[16], path[16];
double mn_area, mn_area_per, mn_per;
int used[16], n;
int check(Pt a, Pt b, int l, int r) {
for (int i = l; i < r; i++) {
if (intersection(a, b, path[i], path[i+1]))
return 0;
if (onSeg(path[i], path[i+1], a))
return 0;
if (onSeg(path[i], path[i+1], b))
return 0;
if (onSeg(a, b, path[i]) || onSeg(a, b, path[i+1]))
return 0;
}
return 1;
}
void dfs(int idx) {
if (idx == n) {
if (check(path[n-1], path[0], 0, n-1)) {
double t = calcArea(path, n), c = calcPer(path, n);
if (mn_area > t || (fabs(mn_area - t) < eps && mn_area_per > c)) {
mn_area = t;
mn_area_per = c;
}
mn_per = min(mn_per, calcPer(path, n));
}
return ;
}
for (int i = 0; i < n; i++) {
if (used[i] == 0) {
used[i] = 1;
path[idx] = p[i];
if (check(path[idx], path[idx-1], 0, idx-1))
dfs(idx+1);
used[i] = 0;
}
}
}
int main() {
int testcase;
scanf("%d", &testcase);
while(testcase--) {
scanf("%d", &n);
for(int i = 0; i < n; i++)
scanf("%lf %lf", &p[i].x, &p[i].y);
mn_area = mn_per = INF;
memset(used, 0, sizeof(used));
path[0] = p[0], used[0] = 1;
dfs(1);
printf("%.4lf\n", fabs(mn_area_per - mn_per));
}
return 0;
}
/*
20
7
84 43
43 64
40 69
22 75
27 94
68 71
64 4
> 65.6943
2
3
1 1
1 2
2 1
4
0 0
1 1
0 2
2 1
*/
| 22.337423 | 78 | 0.469651 | [
"vector"
] |
6cd42195e84afe6a24425a0acc0ee5fc88d89e36 | 880 | cpp | C++ | Ouroboros/Source/oMath/plane_v_plane_v_plane.cpp | igHunterKiller/ouroboros | 5e2cde7e6365341da297da10d8927b091ecf5559 | [
"MIT"
] | null | null | null | Ouroboros/Source/oMath/plane_v_plane_v_plane.cpp | igHunterKiller/ouroboros | 5e2cde7e6365341da297da10d8927b091ecf5559 | [
"MIT"
] | null | null | null | Ouroboros/Source/oMath/plane_v_plane_v_plane.cpp | igHunterKiller/ouroboros | 5e2cde7e6365341da297da10d8927b091ecf5559 | [
"MIT"
] | null | null | null | // Copyright (c) 2016 Antony Arciuolo. See License.txt regarding use.
#include <oMath/plane_v_plane_v_plane.h>
#include <oMath/equal.h>
namespace ouro {
bool plane_v_plane_v_plane(const float4& a, const float4& b, const float4& c, float3* out_intersection)
{
// Goldman, Ronald. Intersection of Three Planes. In A. Glassner,
// ed., Graphics Gems pg 305. Academic Press, Boston, 1991.
// http://paulbourke.net/geometry/3planes/
// check that there is a valid cross product
float3 bXc = cross(b.xyz(), c.xyz());
if (equal(dot(bXc, bXc), 0.0f))
return false;
float3 cXa = cross(c.xyz(), a.xyz());
if (equal(dot(cXa, cXa), 0.0f))
return false;
float3 aXb = cross(a.xyz(), b.xyz());
if (equal(dot(aXb, aXb), 0.0f))
return false;
*out_intersection = (-a.w * bXc - b.w * cXa - c.w * aXb) / determinant(float3x3(a.xyz(), b.xyz(), c.xyz()));
return true;
}
}
| 27.5 | 109 | 0.665909 | [
"geometry"
] |
6cda34f171458934a59e03009b104dd8f3bb3c41 | 4,096 | cc | C++ | algo/array/four_sum.cc | liuheng/recipes | 6f3759ab4e4fa64d9fd83a60ee6b6846510d910b | [
"MIT"
] | null | null | null | algo/array/four_sum.cc | liuheng/recipes | 6f3759ab4e4fa64d9fd83a60ee6b6846510d910b | [
"MIT"
] | null | null | null | algo/array/four_sum.cc | liuheng/recipes | 6f3759ab4e4fa64d9fd83a60ee6b6846510d910b | [
"MIT"
] | null | null | null | #include <cstdio>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
vector<vector<int> > fourSum(vector<int> &num, int target) {
/*
vector<vector<int> > result;
unordered_multimap<int, pair<int, int> > M;
for (auto it1=begin(num); it1!=end(num); ++it1) {
for (auto it2=it1+1; it2!=end(num); ++it2) {
M.insert(make_pair(*it1 + *it2, make_pair(it1-begin(num), it2-begin(num))));
}
}
for (auto it=begin(M); it!=end(M); ++it) {
auto range = M.equal_range(target - it->first);
for (auto it3=range.first; it3!=range.second; ++it3) {
int a = it->second.first;
int b = it->second.second;
int c = it3->second.first;
int d = it3->second.second;
if (a != c && a != d && b != c && b != d) {
vector<int> r = {num.at(a), num.at(b), num.at(c), num.at(d)};
sort(begin(r), end(r));
result.push_back(r);
}
}
}
sort(begin(result), end(result));
result.erase(unique(begin(result), end(result)), result.end());
return result;
*/
vector<vector<int>> result;
if (num.size() < 4) return result;
sort(num.begin(), num.end());
auto last = num.end();
for (auto a = num.begin(); a < prev(last, 3); ++a) {
for (auto b = next(a); b < prev(last, 2); ++b) {
auto c = next(b);
auto d = prev(last);
while (c < d) {
if (*a + *b + *c + *d < target) {
++c;
} else if (*a + *b + *c + *d > target) {
--d;
} else {
result.push_back({ *a, *b, *c, *d });
++c;
--d;
}
}
}
}
sort(result.begin(), result.end());
result.erase(unique(result.begin(), result.end()), result.end());
return result;
}
int main() {
//vector<int> v = {1, 0, -1, 0, -2, 2};
vector<int> v = {91277418,66271374,38763793,4092006,11415077,60468277,1122637,72398035,-62267800,22082642,60359529,-16540633,92671879,-64462734,-55855043,-40899846,88007957,-57387813,-49552230,-96789394,18318594,-3246760,-44346548,-21370279,42493875,25185969,83216261,-70078020,-53687927,-76072023,-65863359,-61708176,-29175835,85675811,-80575807,-92211746,44755622,-23368379,23619674,-749263,-40707953,-68966953,72694581,-52328726,-78618474,40958224,-2921736,-55902268,-74278762,63342010,29076029,58781716,56045007,-67966567,-79405127,-45778231,-47167435,1586413,-58822903,-51277270,87348634,-86955956,-47418266,74884315,-36952674,-29067969,-98812826,-44893101,-22516153,-34522513,34091871,-79583480,47562301,6154068,87601405,-48859327,-2183204,17736781,31189878,-23814871,-35880166,39204002,93248899,-42067196,-49473145,-75235452,-61923200,64824322,-88505198,20903451,-80926102,56089387,-58094433,37743524,-71480010,-14975982,19473982,47085913,-90793462,-33520678,70775566,-76347995,-16091435,94700640,17183454,85735982,90399615,-86251609,-68167910,-95327478,90586275,-99524469,16999817,27815883,-88279865,53092631,75125438,44270568,-23129316,-846252,-59608044,90938699,80923976,3534451,6218186,41256179,-9165388,-11897463,92423776,-38991231,-6082654,92275443,74040861,77457712,-80549965,-42515693,69918944,-95198414,15677446,-52451179,-50111167,-23732840,39520751,-90474508,-27860023,65164540,26582346,-20183515,99018741,-2826130,-28461563,-24759460,-83828963,-1739800,71207113,26434787,52931083,-33111208,38314304,-29429107,-5567826,-5149750,9582750,85289753,75490866,-93202942,-85974081,7365682,-42953023,21825824,68329208,-87994788,3460985,18744871,-49724457,-12982362,-47800372,39958829,-95981751,-71017359,-18397211,27941418,-34699076,74174334,96928957,44328607,49293516,-39034828,5945763,-47046163,10986423,63478877,30677010,-21202664,-86235407,3164123,8956697,-9003909,-18929014,-73824245};
auto result = fourSum(v, -236727523);
for (auto x: result) {
for (auto i: x) {
printf("%d ", i);
}
printf("\n");
}
}
| 56.109589 | 1,904 | 0.627686 | [
"vector"
] |
6cdb261bd85c12c41b72ea1b3c244643aa6d3ccb | 1,516 | cpp | C++ | Source Code/Source/ReturnoftheGorm/HealthBox.cpp | creosB/Return-Of-the-Gorm | 09f413cf30ae5bd74dd8f8afccf3a2824a82eeb3 | [
"MIT"
] | null | null | null | Source Code/Source/ReturnoftheGorm/HealthBox.cpp | creosB/Return-Of-the-Gorm | 09f413cf30ae5bd74dd8f8afccf3a2824a82eeb3 | [
"MIT"
] | null | null | null | Source Code/Source/ReturnoftheGorm/HealthBox.cpp | creosB/Return-Of-the-Gorm | 09f413cf30ae5bd74dd8f8afccf3a2824a82eeb3 | [
"MIT"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "HealthBox.h"
#include "Components/StaticMeshComponent.h"
#include "ContraCharacter.h"
#include "Kismet/GameplayStatics.h"
// Sets default values
AHealthBox::AHealthBox()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = false;
HealthBoxMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("HealthBox Mesh"));
HealthBoxMesh->OnComponentHit.AddDynamic(this, &AHealthBox::OnHit);
RootComponent = HealthBoxMesh;
}
// Called when the game starts or when spawned
void AHealthBox::BeginPlay()
{
Super::BeginPlay();
}
// When hit the player on healthbox, it will give 10.0f health value. After taking health, it will destroy own.
void AHealthBox::OnHit(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherComponent,
FVector NormalImpulse, const FHitResult& Hit)
{
AContraCharacter* ContraCharacter = Cast<AContraCharacter>(OtherActor);
if (!ContraCharacter) { return; }
if(ContraCharacter && OtherActor != this)
{
ContraCharacter->Health += GiveHealthValue;
FindPointer();
UGameplayStatics::SpawnEmitterAtLocation(this,GiveHealthParticle,GetActorLocation());
UGameplayStatics::SpawnSoundAtLocation(this, GiveHealthSound, GetActorLocation());
Destroy();
}
}
void AHealthBox::FindPointer()
{
if (!GiveHealthSound) { return; }
if (!GiveHealthParticle) { return; }
}
| 27.563636 | 114 | 0.766491 | [
"mesh"
] |
6cdf488660978a36c77e6e83daa925b97f7307c8 | 10,851 | cpp | C++ | 3rdparty/mygui/src/MyGUI_Message.cpp | Osumi-Akari/energytycoon | 25d18a0ee4a9f8833e678af297734602918a92e9 | [
"Unlicense"
] | null | null | null | 3rdparty/mygui/src/MyGUI_Message.cpp | Osumi-Akari/energytycoon | 25d18a0ee4a9f8833e678af297734602918a92e9 | [
"Unlicense"
] | null | null | null | 3rdparty/mygui/src/MyGUI_Message.cpp | Osumi-Akari/energytycoon | 25d18a0ee4a9f8833e678af297734602918a92e9 | [
"Unlicense"
] | null | null | null | /*!
@file
@author Albert Semenov
@date 01/2008
@module
*//*
This file is part of MyGUI.
MyGUI is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MyGUI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with MyGUI. If not, see <http://www.gnu.org/licenses/>.
*/
#include "MyGUI_Precompiled.h"
#include "MyGUI_Message.h"
#include "MyGUI_WidgetSkinInfo.h"
#include "MyGUI_WidgetManager.h"
#include "MyGUI_LayerManager.h"
#include "MyGUI_InputManager.h"
#include "MyGUI_ResourceManager.h"
#include "MyGUI_WidgetOIS.h"
#include "MyGUI_MessageFactory.h"
#include "MyGUI_Gui.h"
#include "MyGUI_ControllerManager.h"
#include "MyGUI_ControllerFadeAlpha.h"
#include "MyGUI_StaticImage.h"
namespace MyGUI
{
const float MESSAGE_ALPHA_MAX = 0.5f;
const float MESSAGE_ALPHA_MIN = 0.0f;
const float MESSAGE_SPEED_COEF = 3.0f;
Message::Message(WidgetStyle _style, const IntCoord& _coord, Align _align, const WidgetSkinInfoPtr _info, WidgetPtr _parent, ICroppedRectangle * _croppedParent, IWidgetCreator * _creator, const std::string & _name) :
Base(_style, _coord, _align, _info, _parent, _croppedParent, _creator, _name),
mWidgetText(nullptr),
mInfoOk(MessageBoxStyle::None),
mInfoCancel(MessageBoxStyle::None),
mSmoothShow(false),
mWidgetFade(nullptr),
mIcon(nullptr),
mLeftOffset1(0),
mLeftOffset2(0)
{
initialiseWidgetSkin(_info);
}
Message::~Message()
{
shutdownWidgetSkin();
}
void Message::baseChangeWidgetSkin(WidgetSkinInfoPtr _info)
{
shutdownWidgetSkin();
Base::baseChangeWidgetSkin(_info);
initialiseWidgetSkin(_info);
}
void Message::initialiseWidgetSkin(WidgetSkinInfoPtr _info)
{
// парсим виджет для текста
for (VectorWidgetPtr::iterator iter=mWidgetChildSkin.begin(); iter!=mWidgetChildSkin.end(); ++iter) {
if (*(*iter)->_getInternalData<std::string>() == "Text") {
MYGUI_DEBUG_ASSERT( ! mWidgetText, "widget already assigned");
mWidgetText = (*iter);
mOffsetText.set(mCoord.width - mWidgetText->getWidth(), mCoord.height - mWidgetText->getHeight());
mLeftOffset2 = mLeftOffset1 = mWidgetText->getLeft();
}
else if (*(*iter)->_getInternalData<std::string>() == "Icon") {
MYGUI_DEBUG_ASSERT( ! mIcon, "widget already assigned");
mIcon = (*iter)->castType<StaticImage>();
}
}
MYGUI_ASSERT(nullptr != mWidgetText, "Child Text not found in skin (MessageBox must have widget for text)");
if (mIcon != nullptr) {
mLeftOffset2 = mIcon->getRight() + 3;
}
// парсим свойства
const MapString & properties = _info->getProperties();
if (!properties.empty()) {
MapString::const_iterator iter = properties.find("ButtonSkin");
if (iter != properties.end()) mButtonSkin = iter->second;
iter = properties.find("ButtonType");
if (iter != properties.end()) mButtonType = iter->second;
iter = properties.find("ButtonSize");
if (iter != properties.end()) mButtonSize = IntSize::parse(iter->second);
iter = properties.find("ButtonOffset");
if (iter != properties.end()) mButtonOffset = IntSize::parse(iter->second);
iter = properties.find("DefaultLayer");
if (iter != properties.end()) mDefaultLayer = iter->second;
iter = properties.find("FadeSkin");
if (iter != properties.end()) mFadeSkin = iter->second;
iter = properties.find("FadeLayer");
if (iter != properties.end()) mFadeLayer = iter->second;
}
}
void Message::shutdownWidgetSkin()
{
mWidgetText = nullptr;
mIcon = nullptr;
}
void Message::setMessageText(const Ogre::UTFString & _message)
{
mWidgetText->setCaption(_message);
mWidgetText->setShadow(true);
updateSize();
}
MessageBoxStyle Message::addButtonName(const Ogre::UTFString & _name)
{
//FIXME
if (mVectorButton.size() >= MessageBoxStyle::_CountUserButtons) {
MYGUI_LOG(Warning, "Too many buttons in message box, ignored");
return MessageBoxStyle::None;
}
// бит, номер кнопки + смещение до Button1
MessageBoxStyle info = MessageBoxStyle(MessageBoxStyle::Enum(MYGUI_FLAG(mVectorButton.size() + MessageBoxStyle::_IndexUserButton1)));
// запоминаем кнопки для отмены и подтверждения
if (mVectorButton.empty()) mInfoOk = info;
mInfoCancel = info;
WidgetPtr button = createWidgetT(mButtonType, mButtonSkin, IntCoord(), Align::Left | Align::Bottom);
button->eventMouseButtonClick = newDelegate(this, &Message::notifyButtonClick);
button->setCaption(_name);
button->_setInternalData(info);
button->setShadow(true);
mVectorButton.push_back(button);
updateSize();
return info;
}
void Message::setMessageIcon(MessageBoxStyle _icon)
{
if (nullptr == mIcon) return;
if (mIcon->getItemResource() != nullptr) {
mIcon->setItemName( getIconName(_icon.getIconIndex()) );
}
else {
mIcon->setImageIndex(_icon.getIconIndex());
}
updateSize();
}
void Message::setMessageButton(MessageBoxStyle _info)
{
clearButton();
std::vector<MessageBoxStyle> buttons = _info.getButtons();
for (size_t index=0; index<buttons.size(); ++index)
{
// корректируем ее номер
MessageBoxStyle info = buttons[index];
// если бит есть то ставим кнопку
addButtonName(factory::MessageFactory::getButtonName(info));
// внутри адд сбрасывается
mVectorButton.back()->_setInternalData(info);
// первая кнопка
if (mVectorButton.size() == 1) mInfoOk = info;
// последняя кнопка
mInfoCancel = info;
}
updateSize();
}
void Message::setMessageStyle(MessageBoxStyle _style)
{
setMessageButton(_style);
setMessageIcon(_style);
}
void Message::notifyButtonClick(MyGUI::WidgetPtr _sender)
{
_destroyMessage(*_sender->_getInternalData<MessageBoxStyle>());
}
void Message::clearButton()
{
for (VectorWidgetPtr::iterator iter=mVectorButton.begin(); iter!=mVectorButton.end(); ++iter) {
WidgetManager::getInstance().destroyWidget(*iter);
}
mVectorButton.clear();
}
void Message::onKeyButtonPressed(KeyCode _key, Char _char)
{
Base::onKeyButtonPressed(_key, _char);
if ((_key == KeyCode::Return) || (_key == KeyCode::NumpadEnter)) _destroyMessage(mInfoOk);
else if (_key == KeyCode::Escape) _destroyMessage(mInfoCancel);
}
void Message::_destroyMessage(MessageBoxStyle _result)
{
eventMessageBoxResult(this, _result);
if (nullptr != mWidgetFade) {
if (mSmoothShow) {
ControllerFadeAlpha * controller = new ControllerFadeAlpha(MESSAGE_ALPHA_MIN, MESSAGE_SPEED_COEF, false);
controller->eventPostAction = newDelegate(action::actionWidgetDestroy);
ControllerManager::getInstance().addItem(mWidgetFade, controller);
}
else WidgetManager::getInstance().destroyWidget(mWidgetFade);
}
if (mSmoothShow) destroySmooth();
else WidgetManager::getInstance().destroyWidget(this);
}
void Message::setSmoothShow(bool _smooth)
{
mSmoothShow = _smooth;
if (mSmoothShow)
{
setAlpha(ALPHA_MIN);
setVisible(true);
setVisibleSmooth(true);
}
}
void Message::setWindowFade(bool _fade)
{
return; //пока пропустим
if (_fade) {
if (nullptr == mWidgetFade) {
Gui & gui = Gui::getInstance();
mWidgetFade = gui.createWidgetT(Widget::getClassTypeName(), mFadeSkin, IntCoord(0, 0, (int)gui.getViewWidth(), (int)gui.getViewHeight()), Align::Stretch, mFadeLayer);
if (mSmoothShow) {
mWidgetFade->setVisible(false);
ControllerFadeAlpha * controller = new ControllerFadeAlpha(MESSAGE_ALPHA_MAX, MESSAGE_SPEED_COEF, false);
ControllerManager::getInstance().addItem(mWidgetFade, controller);
}
else mWidgetFade->setAlpha(MESSAGE_ALPHA_MAX);
}
}
else {
if (nullptr != mWidgetFade) {
WidgetManager::getInstance().destroyWidget(mWidgetFade);
mWidgetFade = nullptr;
}
}
}
const char * Message::getIconName(size_t _index)
{
static const size_t CountIcons = 4;
static const char * IconNames[CountIcons + 1] = { "Info", "Quest", "Error", "Warning", "" };
if (_index >= CountIcons) return IconNames[CountIcons];
return IconNames[_index];
}
MyGUI::MessagePtr Message::createMessageBox(
const std::string & _skin,
const Ogre::UTFString & _caption,
const Ogre::UTFString & _message,
MessageBoxStyle _style,
const std::string & _layer,
bool _modal,
const std::string & _button1,
const std::string & _button2,
const std::string & _button3,
const std::string & _button4)
{
MessagePtr mess = Gui::getInstance().createWidget<Message>(_skin, IntCoord(), Align::Default, _layer);
mess->setCaption(_caption);
mess->setMessageText(_message);
mess->setShadow(true);
mess->setSmoothShow(true);
if (_modal) mess->setWindowFade(true);
mess->setMessageStyle(_style);
if (false == _button1.empty()) {
mess->addButtonName(_button1);
if (false == _button2.empty()) {
mess->addButtonName(_button2);
if (false == _button3.empty()) {
mess->addButtonName(_button3);
}
}
}
if (_layer.empty()) LayerManager::getInstance().attachToLayerKeeper(mess->getDefaultLayer(), mess);
if (_modal) InputManager::getInstance().addWidgetModal(mess);
return mess;
}
void Message::updateSize()
{
ISubWidgetText* text = mWidgetText->getSubWidgetText();
IntSize size = text ? text->getTextSize() : IntSize();
// минимум высота иконки
if ((nullptr != mIcon) && (mIcon->getImageIndex() != ITEM_NONE)) {
if (size.height < mIcon->getHeight()) size.height = mIcon->getHeight();
size.width += mIcon->getSize().width;
}
size += mOffsetText;
size.width += 3;
int width = ((int)mVectorButton.size() * mButtonSize.width) + (((int)mVectorButton.size()+1) * mButtonOffset.width);
if (size.width < width) size.width = width;
int offset = (size.width - width)/2;
offset += mButtonOffset.width;
IntSize view((int)Gui::getInstance().getViewWidth(), (int)Gui::getInstance().getViewHeight());
setCoord((view.width-size.width)/2, (view.height-size.height)/2, size.width, size.height);
if (nullptr != mIcon) {
if (mIcon->getImageIndex() != ITEM_NONE) mWidgetText->setCoord(mLeftOffset2, mWidgetText->getTop(), mWidgetText->getWidth(), mWidgetText->getHeight());
else mWidgetText->setCoord(mLeftOffset1, mWidgetText->getTop(), mWidgetText->getWidth(), mWidgetText->getHeight());
}
for (VectorWidgetPtr::iterator iter=mVectorButton.begin(); iter!=mVectorButton.end(); ++iter) {
(*iter)->setCoord(offset, mCoord.height - mButtonOffset.height, mButtonSize.width, mButtonSize.height);
offset += mButtonOffset.width + mButtonSize.width;
}
}
} // namespace MyGUI
| 31.543605 | 217 | 0.714589 | [
"vector"
] |
6cece6520bca40860b998cb70a5434e46fe7ed70 | 1,357 | hpp | C++ | Animal.hpp | Athanasius2/CS3210-final | 78eaef5622187724d3e8f0e18ea22f7c6d6b770a | [
"MIT"
] | null | null | null | Animal.hpp | Athanasius2/CS3210-final | 78eaef5622187724d3e8f0e18ea22f7c6d6b770a | [
"MIT"
] | null | null | null | Animal.hpp | Athanasius2/CS3210-final | 78eaef5622187724d3e8f0e18ea22f7c6d6b770a | [
"MIT"
] | null | null | null | #ifndef ANIMAL_HPP
#define ANIMAL_HPP
#include "Actor.hpp"
#include "Environment.hpp"
#include <vector>
#include <map>
#include <memory>
#include <utility>
#include <algorithm>
namespace cppfinal
{
class Animal : public Actor
{
private:
std::vector<char> eats;
//TODO: move energy to actor
int energy;
enum State {REPRODUCE, HUNGRY, HUNTED};
State state; //Default state = REPRODUCE
bool reproducing;
void move(Environment::Direction d);
bool can_move(Environment::Direction d);
public:
Animal(char t, int nrg, std::vector<char> e, std::pair<int, int> p) : Actor{ t, nrg, p }, energy{ nrg }, eats{ e }, reproducing{false} {}
std::shared_ptr<Actor> clone_to(std::pair<int, int> p) const override
{
auto an = std::make_unique<Animal>(*this);
an->set_pos(p);
return an;
}
void act() override;
char print() override {return gettype();}
//TODO: move energy to actor.
int get_energy() override { return energy; }
bool is_eaten() override { return is_dead(); } //not totally logical, but it works.
bool is_reproducing() override { return reproducing; }
bool can_reproduce(char t) override;
int eat() override { die(); return energy; }
bool is_dangerous(char t) override { return std::any_of(eats.begin(), eats.end(), [t](char c) { return (c == t); }); }
~Animal();
};
}
#endif
| 20.560606 | 140 | 0.665438 | [
"vector"
] |
6cf034946e4d461e4c595225855cb82d5050ccda | 6,329 | cpp | C++ | 0710747.cpp | Jackie890621/Interval-Tree | 00e3151e4c3ca69982660181bc04c796a0b02215 | [
"MIT"
] | null | null | null | 0710747.cpp | Jackie890621/Interval-Tree | 00e3151e4c3ca69982660181bc04c796a0b02215 | [
"MIT"
] | null | null | null | 0710747.cpp | Jackie890621/Interval-Tree | 00e3151e4c3ca69982660181bc04c796a0b02215 | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <climits>
#include <algorithm>
#include <time.h>
using namespace std;
vector<int> O;
vector<vector<int>> Overlap;
bool flag;
int min_area = INT_MAX;
vector<int> area_list;
vector<int> search_list;
struct Interval
{
int order;
int x_low, y_low;
int x_high, y_high;
};
struct Node
{
Interval *n;
Node *left;
Node *right;
};
Node *newNode(Interval n)
{
Node *temp = new Node;
temp->n = new Interval(n);
temp->left = NULL;
temp->right = NULL;
return temp;
}
Node *insert(Node *root, Interval n)
{
if (root == NULL) {
return newNode(n);
}
int root_low = root->n->x_low;
int low = n.x_low;
if (low < root_low) {
root->left = insert(root->left, n);
} else {
root->right = insert(root->right, n);
}
return root;
}
bool overlap(Interval n1, Interval n2)
{
if (n1.x_low <= n2.x_low && n1.x_high >= n2.x_high) {
if (n1.y_low <= n2.y_low && n1.y_high >= n2.y_high) {
if ((n2.x_low - n1.x_low) >= 20 &&
(n2.y_low - n1.y_low) >= 20 &&
(n1.x_high - n2.x_high) >= 20 &&
(n1.y_high - n2.y_high) >= 20) {
flag = false;
} else {
flag = true;
}
return true;
} else {
return false;
}
} else {
return false;
}
}
void overlapSearch(Node *root, Interval n)
{
if (root == NULL) {
return;
}
overlapSearch(root->left, n);
if (overlap(*(root->n), n)) {
O.push_back(root->n->order);
if (flag) {
O.push_back(1);
flag = false;
} else {
O.push_back(0);
}
Overlap.push_back(O);
O.clear();
}
overlapSearch(root->right, n);
}
void Search(Node *root, Interval n)
{
if (root == NULL) {
return;
}
if (root->n->x_low == n.x_low &&
root->n->y_low == n.y_low &&
root->n->x_high == n.x_high &&
root->n->y_high == n.y_high) {
if (search_list.size() == 0) {
search_list.push_back(root->n->order);
} else if (search_list.back() != root->n->order) {
search_list.push_back(root->n->order);
}
if (root->right != NULL) {
Search(root->right, n);
} else {
return;
}
return;
}
if (root->n->x_low > n.x_low) {
Search(root->left, n);
} else {
Search(root->right, n);
}
}
Node *Delete(Node *root, Interval n)
{
if (root == NULL) {
return root;
}
if (root->n->x_low > n.x_low) {
root->left = Delete(root->left, n);
} else if (root->n->x_low < n.x_low) {
root->right = Delete(root->right, n);
} else {
if (root->n->x_high != n.x_high ||
root->n->y_low != n.y_low ||
root->n->y_high != n.y_high) {
root->right = Delete(root->right, n);
} else {
if (root->left == NULL && root->right == NULL) {
return NULL;
} else if (root->left == NULL){
Node *temp = root->right;
free(root);
return temp;
} else if (root->right == NULL){
Node *temp = root->left;
free(root);
return temp;
}
Node *temp = root->right;
while (temp->left != NULL) {
temp = temp->left;
if (temp->n->x_low == n.x_low &&
temp->n->x_high == n.x_high &&
temp->n->y_low == n.y_low &&
temp->n->y_high == n.y_high) {
break;
}
}
root->n->x_low = temp->n->x_low;
root->n->x_high = temp->n->x_high;
root->n->y_low = temp->n->y_low;
root->n->y_high = temp->n->y_high;
root->n->order = temp->n->order;
root->right = Delete(root->right, *temp->n);
}
}
return root;
}
void Area(Node *root, int x_low, int y_low)
{
if (root == NULL) {
return;
}
if (root->n->x_low == x_low && root->n->y_low == y_low) {
int area = (root->n->x_high - x_low) * (root->n->y_high - y_low);
if (area < min_area) {
area_list.clear();
min_area = area;
area_list.push_back(root->n->order);
} else if (area == min_area && area_list.back() != root->n->order) {
area_list.push_back(root->n->order);
}
if (root->right != NULL) {
Area(root->right, x_low, y_low);
} else {
return;
}
return;
}
if (root->n->x_low > x_low) {
Area(root->left, x_low, y_low);
} else {
Area(root->right, x_low, y_low);
}
}
int main(int argc, char *argv[])
{
time_t t = clock();
Node *root = NULL;
vector<string> res;
string result;
string text;
ifstream MyReadFile(argv[1]);
ofstream MyFile(argv[2]);
while (getline(MyReadFile, text)) {
res.clear();
stringstream input(text);
while (input >> result) {
res.push_back(result);
}
Interval n;
switch (res[0][0]) {
case 'I':
n.order = stoi(res[1].substr(1));
n.x_low = stoi(res[2]);
n.y_low = stoi(res[3]);
n.x_high = stoi(res[4]);
n.y_high = stoi(res[5]);
root = insert(root, n);
break;
case 'D':
n.x_low = stoi(res[1]);
n.y_low = stoi(res[2]);
n.x_high = stoi(res[3]);
n.y_high = stoi(res[4]);
root = Delete(root, n);
break;
case 'S':
n.x_low = stoi(res[1]);
n.y_low = stoi(res[2]);
n.x_high = stoi(res[3]);
n.y_high = stoi(res[4]);
Search(root, n);
MyFile << 'S' << endl;
for (int i = 0; i < search_list.size(); i++) {
MyFile << 'r' << search_list[i] << endl;
}
search_list.clear();
break;
case 'O':
n.x_low = stoi(res[1]);
n.y_low = stoi(res[2]);
n.x_high = stoi(res[3]);
n.y_high = stoi(res[4]);
overlapSearch(root, n);
MyFile << 'O' << endl;
sort(Overlap.begin(), Overlap.end());
for (int i = 0; i < Overlap.size(); i++) {
if (Overlap[i][1] == 1) {
MyFile << 'r' << Overlap[i][0] << " violate" << endl;
} else {
MyFile << 'r' << Overlap[i][0] << endl;
}
}
Overlap.clear();
break;
case 'A':
Area(root, stoi(res[1]), stoi(res[2]));
sort(area_list.begin(), area_list.end());
MyFile << 'A' << endl;
for (int i = 0; i < area_list.size(); i++) {
MyFile << 'r' << area_list[i] << endl;
}
min_area = INT_MAX;
area_list.clear();
break;
}
}
MyReadFile.close();
t = clock() - t;
cout << double(t) / CLOCKS_PER_SEC << endl;
return 0;
}
| 21.600683 | 70 | 0.521883 | [
"vector"
] |
6cf3b33971352646216331a49cab42a4343cf778 | 7,560 | cpp | C++ | lib/Target/Sophon/BM188x/BM188xTargetTransformInfo.cpp | LiuLeif/onnc | 3f69e46172a9c33cc04541ff7fd78d5d7b6bdbba | [
"BSD-3-Clause"
] | 450 | 2018-08-03T08:17:03.000Z | 2022-03-17T17:21:06.000Z | lib/Target/Sophon/BM188x/BM188xTargetTransformInfo.cpp | ffk0716/onnc | 91e4955ade64b479db17aaeccacf4b7339fe44d2 | [
"BSD-3-Clause"
] | 104 | 2018-08-13T07:31:50.000Z | 2021-08-24T11:24:40.000Z | lib/Target/Sophon/BM188x/BM188xTargetTransformInfo.cpp | ffk0716/onnc | 91e4955ade64b479db17aaeccacf4b7339fe44d2 | [
"BSD-3-Clause"
] | 100 | 2018-08-12T04:27:39.000Z | 2022-03-11T04:17:42.000Z | //===---------------------------------------------------------------------===//
//
// The ONNC Project
//
// Copyright(c) 2018, The ONNC Team
//
// This file is part of the ONNC Project and is distributed under
// 3-clause BSD license (https://opensource.org/licenses/BSD-3-Clause)
//
// See LICENSE.TXT for details.
//
//===---------------------------------------------------------------------===//
#include "BM188xTargetTransformInfo.h"
#include "TGBackend.h"
#include <algorithm>
#include <iostream>
#include <onnc/Target/TargetMemInfo.h>
#include <unordered_map>
using namespace onnc;
namespace {
const int NPU_NUM = 32;
const int EU_NUM = 16;
const int BUS_BITWIDTH = 128;
using CostFunction = int (*)(TGBackend *, const xNode *pNode);
using CostModelMap = std::unordered_map<xNodeKind, CostFunction>;
inline int idiv_round(int pNumerator, int pDenominator)
{
return (pNumerator + pDenominator - 1) / pDenominator;
}
size_t getNumNeuron(const xValue &pValue)
{
size_t total = 1;
for (const xDimension &dim : pValue.sizes())
total *= dim.dim;
return total;
}
#if 0
// Currently not used by anyone
size_t getNumElems(const xNode &pNode)
{
size_t total = 1;
for (const xValue *v : pNode.inputs())
for (const xDimension &dim : v->sizes())
total *= dim.dim;
return total;
}
#endif
int ZeroCost(TGBackend *pTGBackend, const xNode *pNode) { return 0; }
int countHWStepsFromOutputValue(const xValue *pValue)
{
auto ResultDim = pValue->sizes();
int DimNum = ResultDim.size();
int MinDimNum = std::min(4, DimNum);
assert(DimNum > 0 && "ResultDim is under zero");
std::vector<int> NCHW(4, 1);
for (int i = 0; i < MinDimNum; ++i)
NCHW[i + 4 - MinDimNum] = ResultDim[i].dim;
int HWSteps = NCHW[0] * idiv_round(NCHW[1], NPU_NUM) *
idiv_round(NCHW[2] * NCHW[3], EU_NUM);
for (int i = 4; i < DimNum; ++i)
HWSteps *= ResultDim[i].dim;
return HWSteps;
}
template <int m_Factor8Bit, int m_Factor16Bit>
int TensorOpCost(TGBackend *pTGBackend, const xNode *pNode)
{
auto *Value = pNode->outputs().at(0);
int HWSteps = countHWStepsFromOutputValue(Value);
int TotalCycles = HWSteps * m_Factor8Bit;
return TotalCycles;
}
int ConvOpCost(TGBackend *pTGBackend, const xNode *pNode)
{
/* From wiki
RES_N * idiv_round((RES_C_START + RES_C), LANE_NUM)
* idiv_round(RES_W * RES_H, EU_NUM)
* (OPD1_W * OPD1_H * OPD0_C *
(((STR_W + 1) > MIN(OPD0_C, LANE_NUM))
? (STR_W + 1) / MIN(OPD0_C, LANE_NUM) : 1)
+ (HAVE_BIAS ? 2 : 0) + 3
);
*/
auto *OutputValue = pNode->outputs().at(0);
auto OutputDim = OutputValue->sizes();
// TODO(arcbbb): Assume 2d conv here
assert(OutputDim.size() == 4);
int OutputN = OutputDim[0].dim;
int OutputC = OutputDim[1].dim;
int OutputH = OutputDim[2].dim;
int OutputW = OutputDim[3].dim;
int HWSteps = OutputN * idiv_round(OutputC, NPU_NUM) *
idiv_round(OutputH * OutputW, EU_NUM);
auto *WeightValue = pNode->inputs().at(1);
int WeightCount = 1;
for (auto dim : WeightValue->sizes()) {
WeightCount *= dim.dim;
}
bool HasBias = pNode->inputs().size() == 3;
int BiasCycle;
if (HasBias) {
BiasCycle = 2;
} else {
BiasCycle = 0;
}
int BaseCost = 3;
int StepCost = (WeightCount + BiasCycle + BaseCost);
int TotalCycles = HWSteps * StepCost;
return TotalCycles;
}
int GemmOpCost(TGBackend *pTGBackend, const xNode *pNode)
{
/* From wiki
RES_N * idiv_round(RES_C_START+RES_C, LANE_NUM)
* idiv_round(RES_W,EU_NUM)
* ((OPD0_W*(OPD0_C-1)+OPD1_W)+6+(HAVE_BIAS?2:0)+(ADD_RES?2:0))
*/
// A' = transpose(A) if transA else A
// B' = transpose(B) if transB else B
// Y = alpha * A' * B' + beta * C
auto *OutputValue = pNode->outputs().at(0);
auto OutputDim = OutputValue->sizes();
auto ADim = pNode->inputs()[0]->sizes();
auto BDim = pNode->inputs()[1]->sizes();
// A: M x K
int64_t DimM = ADim[0].dim;
int64_t DimK = ADim[1].dim;
if (pNode->hasAttribute(xSymbol("transA"))) {
auto transA = pNode->i(xSymbol("transA"));
DimM = transA ? ADim[1].dim : ADim[0].dim;
DimK = transA ? ADim[0].dim : ADim[1].dim;
}
// B: DimK x N
int64_t DimN = BDim[1].dim;
if (pNode->hasAttribute(xSymbol("transB"))) {
auto transB = pNode->i(xSymbol("transB"));
DimN = transB ? BDim[0].dim : BDim[1].dim;
}
int HWSteps = idiv_round(DimM, NPU_NUM) * idiv_round(DimN, EU_NUM);
int StepCost = (DimK * (DimM - 1) + DimN) + 6;
int TotalCycles = HWSteps * StepCost;
return TotalCycles;
}
int MaxPoolOpCost(TGBackend *pTGBackend, const xNode *pNode)
{
/* From 1682
int ActiveEUNum = idiv_round(EU_NUM/stride_w);
int TotalCycle = 6 + input_n * idiv_round(input_c, NPU_NUM) * kh * kw
* idiv_round(output_h * output_w, ActiveEUNum);
*/
auto *OutputValue = pNode->outputs().at(0);
auto OutputDim = OutputValue->sizes();
assert(OutputDim.size() == 4);
auto &KernelShape = pNode->is(xSymbol("kernel_shape"));
int KHeight = KernelShape.at(0);
int KWidth = KernelShape.at(1);
auto &StrideShape = pNode->is(xSymbol("strides"));
int StrideW = StrideShape.at(1);
int OutputN = OutputDim[0].dim;
int OutputC = OutputDim[1].dim;
int OutputH = OutputDim[2].dim;
int OutputW = OutputDim[3].dim;
int ActiveEUNum = idiv_round(EU_NUM, StrideW);
int HWSteps = idiv_round(OutputH * OutputW, ActiveEUNum);
int StepCost = OutputN * idiv_round(OutputC, NPU_NUM) * KHeight * KWidth + 6;
int TotalCycles = HWSteps * StepCost;
return TotalCycles;
}
int LoadOpCost(TGBackend *pTGBackend, const xNode *pNode)
{
const xValue *OutputValue = pNode->outputs().at(0);
int NumNeuron = getNumNeuron(*OutputValue);
TargetMemInfo *MemInfo = pTGBackend->getMemInfo();
int Bytes = NumNeuron * MemInfo->getElemSize(OutputValue->elemType());
int TotalCycles = (Bytes / (BUS_BITWIDTH >> 3));
return TotalCycles;
}
int StoreOpCost(TGBackend *pTGBackend, const xNode *pNode)
{
auto *InputValue = pNode->inputs().at(0);
int NumNeuron = getNumNeuron(*InputValue);
int TotalCycles = NumNeuron;
return TotalCycles;
}
CostModelMap g_NodeCostModels = {
{ xSymbol("Conv"), ConvOpCost },
{ xSymbol("MaxPool"), MaxPoolOpCost },
{ xSymbol("Gemm"), GemmOpCost },
{ xSymbol("Add"), TensorOpCost<6, 7> },
{ xSymbol("Mul"), TensorOpCost<5, 3> },
{ xSymbol("Sub"), TensorOpCost<6, 7> },
{ xSymbol("Max"), TensorOpCost<2, 2> },
{ xSymbol("Relu"), TensorOpCost<2, 2> },
{ xSymbol("Min"), TensorOpCost<2, 2> },
{ xSymbol("And"), TensorOpCost<2, 5> },
{ xSymbol("Or"), TensorOpCost<2, 5> },
{ xSymbol("Xor"), TensorOpCost<2, 5> },
{ xSymbol("Softmax"), ZeroCost },
{ xSymbol("Dropout"), ZeroCost },
{ xSymbol("Undefined"), ZeroCost },
// ONNC Extension
{ xSymbol("Load"), LoadOpCost },
{ xSymbol("Store"), StoreOpCost },
};
} // namespace
uint64_t BM188xTargetTransformInfo::getOperatorCost(const xNode *pNode,
unsigned pKind) const
{
auto it = g_NodeCostModels.find(pNode->kind());
if (it != g_NodeCostModels.end()) {
return (*it->second)(m_pTGBackend, pNode);
}
std::cerr << "Unsupported node: " << pNode->kind().toString() << "\n";
assert(false && "TG1880TTI::getOperatorCost: Unsupported node.");
return -1;
}
int BM188xTargetTransformInfo::getWarpSize() const { return NPU_NUM; }
int BM188xTargetTransformInfo::getProcessingUnitCount() const { return EU_NUM; }
int BM188xTargetTransformInfo::getBusBitWidth() const { return BUS_BITWIDTH; }
| 29.76378 | 80 | 0.640079 | [
"vector"
] |
6cf4444621b688ea0ae13e9b4d219f1a539f9c85 | 13,466 | cc | C++ | lib/LoadStoreVerificationPass.cc | cojocar/llvm-iskip | c5c3e9119d9b2bc98a4a1f7c7e70407866e8d8c6 | [
"Apache-2.0"
] | 2 | 2017-09-05T18:29:39.000Z | 2019-01-24T08:49:08.000Z | lib/LoadStoreVerificationPass.cc | cojocar/llvm-iskip | c5c3e9119d9b2bc98a4a1f7c7e70407866e8d8c6 | [
"Apache-2.0"
] | null | null | null | lib/LoadStoreVerificationPass.cc | cojocar/llvm-iskip | c5c3e9119d9b2bc98a4a1f7c7e70407866e8d8c6 | [
"Apache-2.0"
] | null | null | null | // Copyright 2016 The Iskip 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.
//
#define DEBUG_TYPE "iskip-lsv"
#include "llvm/Pass.h"
#include "llvm/Support/raw_ostream.h"
#include <llvm/CodeGen/MachineInstrBuilder.h>
#include <llvm/Target/TargetMachine.h>
#include <llvm/Target/TargetInstrInfo.h>
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/MachineLoopInfo.h"
#include "llvm/Pass.h"
#include "llvm/MC/MCInst.h"
#include "llvm/ADT/Statistic.h"
#include "llvm-src/include/llvm/CodeGen/MachineConstantPool.h"
#include "llvm-src/lib/Target/ARM/ARMMachineFunctionInfo.h"
#include "llvm-src/lib/Target/ARM/ARMConstantPoolValue.h"
#include "LoadStoreVerificationPass.h"
#include "util.h"
STATISTIC(LoadStoresVerified, "The # of load/store instrumented");
STATISTIC(StoresNotInstrumented, "The # of store NOT instrumented");
STATISTIC(LoadsNotInstrumented, "The # of loads NOT instrumented");
//
//grep t2LDR
//~/code/llvm-dev/llvm-build/lib/Target/ARM/ARMGenInstrInfo.inc | grep
//-v '{' | tr -s ' ' | awk 'BEGIN {printf "#ifdef __GET_T2_LDR\n#undef
//__GET_T2_LDR\nunsigned __insn_t2_ldr[] = {\n"} {printf " ARM::"$1",\n"}
//END {printf "}\n#endif\n"}' > ../include/t2LDR.inc
//
using namespace llvm;
cl::opt<bool>
llvm::IskipEnableLoadStoreVerification("iskip-enable-load-store-verification",
cl::NotHidden,
cl::desc("Enable Load Store Verification Pass"),
cl::init(false));
namespace gen_inc {
#define __GET_T_LDR
#include "tLDR.inc"
#define __GET_T2_LDR
#include "t2LDR.inc"
#define __GET_T_STR
#include "tSTR.inc"
#define __GET_T2_STR
#include "t2STR.inc"
}
namespace {
char LoadStoreVerificationPass::ID = 0;
bool LoadStoreVerificationPass::extractInfo(MachineBasicBlock::iterator
&MBBI, int &frameIdx,
int64_t &immValue)
{
{
MachineOperand &destOperand = MBBI->getOperand(1);
if (destOperand.isFI()) {
frameIdx = destOperand.getIndex();
}
if (MBBI->getOperand(2).isImm()) {
immValue = MBBI->getOperand(2).getImm();
}
}
if (!MBBI->hasOneMemOperand()) {
errs() << "XXX: more than one memory operand: " << *MBBI << "\n";
return false;
}
if (MBBI->getOperand(1).isReg()) {
errs() << "XXX: skip global: " << *MBBI << "\n";
return false;
}
if (frameIdx == -1) {
errs() << "XXX: object at unknown position on the stack: " << *MBBI << "\n";
return false;
}
return true;
}
bool LoadStoreVerificationPass::verifyLoadInstruction(MachineBasicBlock &MBB,
MachineBasicBlock::iterator
&MBBI)
{
if (!STI->isThumb2())
return false;
switch (MBBI->getDesc().getOpcode()) {
default: return false;
case ARM::t2LDRi12:
break;
}
// TODO: assert instruction is idempotent
int64_t immValue = 0;
int frameIdx = 0;
if (!extractInfo(MBBI, frameIdx, immValue))
return false;
//errs() << "XXX: " << *MBBI << " : " << MBBI->getOperand(1) << " frameIdx=" << frameIdx << ", immValue=" << immValue << "\n";
return insertCheckLoadStore(MBB, MBBI, true, frameIdx, immValue);
}
bool LoadStoreVerificationPass::verifyStoreInstruction(MachineBasicBlock &MBB,
MachineBasicBlock::iterator
&MBBI)
{
if (!STI->isThumb2())
return false;
switch (MBBI->getDesc().getOpcode()) {
default: return false;
case ARM::t2STRi12:
break;
}
// TODO: assert instruction is idempotent
int64_t immValue = 0;
int frameIdx = 0;
if (!extractInfo(MBBI, frameIdx, immValue))
return false;
//errs() << "XXX: " << *MBBI << " : " << MBBI->getOperand(1) << " frameIdx=" << frameIdx << ", immValue=" << immValue << "\n";
return insertCheckLoadStore(MBB, MBBI, false, frameIdx, immValue);
}
bool LoadStoreVerificationPass::insertCheckLoadStore(MachineBasicBlock &MBB,
MachineBasicBlock::iterator
&MBBI,
bool isLoad,
int frameIdx, int64_t immValue)
{
MachineMemOperand *origMO= *MBBI->memoperands_begin();
MachineMemOperand *MyMO = origMO;
DebugLoc DL = MBBI->getDebugLoc();
MachineOperand &SourceRegOperand = MBBI->getOperand(0);
assert(SourceRegOperand.isReg() && "source of store is not a reg?");
unsigned SourceReg = SourceRegOperand.getReg();
bool SourceRegIsKill = SourceRegOperand.isKill();
if (ARMHardeningUtil::isInsideITBundle(MBBI))
return false;
unsigned SpareReg;
if (!ARMHardeningUtil::getSpareRegister(TII, SourceReg, MBB, MBBI, SpareReg)) {
if (ARMHardeningUtil::IskipEnableVerbose)
errs() << "failed to get a spare reg for: " << *MBBI << "\n";
return false;
}
MyMO->setFlags(isLoad ? MachineMemOperand::MOLoad : MachineMemOperand::MOStore);
MachineBasicBlock *MyErrBB = getOrInsertErrorBasicBlock(MBB, MBBI);
MachineBasicBlock::iterator lastInsn = MBBI;
MachineBasicBlock::iterator firstInsn = MBBI;
++firstInsn;
MachineBasicBlock *NewBB =
ARMHardeningUtil::SplitMBBAt(TII,
getAnalysisIfAvailable<MachineLoopInfo>(),
MBB,
firstInsn);
if (!NewBB)
return false;
if (SourceRegIsKill) {
SourceRegOperand.setIsKill(false);
}
++lastInsn;
AddDefaultPred(
BuildMI(MBB, lastInsn, DL, TII->get(ARM::t2LDRi12))
.addReg(SpareReg, RegState::Define)
.addFrameIndex(frameIdx)
.addMemOperand(MyMO)
.addImm(immValue)
);
// TODO: save flags
AddDefaultPred(
BuildMI(MBB, lastInsn, DL, TII->get(ARM::t2CMPrr))
.addReg(SpareReg, RegState::Kill)
.addReg(SourceReg, SourceRegIsKill ? RegState::Kill : 0)
);
BuildMI(MBB, lastInsn, DL, TII->get(ARM::t2Bcc))
.addMBB(MyErrBB)
.addImm((int64_t)ARMCC::NE)
.addReg(0);
BuildMI(MBB, lastInsn, DL, TII->get(ARM::t2B))
.addMBB(NewBB)
.addImm((int64_t)ARMCC::AL)
.addReg(0);
if (!MBB.isSuccessor(MyErrBB))
MBB.addSuccessorWithoutProb(MyErrBB);
return true;
}
bool isCPSRdefAfterInsn(MachineBasicBlock &MBB,
MachineBasicBlock::iterator &MBBI
)
{
// TODO: save flags only when necessary
return true;
}
MachineBasicBlock *
LoadStoreVerificationPass::getOrInsertErrorBasicBlock(MachineBasicBlock
&MBB,
MachineBasicBlock::iterator
&MBBI)
{
if (ErrBB != nullptr)
return ErrBB;
MachineFunction *MF = MBB.getParent();
const BasicBlock *BB = MBB.getBasicBlock();
ErrBB = MF->CreateMachineBasicBlock(BB);
DebugLoc DL;// = MBBI->getDebugLoc();
//BuildMI(ErrBB, DL, TII->get(ARM::t2UDF)).addImm(255 & (udfCnt++));
BuildMI(ErrBB, DL, TII->get(ARM::t2UDF)).addImm(99);
//BuildMI(ErrBB, DL, TII->get(ARM::t2UDF)).addImm(255 & (udfCnt++));
// TODO: cannot insert b .
//AddDefaultPred(
// BuildMI(ErrBB, DL, TII->get(ARM::t2B))
// .addMBB(ErrBB)
// );
//ErrBB->addSuccessor(ErrBB);
//MF.insert(MF.end(), ErrBB);
//ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
//unsigned PCLabelId = AFI->createPICLabelUId();
MF->push_back(ErrBB);
if (ARMHardeningUtil::IskipEnableVerbose)
errs() << "Inserting error handling BasicBlock\n";
//AddDefaultPred(
// BuildMI(
// ErrBB,
// DL, TII->get(ARM::tBX_RET)));
// This prevents ErrBB to be eliminated by the control flow optimizer
// pass
ErrBB->setIsEHPad();
ErrBB->setIsEHFuncletEntry();
//ErrBB->setHasAddressTaken();
return ErrBB;
}
bool LoadStoreVerificationPass::isLoad(MachineBasicBlock::iterator
&MBBI)
{
// /usr/local/google/home/cojocar/code/llvm-dev/llvm-src/lib/Target/ARM/ARMInstrThumb.td
const MCInstrDesc &desc = MBBI->getDesc();
#define check_in_array(a, opcode) \
do { \
unsigned idx; \
for (idx = 0; idx < ARRAY_LEN(a); ++idx) { \
if (a[idx] == opcode) \
return true; \
} \
} while (0)
check_in_array(gen_inc::__insn_t_ldr, desc.getOpcode());
check_in_array(gen_inc::__insn_t2_ldr, desc.getOpcode());
#if 0 // this is thumb mode
switch (desc.getOpcode()) {
// load/store
case ARM::tLDRpci:
case ARM::tLDRspi:
case ARM::tLDRi:
case ARM::tLDRr:
case ARM::tLDRBi:
case ARM::tLDRBr:
case ARM::tLDRHi:
case ARM::tLDRHr:
case ARM::tLDRSB:
case ARM::tLDRSH:
// load/store multiple
case ARM::tLDMIA:
case ARM::tLDMIA_UPD:
return true;
// TODO: pop/store
default:
return false;
};
#endif
return false;
}
bool LoadStoreVerificationPass::isStore(MachineBasicBlock::iterator
&MBBI)
{
const MCInstrDesc &desc = MBBI->getDesc();
check_in_array(gen_inc::__insn_t_str, desc.getOpcode());
check_in_array(gen_inc::__insn_t2_str, desc.getOpcode());
#if 0
switch (desc.getOpcode()) {
// load/store
case ARM::tSTRspi:
case ARM::tSTRi:
case ARM::tSTRr:
case ARM::tSTRBi:
case ARM::tSTRBr:
case ARM::tSTRHi:
case ARM::tSTRHr:
// load/store multiple
case ARM::tSTMIA_UPD:
return true;
// TODO: pop/store
default:
return false;
};
#endif
return false;
}
bool LoadStoreVerificationPass::loadStoreVerificationBB(MachineBasicBlock &MBB)
{
MachineBasicBlock::iterator MBBI;
bool modified = false;
if (MBB.begin() == MBB.end())
return false;
// do the loads
for (MBBI = MBB.begin(); MBBI != MBB.end(); ++MBBI) {
if (isInstructionIdempotent(MBBI)) {
if (isLoad(MBBI)) {
bool m = verifyLoadInstruction(MBB, MBBI);
LoadsNotInstrumented += !m;
modified |= m;
if (m) {
++LoadStoresVerified;
++LoadStoreVerificationPass::MyLoadStoresVerified;
// skip the rest of the basic block as we inserted a
// terminator
break;
}
}
}
}
// do the stores
for (MBBI = MBB.begin(); MBBI != MBB.end(); ++MBBI) {
if (isInstructionIdempotent(MBBI)) {
if (isStore(MBBI)) {
bool m = verifyStoreInstruction(MBB, MBBI);
StoresNotInstrumented += !m;
modified |= m;
if (m) {
++LoadStoresVerified;
++LoadStoreVerificationPass::MyLoadStoresVerified;
// skip the rest of the basic block as we inserted a
// terminator
break;
}
}
}
}
return modified;
}
bool
LoadStoreVerificationPass::isInstructionIdempotent(MachineBasicBlock::iterator
&MBBI)
{
//errs() << "TODO: " << *MBBI << "\n";
switch (MBBI->getDesc().getOpcode()) {
case ARM::t2LDRB_PRE :
case ARM::t2LDRD_PRE :
case ARM::t2LDRH_PRE :
case ARM::t2LDRSB_PRE :
case ARM::t2LDRSH_PRE :
case ARM::t2LDR_PRE :
case ARM::t2STRB_PRE :
case ARM::t2STRD_PRE :
case ARM::t2STRH_PRE :
case ARM::t2STR_PRE :
case ARM::t2LDRB_POST :
case ARM::t2LDRD_POST :
case ARM::t2LDRH_POST :
case ARM::t2LDRSB_POST:
case ARM::t2LDRSH_POST:
case ARM::t2LDR_POST :
case ARM::t2STRB_POST :
case ARM::t2STRD_POST :
case ARM::t2STRH_POST :
case ARM::t2STR_POST :
return false;
};
return true;
}
bool LoadStoreVerificationPass::runOnMachineFunction(MachineFunction &Fn)
{
bool modified = false;
ErrBB = nullptr;
if (!ARMHardeningUtil::shouldRunPassOnFunction(Fn))
return false;
STI = &static_cast<const ARMSubtarget &>(Fn.getSubtarget());
TII = STI->getInstrInfo();
TRI= Fn.getSubtarget().getRegisterInfo();
if (Fn.getName() == "uart_rx_buf" ||
Fn.getName() == "uart_tx_buf" ||
Fn.getName() == "my_uart_tx_char" ||
Fn.getName() == "my_uart_rx_char" ||
Fn.getName() == "my_uart_init" ||
Fn.getName() == "uart_tx_char" ||
Fn.getName() == "uart_rx_char" ||
Fn.getName() == "uart_init") {
errs() << "blacklisted: " << Fn.getName() << "\n";
return false;
}
if (ARMHardeningUtil::IskipEnableVerbose)
errs() << "ARMHardening(external, load/store verification): " <<
Fn.getName() << "\n";
for (auto &bb : Fn) {
modified |= loadStoreVerificationBB(bb);
}
if (ARMHardeningUtil::IskipEnableVerbose)
errs() << LoadStoreVerificationPass::MyLoadStoresVerified <<
" load/stores instrumented" << "\n";
return modified;
}
}
FunctionPass *llvm::createLoadStoreVerificationPass() {
return new LoadStoreVerificationPass();
}
| 28.409283 | 128 | 0.615922 | [
"object"
] |
6cf6b27000428eef5c2cee7225d50c161b345607 | 599 | cpp | C++ | DataStructure/Array/64_minimal_path_sum.cpp | xtstc131/mall0x_Leetcode | db528f2a78808d4123785c35218cce00906166dd | [
"MIT"
] | 1 | 2019-12-25T16:19:21.000Z | 2019-12-25T16:19:21.000Z | DataStructure/Array/64_minimal_path_sum.cpp | xtstc131/mall0x_Leetcode | db528f2a78808d4123785c35218cce00906166dd | [
"MIT"
] | null | null | null | DataStructure/Array/64_minimal_path_sum.cpp | xtstc131/mall0x_Leetcode | db528f2a78808d4123785c35218cce00906166dd | [
"MIT"
] | null | null | null | #include "header.hpp"
class Solution
{
public:
int minPathSum(vector<vector<int>> &grid)
{
int m = grid.size();
if (m == 0)
return 0;
int n = grid[0].size();
vector<int> memo(n, INT_MAX);
memo[0] = 0;
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
{
if (j == 0)
{
memo[j] += grid[i][j];
}
else
memo[j] = min(memo[j], memo[j - 1]) + grid[i][j];
}
return memo[n - 1];
}
}; | 23.96 | 69 | 0.347245 | [
"vector"
] |
9f05c14b09fbc6ca69ea20bafc7aa95335e7dcda | 1,913 | cpp | C++ | bin/snp_search/snp_search.cpp | LyonsLab/coge | 1d9a8e84a8572809ee3260ede44290e14de3bdd1 | [
"BSD-2-Clause"
] | 37 | 2015-02-24T18:58:30.000Z | 2021-03-07T21:22:18.000Z | bin/snp_search/snp_search.cpp | LyonsLab/coge | 1d9a8e84a8572809ee3260ede44290e14de3bdd1 | [
"BSD-2-Clause"
] | 12 | 2016-06-09T21:57:00.000Z | 2020-09-11T18:48:51.000Z | bin/snp_search/snp_search.cpp | LyonsLab/coge | 1d9a8e84a8572809ee3260ede44290e14de3bdd1 | [
"BSD-2-Clause"
] | 19 | 2016-03-26T08:15:17.000Z | 2021-04-12T05:03:29.000Z | #include <fstream>
#include <iostream>
#include <string>
#include <string.h>
#include <vector>
using namespace std;
int nth_token(string& s, int n) {
int i = 0;
int total_commas = n - 1;
for (int num_commas=0,l=s.size(); i<l && num_commas<total_commas; i++) {
if (s[i] == ',')
num_commas++;
}
return i;
}
void output(string& line) {
char buf[line.size() + 1];
strcpy(buf, line.c_str());
char* start = buf;
char* l = buf;
int count = 0;
while (*l) {
if (*l == ',') {
count++;
*l = 0;
if (count == 2 || count == 3 || count == 8)
cout << start;
else
cout << '"' << start << '"';
cout << ',';
start = l + 1;
}
l++;
}
cout << '"' << start << "\"\n";
}
void split(char* s, vector<string>& tokens) {
char* p = s + 1;
while (char c = *p) {
if (c == ',') {
tokens.push_back(string(s, p - s));
s = p + 1;
p = s + 1;
} else
p++;
}
tokens.push_back(string(s));
}
// usage: snp_search file chromosome snp_types
// snp_types is comma delimited
int main(int argc, char* argv[]) {
char* chr = argv[2];
int chr_len = strlen(chr);
if (!strcmp(chr, "Any"))
chr = NULL;
vector<string> snp_types;
split(argv[3], snp_types);
string line;
ifstream f (argv[1]);
while (getline(f, line)) {
if (chr)
if (strncmp(line.c_str(), chr, chr_len) || line[chr_len] != ',')
continue;
int fourth_token = nth_token(line, 4);
for (vector<string>::iterator snp_type = snp_types.begin(); snp_type != snp_types.end(); snp_type++) {
char initial = (*snp_type)[0];
char from = 0;
char to;
if (initial != 'd' && initial != 'i') {
from = initial;
to = (*snp_type)[2];
initial = 's';
}
if (line[fourth_token] == initial)
if (from) {
int comma = line.find(',', fourth_token + 4);
if (from == line[comma + 1] && to == line[comma + 3])
output(line);
} else
output(line);
}
}
f.close();
return 0;
}
| 20.569892 | 104 | 0.550444 | [
"vector"
] |
9f06b0d81ced193b852cb20761dfca4fb2bae1c0 | 15,416 | cpp | C++ | packages/Adapters/STKMesh/example/mesh_deformation.cpp | chiao45/DataTransferKit | 51923eb08ccd4c12c5a5ea5f136f5ccbbbeb6243 | [
"BSD-3-Clause"
] | 1 | 2020-07-26T03:50:31.000Z | 2020-07-26T03:50:31.000Z | packages/Adapters/STKMesh/example/mesh_deformation.cpp | chiao45/DataTransferKit | 51923eb08ccd4c12c5a5ea5f136f5ccbbbeb6243 | [
"BSD-3-Clause"
] | null | null | null | packages/Adapters/STKMesh/example/mesh_deformation.cpp | chiao45/DataTransferKit | 51923eb08ccd4c12c5a5ea5f136f5ccbbbeb6243 | [
"BSD-3-Clause"
] | 1 | 2018-07-09T18:39:38.000Z | 2018-07-09T18:39:38.000Z | //---------------------------------------------------------------------------//
/*
Copyright (c) 2012, Stuart R. Slattery
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
*: Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
*: Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
*: Neither the name of the University of Wisconsin - Madison 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.
*/
//---------------------------------------------------------------------------//
/*!
* \file mesh_deformation.cpp
* \author Stuart Slattery
* \brief Mesh deformation example.
*/
//---------------------------------------------------------------------------//
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <sstream>
#include <vector>
#include "DTK_C_API.h"
#include "Teuchos_CommandLineProcessor.hpp"
#include "Teuchos_ParameterList.hpp"
#include "Teuchos_XMLParameterListCoreHelpers.hpp"
#include <Teuchos_Array.hpp>
#include <Teuchos_ArrayRCP.hpp>
#include <Teuchos_CommHelpers.hpp>
#include <Teuchos_DefaultComm.hpp>
#include <Teuchos_DefaultMpiComm.hpp>
#include <Teuchos_GlobalMPISession.hpp>
#include <Teuchos_OpaqueWrapper.hpp>
#include <Teuchos_RCP.hpp>
#include <Teuchos_StandardCatchMacros.hpp>
#include <Teuchos_TimeMonitor.hpp>
#include <Teuchos_TypeTraits.hpp>
#include <Teuchos_VerboseObject.hpp>
#include <Tpetra_MultiVector.hpp>
#include <Intrepid_FieldContainer.hpp>
#include <stk_util/parallel/Parallel.hpp>
#include <stk_mesh/base/BulkData.hpp>
#include <stk_mesh/base/CoordinateSystems.hpp>
#include <stk_mesh/base/Field.hpp>
#include <stk_mesh/base/FieldBase.hpp>
#include <stk_mesh/base/GetEntities.hpp>
#include <stk_mesh/base/MetaData.hpp>
#include <stk_mesh/base/Selector.hpp>
#include <stk_mesh/base/Types.hpp>
#include <stk_topology/topology.hpp>
#include <stk_io/IossBridge.hpp>
#include <stk_io/StkMeshIoBroker.hpp>
#include <Ioss_SubSystem.h>
#include <init/Ionit_Initializer.h>
//---------------------------------------------------------------------------//
// Set displacement field data on the boundary.
void setBoundaryDisplacement( stk::mesh::BulkData &bulk_data,
stk::mesh::Selector &fixed_selector,
stk::mesh::Selector &moving_selector,
stk::mesh::Selector &interior_selector,
Teuchos::Array<double> &coord_field,
Teuchos::Array<double> &displace_field, double ux,
double uy, int &num_boundary, int &num_interior )
{
// Get the fixed boundary nodes.
stk::mesh::BucketVector fixed_part_buckets =
fixed_selector.get_buckets( stk::topology::NODE_RANK );
std::vector<stk::mesh::Entity> fixed_part_nodes;
stk::mesh::get_selected_entities( fixed_selector, fixed_part_buckets,
fixed_part_nodes );
int fixed_num_part_nodes = fixed_part_nodes.size();
// Get the moving boundary nodes.
stk::mesh::BucketVector moving_part_buckets =
moving_selector.get_buckets( stk::topology::NODE_RANK );
std::vector<stk::mesh::Entity> moving_part_nodes;
stk::mesh::get_selected_entities( moving_selector, moving_part_buckets,
moving_part_nodes );
int moving_num_part_nodes = moving_part_nodes.size();
// Get the number of boundary nodes.
num_boundary = fixed_num_part_nodes + moving_num_part_nodes;
// Get the interior nodes.
stk::mesh::BucketVector interior_part_buckets =
interior_selector.get_buckets( stk::topology::NODE_RANK );
std::vector<stk::mesh::Entity> interior_part_nodes;
stk::mesh::get_selected_entities( interior_selector, interior_part_buckets,
interior_part_nodes );
num_interior = interior_part_nodes.size();
// Allocate
int total_num_nodes = num_boundary + num_interior;
coord_field.resize( 3 * total_num_nodes );
displace_field.resize( 3 * total_num_nodes );
// NOTE: The mesh is actually 3D.
// Get the coordinate field.
const stk::mesh::FieldBase *coord_data_base =
bulk_data.mesh_meta_data().coordinate_field();
const stk::mesh::Field<double, stk::mesh::Cartesian3d> *coord_data =
dynamic_cast<const stk::mesh::Field<double, stk::mesh::Cartesian3d> *>(
coord_data_base );
double *coords;
// Create an offset. f is an offset here. its used to index into a global
// array. The coordinate array is broken up into chunks of the fixed
// boundary, moving boundary, and interior node. The coordinates and
// displacements for these exist in different STK mesh parts so we break
// the coordinate and field assignment into loops over nodes in each part.
int f = 0;
// Get the fixed data.
for ( int n = 0; n < fixed_num_part_nodes; ++n )
{
f = n;
displace_field[f * 3] = 0.0;
displace_field[f * 3 + 1] = 0.0;
coords = stk::mesh::field_data( *coord_data, fixed_part_nodes[n] );
coord_field[f * 3] = coords[0];
coord_field[f * 3 + 1] = coords[1];
}
// Get the moving data.
for ( int n = 0; n < moving_num_part_nodes; ++n )
{
f = n + fixed_num_part_nodes;
displace_field[f * 3] = ux;
displace_field[f * 3 + 1] = uy;
coords = stk::mesh::field_data( *coord_data, moving_part_nodes[n] );
coord_field[f * 3] = coords[0];
coord_field[f * 3 + 1] = coords[1];
}
// Get the interior data.
for ( int n = 0; n < num_interior; ++n )
{
f = n + num_boundary;
displace_field[f * 3] = 0.0;
displace_field[f * 3 + 1] = 0.0;
coords = stk::mesh::field_data( *coord_data, interior_part_nodes[n] );
coord_field[f * 3] = coords[0];
coord_field[f * 3 + 1] = coords[1];
}
}
//---------------------------------------------------------------------------//
// Deform the mesh.
void deformMesh( stk::mesh::BulkData &bulk_data,
stk::mesh::Selector &fixed_selector,
stk::mesh::Selector &moving_selector,
stk::mesh::Selector &interior_selector,
Teuchos::Array<double> &displace_field )
{
// Get the fixed boundary nodes.
stk::mesh::BucketVector fixed_part_buckets =
fixed_selector.get_buckets( stk::topology::NODE_RANK );
std::vector<stk::mesh::Entity> fixed_part_nodes;
stk::mesh::get_selected_entities( fixed_selector, fixed_part_buckets,
fixed_part_nodes );
int fixed_num_part_nodes = fixed_part_nodes.size();
// Get the moving boundary nodes.
stk::mesh::BucketVector moving_part_buckets =
moving_selector.get_buckets( stk::topology::NODE_RANK );
std::vector<stk::mesh::Entity> moving_part_nodes;
stk::mesh::get_selected_entities( moving_selector, moving_part_buckets,
moving_part_nodes );
int moving_num_part_nodes = moving_part_nodes.size();
// Get the number of boundary nodes.
int num_boundary_nodes = fixed_num_part_nodes + moving_num_part_nodes;
// Get the interior nodes.
stk::mesh::BucketVector interior_part_buckets =
interior_selector.get_buckets( stk::topology::NODE_RANK );
std::vector<stk::mesh::Entity> interior_part_nodes;
stk::mesh::get_selected_entities( interior_selector, interior_part_buckets,
interior_part_nodes );
int interior_num_part_nodes = interior_part_nodes.size();
// Get the coordinate field.
const stk::mesh::FieldBase *coord_field_base =
bulk_data.mesh_meta_data().coordinate_field();
const stk::mesh::Field<double, stk::mesh::Cartesian3d> *coord_field =
dynamic_cast<const stk::mesh::Field<double, stk::mesh::Cartesian3d> *>(
coord_field_base );
double *coords;
// Get the fixed boundary node coordinates.
int f = 0;
for ( int n = 0; n < fixed_num_part_nodes; ++n )
{
f = n;
coords = stk::mesh::field_data( *coord_field, fixed_part_nodes[n] );
coords[0] += displace_field[f * 3];
coords[1] += displace_field[f * 3 + 1];
}
// NOTE: Recall mesh is 3D despite what the filename might say...
// Get the moving boundary node coordinates.
for ( int n = 0; n < moving_num_part_nodes; ++n )
{
f = n + fixed_num_part_nodes;
coords = stk::mesh::field_data( *coord_field, moving_part_nodes[n] );
coords[0] += displace_field[f * 3];
coords[1] += displace_field[f * 3 + 1];
}
// Get the interior node coordinates.
for ( int n = 0; n < interior_num_part_nodes; ++n )
{
f = n + num_boundary_nodes;
coords = stk::mesh::field_data( *coord_field, interior_part_nodes[n] );
coords[0] += displace_field[f * 3];
coords[1] += displace_field[f * 3 + 1];
}
}
//---------------------------------------------------------------------------//
// Example driver.
//
// This example takes a mesh (mesh_deform_2d.exo) and deforms it based on the
// movement of nodes on the interior boundary using spline interpolation. The
// exterior boundary nodes of the mesh are fixed. This technique is originally
// described in:
//
// A. Boer, M. vand er Schoot, and H. Bijl, "Mesh deformation based on radial
// basis function interpolation", Computers and Structures, vol 85,
// pp. 784-795, 2007.
//
// To execute the driver run:
//
// ./DataTransferKitSTKMeshAdapters_STKMeshDeformation.exe
//
//---------------------------------------------------------------------------//
int main( int argc, char *argv[] )
{
// INITIALIZATION
// --------------
// Setup communication.
Teuchos::GlobalMPISession mpiSession( &argc, &argv );
Teuchos::RCP<const Teuchos::Comm<int>> comm =
Teuchos::DefaultComm<int>::getComm();
// Set the mesh i/o data.
std::string mesh_input_file = "mesh_deform_2d.exo";
std::string mesh_output_file = "mesh_deform_2d_out.exo";
std::string part_name = "domain";
std::string fixed_bnd_name = "fixed_boundary";
std::string moving_bnd_name = "moving_boundary";
// Get the raw mpi communicator (basic typedef in STK).
Teuchos::RCP<const Teuchos::MpiComm<int>> mpi_comm =
Teuchos::rcp_dynamic_cast<const Teuchos::MpiComm<int>>( comm );
Teuchos::RCP<const Teuchos::OpaqueWrapper<MPI_Comm>> opaque_comm =
mpi_comm->getRawMpiComm();
stk::ParallelMachine parallel_machine = ( *opaque_comm )();
// MESH READ
// ----------------
// Load the mesh.
stk::io::StkMeshIoBroker broker( parallel_machine );
std::size_t input_index = broker.add_mesh_database(
mesh_input_file, "exodus", stk::io::READ_MESH );
broker.set_active_mesh( input_index );
broker.create_input_mesh();
// Get the domain part.
stk::mesh::Part *part = broker.meta_data().get_part( part_name );
stk::mesh::Selector global_selector( *part );
// Create the source bulk data.
broker.populate_bulk_data();
Teuchos::RCP<stk::mesh::BulkData> bulk_data =
Teuchos::rcpFromRef( broker.bulk_data() );
// DISPLACEMENT SETUP
// ------------------
// Fixed boundary does not move.
stk::mesh::Part *fixed_bnd_part =
broker.meta_data().get_part( fixed_bnd_name );
stk::mesh::Selector fixed_selector( *fixed_bnd_part );
// Moving boundary moves.
stk::mesh::Part *moving_bnd_part =
broker.meta_data().get_part( moving_bnd_name );
stk::mesh::Selector moving_selector( *moving_bnd_part );
// Get the interior.
stk::mesh::Selector interior_selector =
global_selector - fixed_selector - moving_selector;
// Define the displacement for the interior boundary. The exterior
// boundary will not move.
double ux = 1.0;
double uy = 1.0;
// Set the displacement.
Teuchos::Array<double> coord_field;
Teuchos::Array<double> displace_field;
int num_boundary = 0;
int num_interior = 0;
setBoundaryDisplacement( *bulk_data, fixed_selector, moving_selector,
interior_selector, coord_field, displace_field, ux,
uy, num_boundary, num_interior );
// DISPLACEMENT TRANSFER SETUP
// ---------------------------
// Use spline interpolation and a fairly large radius for a smooth
// deformation of the mesh.
std::string options =
"{ \"Map Type\": \"Spline Interpolation\", \"RBF Radius\": \"4.0\" }";
// Create the map between the boundary nodes and the interior nodes.
DTK_Map *map = DTK_Map_create(
parallel_machine, coord_field( 0, 3 * num_boundary ).getRawPtr(),
num_boundary, DTK_INTERLEAVED,
coord_field( 3 * num_boundary, 3 * num_interior ).getRawPtr(),
num_interior, DTK_INTERLEAVED, 3, options.c_str() );
// NOTE: The mesh is 3D!
// DISPLACEMENT TRANSFER
// ---------------------
// Apply the map to transfer the displacement from the boundary nodes to
// the interior nodes.
DTK_Map_apply(
map, displace_field( 0, 3 * num_boundary ).getRawPtr(), DTK_INTERLEAVED,
displace_field( 3 * num_boundary, 3 * num_interior ).getRawPtr(),
DTK_INTERLEAVED, 3, false );
// cleanup
DTK_Map_delete( map );
// MESH DEFORMATION
// ----------------
// Apply the deformed coordinate field to the STK mesh
deformMesh( *bulk_data, fixed_selector, moving_selector, interior_selector,
displace_field );
// DEFORMED MESH WRITE
// -------------------
// Write the STK mesh to file. Visualize to see the deformation.
std::size_t output_index =
broker.create_output_mesh( mesh_output_file, stk::io::WRITE_RESULTS );
broker.begin_output_step( output_index, 0.0 );
broker.end_output_step( output_index );
}
//---------------------------------------------------------------------------//
// end tstSTK_Mesh.cpp
//---------------------------------------------------------------------------//
| 38.158416 | 80 | 0.63499 | [
"mesh",
"vector",
"3d"
] |
9f09e0b5a3b7c45f997bf2c0a09fcee84e0732a4 | 1,215 | hh | C++ | L1Trigger/Phase2L1Taus/interface/L1NNTauProducer.hh | thesps/cmssw | ad5315934948ce96699b29cc1d5b03a59f99634f | [
"Apache-2.0"
] | null | null | null | L1Trigger/Phase2L1Taus/interface/L1NNTauProducer.hh | thesps/cmssw | ad5315934948ce96699b29cc1d5b03a59f99634f | [
"Apache-2.0"
] | null | null | null | L1Trigger/Phase2L1Taus/interface/L1NNTauProducer.hh | thesps/cmssw | ad5315934948ce96699b29cc1d5b03a59f99634f | [
"Apache-2.0"
] | null | null | null | #ifndef L1TRIGGER_PHASE2L1TAU_L1NNTAU_H
#define L1TRIGGER_PHASE2L1TAU_L1NNTAU_H
#include <iostream>
#include <vector>
#include <TLorentzVector.h>
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/stream/EDProducer.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "DataFormats/Phase2L1ParticleFlow/interface/PFTau.h"
#include "DataFormats/Phase2L1ParticleFlow/interface/PFCandidate.h"
#include "L1Trigger/Phase2L1Taus/interface/TauNNId.h"
using namespace l1t;
class L1NNTauProducer : public edm::stream::EDProducer<> {
public:
explicit L1NNTauProducer(const edm::ParameterSet&);
~L1NNTauProducer();
private:
TauNNId *fTauNNId;
void addTau(l1t::PFCandidate &iCand,const l1t::PFCandidateCollection &iParts, std::unique_ptr<PFTauCollection> &outputTaus);
float deltaR(auto iPart1, auto iPart2);
virtual void produce( edm::Event& iEvent, const edm::EventSetup& iSetup ) override;
double fSeedPt;
double fConeSize;
double fTauSize;
int fMaxTaus;
int fNParticles;
edm::EDGetTokenT< vector<l1t::PFCandidate> > fL1PFToken;
};
#endif
| 28.928571 | 126 | 0.790947 | [
"vector"
] |
9f0f803c82709779da414f6f6a79ae69114fe84e | 2,265 | cpp | C++ | geode/openmesh/decimate.cpp | otherlab/geode | 18ccf114f02ca733a92b223541161f0405f12535 | [
"BSD-3-Clause"
] | 75 | 2015-02-08T22:04:31.000Z | 2022-02-26T14:31:43.000Z | geode/openmesh/decimate.cpp | bantamtools/geode | d906f1230b14953b68af63aeec2f7b0418d5fdfd | [
"BSD-3-Clause"
] | 15 | 2015-01-08T15:11:38.000Z | 2021-09-05T13:27:22.000Z | geode/openmesh/decimate.cpp | bantamtools/geode | d906f1230b14953b68af63aeec2f7b0418d5fdfd | [
"BSD-3-Clause"
] | 22 | 2015-03-11T16:43:13.000Z | 2021-02-15T09:37:51.000Z | #include <geode/config.h>
#ifdef GEODE_OPENMESH
#include <geode/openmesh/decimate.h>
#include <OpenMesh/Tools/Decimater/ModQuadricT.hh>
#include <OpenMesh/Tools/Decimater/ModNormalFlippingT.hh>
#include <OpenMesh/Tools/Decimater/ModBaseT.hh>
#include <geode/geometry/Triangle3d.h>
#include <geode/python/wrap.h>
namespace geode {
typedef real T;
typedef Vector<T,3> TV;
template class FaceQualityModule<DecimaterT>;
template class BoundaryPreservationModule<DecimaterT>;
int decimate(TriMesh &mesh, int max_collapses, double maxangleerror, double maxquadricerror, double min_face_quality) {
// need normals for this
mesh.request_face_normals();
mesh.update_face_normals();
DecimaterT decimater(mesh);
// module types
typedef OpenMesh::Decimater::ModNormalFlippingT<DecimaterT>::Handle HModNormalFlipping;
typedef OpenMesh::Decimater::ModQuadricT<DecimaterT>::Handle HModQuadric;
// Quadric
HModQuadric hModQuadric;
decimater.add(hModQuadric);
if (maxquadricerror == std::numeric_limits<double>::infinity())
decimater.module(hModQuadric).unset_max_err(); // use only as priority
else
decimater.module(hModQuadric).set_max_err(sqr(maxquadricerror));
// prevent ruining the boundary
BoundaryPreservationModule<DecimaterT>::Handle hModBoundary;
decimater.add(hModBoundary);
decimater.module(hModBoundary).set_max_error(maxquadricerror);
// prevent creation of crappy triangles
if (min_face_quality > 0.) {
FaceQualityModule<DecimaterT>::Handle hModFaceQuality;
decimater.add(hModFaceQuality);
decimater.module(hModFaceQuality).min_quality(min_face_quality);
}
// normal change termination criterion
if (maxangleerror > 0.) {
HModNormalFlipping hModNormalFlipping;
decimater.add(hModNormalFlipping);
decimater.module(hModNormalFlipping).set_normal_deviation((float)maxangleerror);
}
if (!decimater.initialize()) {
std::cerr << "ERROR: could not initialize decimation." << std::endl;
return 0;
}
const int count = (int) decimater.decimate(max_collapses);
mesh.release_face_normals();
mesh.garbage_collection();
return count;
}
}
using namespace geode;
void wrap_openmesh_decimate() {
GEODE_FUNCTION_2(decimate_openmesh,decimate)
}
#endif // GEODE_OPENMESH
| 29.415584 | 119 | 0.769978 | [
"mesh",
"geometry",
"vector"
] |
2f64d8a909a159ed112066bacd3c0d94840d8a4b | 9,649 | cc | C++ | tools/festvox/src/vc/src/sub/anasyn_sub.cc | jantunez14/merlin | 66d602919aa8d3ca20b77d4515b8214b5b1be508 | [
"Apache-2.0"
] | 4 | 2015-05-14T20:44:23.000Z | 2019-02-22T21:05:52.000Z | festvox/src/vc/src/sub/anasyn_sub.cc | zeehio/festival_suite | 9f555b42f0ba7432a52ba1c8f26cf7482950e38b | [
"BSD-3-Clause"
] | 3 | 2020-06-05T18:09:02.000Z | 2021-06-10T20:06:02.000Z | festvox/src/vc/src/sub/anasyn_sub.cc | zeehio/festival_suite | 9f555b42f0ba7432a52ba1c8f26cf7482950e38b | [
"BSD-3-Clause"
] | null | null | null | /*********************************************************************/
/* */
/* Nagoya Institute of Technology, Aichi, Japan, */
/* Nara Institute of Science and Technology, Nara, Japan */
/* and */
/* Carnegie Mellon University, Pittsburgh, PA */
/* Copyright (c) 2003-2004 */
/* All Rights Reserved. */
/* */
/* Permission is hereby granted, free of charge, to use and */
/* distribute this software and its documentation without */
/* restriction, including without limitation the rights to use, */
/* copy, modify, merge, publish, distribute, sublicense, and/or */
/* sell copies of this work, and to permit persons to whom this */
/* work is furnished to do so, subject to the following conditions: */
/* */
/* 1. The code must retain the above copyright notice, this list */
/* of conditions and the following disclaimer. */
/* 2. Any modifications must be clearly marked as such. */
/* 3. Original authors' names are not deleted. */
/* */
/* NAGOYA INSTITUTE OF TECHNOLOGY, NARA INSTITUTE OF SCIENCE AND */
/* TECHNOLOGY, CARNEGIE MELLON UNIVERSITY, AND THE CONTRIBUTORS TO */
/* THIS WORK DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, */
/* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, */
/* IN NO EVENT SHALL NAGOYA INSTITUTE OF TECHNOLOGY, NARA */
/* INSTITUTE OF SCIENCE AND TECHNOLOGY, CARNEGIE MELLON UNIVERSITY, */
/* NOR THE CONTRIBUTORS BE LIABLE FOR ANY SPECIAL, INDIRECT OR */
/* CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM */
/* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, */
/* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN */
/* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
/* */
/*********************************************************************/
/* */
/* Author : Tomoki Toda (tomoki@ics.nitech.ac.jp) */
/* Date : June 2004 */
/* */
/*-------------------------------------------------------------------*/
/* */
/* Analysis-synthesis subroutine */
/* */
/*-------------------------------------------------------------------*/
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "../include/basic.h"
#include "../include/fileio.h"
#include "../include/filter.h"
#include "../include/memory.h"
#include "../include/option.h"
#include "../include/voperate.h"
#include "sptk_sub.h"
#include "anasyn_sub.h"
// read header of wav file
char *xreadheader_wav(char *filename)
{
char *header = NULL;
FILE *fp;
// memory allocate
if ((header = (char *)malloc((int)44 * sizeof(char))) == NULL) {
fprintf(stderr, "Read header: Memory allcation is failed\n");
exit(0);
}
// open file
if (NULL == (fp = fopen(filename, "rb"))) {
fprintf(stderr, "can't open file: %s\n", filename);
return NULL;
}
// read data
fread(header, sizeof(char), (int)44, fp);
// close file
fclose(fp);
return header;
}
// write header of wav file
void writessignal_wav(char *filename, SVECTOR vector, double fs)
{
char riff[5] = "RIFF";
char riffsize[4] = "";
char wave[5] = "WAVE";
char fmt[5] = "fmt ";
char fmtsize[4] = "";
unsigned short format = 1;
unsigned short channel = 1;
char sampling[4] = "";
char bps[4] = "";
char block = 2;
char dummy1 = 0;
char bit = 16;
char dummy2 = 0;
char data[5] = "data";
char datasize[4] = "";
unsigned long tmp;
FILE *fp;
fmtsize[3] = 0x00; fmtsize[2] = 0x00;
fmtsize[1] = 0x00; fmtsize[0] = 0x10;
tmp = (unsigned long)(vector->length * 2);
datasize[3] = (char)(tmp >> 24); datasize[2] = (char)(tmp >> 16);
datasize[1] = (char)(tmp >> 8); datasize[0] = (char)tmp;
tmp += (unsigned long)36;
riffsize[3] = (char)(tmp >> 24); riffsize[2] = (char)(tmp >> 16);
riffsize[1] = (char)(tmp >> 8); riffsize[0] = (char)tmp;
tmp = (unsigned long)fs;
sampling[3] = (char)(tmp >> 24); sampling[2] = (char)(tmp >> 16);
sampling[1] = (char)(tmp >> 8); sampling[0] = (char)tmp;
tmp += tmp;
bps[3] = (char)(tmp >> 24); bps[2] = (char)(tmp >> 16);
bps[1] = (char)(tmp >> 8); bps[0] = (char)tmp;
// open file
check_dir(filename);
if (NULL == (fp = fopen(filename, "wb"))) {
fprintf(stderr, "can't open file: %s\n", filename);
return;
}
// write header
fwrite(riff, sizeof(char), 4, fp);
fwrite(riffsize, sizeof(char), 4, fp);
fwrite(wave, sizeof(char), 4, fp);
fwrite(fmt, sizeof(char), 4, fp);
fwrite(fmtsize, sizeof(char), 4, fp);
fwrite(&format, sizeof(unsigned short), 1, fp);
fwrite(&channel, sizeof(unsigned short), 1, fp);
fwrite(sampling, sizeof(char), 4, fp);
fwrite(bps, sizeof(char), 4, fp);
fwrite(&block, sizeof(char), 1, fp);
fwrite(&dummy1, sizeof(char), 1, fp);
fwrite(&bit, sizeof(char), 1, fp);
fwrite(&dummy2, sizeof(char), 1, fp);
fwrite(data, sizeof(char), 4, fp);
fwrite(datasize, sizeof(char), 4, fp);
// write data
fwriteshort(vector->data, vector->length, 0, fp);
// close file
if (fp != stdout)
fclose(fp);
return;
}
void check_header(char *file, double *fs, XBOOL *float_flag, XBOOL msg_flag)
{
char *header = NULL;
// get header
if ((header = xreadheader_wav(file)) == NULL) {
fprintf(stderr, "Can't read header %s\n", file);
exit(1);
}
// read header-information
if ((strncmp(header, "RIFF", 4) != 0 ||
strncmp(header + 8, "WAVE", 4) != 0) ||
(strncmp(header + 12, "fmt", 3) != 0 ||
strncmp(header + 36, "data", 4) != 0)) {
fprintf(stderr, "no wav file: %s\n", file);
exit(1);
} else {
if (fs != NULL) {
*fs = (double)(((((header[27] << 24) & 0xff000000) |
((header[26] << 16) & 0xff0000))) |
((((header[25] << 8) & 0xff00) |
((header[24]) & 0xff))));
if (msg_flag == XTRUE)
fprintf(stderr, "Sampling frequency %5.0f [Hz]\n", *fs);
}
}
if (header[34] == 16) {
if (msg_flag == XTRUE) fprintf(stderr, "16bit short wave\n");
*float_flag = XFALSE;
} else if (header[34] == 32) {
if (msg_flag == XTRUE) fprintf(stderr, "32bit float wave\n");
*float_flag = XTRUE;
} else {
fprintf(stderr, "no wav file: %s\n", file);
fprintf(stderr, "Please use this type: signed 16 bit or float 32 bit\n");
exit(1);
}
xfree(header);
return;
}
DVECTOR xread_wavfile(char *file, double *fs, XBOOL msg_flag)
{
long headlen = 44;
SVECTOR xs = NODATA;
FVECTOR xf = NODATA;
DVECTOR xd = NODATA;
XBOOL float_flag = XFALSE;
// read header
check_header(file, fs, &float_flag, msg_flag);
// read waveform
if (float_flag == XFALSE) {
// read short wave data
if ((xs = xreadssignal(file, headlen, 0)) == NODATA) {
exit(1);
} else {
xd = xsvtod(xs); xsvfree(xs);
}
} else {
// read float wave data
if ((xf = xreadfsignal(file, headlen, 0)) == NODATA) {
exit(1);
} else {
xd = xfvtod(xf); xfvfree(xf);
dvscoper(xd, "*", 32000.0);
}
}
if (msg_flag == XTRUE) fprintf(stderr, "read wave: %s\n", file);
return xd;
}
// cut low noise (f < f0floor)
void cleaninglownoise(DVECTOR x,
double fs,
double f0floor)
{
long nn, flp, k;
double flm;
DVECTOR wlp = NODATA;
DVECTOR tx = NODATA;
DVECTOR ttx = NODATA;
flm = 50.0;
flp = (long)round(fs * flm / 1000.0);
nn = x->length;
wlp = fir1(flp * 2, f0floor / (fs / 2.0));
wlp->data[flp] = wlp->data[flp] - 1.0;
dvscoper(wlp, "*", -1.0);
tx = xdvzeros(x->length + 2 * wlp->length);
dvcopy(tx, x);
ttx = xdvfftfiltm(wlp, tx, wlp->length * 2);
for (k = 0; k < nn; k++) x->data[k] = ttx->data[k + flp];
// memory free
xdvfree(wlp);
xdvfree(tx);
xdvfree(ttx);
return;
}
// lowpass FIR digital filter by using Hamming window
DVECTOR fir1(long len, // return [length + 1]
double cutoff) // cut-off frequency
{
long k, length;
double half;
double value, a;
DVECTOR filter;
// 0 <= cufoff <= 1
cutoff = MIN(cutoff, 1.0);
cutoff = MAX(cutoff, 0.0);
half = (double)len / 2.0;
length = len + 1;
// memory allocate
filter = xdvalloc(length);
// hamming window
for (k = 0; k < length; k++) {
filter->data[k] = 0.54 - 0.46 * cos(2.0 * PI * (double)k / (double)(length - 1));
}
// calculate lowpass filter
for (k = 0; k < length; k++) {
a = PI * ((double)k - half);
if (a == 0.0) {
value = cutoff;
} else {
value = sin(PI * cutoff * ((double)k - half)) / a;
}
filter->data[k] *= value;
}
return filter;
}
| 31.636066 | 82 | 0.510312 | [
"vector"
] |
2f6b79ea7558b4548782342fca84b94511c521ca | 8,646 | cpp | C++ | Source/Engine/Renderer/Scene/Scene.cpp | yuvanw/ViceEngine | 7259b53483b3d5a516182c9ded42a3c5219ba66f | [
"MIT"
] | null | null | null | Source/Engine/Renderer/Scene/Scene.cpp | yuvanw/ViceEngine | 7259b53483b3d5a516182c9ded42a3c5219ba66f | [
"MIT"
] | null | null | null | Source/Engine/Renderer/Scene/Scene.cpp | yuvanw/ViceEngine | 7259b53483b3d5a516182c9ded42a3c5219ba66f | [
"MIT"
] | null | null | null | #include "Scene.h"
#include "SceneFile.h"
FScene::FScene(const FStringId& InSceneFileName)
{
// Parse .scn file.
FSceneFile SceneFile(InSceneFileName);
// Create skybox if one was specified.
if (SceneFile.bHasSkybox)
{
const ANSICHAR* SkyboxName = SceneFile.Skybox.Name.GetString().GetData();
FCubemap Cubemap(
SceneFile.Skybox.RightTextureFileName.GetString().GetData(),
SceneFile.Skybox.LeftTextureFileName.GetString().GetData(),
SceneFile.Skybox.TopTextureFileName.GetString().GetData(),
SceneFile.Skybox.BottomTextureFileName.GetString().GetData(),
SceneFile.Skybox.BackTextureFileName.GetString().GetData(),
SceneFile.Skybox.FrontTextureFileName.GetString().GetData()
);
TSharedPtr<FSkybox> Skybox = MakeShared<FSkybox>(SkyboxName, Cubemap);
SetSkybox(Skybox);
}
// Create directional lights.
for (const FDirectionalLightInfo& DirectionalLightInfo : SceneFile.DirectionalLights)
{
TSharedPtr<FDirectionalLight> DirectionalLight = MakeShared<FDirectionalLight>
(
DirectionalLightInfo.Name,
DirectionalLightInfo.Direction,
DirectionalLightInfo.Color,
DirectionalLightInfo.Intensity
);
AddDirectionalLight(DirectionalLight);
}
// Create point lights.
for (const FPointLightInfo& PointLightInfo : SceneFile.PointLights)
{
TSharedPtr<FPointLight> PointLight = MakeShared<FPointLight>
(
PointLightInfo.Name,
PointLightInfo.Position,
PointLightInfo.Color,
PointLightInfo.Intensity,
FAttenuation
(
PointLightInfo.Attenuation.Constant,
PointLightInfo.Attenuation.Linear,
PointLightInfo.Attenuation.Quadratic
)
);
AddPointLight(PointLight);
}
// Create models.
for (const FModelInfo& ModelInfo : SceneFile.Models)
{
float RotationRadiansX = FMath::DegreesToRadians(ModelInfo.Transform.Rotation.X);
float RotationRadiansY = FMath::DegreesToRadians(ModelInfo.Transform.Rotation.Y);
float RotationRadiansZ = FMath::DegreesToRadians(ModelInfo.Transform.Rotation.Z);
FVector3D Rotation = { RotationRadiansX, RotationRadiansY, RotationRadiansZ };
TSharedPtr<FModel> Model = MakeShared<FModel>(ModelInfo.Name.GetString().GetData(), ModelInfo.FileName.GetString().GetData());
Model->SetPosition(ModelInfo.Transform.Position);
Model->SetRotation(Rotation);
Model->SetScale(ModelInfo.Transform.Scale);
AddModel(Model);
}
}
void FScene::SetSkybox(const TSharedPtr<FSkybox>& InSkybox)
{
if (InSkybox)
{
FSetScene<FSkybox>(*InSkybox, *this);
}
Skybox = InSkybox;
}
void FScene::AddModel(const TSharedPtr<FModel>& InModel)
{
FSetScene<FModel>(*InModel, *this);
VisibleModels.Add(InModel);
}
void FScene::AddModel(const FStringId& InModelName, const FStringId& InModelFileName)
{
TSharedPtr<FModel> Model = MakeShared<FModel>(InModelName, InModelFileName);
FSetScene<FModel>(*Model, *this);
VisibleModels.Add(Model);
}
void FScene::AddDirectionalLight(const TSharedPtr<FDirectionalLight>& InDirectionalLight)
{
FSetScene<FDirectionalLight>(*InDirectionalLight, *this);
VisibleDirectionalLights.Add(InDirectionalLight);
}
void FScene::AddPointLight(const TSharedPtr<FPointLight>& InPointLight)
{
FSetScene<FPointLight>(*InPointLight, *this);
VisiblePointLights.Add(InPointLight);
}
bool FScene::RemoveModel(const TSharedPtr<FModel>& InModel)
{
// Try removing model from VisibleModels. If it isn't in VisibleModels, try removing it from InvisibleModels.
return VisibleModels.RemoveFirst(InModel) || InvisibleModels.RemoveFirst(InModel);
}
bool FScene::RemoveDirectionalLight(const TSharedPtr<FDirectionalLight>& InDirectionalLight)
{
return VisibleDirectionalLights.RemoveFirst(InDirectionalLight) || InvisibleDirectionalLights.RemoveFirst(InDirectionalLight);
}
bool FScene::RemovePointLight(const TSharedPtr<FPointLight>& InPointLight)
{
return VisiblePointLights.RemoveFirst(InPointLight) || InvisiblePointLights.RemoveFirst(InPointLight);
}
void FScene::SetModelVisible(const FStringId& InModelName)
{
const TSharedPtr<FModel>* ModelPtr = InvisibleModels.FindByPredicate(
[&InModelName](const TSharedPtr<FModel>& InModel)
{
return InModel->GetName() == InModelName;
}
);
if (ModelPtr)
{
const TSharedPtr<FModel>& Model = *ModelPtr;
VisibleModels.Add(Model);
InvisibleModels.RemoveFirst(Model);
}
}
void FScene::SetModelInvisible(const FStringId& InModelName)
{
const TSharedPtr<FModel>* ModelPtr = VisibleModels.FindByPredicate(
[&InModelName](const TSharedPtr<FModel>& InModel)
{
return InModel->GetName() == InModelName;
}
);
if (ModelPtr)
{
const TSharedPtr<FModel>& Model = *ModelPtr;
InvisibleModels.Add(Model);
VisibleModels.RemoveFirst(Model);
}
}
void FScene::SetDirectionalLightVisible(const FStringId& InDirectionalLightName)
{
const TSharedPtr<FDirectionalLight>* DirectionalLightPtr = InvisibleDirectionalLights.FindByPredicate(
[&InDirectionalLightName](const TSharedPtr<FDirectionalLight>& InDirectionalLight)
{
return InDirectionalLight->GetName() == InDirectionalLightName;
}
);
if (DirectionalLightPtr)
{
const TSharedPtr<FDirectionalLight>& DirectionalLight = *DirectionalLightPtr;
VisibleDirectionalLights.Add(DirectionalLight);
InvisibleDirectionalLights.RemoveFirst(DirectionalLight);
}
}
void FScene::SetDirectionalLightInvisible(const FStringId& InDirectionalLightName)
{
const TSharedPtr<FDirectionalLight>* DirectionalLightPtr = VisibleDirectionalLights.FindByPredicate(
[&InDirectionalLightName](const TSharedPtr<FDirectionalLight>& InDirectionalLight)
{
return InDirectionalLight->GetName() == InDirectionalLightName;
}
);
if (DirectionalLightPtr)
{
const TSharedPtr<FDirectionalLight>& DirectionalLight = *DirectionalLightPtr;
InvisibleDirectionalLights.Add(DirectionalLight);
VisibleDirectionalLights.RemoveFirst(DirectionalLight);
}
}
void FScene::SetPointLightVisible(const FStringId& InPointLightName)
{
const TSharedPtr<FPointLight>* PointLightPtr = InvisiblePointLights.FindByPredicate(
[&InPointLightName](const TSharedPtr<FPointLight>& InPointLight)
{
return InPointLight->GetName() == InPointLightName;
}
);
if (PointLightPtr)
{
const TSharedPtr<FPointLight>& PointLight = *PointLightPtr;
VisiblePointLights.Add(PointLight);
InvisiblePointLights.RemoveFirst(PointLight);
}
}
void FScene::SetPointLightInvisible(const FStringId& InPointLightName)
{
const TSharedPtr<FPointLight>* PointLightPtr = VisiblePointLights.FindByPredicate(
[&InPointLightName](const TSharedPtr<FPointLight>& InPointLight)
{
return InPointLight->GetName() == InPointLightName;
}
);
if (PointLightPtr)
{
const TSharedPtr<FPointLight>& PointLight = *PointLightPtr;
InvisiblePointLights.Add(PointLight);
VisiblePointLights.RemoveFirst(PointLight);
}
}
bool FScene::IsModelVisible(const FStringId& InModelName)
{
return VisibleModels.IsContainedByPredicate(
[&InModelName](const TSharedPtr<FModel>& InModel)
{
return InModel->GetName() == InModelName;
}
);
}
bool FScene::IsDirectionalLightVisible(const FStringId& InDirectionalLightName)
{
return VisibleDirectionalLights.IsContainedByPredicate(
[&InDirectionalLightName](const TSharedPtr<FDirectionalLight>& InDirectionalLight)
{
return InDirectionalLight->GetName() == InDirectionalLightName;
}
);
}
bool FScene::IsPointLightVisible(const FStringId& InPointLightName)
{
return VisiblePointLights.IsContainedByPredicate(
[&InPointLightName](const TSharedPtr<FPointLight>& InPointLight)
{
return InPointLight->GetName() == InPointLightName;
}
);
}
bool FScene::IsModelContained(const FStringId& InModelName)
{
auto IsSameName = [&InModelName](const TSharedPtr<FModel>& InModel)
{
return InModel->GetName() == InModelName;
};
// First check if the model is in VisibleModels, then check if it's in InvisibleModels.
return VisibleModels.IsContainedByPredicate(IsSameName) || InvisibleModels.IsContainedByPredicate(IsSameName);
}
bool FScene::IsDirectionalLightContained(const FStringId& InDirectionalLightName)
{
auto IsSameName = [&InDirectionalLightName](const TSharedPtr<FDirectionalLight>& InDirectionalLight)
{
return InDirectionalLight->GetName() == InDirectionalLightName;
};
return VisibleDirectionalLights.IsContainedByPredicate(IsSameName) || InvisibleDirectionalLights.IsContainedByPredicate(IsSameName);
}
bool FScene::IsPointLightContained(const FStringId& InPointLightName)
{
auto IsSameName = [&InPointLightName](const TSharedPtr<FPointLight>& InPointLight)
{
return InPointLight->GetName() == InPointLightName;
};
return VisiblePointLights.IsContainedByPredicate(IsSameName) || InvisiblePointLights.IsContainedByPredicate(IsSameName);
}
| 30.336842 | 133 | 0.784872 | [
"model",
"transform"
] |
2f6ea168f3280e84eddfd091c76f7d249a88c496 | 3,062 | cpp | C++ | src/common.cpp | kamdiedrich/clpeak | 8edab23fbc867adbada21378d65774c670c2aaf9 | [
"Unlicense"
] | null | null | null | src/common.cpp | kamdiedrich/clpeak | 8edab23fbc867adbada21378d65774c670c2aaf9 | [
"Unlicense"
] | null | null | null | src/common.cpp | kamdiedrich/clpeak | 8edab23fbc867adbada21378d65774c670c2aaf9 | [
"Unlicense"
] | null | null | null | #include <common.h>
#include <math.h>
#include <iostream>
#include <string>
using namespace std;
device_info_t getDeviceInfo(cl::Device &d)
{
device_info_t devInfo;
devInfo.deviceName = d.getInfo<CL_DEVICE_NAME>();
devInfo.driverVersion = d.getInfo<CL_DRIVER_VERSION>();
devInfo.numCUs = (uint)d.getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>();
vector<size_t> maxWIPerDim;
maxWIPerDim = d.getInfo<CL_DEVICE_MAX_WORK_ITEM_SIZES>();
devInfo.maxWGSize = (uint)maxWIPerDim[0];
// Limiting max work-group size to 256
#define MAX_WG_SIZE 256
devInfo.maxWGSize = MIN(devInfo.maxWGSize, MAX_WG_SIZE);
// FIXME limit max-workgroup size for qualcomm platform to 128
// Kernel launch fails for workgroup size 256(CL_DEVICE_MAX_WORK_ITEM_SIZES)
string vendor = d.getInfo<CL_DEVICE_VENDOR>();
if( (vendor.find("QUALCOMM") != std::string::npos) ||
(vendor.find("qualcomm") != std::string::npos) )
{
devInfo.maxWGSize = MIN(devInfo.maxWGSize, 128);
}
devInfo.maxAllocSize = (uint)d.getInfo<CL_DEVICE_MAX_MEM_ALLOC_SIZE>();
devInfo.maxGlobalSize = (uint)d.getInfo<CL_DEVICE_GLOBAL_MEM_SIZE>();
devInfo.maxClockFreq = (uint)d.getInfo<CL_DEVICE_MAX_CLOCK_FREQUENCY>();
devInfo.doubleSupported = false;
devInfo.halfSupported = false;
std::string extns = d.getInfo<CL_DEVICE_EXTENSIONS>();
if((extns.find("cl_khr_fp16") != std::string::npos))
devInfo.halfSupported = true;
if((extns.find("cl_khr_fp64") != std::string::npos) || (extns.find("cl_amd_fp64") != std::string::npos))
devInfo.doubleSupported = true;
devInfo.deviceType = d.getInfo<CL_DEVICE_TYPE>();
if(devInfo.deviceType & CL_DEVICE_TYPE_CPU) {
devInfo.gloalBWIters = 20;
devInfo.computeWgsPerCU = 512;
devInfo.computeIters = 10;
} else { // GPU
devInfo.gloalBWIters = 50;
devInfo.computeWgsPerCU = 2048;
devInfo.computeIters = 30;
}
devInfo.transferBWIters = 20;
devInfo.kernelLatencyIters = 20000;
return devInfo;
}
float timeInUS(cl::Event &timeEvent)
{
cl_ulong start = timeEvent.getProfilingInfo<CL_PROFILING_COMMAND_START>() / 1000;
cl_ulong end = timeEvent.getProfilingInfo<CL_PROFILING_COMMAND_END>() / 1000;
return (float)((int)end - (int)start);
}
void Timer::start()
{
tick = chrono::high_resolution_clock::now();
}
float Timer::stopAndTime()
{
tock = chrono::high_resolution_clock::now();
return (float)(chrono::duration_cast<chrono::microseconds>(tock - tick).count());
}
void populate(float *ptr, uint N)
{
srand((unsigned int)time(NULL));
for(int i=0; i<(int)N; i++)
{
//ptr[i] = (float)rand();
ptr[i] = (float)i;
}
}
void populate(double *ptr, uint N)
{
srand((unsigned int)time(NULL));
for(int i=0; i<(int)N; i++)
{
//ptr[i] = (double)rand();
ptr[i] = (double)i;
}
}
uint roundToPowOf2(uint number, int maxPower)
{
int i;
if ((maxPower > 0) && (number > ((uint)1 << maxPower)))
return (1 << maxPower);
for (i=1 ; i < (int)(8*sizeof(int)) ; i++)
if (((uint)1 << i) > number)
break;
return (1 << (i-1));
}
| 24.894309 | 106 | 0.679621 | [
"vector"
] |
2f735e90418c98539bd4ada4da1e17e8bac1e008 | 3,291 | cpp | C++ | TG/bookcodes/ch5/uva11865.cpp | Anyrainel/aoapc-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | 3 | 2017-08-15T06:00:01.000Z | 2018-12-10T09:05:53.000Z | TG/bookcodes/ch5/uva11865.cpp | Anyrainel/aoapc-related-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | null | null | null | TG/bookcodes/ch5/uva11865.cpp | Anyrainel/aoapc-related-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | 2 | 2017-09-16T18:46:27.000Z | 2018-05-22T05:42:03.000Z | // UVa11865 Stream My Contest
// Rujia Liu
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
using namespace std;
const int INF = 1000000000;
const int maxn = 100 + 10;
// 固定根的最小树型图,邻接矩阵写法
struct MDST {
int n;
int w[maxn][maxn]; // 边权
int vis[maxn]; // 访问标记,仅用来判断无解
int ans; // 计算答案
int removed[maxn]; // 每个点是否被删除
int cid[maxn]; // 所在圈编号
int pre[maxn]; // 最小入边的起点
int iw[maxn]; // 最小入边的权值
int max_cid; // 最大圈编号
void init(int n) {
this->n = n;
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++) w[i][j] = INF;
}
void AddEdge(int u, int v, int cost) {
w[u][v] = min(w[u][v], cost); // 重边取权最小的
}
// 从s出发能到达多少个结点
int dfs(int s) {
vis[s] = 1;
int ans = 1;
for(int i = 0; i < n; i++)
if(!vis[i] && w[s][i] < INF) ans += dfs(i);
return ans;
}
// 从u出发沿着pre指针找圈
bool cycle(int u) {
max_cid++;
int v = u;
while(cid[v] != max_cid) { cid[v] = max_cid; v = pre[v]; }
return v == u;
}
// 计算u的最小入弧,入弧起点不得在圈c中
void update(int u) {
iw[u] = INF;
for(int i = 0; i < n; i++)
if(!removed[i] && w[i][u] < iw[u]) {
iw[u] = w[i][u];
pre[u] = i;
}
}
// 根结点为s,如果失败则返回false
bool solve(int s) {
memset(vis, 0, sizeof(vis));
if(dfs(s) != n) return false;
memset(removed, 0, sizeof(removed));
memset(cid, 0, sizeof(cid));
for(int u = 0; u < n; u++) update(u);
pre[s] = s; iw[s] = 0; // 根结点特殊处理
ans = max_cid = 0;
for(;;) {
bool have_cycle = false;
for(int u = 0; u < n; u++) if(u != s && !removed[u] && cycle(u)){
have_cycle = true;
// 以下代码缩圈,圈上除了u之外的结点均删除
int v = u;
do {
if(v != u) removed[v] = 1;
ans += iw[v];
// 对于圈外点i,把边i->v改成i->u(并调整权值);v->i改为u->i
// 注意圈上可能还有一个v'使得i->v'或者v'->i存在,因此只保留权值最小的i->u和u->i
for(int i = 0; i < n; i++) if(cid[i] != cid[u] && !removed[i]) {
if(w[i][v] < INF) w[i][u] = min(w[i][u], w[i][v]-iw[v]);
w[u][i] = min(w[u][i], w[v][i]);
if(pre[i] == v) pre[i] = u;
}
v = pre[v];
} while(v != u);
update(u);
break;
}
if(!have_cycle) break;
}
for(int i = 0; i < n; i++)
if(!removed[i]) ans += iw[i];
return true;
}
};
//////// 题目相关
MDST solver;
struct Edge {
int u, v, b, c;
bool operator < (const Edge& rhs) const {
return b > rhs.b;
}
};
const int maxm = 10000 + 10;
int n, m, C;
Edge edges[maxm];
// 取b前cnt大的边构造网络,判断最小树型图的边权和是否小于C
bool check(int cnt) {
solver.init(n);
for(int i = 0; i < cnt; i++)
solver.AddEdge(edges[i].u, edges[i].v, edges[i].c);
if(!solver.solve(0)) return false;
return solver.ans <= C;
}
int main() {
int T;
scanf("%d", &T);
while(T--) {
scanf("%d%d%d", &n, &m, &C);
for(int i = 0; i < m; i++) {
scanf("%d%d%d%d", &edges[i].u, &edges[i].v, &edges[i].b, &edges[i].c);
}
sort(edges, edges+m);
int L = 1, R = m, ans = -1;
while(L <= R) {
int M = L + (R-L)/2;
if(check(M)) { ans = edges[M-1].b; R = M-1; }
else L = M+1;
}
if(ans < 0) printf("streaming not possible.\n");
else printf("%d kbps\n", ans);
}
return 0;
}
| 23.013986 | 82 | 0.476147 | [
"vector"
] |
2f7f94d6705ffd39629a44e46645b23f787ebcfe | 12,639 | cc | C++ | src/EvenDataTree.cc | hunyadix/SplitClusterMerger | 9fa853c97ee8e5e1ec1850384578c92d6dfbebdd | [
"MIT"
] | null | null | null | src/EvenDataTree.cc | hunyadix/SplitClusterMerger | 9fa853c97ee8e5e1ec1850384578c92d6dfbebdd | [
"MIT"
] | null | null | null | src/EvenDataTree.cc | hunyadix/SplitClusterMerger | 9fa853c97ee8e5e1ec1850384578c92d6dfbebdd | [
"MIT"
] | null | null | null | #include "../interface/EventDataTree.h"
// Normal event tree
void EventDataTree::defineEventTreeBranches(TTree*& eventTree, EventData& eventField)
{
eventTree -> Branch("event", &eventField, eventField.list.c_str());
}
void EventDataTree::setEventTreeDataFields(TTree*& eventTree, EventData& eventField)
{
eventTree -> SetBranchAddress("event", &eventField);
}
// Event based cluster pair statistics
// void EventDataTree::defineEventClusterPairsTreeBranches(TTree*& eventTree, EventData& eventField, std::vector<MergingStatisticsData>& eventMergingStatisticsField)
void EventDataTree::defineEventClusterPairsTreeBranches(TTree*& eventTree, EventData& eventField, MergingStatisticsDataArrays mergingStatisticsDataArrays)
{
eventTree -> Branch("event", &eventField, eventField.list.c_str());
// Number of mergeable cluster pairs
eventTree -> Branch("nMergeableClusterPairs", &mergingStatisticsDataArrays.size, "nMergeableClusterPairs/I");
// // Mergeable cluster pair data
eventTree -> Branch("clusterSize_1", &(mergingStatisticsDataArrays.clusterSize_1[0]), "clusterSize_1[nMergeableClusterPairs]/I");
eventTree -> Branch("clusterSize_2", &(mergingStatisticsDataArrays.clusterSize_2[0]), "clusterSize_2[nMergeableClusterPairs]/I");
eventTree -> Branch("sizeDifference", &(mergingStatisticsDataArrays.sizeDifference[0]), "sizeDifference[nMergeableClusterPairs]/I");
eventTree -> Branch("clusterCharge_1", &(mergingStatisticsDataArrays.clusterCharge_1[0]), "clusterCharge_1[nMergeableClusterPairs]/F");
eventTree -> Branch("clusterCharge_2", &(mergingStatisticsDataArrays.clusterCharge_2[0]), "clusterCharge_2[nMergeableClusterPairs]/F");
eventTree -> Branch("chargeDifference", &(mergingStatisticsDataArrays.chargeDifference[0]), "chargeDifference[nMergeableClusterPairs]/F");
eventTree -> Branch("clusterAngle_1", &(mergingStatisticsDataArrays.clusterAngle_1[0]), "clusterAngle_1[nMergeableClusterPairs]/F");
eventTree -> Branch("clusterAngle_2", &(mergingStatisticsDataArrays.clusterAngle_2[0]), "clusterAngle_2[nMergeableClusterPairs]/F");
eventTree -> Branch("angleDifference", &(mergingStatisticsDataArrays.angleDifference[0]), "angleDifference[nMergeableClusterPairs]/F");
eventTree -> Branch("isMarkedAsSplitCluster_1", &(mergingStatisticsDataArrays.isMarkedAsSplitCluster_1[0]), "isMarkedAsSplitCluster_1[nMergeableClusterPairs]/I");
eventTree -> Branch("isMarkedAsSplitCluster_2", &(mergingStatisticsDataArrays.isMarkedAsSplitCluster_2[0]), "isMarkedAsSplitCluster_2[nMergeableClusterPairs]/I");
eventTree -> Branch("distanceInPixels", &(mergingStatisticsDataArrays.distanceInPixels[0]), "distanceInPixels[nMergeableClusterPairs]/I");
// Module data for mergeable cluster pairs
eventTree -> Branch("det", &(mergingStatisticsDataArrays.mod_on[0]).det, "det[nMergeableClusterPairs]/I");
eventTree -> Branch("layer", &(mergingStatisticsDataArrays.mod_on[0]).layer, "layer[nMergeableClusterPairs]/I");
eventTree -> Branch("ladder", &(mergingStatisticsDataArrays.mod_on[0]).ladder, "ladder[nMergeableClusterPairs]/I");
eventTree -> Branch("module", &(mergingStatisticsDataArrays.mod_on[0]).module, "module[nMergeableClusterPairs]/I");
eventTree -> Branch("half", &(mergingStatisticsDataArrays.mod_on[0]).half, "half[nMergeableClusterPairs]/I");
eventTree -> Branch("outer", &(mergingStatisticsDataArrays.mod_on[0]).outer, "outer[nMergeableClusterPairs]/I");
eventTree -> Branch("side", &(mergingStatisticsDataArrays.mod_on[0]).side, "side[nMergeableClusterPairs]/I");
eventTree -> Branch("disk", &(mergingStatisticsDataArrays.mod_on[0]).disk, "disk[nMergeableClusterPairs]/I");
eventTree -> Branch("blade", &(mergingStatisticsDataArrays.mod_on[0]).blade, "blade[nMergeableClusterPairs]/I");
eventTree -> Branch("panel", &(mergingStatisticsDataArrays.mod_on[0]).panel, "panel[nMergeableClusterPairs]/I");
eventTree -> Branch("ring", &(mergingStatisticsDataArrays.mod_on[0]).ring, "ring[nMergeableClusterPairs]/I");
eventTree -> Branch("shl", &(mergingStatisticsDataArrays.mod_on[0]).shl, "shl[nMergeableClusterPairs]/I");
eventTree -> Branch("federr", &(mergingStatisticsDataArrays.mod_on[0]).federr, "federr[nMergeableClusterPairs]/I");
}
void EventDataTree::setEventClusterPairsTreeDataFields (TTree*& eventTree, EventData& eventField, MergingStatisticsDataArrays mergingStatisticsDataArrays)
{
eventTree -> SetBranchAddress("event", &eventField);
// Number of mergeable cluster pairs
eventTree -> SetBranchAddress("nMergeableClusterPairs", &mergingStatisticsDataArrays.size);
// // Mergeable cluster pair data
eventTree -> SetBranchAddress("clusterSize_1", &(mergingStatisticsDataArrays.clusterSize_1[0]));
eventTree -> SetBranchAddress("clusterSize_2", &(mergingStatisticsDataArrays.clusterSize_2[0]));
eventTree -> SetBranchAddress("sizeDifference", &(mergingStatisticsDataArrays.sizeDifference[0]));
eventTree -> SetBranchAddress("clusterCharge_1", &(mergingStatisticsDataArrays.clusterCharge_1[0]));
eventTree -> SetBranchAddress("clusterCharge_2", &(mergingStatisticsDataArrays.clusterCharge_2[0]));
eventTree -> SetBranchAddress("chargeDifference", &(mergingStatisticsDataArrays.chargeDifference[0]));
eventTree -> SetBranchAddress("clusterAngle_1", &(mergingStatisticsDataArrays.clusterAngle_1[0]));
eventTree -> SetBranchAddress("clusterAngle_2", &(mergingStatisticsDataArrays.clusterAngle_2[0]));
eventTree -> SetBranchAddress("angleDifference", &(mergingStatisticsDataArrays.angleDifference[0]));
eventTree -> SetBranchAddress("isMarkedAsSplitCluster_1", &(mergingStatisticsDataArrays.isMarkedAsSplitCluster_1[0]));
eventTree -> SetBranchAddress("isMarkedAsSplitCluster_2", &(mergingStatisticsDataArrays.isMarkedAsSplitCluster_2[0]));
eventTree -> SetBranchAddress("distanceInPixels", &(mergingStatisticsDataArrays.distanceInPixels[0]));
// Module data for mergeable cluster pairs
eventTree -> SetBranchAddress("det", &(mergingStatisticsDataArrays.mod_on[0]).det);
eventTree -> SetBranchAddress("layer", &(mergingStatisticsDataArrays.mod_on[0]).layer);
eventTree -> SetBranchAddress("ladder", &(mergingStatisticsDataArrays.mod_on[0]).ladder);
eventTree -> SetBranchAddress("module", &(mergingStatisticsDataArrays.mod_on[0]).module);
eventTree -> SetBranchAddress("half", &(mergingStatisticsDataArrays.mod_on[0]).half);
eventTree -> SetBranchAddress("outer", &(mergingStatisticsDataArrays.mod_on[0]).outer);
eventTree -> SetBranchAddress("side", &(mergingStatisticsDataArrays.mod_on[0]).side);
eventTree -> SetBranchAddress("disk", &(mergingStatisticsDataArrays.mod_on[0]).disk);
eventTree -> SetBranchAddress("blade", &(mergingStatisticsDataArrays.mod_on[0]).blade);
eventTree -> SetBranchAddress("panel", &(mergingStatisticsDataArrays.mod_on[0]).panel);
eventTree -> SetBranchAddress("ring", &(mergingStatisticsDataArrays.mod_on[0]).ring);
eventTree -> SetBranchAddress("shl", &(mergingStatisticsDataArrays.mod_on[0]).shl);
eventTree -> SetBranchAddress("federr", &(mergingStatisticsDataArrays.mod_on[0]).federr);
}
// // void EventDataTree::defineEventClusterPairsTreeBranches(TTree*& eventTree, EventData& eventField, std::vector<MergingStatisticsData>& eventMergingStatisticsField)
// void EventDataTree::defineEventClusterPairsTreeBranches(TTree*& eventTree, EventData& eventField,
// int clusterSize_1,
// int clusterSize_2,
// int sizeDifference,
// float clusterCharge_1,
// float clusterCharge_2,
// float chargeDifference,
// float clusterAngle_1,
// float clusterAngle_2,
// float angleDifference,
// int isMarkedAsSplitCluster_1,
// int isMarkedAsSplitCluster_2,
// int distanceInPixels)
// {
// eventTree -> Branch("event", &eventField, eventField.list.c_str());
// // Number of mergeable cluster pairs
// int size = eventMergingStatisticsField.size();
// eventTree -> Branch("nMergeableClusterPairs", &size, "nMergeableClusterPairs/I");
// // // Mergeable cluster pair data
// eventTree -> Branch("clusterSize_1", &eventMergingStatisticsField.clusterSize_1, "clusterSize_1[nMergeableClusterPairs]/I");
// eventTree -> Branch("clusterSize_2", &eventMergingStatisticsField.clusterSize_2, "clusterSize_2[nMergeableClusterPairs]/I");
// eventTree -> Branch("sizeDifference", &eventMergingStatisticsField.sizeDifference, "sizeDifference[nMergeableClusterPairs]/I");
// eventTree -> Branch("clusterCharge_1", &eventMergingStatisticsField.clusterCharge_1, "clusterCharge_1[nMergeableClusterPairs]/F");
// eventTree -> Branch("clusterCharge_2", &eventMergingStatisticsField.clusterCharge_2, "clusterCharge_2[nMergeableClusterPairs]/F");
// eventTree -> Branch("chargeDifference", &eventMergingStatisticsField.chargeDifference, "chargeDifference[nMergeableClusterPairs]/F");
// eventTree -> Branch("clusterAngle_1", &eventMergingStatisticsField.clusterAngle_1, "clusterAngle_1[nMergeableClusterPairs]/F");
// eventTree -> Branch("clusterAngle_2", &eventMergingStatisticsField.clusterAngle_2, "clusterAngle_2[nMergeableClusterPairs]/F");
// eventTree -> Branch("angleDifference", &eventMergingStatisticsField.angleDifference, "angleDifference[nMergeableClusterPairs]/F");
// eventTree -> Branch("isMarkedAsSplitCluster_1", &eventMergingStatisticsField.isMarkedAsSplitCluster_1, "isMarkedAsSplitCluster_1[nMergeableClusterPairs]/I");
// eventTree -> Branch("isMarkedAsSplitCluster_2", &eventMergingStatisticsField.isMarkedAsSplitCluster_2, "isMarkedAsSplitCluster_2[nMergeableClusterPairs]/I");
// eventTree -> Branch("distanceInPixels", &eventMergingStatisticsField.distanceInPixels, "distanceInPixels[nMergeableClusterPairs]/I");
// // Module data for mergeable cluster pairs
// eventTree -> Branch("det", &eventMergingStatisticsField.mod_on.det, "det[nMergeableClusterPairs]/I");
// eventTree -> Branch("layer", &eventMergingStatisticsField.mod_on.layer, "layer[nMergeableClusterPairs]/I");
// eventTree -> Branch("ladder", &eventMergingStatisticsField.mod_on.ladder, "ladder[nMergeableClusterPairs]/I");
// eventTree -> Branch("module", &eventMergingStatisticsField.mod_on.module, "module[nMergeableClusterPairs]/F");
// eventTree -> Branch("half", &eventMergingStatisticsField.mod_on.half, "half[nMergeableClusterPairs]/F");
// eventTree -> Branch("outer", &eventMergingStatisticsField.mod_on.outer, "outer[nMergeableClusterPairs]/F");
// eventTree -> Branch("side", &eventMergingStatisticsField.mod_on.side, "side[nMergeableClusterPairs]/F");
// eventTree -> Branch("disk", &eventMergingStatisticsField.mod_on.disk, "disk[nMergeableClusterPairs]/F");
// eventTree -> Branch("blade", &eventMergingStatisticsField.mod_on.blade, "blade[nMergeableClusterPairs]/F");
// eventTree -> Branch("panel", &eventMergingStatisticsField.mod_on.panel, "panel[nMergeableClusterPairs]/I");
// eventTree -> Branch("ring", &eventMergingStatisticsField.mod_on.ring, "ring[nMergeableClusterPairs]/I");
// eventTree -> Branch("shl", &eventMergingStatisticsField.mod_on.shl, "shl[nMergeableClusterPairs]/I");
// eventTree -> Branch("federr", &eventMergingStatisticsField.mod_on.federr, "federr[nMergeableClusterPairs]/I");
// // auto data = eventMergingStatisticsField.data();
// // eventTree -> Branch("mergeableClusterPairStatistics", &data, "eventMergingStatisticsField[12][nMergeableClusterPairs]/F");
// // eventTree -> Branch("module", &eventMergingStatisticsField.mod, ModuleData::list.c_str());
// // eventTree -> Branch("module_on", &eventMergingStatisticsField.mod_on, ModuleData::list.c_str());
// }
// void EventDataTree::setEventClusterPairsTreeDataFields (TTree*& eventTree, EventData& eventField, std::vector<MergingStatisticsData>& eventMergingStatisticsField)
// {
// int size = eventMergingStatisticsField.size();
// eventTree -> SetBranchAddress("nMergeableClusterPairs", &size);
// auto data = eventMergingStatisticsField.data();
// eventTree -> SetBranchAddress("mergeableClusterPairStatistics", &data);
// // eventTree -> SetBranchAddress("module", &eventMergingStatisticsField.mod);
// // eventTree -> SetBranchAddress("module_on", &eventMergingStatisticsField.mod_on);
// }
| 85.398649 | 168 | 0.749031 | [
"vector"
] |
2f7fbc40079e3430f56971926f6a8d1e0466a820 | 14,705 | cpp | C++ | deps/perceptualdiff-master/metric.cpp | julescmay/LuxCore | 3a6233f37afaf064300f52854715c0ab9ca2103e | [
"Apache-2.0"
] | 826 | 2017-12-12T15:38:16.000Z | 2022-03-28T07:12:40.000Z | deps/perceptualdiff-master/metric.cpp | julescmay/LuxCore | 3a6233f37afaf064300f52854715c0ab9ca2103e | [
"Apache-2.0"
] | 531 | 2017-12-03T17:21:06.000Z | 2022-03-20T19:22:11.000Z | deps/perceptualdiff-master/metric.cpp | julescmay/LuxCore | 3a6233f37afaf064300f52854715c0ab9ca2103e | [
"Apache-2.0"
] | 133 | 2017-12-13T18:46:10.000Z | 2022-03-27T16:21:00.000Z | /*
Metric
Copyright (C) 2006-2011 Yangli Hector Yee
Copyright (C) 2011-2016 Steven Myint, Jeff Terrace
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "metric.h"
#include "lpyramid.h"
#include "rgba_image.h"
#include <ciso646>
#include <cmath>
#include <cstddef>
#include <iostream>
#include <vector>
#include <algorithm>
namespace pdiff
{
#if _MSC_VER <= 1800
static const auto pi = 3.14159265f;
static float to_radians(const float degrees) // LCOV_EXCL_LINE
{
return degrees * pi / 180.f; // LCOV_EXCL_LINE
}
static float to_degrees(const float radians) // LCOV_EXCL_LINE
{
return radians * 180.f / pi; // LCOV_EXCL_LINE
}
#else
constexpr auto pi = 3.14159265f;
constexpr float to_radians(const float degrees) // LCOV_EXCL_LINE
{
return degrees * pi / 180.f; // LCOV_EXCL_LINE
}
constexpr float to_degrees(const float radians) // LCOV_EXCL_LINE
{
return radians * 180.f / pi; // LCOV_EXCL_LINE
}
#endif
// Given the adaptation luminance, this function returns the
// threshold of visibility in cd per m^2.
//
// TVI means Threshold vs Intensity function.
// This version comes from Ward Larson Siggraph 1997.
//
// Returns the threshold luminance given the adaptation luminance.
// Units are candelas per meter squared.
static float tvi(const float adaptation_luminance)
{
const auto log_a = log10f(adaptation_luminance);
float r;
if (log_a < -3.94f)
{
r = -2.86f;
}
else if (log_a < -1.44f)
{
r = powf(0.405f * log_a + 1.6f, 2.18f) - 2.86f;
}
else if (log_a < -0.0184f)
{
r = log_a - 0.395f;
}
else if (log_a < 1.9f)
{
r = powf(0.249f * log_a + 0.65f, 2.7f) - 0.72f;
}
else
{
r = log_a - 1.255f;
}
return powf(10.0f, r);
}
// computes the contrast sensitivity function (Barten SPIE 1989)
// given the cycles per degree (cpd) and luminance (lum)
static float csf(const float cpd, const float lum)
{
const auto a = 440.f * powf((1.f + 0.7f / lum), -0.2f);
const auto b = 0.3f * powf((1.0f + 100.0f / lum), 0.15f);
return a * cpd * expf(-b * cpd) * sqrtf(1.0f + 0.06f * expf(b * cpd));
}
/*
* Visual Masking Function
* from Daly 1993
*/
static float mask(const float contrast)
{
const auto a = powf(392.498f * contrast, 0.7f);
const auto b = powf(0.0153f * a, 4.f);
return powf(1.0f + b, 0.25f);
}
// convert Adobe RGB (1998) with reference white D65 to XYZ
static void adobe_rgb_to_xyz(const float r, const float g, const float b,
float &x, float &y, float &z)
{
// matrix is from http://www.brucelindbloom.com/
x = r * 0.576700f + g * 0.185556f + b * 0.188212f;
y = r * 0.297361f + g * 0.627355f + b * 0.0752847f;
z = r * 0.0270328f + g * 0.0706879f + b * 0.991248f;
}
struct White
{
White()
{
adobe_rgb_to_xyz(1.f, 1.f, 1.f, x, y, z);
}
float x;
float y;
float z;
};
static const White global_white;
static void xyz_to_lab(const float x, const float y, const float z,
float &l, float &a, float &b)
{
const float epsilon = 216.0f / 24389.0f;
const float kappa = 24389.0f / 27.0f;
const float r[] = {
x / global_white.x,
y / global_white.y,
z / global_white.z
};
float f[3];
for (auto i = 0u; i < 3; i++)
{
if (r[i] > epsilon)
{
f[i] = powf(r[i], 1.0f / 3.0f);
}
else
{
f[i] = (kappa * r[i] + 16.0f) / 116.0f;
}
}
l = 116.0f * f[1] - 16.0f;
a = 500.0f * (f[0] - f[1]);
b = 200.0f * (f[1] - f[2]);
}
static unsigned int adaptation(const float num_one_degree_pixels)
{
auto num_pixels = 1.f;
auto adaptation_level = 0u;
for (auto i = 0u; i < MAX_PYR_LEVELS; i++)
{
adaptation_level = i;
if (num_pixels > num_one_degree_pixels)
{
break;
}
num_pixels *= 2;
}
return adaptation_level; // LCOV_EXCL_LINE
}
PerceptualDiffParameters::PerceptualDiffParameters()
: luminance_only(false),
field_of_view(45.0f),
gamma(2.2f),
luminance(100.0f),
threshold_pixels(100),
color_factor(1.0f)
{
}
bool yee_compare(const RGBAImage &image_a,
const RGBAImage &image_b,
const PerceptualDiffParameters &args,
size_t *const output_num_pixels_failed,
float *const output_error_sum,
std::string *const output_reason,
RGBAImage *const output_image_difference,
std::ostream *const output_verbose)
{
if ((image_a.get_width() != image_b.get_width()) or
(image_a.get_height() != image_b.get_height()))
{
if (output_reason)
{
*output_reason = "Image dimensions do not match\n";
}
return false;
}
const auto w = image_a.get_width();
const auto h = image_a.get_height();
const auto dim = w * h;
auto identical = true;
for (auto i = 0u; i < dim; i++)
{
if (image_a.get(i) != image_b.get(i))
{
identical = false;
break;
}
}
if (identical)
{
if (output_reason)
{
*output_reason = "Images are binary identical\n";
}
return true;
}
// Assuming colorspaces are in Adobe RGB (1998) convert to XYZ.
std::vector<float> a_lum(dim);
std::vector<float> b_lum(dim);
std::vector<float> a_a(dim);
std::vector<float> b_a(dim);
std::vector<float> a_b(dim);
std::vector<float> b_b(dim);
if (output_verbose)
{
*output_verbose << "Converting RGB to XYZ\n";
}
const auto gamma = args.gamma;
const auto luminance = args.luminance;
#pragma omp parallel for shared(args, a_lum, b_lum, a_a, a_b, b_a, b_b)
for (auto y = 0; y < static_cast<ptrdiff_t>(h); y++)
{
for (auto x = 0u; x < w; x++)
{
const auto i = x + y * w;
// perceptualdiff used to use premultiplied alphas when loading
// the image. This is no longer the case since the switch to
// FreeImage. We need to do the multiplication here now. As was
// the case with premultiplied alphas, differences in alphas
// won't be detected where the color is black.
const auto a_alpha = image_a.get_alpha(i) / 255.f;
const auto a_color_r = powf(
image_a.get_red(i) / 255.f * a_alpha,
gamma);
const auto a_color_g = powf(
image_a.get_green(i) / 255.f * a_alpha,
gamma);
const auto a_color_b = powf(
image_a.get_blue(i) / 255.f * a_alpha,
gamma);
float a_x;
float a_y;
float a_z;
adobe_rgb_to_xyz(a_color_r, a_color_g, a_color_b,
a_x, a_y, a_z);
float l;
xyz_to_lab(a_x, a_y, a_z, l, a_a[i], a_b[i]);
const auto b_alpha = image_b.get_alpha(i) / 255.f;
const auto b_color_r = powf(
image_b.get_red(i) / 255.f * b_alpha,
gamma);
const auto b_color_g = powf(
image_b.get_green(i) / 255.f * b_alpha,
gamma);
const auto b_color_b = powf(
image_b.get_blue(i) / 255.f * b_alpha,
gamma);
float b_x;
float b_y;
float b_z;
adobe_rgb_to_xyz(b_color_r, b_color_g, b_color_b,
b_x, b_y, b_z);
xyz_to_lab(b_x, b_y, b_z, l, b_a[i], b_b[i]);
a_lum[i] = a_y * luminance;
b_lum[i] = b_y * luminance;
}
}
if (output_verbose)
{
*output_verbose << "Constructing Laplacian Pyramids\n";
}
const LPyramid la(a_lum, w, h);
const LPyramid lb(b_lum, w, h);
const auto num_one_degree_pixels =
to_degrees(2 *
std::tan(args.field_of_view * to_radians(.5f)));
const auto pixels_per_degree = w / num_one_degree_pixels;
if (output_verbose)
{
*output_verbose << "Performing test\n";
}
const auto adaptation_level = adaptation(num_one_degree_pixels);
float cpd[MAX_PYR_LEVELS];
cpd[0] = 0.5f * pixels_per_degree;
for (auto i = 1u; i < MAX_PYR_LEVELS; i++)
{
cpd[i] = 0.5f * cpd[i - 1];
}
const auto csf_max = csf(3.248f, 100.0f);
static_assert(MAX_PYR_LEVELS > 2,
"MAX_PYR_LEVELS must be greater than 2");
float f_freq[MAX_PYR_LEVELS - 2];
for (auto i = 0u; i < MAX_PYR_LEVELS - 2; i++)
{
f_freq[i] = csf_max / csf(cpd[i], 100.0f);
}
auto pixels_failed = 0u;
auto error_sum = 0.;
#pragma omp parallel for reduction(+ : pixels_failed, error_sum) \
shared(args, a_a, a_b, b_a, b_b, cpd, f_freq)
for (auto y = 0; y < static_cast<ptrdiff_t>(h); y++)
{
for (auto x = 0u; x < w; x++)
{
const auto index = y * w + x;
const auto adapt = std::max(
(la.get_value(x, y, adaptation_level) +
lb.get_value(x, y, adaptation_level)) * 0.5f,
1e-5f);
auto sum_contrast = 0.f;
auto factor = 0.f;
for (auto i = 0u; i < MAX_PYR_LEVELS - 2; i++)
{
const auto n1 =
std::abs(la.get_value(x, y, i) -
la.get_value(x, y, i + 1));
const auto n2 =
std::abs(lb.get_value(x, y, i) -
lb.get_value(x, y, i + 1));
const auto numerator = std::max(n1, n2);
const auto d1 = std::abs(la.get_value(x, y, i + 2));
const auto d2 = std::abs(lb.get_value(x, y, i + 2));
const auto denominator = std::max(std::max(d1, d2), 1e-5f);
const auto contrast = numerator / denominator;
const auto f_mask = mask(contrast * csf(cpd[i], adapt));
factor += contrast * f_freq[i] * f_mask;
sum_contrast += contrast;
}
sum_contrast = std::max(sum_contrast, 1e-5f);
factor /= sum_contrast;
factor = std::min(std::max(factor, 1.f), 10.f);
const auto delta =
std::abs(la.get_value(x, y, 0) - lb.get_value(x, y, 0));
error_sum += delta;
auto pass = true;
// Pure luminance test.
if (delta > factor * tvi(adapt))
{
pass = false;
}
if (not args.luminance_only)
{
// CIE delta E test with modifications.
auto color_scale = args.color_factor;
// Ramp down the color test in scotopic regions.
if (adapt < 10.0f)
{
// Don't do color test at all.
color_scale = 0.0;
}
const auto da = a_a[index] - b_a[index];
const auto db = a_b[index] - b_b[index];
const auto delta_e = (da * da + db * db) * color_scale;
error_sum += delta_e;
if (delta_e > factor)
{
pass = false;
}
}
if (pass)
{
if (output_image_difference)
{
output_image_difference->set(0, 0, 0, 255, index);
}
}
else
{
pixels_failed++;
if (output_image_difference)
{
output_image_difference->set(255, 0, 0, 255, index);
}
}
}
}
const auto different =
std::to_string(pixels_failed) + " pixels are different\n";
const auto passed = pixels_failed < args.threshold_pixels;
if (output_reason)
{
if (passed)
{
*output_reason =
"Images are perceptually indistinguishable\n" + different;
}
else
{
*output_reason = "Images are visibly different\n" + different;
}
}
if (output_num_pixels_failed)
{
*output_num_pixels_failed = pixels_failed;
}
if (output_error_sum)
{
*output_error_sum = error_sum;
}
return passed;
}
}
| 30.382231 | 79 | 0.484869 | [
"vector"
] |
2f87c5022278b9b7881c7b3c8c7190c9f35e127a | 3,754 | cpp | C++ | cpp-7/sketches.cpp | Evg503/Stepik | f84cddfd311b067bf34c3ef3df69956c51e25096 | [
"MIT"
] | null | null | null | cpp-7/sketches.cpp | Evg503/Stepik | f84cddfd311b067bf34c3ef3df69956c51e25096 | [
"MIT"
] | null | null | null | cpp-7/sketches.cpp | Evg503/Stepik | f84cddfd311b067bf34c3ef3df69956c51e25096 | [
"MIT"
] | null | null | null | #include <iostream>
/*
struct Number {};
struct BigInt : Number
{
BigInt(int x);
};
struct String
{
explicit String(char const * s);
explicit operator char const *() const;
};
void a()
{
int a = 3.5;
double b = 7;
BigInt c = 100500;
String d = static_cast<String>("Stepik");
Number * e = &c;
BigInt * f = static_cast<BigInt *>(e);
void * g = f;
BigInt * h = static_cast<BigInt *>(g);
}
void f2()
{
int a = 27;
int const b = 412;
int * pa = &a;
int const c = a;
int d = b;//const_cast<int &>(b);
int const * p1 = pa;//const_cast<int const *>(pa);
int * const * p2 = &pa;
int const ** p3 = const_cast<int const **>(&pa);
int const * const * p4 = &pa;//const_cast<int const * const *>(&pa);
}
void f3()
{
String s("Hello");
//delete s; // 1
//if (s) { } // 2
//char const * p1 = s; // 3
char const * p2 = (char const*)s; // 4
char const * p3 = static_cast<char const*>(s); // 5
//char const * s2 = s + 4; // 6
}
*/
struct Str
{
Str()=default;
Str(Str const &)=default;
Str(Str &&)
{
std::cout << "Str(Str &&)" << std::endl;
};
};
Str & fun1(Str & s)
{
return s;
}
Str && fun2(Str & s)
{
return std::move(s);
}
Str fun3(Str & s)
{
return std::move(s);
}
Str fun4(Str s)
{
return std::move(s);
}
Str fun5(Str s)
{
return std::forward<Str>(s);
}
Str && fun6(Str && s)
{
return std::move(s);
}
Str fun7(Str && s)
{
return s;
}
int mainfun()
{
Str s;
std:: cout << "\nfun1:";
fun1(s);
std:: cout << "\nfun2:";
fun2(s);
std:: cout << "\nfun3:";
fun3(s);
std:: cout << "\nfun4:";
fun4(s);
std:: cout << "\nfun5:";
fun5(s);
std:: cout << "\nfun6:";
fun6(Str());
std:: cout << "\nfun7:";
fun7(Str());
}
#include <list>
int mainlists()
{
std::list<int> l = {1,2,3};
l.insert(l.begin(), 4);
l.insert(l.end(), 5);
auto it = l.begin();
++it;
++it;
l.insert(it, 6);
auto rit1 = l.rbegin();
++rit1;
++rit1;
l.insert(rit1.base(), 7);
auto rit2 = l.rbegin();
++rit2;
++rit2;
l.insert(rit2.base(), 8);
for(auto i:l)
std::cout << i << ' ';
}
template<class FwdIt>
FwdIt remove_nth(FwdIt p, FwdIt q, size_t n)
{
FwdIt i = p;
for(; p != q; --n)
{
if(n==0)
{
++p;
continue;
}
*i++ = *p++;
}
return i;
}
#include <vector>
int main_remove_nth(){
std::vector<int> v = {0,1,2,3,4,5,6,7,8,9,10};
for(auto i:v)
std::cout << i << ' ';
std::cout <<std::endl;
v.erase(remove_nth(v.begin(), v.end(), 11), v.end());
// теперь в v = {0,1,2,3,4,6,7,8,9,10};
for(auto i:v)
std::cout << i << ' ';
std::cout <<std::endl;
}
struct ElementN
{
explicit ElementN(size_t n)
: n(n), i(0)
{}
template<class T>
bool operator()(T const& t) { return (i++ == n); }
size_t n;
size_t i;
};
#include <algorithm>
int mainElementN()
{
std::vector<int> v = { 0,1,2,3,4,5,6,7,8,9,10,11,12 };
v.erase(std::remove_if(v.begin(), v.end(), ElementN(3)), v.end());
for (int i: v)
std::cout << i << ' ';
return 0;
}
#include <algorithm>
#include <vector>
template<class Iterator>
size_t count_permutations(Iterator p, Iterator q)
{
using T = typename std::iterator_traits<Iterator>::value_type;
size_t count = 0;
std::vector<T> v(p,q);
auto b = v.begin();
auto e = v.end();
std::sort(b, e);
do{
if(std::adjacent_find(b, e) == e) ++count;
}while(std::next_permutation(b, e));
return count;
}
#include <array>
int main()
{
std::array<int, 3> a1 = {1,2,3};
size_t c1 = count_permutations(a1.begin(), a1.end()); // 6
std::cout << "c1(6)=" << c1 <<std::endl;
std::array<int, 5> a2 = {1,2,3,4,4};
size_t c2 = count_permutations(a2.begin(), a2.end()); // 36
std::cout << "c2(36)=" << c2 <<std::endl;
}
| 15.137097 | 70 | 0.531433 | [
"vector"
] |
2f8cd9c574ae57d9bc549853b40e27e26c1c1c9b | 10,372 | cpp | C++ | main.cpp | aljpetri/DynamicMinimizer | 31f9c79293abdc6483ce3c47dc8e3b41706b7f7c | [
"MIT"
] | null | null | null | main.cpp | aljpetri/DynamicMinimizer | 31f9c79293abdc6483ce3c47dc8e3b41706b7f7c | [
"MIT"
] | null | null | null | main.cpp | aljpetri/DynamicMinimizer | 31f9c79293abdc6483ce3c47dc8e3b41706b7f7c | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
// get_kmer_minimizers.h
// get kmer minimizer header file.
//
// holding the get kmer_minimizer method which is a basic building block of the algorithm
//
////////////////////////////////////////////////////////////////////////////////
// author: Alexander Petri
#include "Minimizer.h"
#include "main.h"
#include "B-tree.hh"
#include "B_tree_node.hh"
#include "generate_random_test_cases.h"
//#include "Alter_Minimizers_Algo.h"
#include "get_kmer_minimizers.h"
#include "brute_force_normal_string.h"
#include "B_tree_operations.h"
#include "dynamic_minimizer.h"
#include "dynamic_minimizer_no.h"
#include "brute_force.h"
#include "dynseq_functions.h"
#include "include/dynamic.hpp"
using namespace std;
using namespace md;
using namespace dyn;
typedef typename B_tree<int,int,7,3>::key_t _key_t;
typedef typename B_tree<int,int,7,3>::shifted_key_ptr_t _shifted_key_ptr_t;
//typedef typename B_tree<int,int,3,1>::key_t _key_t;
//typedef typename B_tree<int,int,3,1>::shifted_key_ptr_t _shifted_key_ptr_t;
int main(){
//Predefined sequences for debugging reasons only
//auto sequence="CCCAACCCGGCGCGGCCAAGAAGCCAGCCAGGCGAAAACAAGGAGGCGAGAGCACCGCGCGAACCGGACGCGGCCCCCCAAAAAAGAAGAAACACGAAGA"s;
//auto sequence= "TCAACGGTCTCTGAGCGTCAACCTCGTACTTAGAAGGGCGGAACCGCCAGCGTGCCTACTCCAGTCGTCGATTTACATTAACATACGTTCTCAGCTCTAA"s;
//auto sequence= "ATGCGATATCGTAGGCGTCGATGGAGAGCTAGATCGATCGATCTAAATCCCGATCGATTCCGAGCGCGATCAAAGCGCGATAGGCTAGCTAAAGCTAGCA"s;
//auto sequence="231032101233101"s;
//main parameters needed for the algorithm
int k = 4;
int w= 6;
int seqlen=100;
int numbervars=5;
string sequence=generate_random_sequence(seqlen);
std::string sequence2=sequence;
//cout<<"Random sequence: "<<sequence<<"\n";
const uint64_t sigma=4;
const uint64_t sigma2=0;
wt_str dynamic_sequence(sigma);
wt_str dynamic_sequence2(sigma);
//sstd::string finalsequence="";
//dynamic_sequence.insert(0,'a');
//dynamic_sequence.
std::vector<char> myVector(sequence.begin(), sequence.end());
for (int i=0;i<myVector.size();i++){
dynamic_sequence.push_back(myVector[i]);
}
for (int i=0;i<myVector.size();i++){
dynamic_sequence2.push_back(myVector[i]);
}
cout<<"Size: "<<dynamic_sequence.size()<<"\n";
cout<<"aSize: "<<dynamic_sequence.alphabet_size()<<"\n";
//std::string substr=dynseq_get_substr(dynamic_sequence,0,3);
//cout<<"Substring: "<<substr<<"\n";
// cout<<"Dynseq before: "<<dynseq_tostring(dynamic_sequence)<<"\n";
vector<Variant> variants=generate_random_variations(sequence,numbervars);
cout<<"Random variations generated\n";
vector<Variant> variants2=variants;
vector<Variant> variants3=variants;
/*vector<Variant> variants;
int pos=6;
int origlen=1;
int len=1;
std::string vsequence="A";
Variant this_variant=Variant(pos,origlen,len,vsequence);
variants.push_back(this_variant);
pos=15;
origlen=4;
len=9;
vsequence="CGCAGCGAC";
Variant v_0=Variant(pos,origlen,len,vsequence);
variants.push_back(v_0);
pos=34;
origlen=3;
len=4;
vsequence="ACCA";
Variant v_1=Variant(pos,origlen,len,vsequence);
variants.push_back(v_1);
pos=40;
origlen=3;
len=6;
vsequence="AGAGCG";
Variant v_2=Variant(pos,origlen,len,vsequence);
variants.push_back(v_2);
pos=62;
origlen=2;
len=9;
vsequence="GAACACACA";
Variant v_5=Variant(pos,origlen,len,vsequence);
variants.push_back(v_5);
pos=68;
origlen=1;
len=9;
vsequence="GGCGAAAGA";
Variant v_3=Variant(pos,origlen,len,vsequence);
variants.push_back(v_3);
pos=82;
origlen=2;
len=12;
vsequence="CACCGGGCGAGC";
Variant v_4=Variant(pos,origlen,len,vsequence);
variants.push_back(v_4);
/*6: 1 1 A
15: 4 9 CGCAGCGAC
34: 3 4 ACCA
40: 3 6 AGAGCG
62: 2 9 GAACACACA
68: 1 9 GGCGAAAGA
82: 2 12 CACCGGGCGAGC
*/
//vector<Minimizer> minimizers;
/*for(int i=1;i<21;i++){
int pos=i;
std::string seq="AAAAA";
Minimizer m0=Minimizer (pos,seq);
minimizers.push_back(m0);
}*/
//cout<<"random variants generated from random sequence \n";
auto begin = chrono::high_resolution_clock::now();
vector<Minimizer> minimizers = get_kmer_minimizers(sequence,k,w);
auto sndtime=std::chrono::system_clock::now();
auto dur=sndtime-begin;
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(dur).count();
cout<<"Time needed: "<< ms<<"miliseconds\n";
cout<<"Random variants:\n";
for(int i=0;i<variants.size();i++){
variants.at(i).printVariant();
}
//for (int i=0;i< variants.size();i++){
// variants[i].printVariant();
//}
//write the minimizers to the command line
/*for(int i=0;i<minimizers.size();i++){
minimizers.at(i).printMinimizer();
}*/
//int val=3;
//cout<<sequence<<"\n";
//vector<Minimizer> minis=get_kmer_minimizers(sequence,k,w);
B_tree<int,std::string,7,3>* minimizerTree = new B_tree<int,std::string,7,3>();
B_tree<int,std::string,7,3>* minimizerTreeAlgo2 = new B_tree<int,std::string,7,3>();
//generates the B-tree holding the minimizers generated above and fills it
//B_tree<int,std::pair<std::string,int>,7,3>* minimizerTree = new B_tree<int,std::pair<std::string,int>,7,3>();
//B_tree<int,std::pair<std::string,int>,7,3>* minimizerTree = new B_tree<int,std::pair<std::string,int>,7,3>();
//fill_minimizer_tree(minimizerTree,minis);
//int posshift=0;
//std::vector<Minimizer> minis=get_kmer_minimizers_algo(sequence,k,w,posshift);
fill_minimizer_tree(minimizerTree,minimizers);
fill_minimizer_tree(minimizerTreeAlgo2,minimizers);
print_minimizerTree(minimizerTree);
//cout<<"Dynseq before: "<<dynseq_tostring(dynamic_sequence)<<"\n";
//dynseq_update_substr(dynamic_sequence, 0, 4,"AAAAAAAAAAAAA");
//cout<<"Dynseq after: "<<dynseq_tostring(dynamic_sequence)<<"\n";
/*int elem=9;
int shift=4;
minimizerTree->search(elem);
minimizerTree->shift_greater(elem,shift);
print_minimizerTree(minimizerTree);
*/
B_tree<int,std::string,7,3>* minimizerTreeBF = new B_tree<int,std::string,7,3>();
//compute_dynamic_minimizers(minimizerTree,dynamic_sequence,variants,k,w);
cout<<"Starting normal compute dynamic minimizers\n";
auto begin3 = chrono::high_resolution_clock::now();
compute_dynamic_minimizers(minimizerTree,dynamic_sequence2,variants,k,w);
auto sndtime3=std::chrono::system_clock::now();
auto dur3=sndtime3-begin3;
auto msalgo = std::chrono::duration_cast<std::chrono::milliseconds>(dur3).count();
cout<<"Starting compute dynamic minimizers without dynseq\n";
auto begin2no = chrono::high_resolution_clock::now();
sequence=compute_dynamic_minimizers_no_dynseq(minimizerTreeAlgo2,sequence,variants2,k,w);
auto sndtime2no=std::chrono::system_clock::now();
auto durno=sndtime2no-begin2no;
auto msalgono = std::chrono::duration_cast<std::chrono::milliseconds>(durno).count();
cout<<"Starting brute force\n";
auto begin2 = chrono::high_resolution_clock::now();
brute_force_minimizer_computation(minimizerTreeBF,dynamic_sequence,variants3,k,w);
auto sndtime2=std::chrono::system_clock::now();
auto dur2=sndtime2-begin2;
auto msbf = std::chrono::duration_cast<std::chrono::milliseconds>(dur).count();
std::vector<Minimizer> newminisbf=minimizer_to_vector(minimizerTreeBF);
cout<<"Main Hello World!\n";
//std::vector<Minimizer> newminisalgono=minimizer_to_vector(minimizerTreeAlgo2);
cout<<"Main Hello World2!\n";
std::string bf_result=dynseq_tostring(dynamic_sequence);
cout<<"Main Hello World\n";
//*print_minimizerTree(minimizerTree);
std::string algo_result=dynseq_tostring(dynamic_sequence2);
//for(int i=0;i<newminisbf.size();i++){
// Minimizer bfmini=newminisbf[i];
// cout<<"Minimizer "<<bfmini.getSequence()<<": "<<bfmini.getPosition()<<"\n";
//}
cout<<"Algo: "<<algo_result<<"\n";
cout<<"Algo no dynseq: "<<sequence<<"\n";
if(bf_result.compare(algo_result)==0){
cout<<"The algorithm returned the right sequence!\n";
}
if(bf_result.compare(sequence)==0){
cout<<"The algorithm no dynseq returned the right sequence!\n";
}
std::vector<Minimizer> algominis=minimizer_to_vector(minimizerTree);
cout<<"Main Hello World algominis\n";
cout<<"Bf-Minimizer vs AlgoMinimizer\n";
bool rightMinis=true;
bool rightMinisno=true;
for(int i=0;i<newminisbf.size();i++){
Minimizer bfmini=newminisbf[i];
if(i<=algominis.size()){
Minimizer algomini=algominis[i];
cout<<"Minimizer "<<bfmini.getSequence()<<": "<<bfmini.getPosition()<<" vs "<< algomini.getSequence()<<": "<<algomini.getPosition()<<" "<<(bfmini.getSequence()==algomini.getSequence() && bfmini.getPosition()==algomini.getPosition())<<"\n";
if(!(bfmini.getSequence()==algomini.getSequence() && bfmini.getPosition()==algomini.getPosition())){
rightMinis=false;
//cout<<"here wrong\n";
}
}
/*if(i<=algominis.size()){
Minimizer algominino=newminisalgono[i];
if(!(bfmini.getSequence()==algominino.getSequence() && bfmini.getPosition()==algominino.getPosition())){
rightMinisno=false;
//cout<<"here wrong\n";
}
}*/
}
cout<<"Time needed for algo without dynseq: "<< msalgono<<"miliseconds\n";
cout<<"Time needed for algo: "<< msalgo<<"miliseconds\n";
cout<<"Time needed for bf: "<< msbf<<"miliseconds\n";
//cout<<"Algo: "<<algo_result<<"\n";
//cout<<"Algo no dynseq: "<<sequence<<"\n";
if(bf_result.compare(algo_result)==0){
cout<<"The algorithm returned the right sequence!\n";
}
if(bf_result.compare(sequence)==0){
cout<<"The algorithm no dynseq returned the right sequence!\n";
}
if(rightMinis){
cout<<"The algorithm delivered the right minimizers!\n";
}
/*if(rightMinisno){
cout<<"The algorithm no dynseq delivered the right minimizers!\n";
}*/
else{
cout<<"ERROR\n";
}
brute_force_minimizer_computation_normal_string(minimizerTreeBF,sequence2,variants3,k,w);
//std::vector<Minimizer> newminimethod=minimizer_to_vector(minimizerTree);
/*int pos=3;
int shift=2;
minimizerTree->shift_greater(pos,shift);
print_minimizerTree(minimizerTree);
cout<<"End of Tree\n";
pos=9;
minimizerTree->shift_greater(pos,shift);
print_minimizerTree(minimizerTree);
cout<<"End of Tree\n";
int left=5;
int right=23;
delete_minimizers(minimizerTree,left,right);
print_minimizerTree(minimizerTree);*/
}
| 36.521127 | 252 | 0.705361 | [
"vector"
] |
2f8d3ce49e15073358b280ef8695be013ee7c232 | 1,871 | cpp | C++ | alignment/PrintTupleCountTable.cpp | mchaisso/blasr | 044b97e6e581a936d93e8226b25ac44aebf3c9da | [
"BSD-3-Clause"
] | 17 | 2015-05-05T12:41:15.000Z | 2021-03-24T05:50:58.000Z | alignment/PrintTupleCountTable.cpp | EichlerLab/blasr | c9bced1fedfb026b4992e2b49e4ffa0f107819ea | [
"BSD-3-Clause"
] | 6 | 2015-07-07T14:01:00.000Z | 2021-04-17T07:53:12.000Z | alignment/PrintTupleCountTable.cpp | EichlerLab/blasr | c9bced1fedfb026b4992e2b49e4ffa0f107819ea | [
"BSD-3-Clause"
] | 10 | 2015-01-22T19:27:40.000Z | 2022-02-17T06:43:01.000Z | #include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include "../common/FASTASequence.h"
#include "../common/FASTAReader.h"
#include "../common/tuples/DNATuple.h"
#include "../common/tuples/CompressedDNATuple.h"
#include "../common/tuples/TupleMetrics.h"
#include "../common/datastructures/tuplelists/TupleCountTable.h"
#include "../common/CommandLineParser.h"
#include "../common/utils.h"
#ifdef COMPRESSED
typedef TupleCountTable<FASTASequence, CompressedDNATuple<FASTASequence> > CountTable;
#else
typedef TupleCountTable<FASTASequence, DNATuple> CountTable;
#endif
int main(int argc, char* argv[]) {
CommandLineParser clp;
string tableFileName;
vector<string> sequenceFiles;
TupleMetrics tm;
tm.tupleSize = 8;
clp.SetProgramName("printTupleCountTable");
clp.SetProgramSummary("Count the number of occurrences of every k-mer in a file.");
clp.RegisterStringOption("table", &tableFileName, "Output table name.", true);
clp.RegisterIntOption("wordsize", &tm.tupleSize, "Size of words to count",
CommandLineParser::NonNegativeInteger, false);
clp.RegisterStringListOption("reads", &sequenceFiles, "All sequences.", false);
clp.RegisterPreviousFlagsAsHidden();
vector<string> opts;
if (argc == 2) {
string fastaFileName = argv[1];
sequenceFiles.push_back(fastaFileName);
tableFileName = fastaFileName + ".ctab";
}
else {
clp.ParseCommandLine(argc, argv, opts);
}
tm.InitializeMask();
ofstream tableOut;
CrucialOpen(tableFileName, tableOut, std::ios::out| std::ios::binary);
CountTable table;
table.InitCountTable(tm);
int i;
FASTASequence seq;
for (i = 0; i < sequenceFiles.size(); i++ ){
FASTAReader reader;
reader.Init(sequenceFiles[i]);
while (reader.GetNext(seq)) {
seq.ToUpper();
table.AddSequenceTupleCountsLR(seq);
}
}
table.Write(tableOut);
return 0;
}
| 28.348485 | 86 | 0.730625 | [
"vector"
] |
2f9204e46573798938eacde072e4e63b2e96a15d | 1,624 | cpp | C++ | e-olymp/Almost-shortest-path.cpp | MaGnsio/CP-Problems | a7f518a20ba470f554b6d54a414b84043bf209c5 | [
"Unlicense"
] | 3 | 2020-11-01T06:31:30.000Z | 2022-02-21T20:37:51.000Z | e-olymp/Almost-shortest-path.cpp | MaGnsio/CP-Problems | a7f518a20ba470f554b6d54a414b84043bf209c5 | [
"Unlicense"
] | null | null | null | e-olymp/Almost-shortest-path.cpp | MaGnsio/CP-Problems | a7f518a20ba470f554b6d54a414b84043bf209c5 | [
"Unlicense"
] | 1 | 2021-05-05T18:56:31.000Z | 2021-05-05T18:56:31.000Z | /**
* author: MaGnsi0
* created: 10/06/2021 01:23:22
**/
#include <bits/stdc++.h>
using namespace std;
void bfs(int& n, vector<vector<int>>& adj, vector<int>& d, int& s, int& e) {
queue<int> q;
q.push(s);
d[s] = 0;
while (!q.empty()) {
int v = q.front();
q.pop();
for (auto& u : adj[v]) {
if (d[u] == INT_MAX) {
q.push(u);
d[u] = d[v] + 1;
}
}
}
}
int main() {
ios_base::sync_with_stdio (0); cin.tie (0); cout.tie (0);
int n, m, s, e;
cin >> n >> m >> s >> e;
vector<vector<int>> adj(n + 1);
vector<pair<int, int>> edges;
for (int i = 0; i < m; ++i) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
edges.push_back({u, v});
}
vector<int> ds(n + 1, INT_MAX), de(n + 1, INT_MAX);
set<pair<int, int>> forbidden;
bfs(n, adj, ds, s, e);
bfs(n, adj, de, e, s);
for (auto& [u, v] : edges) {
if (ds[u] + 1 + de[v] == ds[e] || de[u] + 1 + ds[v] == ds[e]) {
forbidden.insert({min(u, v), max(u, v)});
}
}
vector<int> d(n + 1, INT_MAX);
queue<int> q;
q.push(s);
d[s] = 0;
while (!q.empty()) {
int v = q.front();
q.pop();
for (auto& u : adj[v]) {
if (d[u] != INT_MAX) {
continue;
}
if (forbidden.count({min(u, v), max(u, v)})) {
continue;
}
q.push(u);
d[u] = d[v] + 1;
}
}
cout << (d[e] == INT_MAX ? -1 : d[e]);
}
| 24.606061 | 76 | 0.398399 | [
"vector"
] |
2f95d9cf7ccbb706836e660605429bc66d4bd547 | 1,698 | hpp | C++ | inst/include/Package.hpp | nsaripalli/instrumentr | 4bd52d1c454dd1c188e12f687db6a574536b75ae | [
"MIT"
] | 4 | 2020-06-11T14:58:55.000Z | 2021-10-18T20:19:15.000Z | inst/include/Package.hpp | nsaripalli/instrumentr | 4bd52d1c454dd1c188e12f687db6a574536b75ae | [
"MIT"
] | 42 | 2020-06-29T18:13:52.000Z | 2020-09-29T09:55:12.000Z | inst/include/Package.hpp | nsaripalli/instrumentr | 4bd52d1c454dd1c188e12f687db6a574536b75ae | [
"MIT"
] | 1 | 2021-02-18T13:26:05.000Z | 2021-02-18T13:26:05.000Z | #ifndef INSTRUMENTR_PACKAGE_HPP
#define INSTRUMENTR_PACKAGE_HPP
#include <vector>
#include <string>
#include "Object.hpp"
#include "Function.hpp"
namespace instrumentr {
class Package: public Object {
public:
Package(const std::string& name,
const std::string& directory,
SEXP r_environment)
: Object()
, name_(name)
, directory_(directory)
, r_environment_(r_environment) {
R_PreserveObject(r_environment_);
}
~Package() {
R_ReleaseObject(r_environment_);
}
const std::string& get_name() const {
return name_;
}
const std::string& get_directory() const {
return directory_;
}
SEXP get_environment() {
return r_environment_;
}
std::vector<FunctionSPtr>& get_functions() {
return functions_;
}
const std::vector<FunctionSPtr>& get_functions() const {
return functions_;
}
void add_function(FunctionSPtr function) {
functions_.push_back(function);
}
void remove_function(const FunctionSPtr& function) {
for (int index = functions_.size() - 1; index >= 0; --index) {
if (functions_[index] == function) {
functions_.erase(functions_.begin() + index);
break;
}
}
}
static void initialize();
static void finalize();
static SEXP get_class();
private:
std::string name_;
std::string directory_;
SEXP r_environment_;
std::vector<FunctionSPtr> functions_;
static SEXP class_;
};
using PackageSPtr = std::shared_ptr<Package>;
} // namespace instrumentr
#endif /* INSTRUMENTR_PACKAGE_HPP */
| 21.225 | 70 | 0.618375 | [
"object",
"vector"
] |
2f9c5d69c54dd9af9cc9bdf381d4ee4a3c88b446 | 2,394 | cpp | C++ | miniapp/cosma_miniapp.cpp | simonpintarelli/COSMA | db26aeac475e3b0a15d36d74e56514392d3e8e00 | [
"BSD-3-Clause"
] | null | null | null | miniapp/cosma_miniapp.cpp | simonpintarelli/COSMA | db26aeac475e3b0a15d36d74e56514392d3e8e00 | [
"BSD-3-Clause"
] | 1 | 2020-04-29T17:46:25.000Z | 2020-04-29T17:46:25.000Z | miniapp/cosma_miniapp.cpp | simonpintarelli/COSMA | db26aeac475e3b0a15d36d74e56514392d3e8e00 | [
"BSD-3-Clause"
] | null | null | null | #include <cosma/multiply.hpp>
#include <algorithm>
#include <cctype>
#include <chrono>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <limits>
#include <sstream>
#include <string>
#include <vector>
#include "../utils/parse_strategy.hpp"
using namespace cosma;
template <typename T>
void fill_int(T* ptr, size_t size) {
for (unsigned i = 0u; i < size; ++i) {
ptr[i] = 10*drand48();
}
}
// Reads an environment variable `n_iter`
//
int get_n_iter() {
auto env = std::getenv("n_iter");
return env == nullptr ? 1 : std::atoi(env);
}
void output_matrix(CosmaMatrix<double> &M, int rank) {
std::string local = M.which_matrix() + std::to_string(rank) + ".txt";
std::ofstream local_file(local);
local_file << M << std::endl;
local_file.close();
}
long run(const Strategy &s, MPI_Comm comm = MPI_COMM_WORLD) {
int rank, size;
MPI_Comm_rank(comm, &rank);
MPI_Comm_size(comm, &size);
// Declare A,B and C COSMA matrices objects
CosmaMatrix<double> A('A', s, rank);
CosmaMatrix<double> B('B', s, rank);
CosmaMatrix<double> C('C', s, rank);
double alpha = 1;
double beta = 0;
// fill the matrices with random data
srand48(rank);
fill_int(A.matrix_pointer(), A.matrix_size());
fill_int(B.matrix_pointer(), B.matrix_size());
MPI_Barrier(comm);
auto start = std::chrono::steady_clock::now();
multiply(A, B, C, s, comm, alpha, beta);
MPI_Barrier(comm);
auto end = std::chrono::steady_clock::now();
return std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
.count();
}
int main(int argc, char **argv) {
MPI_Init(&argc, &argv);
int P, rank;
MPI_Comm_size(MPI_COMM_WORLD, &P);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
const Strategy& strategy = parse_strategy(argc, argv);
if (rank == 0) {
std::cout << "Strategy = " << strategy << std::endl;
}
int n_iter = get_n_iter();
std::vector<long> times;
for (int i = 0; i < n_iter; ++i) {
long t_run = 0;
t_run = run(strategy);
times.push_back(t_run);
}
std::sort(times.begin(), times.end());
if (rank == 0) {
std::cout << "COSMA TIMES [ms] = ";
for (auto &time : times) {
std::cout << time << " ";
}
std::cout << std::endl;
}
MPI_Finalize();
return 0;
}
| 23.94 | 77 | 0.601086 | [
"vector"
] |
2f9ce8cbf75c15b2dfd2bfb7313f0457e3736fea | 16,263 | cpp | C++ | Tests/Source/ClosestJammingStepTests.cpp | MINATILO/packing-generation | 4d4f5d037e0687b57178602b989431e82a5c8b96 | [
"MIT"
] | 79 | 2015-08-23T12:05:30.000Z | 2022-03-31T16:39:56.000Z | Tests/Source/ClosestJammingStepTests.cpp | MINATILO/packing-generation | 4d4f5d037e0687b57178602b989431e82a5c8b96 | [
"MIT"
] | 31 | 2015-07-20T17:57:08.000Z | 2022-03-02T10:31:50.000Z | Tests/Source/ClosestJammingStepTests.cpp | MINATILO/packing-generation | 4d4f5d037e0687b57178602b989431e82a5c8b96 | [
"MIT"
] | 36 | 2015-10-14T02:43:16.000Z | 2022-03-18T12:51:03.000Z | // Copyright (c) 2013 Vasili Baranau
// Distributed under the MIT software license
// See the accompanying file License.txt or http://opensource.org/licenses/MIT
#include "../Headers/ClosestJammingStepTests.h"
#include "../Headers/Assert.h"
#include "Core/Headers/Math.h"
#include "Core/Headers/MemoryUtility.h"
#include "Core/Headers/StlUtilities.h"
#include "Generation/Geometries/Headers/BulkGeometry.h"
#include "Generation/Model/Headers/Config.h"
#include "Generation/PackingServices/DistanceServices/Headers/CellListNeighborProvider.h"
#include "Generation/PackingServices/Headers/MathService.h"
#include "Generation/PackingServices/Headers/GeometryService.h"
#include "Generation/PackingServices/Headers/PackingSerializer.h"
#include "Generation/PackingServices/DistanceServices/Headers/ClosestPairProvider.h"
#include "Generation/PackingServices/Headers/GeometryCollisionService.h"
#include "Generation/PackingServices/Headers/GeometryCollisionService.h"
#include "Generation/PackingServices/PostProcessing/Headers/HessianService.h"
#include "Generation/PackingServices/PostProcessing/Headers/RattlerRemovalService.h"
#include "Generation/PackingGenerators/Headers/ClosestJammingStep.h"
using namespace std;
using namespace Core;
using namespace Model;
using namespace Geometries;
using namespace PackingServices;
using namespace PackingGenerators;
namespace Tests
{
boost::shared_ptr<MathService> ClosestJammingStepTests::mathService;
boost::shared_ptr<GeometryService> ClosestJammingStepTests::geometryService;
boost::shared_ptr<INeighborProvider> ClosestJammingStepTests::neighborProvider;
boost::shared_ptr<IClosestPairProvider> ClosestJammingStepTests::closestPairProvider;
boost::shared_ptr<GeometryCollisionService> ClosestJammingStepTests::geometryCollisionService;
boost::shared_ptr<ClosestJammingStep> ClosestJammingStepTests::closestJammingStep;
boost::shared_ptr<IGeometry> ClosestJammingStepTests::geometry;
boost::shared_ptr<SystemConfig> ClosestJammingStepTests::config;
boost::shared_ptr<ModellingContext> ClosestJammingStepTests::context;
boost::shared_ptr<GenerationConfig> ClosestJammingStepTests::generationConfig;
Packing ClosestJammingStepTests::particles;
const int ClosestJammingStepTests::particlesCount = 4;
SpatialVector ClosestJammingStepTests::boxSize = REMOVE_LAST_DIMENSION_IF_NEEDED(10.0, 10.0, 10.0);
void ClosestJammingStepTests::SetUp()
{
mathService.reset(new MathService());
geometryService.reset(new GeometryService(mathService.get()));
geometryCollisionService.reset(new GeometryCollisionService());
neighborProvider.reset(new CellListNeighborProvider(geometryService.get(), geometryCollisionService.get()));
closestPairProvider.reset(new ClosestPairProvider(mathService.get(), neighborProvider.get()));
closestJammingStep.reset(new ClosestJammingStep(geometryService.get(), neighborProvider.get(), closestPairProvider.get(), mathService.get()));
config.reset(new SystemConfig());
config->packingSize = boxSize;
config->particlesCount = particlesCount;
config->boundariesMode = BoundariesMode::Bulk;
geometry.reset(new BulkGeometry(*config));
context.reset(new ModellingContext(config.get(), geometry.get()));
generationConfig.reset(new GenerationConfig());
mathService->SetContext(*context);
geometryService->SetContext(*context);
neighborProvider->SetContext(*context);
closestPairProvider->SetContext(*context);
closestJammingStep->SetContext(*context);
closestJammingStep->SetGenerationConfig(*generationConfig);
particles.clear();
particles.resize(particlesCount);
}
void ClosestJammingStepTests::TearDown()
{
}
void ClosestJammingStepTests::DisplaceParticles_ThreeParticlesInContact_DisplacementsCorrect(FLOAT_TYPE timeStep)
{
SetUp();
closestJammingStep->maxTimeStep = timeStep;
closestJammingStep->SetBondThreshold(1e-10);
closestJammingStep->integrationTimeStep = 1e-4;
// Arrange
// Three particles form a regular triangle, the fourth is away
const FLOAT_TYPE diameter = 0.5; // not 1.0, to test non-trivial diameters
const SpatialVector c0 = REMOVE_LAST_DIMENSION_IF_NEEDED(0, 0, 0);
const SpatialVector c1 = REMOVE_LAST_DIMENSION_IF_NEEDED(diameter, 0, 0);
const SpatialVector c2 = REMOVE_LAST_DIMENSION_IF_NEEDED(diameter * 0.5, diameter * sin(PI / 3.0), 0);
const SpatialVector c3 = REMOVE_LAST_DIMENSION_IF_NEEDED(5, 5, 0);
particles[0] = DomainParticle(0, diameter, c0);
particles[1] = DomainParticle(1, diameter, c1);
particles[2] = DomainParticle(2, diameter, c2);
particles[3] = DomainParticle(3, diameter, c3);
boost::array<SpatialVector, particlesCount> initialPositions = {{c0, c1, c2, c3}};
// Act
closestJammingStep->SetParticles(&particles);
closestJammingStep->DisplaceParticles();
// Assert
// Prepare expected displacements
// From-to
SpatialVector c01, c12, c02;
mathService->FillDistance(c1, c0, &c01);
mathService->FillDistance(c2, c1, &c12);
mathService->FillDistance(c2, c0, &c02);
SpatialVector d0, d1, d2;
VectorUtilities::Add(c01, c02, &d0);
VectorUtilities::MultiplyByValue(d0, - 1.0 / 3.0 * timeStep, &d0);
VectorUtilities::Subtract(c12, c01, &d1);
VectorUtilities::MultiplyByValue(d1, - 1.0 / 3.0 * timeStep, &d1);
VectorUtilities::Add(c12, c02, &d2);
VectorUtilities::MultiplyByValue(d2, 1.0 / 3.0 * timeStep, &d2);
SpatialVector d3 = REMOVE_LAST_DIMENSION_IF_NEEDED(0, 0, 0);
boost::array<SpatialVector, particlesCount> expectedDisplacements = {{d0, d1, d2, d3}};
// Get actual displacements
vector<SpatialVector> actualDisplacements(particlesCount);
for (int i = 0; i < particlesCount; ++i)
{
mathService->FillDistance(particles[i].coordinates, initialPositions[i], &actualDisplacements[i]);
}
// Compare displacements
for (int i = 0; i < particlesCount; ++i)
{
// printf("Index %d, actualDisplacement %g %g %g, expectedDisplacement %g %g %g\n",
// i,
// actualDisplacements[i][0], actualDisplacements[i][1], actualDisplacements[i][2],
// expectedDisplacements[i][0], expectedDisplacements[i][1], expectedDisplacements[i][2]);
Assert::AreVectorsAlmostEqual(actualDisplacements[i], expectedDisplacements[i], "DisplaceParticles_ThreeParticlesInContact_DisplacementsCorrect");
}
TearDown();
}
void ClosestJammingStepTests::DisplaceParticles_FourParticlesInContact_DisplacementsCorrect(FLOAT_TYPE timeStep)
{
SetUp();
closestJammingStep->maxTimeStep = timeStep;
closestJammingStep->SetBondThreshold(1e-10);
closestJammingStep->integrationTimeStep = 1e-4;
// Arrange
// Particles form a "snake"
const FLOAT_TYPE diameter = 0.5; // not 1.0, to test non-trivial diameters
const SpatialVector c0 = REMOVE_LAST_DIMENSION_IF_NEEDED(0, 0, 0);
const SpatialVector c1 = REMOVE_LAST_DIMENSION_IF_NEEDED(c0[0] + diameter * cos(PI / 3.0), c0[1] + diameter * sin(PI / 3.0), 0);
const SpatialVector c2 = REMOVE_LAST_DIMENSION_IF_NEEDED(c1[0] + diameter, c1[1], 0);
const SpatialVector c3 = REMOVE_LAST_DIMENSION_IF_NEEDED(c2[0], c2[1] + diameter, 0);
particles[0] = DomainParticle(0, diameter, c0);
particles[1] = DomainParticle(1, diameter, c1);
particles[2] = DomainParticle(2, diameter, c2);
particles[3] = DomainParticle(3, diameter, c3);
boost::array<SpatialVector, particlesCount> initialPositions = {{c0, c1, c2, c3}};
// Act
closestJammingStep->SetParticles(&particles);
closestJammingStep->DisplaceParticles();
// Assert
// Prepare expected displacements
// From-to
SpatialVector c01, c12, c23;
mathService->FillDistance(c1, c0, &c01);
mathService->FillDistance(c2, c1, &c12);
mathService->FillDistance(c3, c2, &c23);
SpatialVector d0, d1, d2, d3;
// Displacements calculated on paper
VectorUtilities::MultiplyByValue(c01, - 2.0 / 3.0 * timeStep, &d0);
VectorUtilities::Subtract(c01, c12, &d1);
VectorUtilities::MultiplyByValue(d1, 2.0 / 3.0 * timeStep, &d1);
VectorUtilities::MultiplyByValue(c12, 2.0 / 3.0 * timeStep, &d2);
SpatialVector temp;
VectorUtilities::MultiplyByValue(c23, - 0.5 * timeStep, &temp);
VectorUtilities::Add(d2, temp, &d2);
VectorUtilities::MultiplyByValue(c23, 0.5 * timeStep, &d3);
boost::array<SpatialVector, particlesCount> expectedDisplacements = {{d0, d1, d2, d3}};
// Get actual displacements
vector<SpatialVector> actualDisplacements(particlesCount);
for (int i = 0; i < particlesCount; ++i)
{
mathService->FillDistance(particles[i].coordinates, initialPositions[i], &actualDisplacements[i]);
}
// Compare displacements
for (int i = 0; i < particlesCount; ++i)
{
// printf("Index %d, actualDisplacement %g %g %g, expectedDisplacement %g %g %g\n",
// i,
// actualDisplacements[i][0], actualDisplacements[i][1], actualDisplacements[i][2],
// expectedDisplacements[i][0], expectedDisplacements[i][1], expectedDisplacements[i][2]);
Assert::AreVectorsAlmostEqual(actualDisplacements[i], expectedDisplacements[i], "DisplaceParticles_FourParticlesInContact_DisplacementsCorrect");
}
TearDown();
}
void ClosestJammingStepTests::DisplaceParticles_FourParticlesInContactForLargeTime_NoGapsNoIntersections()
{
SetUp();
const FLOAT_TYPE timeStep = 0.001;
closestJammingStep->maxTimeStep = timeStep;
closestJammingStep->SetBondThreshold(1e-10);
closestJammingStep->integrationTimeStep = 1e-7;
// Arrange
// Particles form a "snake"
const FLOAT_TYPE diameter = 0.5; // not 1.0, to test non-trivial diameters
const SpatialVector c0 = REMOVE_LAST_DIMENSION_IF_NEEDED(0, 0, 0);
const SpatialVector c1 = REMOVE_LAST_DIMENSION_IF_NEEDED(c0[0] + diameter * cos(PI / 3.0), c0[1] + diameter * sin(PI / 3.0), 0);
const SpatialVector c2 = REMOVE_LAST_DIMENSION_IF_NEEDED(c1[0] + diameter, c1[1], 0);
const SpatialVector c3 = REMOVE_LAST_DIMENSION_IF_NEEDED(c2[0], c2[1] + diameter, 0);
particles[0] = DomainParticle(0, diameter, c0);
particles[1] = DomainParticle(1, diameter, c1);
particles[2] = DomainParticle(2, diameter, c2);
particles[3] = DomainParticle(3, diameter, c3);
// Act
closestJammingStep->SetParticles(&particles);
closestJammingStep->DisplaceParticles();
// Assert
// No intersections
for (int i = 0; i < particlesCount - 1; ++i)
{
for (int j = i + 1; j < particlesCount; ++j)
{
FLOAT_TYPE distanceSquare = mathService->GetDistanceSquare(particles[i].coordinates, particles[j].coordinates);
const FLOAT_TYPE errorThreshold = 1e-12;
FLOAT_TYPE minDistance = (particles[i].diameter + particles[j].diameter) * 0.5 * (1.0 + timeStep) * (1.0 - errorThreshold);
bool hasIntersection = (distanceSquare < minDistance * minDistance);
Assert::IsTrue(!hasIntersection, "DisplaceParticles_FourParticlesInContactForLargeTime_NoGapsNoIntersections");
}
}
// No gaps
boost::array< pair<int, int>, 3> particlePairs = {{ pair<int, int>(0, 1), pair<int, int>(1, 2), pair<int, int>(2, 3) }};
for (size_t i = 0; i < particlePairs.size(); ++i)
{
const pair<int, int>& pair = particlePairs[i];
FLOAT_TYPE distanceSquare = mathService->GetDistanceSquare(particles[pair.first].coordinates, particles[pair.second].coordinates);
const FLOAT_TYPE errorThreshold = 1e-10;
FLOAT_TYPE maxDistance = (particles[pair.first].diameter + particles[pair.second].diameter) * 0.5 * (1.0 + timeStep) * (1.0 + errorThreshold);
bool hasGap = (distanceSquare > maxDistance * maxDistance);
Assert::IsTrue(!hasGap, "DisplaceParticles_FourParticlesInContactForLargeTime_NoGapsNoIntersections");
}
TearDown();
}
void ClosestJammingStepTests::DisplaceParticles_ThreeParticlesUntilReachingFourth_NoIntersectionsNoGaps()
{
SetUp();
closestJammingStep->SetBondThreshold(1e-10);
closestJammingStep->integrationTimeStep = 1e-7;
// Arrange
// Three particles form a regular triangle, the fourth is away
const FLOAT_TYPE diameter = 0.5; // not 1.0, to test non-trivial diameters
const SpatialVector c0 = REMOVE_LAST_DIMENSION_IF_NEEDED(0, 0, 0);
const SpatialVector c1 = REMOVE_LAST_DIMENSION_IF_NEEDED(diameter, 0, 0);
const SpatialVector c2 = REMOVE_LAST_DIMENSION_IF_NEEDED(diameter * 0.5, diameter * sin(PI / 3.0), 0);
const SpatialVector c3 = REMOVE_LAST_DIMENSION_IF_NEEDED(diameter * 0.5, diameter * sin(PI / 3.0) + diameter + 0.001, 0); // When the third particle will contact this one, the growth will stop
particles[0] = DomainParticle(0, diameter, c0);
particles[1] = DomainParticle(1, diameter, c1);
particles[2] = DomainParticle(2, diameter, c2);
particles[3] = DomainParticle(3, diameter, c3);
// Act
closestJammingStep->SetParticles(&particles);
closestJammingStep->DisplaceParticles();
// Assert
// Get the time step dynamically
FLOAT_TYPE currentTime = mathService->GetNormalizedDistance(particles[2], particles[3]);
// No intersections
for (int i = 0; i < particlesCount - 1; ++i)
{
for (int j = i + 1; j < particlesCount; ++j)
{
FLOAT_TYPE distanceSquare = mathService->GetDistanceSquare(particles[i].coordinates, particles[j].coordinates);
const FLOAT_TYPE errorThreshold = 1e-10;
FLOAT_TYPE minDistance = (particles[i].diameter + particles[j].diameter) * 0.5 * currentTime * (1.0 - errorThreshold);
bool hasIntersection = (distanceSquare < minDistance * minDistance);
Assert::IsTrue(!hasIntersection, "DisplaceParticles_ThreeParticlesUntilReachingFourth_NoIntersectionsNoGaps");
}
}
// No gaps
boost::array< pair<int, int>, 3> particlePairs = {{ pair<int, int>(0, 1), pair<int, int>(1, 2), pair<int, int>(2, 3) }};
for (size_t i = 0; i < particlePairs.size(); ++i)
{
const pair<int, int>& pair = particlePairs[i];
FLOAT_TYPE distanceSquare = mathService->GetDistanceSquare(particles[pair.first].coordinates, particles[pair.second].coordinates);
const FLOAT_TYPE errorThreshold = 1e-10;
FLOAT_TYPE maxDistance = (particles[pair.first].diameter + particles[pair.second].diameter) * 0.5 * currentTime * (1.0 + errorThreshold);
bool hasGap = (distanceSquare > maxDistance * maxDistance);
Assert::IsTrue(!hasGap, "DisplaceParticles_ThreeParticlesUntilReachingFourth_NoIntersectionsNoGaps");
}
TearDown();
}
void ClosestJammingStepTests::RunTests()
{
DisplaceParticles_ThreeParticlesInContact_DisplacementsCorrect(1e-8);
DisplaceParticles_ThreeParticlesInContact_DisplacementsCorrect(0.1);
DisplaceParticles_FourParticlesInContact_DisplacementsCorrect(1e-8);
DisplaceParticles_FourParticlesInContactForLargeTime_NoGapsNoIntersections();
DisplaceParticles_ThreeParticlesUntilReachingFourth_NoIntersectionsNoGaps();
}
}
| 45.427374 | 200 | 0.675644 | [
"geometry",
"vector",
"model"
] |
2f9fc9e3402d775f0723036645f21af163b57168 | 2,206 | cpp | C++ | 1. White/Week 4/07. Students list/main.cpp | AmaterasuOmikami/The-art-of-modern-Cpp-development | 4f0958197da92d216ee526384a6f7386a0fe62a0 | [
"MIT"
] | 1 | 2022-02-17T10:58:58.000Z | 2022-02-17T10:58:58.000Z | 1. White/Week 4/07. Students list/main.cpp | AmaterasuOmikami/The-art-of-modern-Cpp-development | 4f0958197da92d216ee526384a6f7386a0fe62a0 | [
"MIT"
] | null | null | null | 1. White/Week 4/07. Students list/main.cpp | AmaterasuOmikami/The-art-of-modern-Cpp-development | 4f0958197da92d216ee526384a6f7386a0fe62a0 | [
"MIT"
] | null | null | null | /*
* Определите структуру «Студент» со следующими полями: имя, фамилия, день,
* месяц и год рождения. Создайте вектор из таких структур, заполните его из
* входных данных и затем по запросам выведите нужные поля. Чтение и запись
* данных в этой задаче производится с использованием стандартных потоков.
*
* Формат ввода
* Первая строка содержит одно целое число N от 0 до 10000 — число студентов.
* Далее идут N строк, каждая из которых содержит две строки длиной от 1 до 15
* символов — имя и фамилию очередного студента, и три целых числа от 0 до
* 1000000000 — день, месяц и год рождения.
* Следующая строка содержит одно целое число M от 0 до 10000 — число запросов.
* Следующие M строк содержат строку длиной от 1 до 15 символов — запрос, и
* целое число от 1 до 1000000000 — номер студента (нумерация начинается с 1).
*
* Формат вывода
* Для запроса вида name K, где K от 1 до N, выведите через пробел имя и фамилию
* K-го студента.
* Для запроса вида date K, где K от 1 до N, выведите через точку день, месяц и
* год рождения K-го студента.
* Для остальных запросов выведите bad request.
*
* NB: неверные запросы могут выходить за границы, указанные для данных.
*/
#include <iostream>
#include <vector>
using namespace std;
struct Student {
string first_name;
string last_name;
int birth_day;
int birth_month;
int birth_year;
};
int main() {
int n;
cin >> n;
vector<Student> students(n);
for (auto& student : students) {
cin >> student.first_name
>> student.last_name
>> student.birth_day
>> student.birth_month
>> student.birth_year;
}
int m;
cin >> m;
for (int i = 0; i < m; ++i) {
string command;
cin >> command;
int id;
cin >> id;
--id;
if (!(0 <= id && id < n)) {
cout << "bad request" << endl;
continue;
}
if (command == "name") {
cout << students[id].first_name << ' '
<< students[id].last_name << endl;
} else if (command == "date") {
cout << students[id].birth_day << '.'
<< students[id].birth_month << '.'
<< students[id].birth_year << endl;
} else {
cout << "bad request" << endl;
}
}
}
| 28.649351 | 80 | 0.643246 | [
"vector"
] |
2fb8aae3d7be0936cabd1b5eeb1db979f04e45cb | 1,717 | hpp | C++ | irohad/simulator/verified_proposal_creator.hpp | truongnmt/iroha | e9b969df9a0eb6ce62eae3ab62c5c3f046a5e6e1 | [
"Apache-2.0"
] | null | null | null | irohad/simulator/verified_proposal_creator.hpp | truongnmt/iroha | e9b969df9a0eb6ce62eae3ab62c5c3f046a5e6e1 | [
"Apache-2.0"
] | null | null | null | irohad/simulator/verified_proposal_creator.hpp | truongnmt/iroha | e9b969df9a0eb6ce62eae3ab62c5c3f046a5e6e1 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright Soramitsu Co., Ltd. 2017 All Rights Reserved.
* http://soramitsu.co.jp
*
* 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 IROHA_VERIFIED_PROPOSAL_CREATOR_HPP
#define IROHA_VERIFIED_PROPOSAL_CREATOR_HPP
#include <rxcpp/rx-observable.hpp>
#include "validation/stateful_validator_common.hpp"
namespace shared_model {
namespace interface {
class Proposal;
}
} // namespace shared_model
namespace iroha {
namespace simulator {
/**
* Interface for providing proposal validation
*/
class VerifiedProposalCreator {
public:
/**
* Processing proposal for making stateful validation
* @param proposal - object for validation
*/
virtual void process_proposal(
const shared_model::interface::Proposal &proposal) = 0;
/**
* Emit proposals that was verified by validation
* @return
*/
virtual rxcpp::observable<
std::shared_ptr<iroha::validation::VerifiedProposalAndErrors>>
on_verified_proposal() = 0;
virtual ~VerifiedProposalCreator() = default;
};
} // namespace simulator
} // namespace iroha
#endif // IROHA_VERIFIED_PROPOSAL_CREATOR_HPP
| 29.603448 | 75 | 0.70297 | [
"object"
] |
2fd3131648a667c3ee868c83a905916658786556 | 1,938 | cpp | C++ | src/ToGraphvizWriter.cpp | dueringa/WikiWalker | 24a83936efac1e217af949275b0677861c216957 | [
"MIT"
] | null | null | null | src/ToGraphvizWriter.cpp | dueringa/WikiWalker | 24a83936efac1e217af949275b0677861c216957 | [
"MIT"
] | 1 | 2018-03-17T15:42:18.000Z | 2018-03-19T11:49:03.000Z | src/ToGraphvizWriter.cpp | dueringa/WikiWalker | 24a83936efac1e217af949275b0677861c216957 | [
"MIT"
] | null | null | null | //! \file ToGraphvizWriter.cpp
#include "ToGraphvizWriter.h"
#include <string>
// uh-oh...
#include <regex>
#include "Article.h"
namespace WikiWalker
{
static void writeHeader(std::ostream& os)
{
os << "digraph G {";
os << std::endl;
}
static void writeFooter(std::ostream& os)
{
os << "}";
os << std::endl;
}
/*! \bug When writing an #Article only, attributes are only set on the article
* itself. Attributes won't be written on linked articles.
* However, when writing an #ArticleCollection, all articles are included, so
* all attibutes will be written.
*/
static void writeArticle(const Article* a, std::ostream& os)
{
std::string atitle = a->title();
// search for quotes
std::regex re(R"(")");
// replace by escaped quote
atitle = std::regex_replace(atitle, re, R"(\")");
// marked articles are printed as box
if(a->marked()) {
os << R"(")" << atitle << R"(" [shape=box];)" << std::endl;
}
if(!a->analyzed()) {
os << R"(")" << atitle << R"(" [fillcolor=gray,style=filled];)"
<< std::endl;
}
// unanalyzed articles are printed greyed out
for(auto al = a->linkBegin(); al != a->linkEnd(); al++) {
auto lck_article = al->lock();
if(lck_article != nullptr) {
std::string alinkedtitle = lck_article->title();
os << R"(")" << atitle << R"(" -> ")"
<< std::regex_replace(alinkedtitle, re, R"(\")") << R"(";)"
<< std::endl;
}
}
}
void ToGraphvizWriter::output(const Article* a, std::ostream& os)
{
writeHeader(os);
writeArticle(a, os);
writeFooter(os);
}
void ToGraphvizWriter::output(const CollectionUtils::ArticleCollection& ac,
std::ostream& os)
{
writeHeader(os);
for(auto a : ac) {
writeArticle(a.second.get(), os);
}
writeFooter(os);
}
} // namespace WikiWalker
| 23.634146 | 80 | 0.567595 | [
"shape"
] |
2fd4f5c2197b0a9ea00a951cbbd62ef68b9f9a4b | 13,255 | hpp | C++ | source/patterns.hpp | huhlig/libcube | f322593b511ec75375a4a9ac3fd3596a64c39933 | [
"Apache-2.0"
] | 2 | 2020-01-18T21:34:24.000Z | 2020-07-12T04:31:20.000Z | source/patterns.hpp | huhlig/libcube | f322593b511ec75375a4a9ac3fd3596a64c39933 | [
"Apache-2.0"
] | null | null | null | source/patterns.hpp | huhlig/libcube | f322593b511ec75375a4a9ac3fd3596a64c39933 | [
"Apache-2.0"
] | null | null | null | #ifndef LEDCUBE_PATTERNS_HPP
#define LEDCUBE_PATTERNS_HPP
#include "cube.hpp"
#include <vector>
std::vector<MonochromeCube<4, 4, 4>::Frame> pattern_1{
MonochromeCube<4, 4, 4>::Frame(MonochromeCube<4, 4, 4>::Buffer{
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
}),
MonochromeCube<4, 4, 4>::Frame(MonochromeCube<4, 4, 4>::Buffer{
0xFF, 0x00, 0x00, 0x00,
0xFF, 0x00, 0x00, 0x00,
0xFF, 0x00, 0x00, 0x00,
0xFF, 0x00, 0x00, 0x00,
0xFF, 0x00, 0x00, 0x00,
0xFF, 0x00, 0x00, 0x00,
0xFF, 0x00, 0x00, 0x00,
0xFF, 0x00, 0x00, 0x00,
0xFF, 0x00, 0x00, 0x00,
0xFF, 0x00, 0x00, 0x00,
0xFF, 0x00, 0x00, 0x00,
0xFF, 0x00, 0x00, 0x00,
0xFF, 0x00, 0x00, 0x00,
0xFF, 0x00, 0x00, 0x00,
0xFF, 0x00, 0x00, 0x00,
0xFF, 0x00, 0x00, 0x00
}),
MonochromeCube<4, 4, 4>::Frame(MonochromeCube<4, 4, 4>::Buffer{
0xAA, 0xFF, 0x00, 0x00,
0xAA, 0xFF, 0x00, 0x00,
0xAA, 0xFF, 0x00, 0x00,
0xAA, 0xFF, 0x00, 0x00,
0xAA, 0xFF, 0x00, 0x00,
0xAA, 0xFF, 0x00, 0x00,
0xAA, 0xFF, 0x00, 0x00,
0xAA, 0xFF, 0x00, 0x00,
0xAA, 0xFF, 0x00, 0x00,
0xAA, 0xFF, 0x00, 0x00,
0xAA, 0xFF, 0x00, 0x00,
0xAA, 0xFF, 0x00, 0x00,
0xAA, 0xFF, 0x00, 0x00,
0xAA, 0xFF, 0x00, 0x00,
0xAA, 0xFF, 0x00, 0x00,
0xAA, 0xFF, 0x00, 0x00
}),
MonochromeCube<4, 4, 4>::Frame(MonochromeCube<4, 4, 4>::Buffer{
0x88, 0xAA, 0xFF, 0x00,
0x88, 0xAA, 0xFF, 0x00,
0x88, 0xAA, 0xFF, 0x00,
0x88, 0xAA, 0xFF, 0x00,
0x88, 0xAA, 0xFF, 0x00,
0x88, 0xAA, 0xFF, 0x00,
0x88, 0xAA, 0xFF, 0x00,
0x88, 0xAA, 0xFF, 0x00,
0x88, 0xAA, 0xFF, 0x00,
0x88, 0xAA, 0xFF, 0x00,
0x88, 0xAA, 0xFF, 0x00,
0x88, 0xAA, 0xFF, 0x00,
0x88, 0xAA, 0xFF, 0x00,
0x88, 0xAA, 0xFF, 0x00,
0x88, 0xAA, 0xFF, 0x00,
0x88, 0xAA, 0xFF, 0x00
}),
MonochromeCube<4, 4, 4>::Frame(MonochromeCube<4, 4, 4>::Buffer{
0x80, 0x88, 0xAA, 0xFF,
0x80, 0x88, 0xAA, 0xFF,
0x80, 0x88, 0xAA, 0xFF,
0x80, 0x88, 0xAA, 0xFF,
0x80, 0x88, 0xAA, 0xFF,
0x80, 0x88, 0xAA, 0xFF,
0x80, 0x88, 0xAA, 0xFF,
0x80, 0x88, 0xAA, 0xFF,
0x80, 0x88, 0xAA, 0xFF,
0x80, 0x88, 0xAA, 0xFF,
0x80, 0x88, 0xAA, 0xFF,
0x80, 0x88, 0xAA, 0xFF,
0x80, 0x88, 0xAA, 0xFF,
0x80, 0x88, 0xAA, 0xFF,
0x80, 0x88, 0xAA, 0xFF,
0x80, 0x88, 0xAA, 0xFF
}),
MonochromeCube<4, 4, 4>::Frame(MonochromeCube<4, 4, 4>::Buffer{
0x00, 0x80, 0x88, 0xAA,
0x00, 0x80, 0x88, 0xAA,
0x00, 0x80, 0x88, 0xAA,
0x00, 0x80, 0x88, 0xAA,
0x00, 0x80, 0x88, 0xAA,
0x00, 0x80, 0x88, 0xAA,
0x00, 0x80, 0x88, 0xAA,
0x00, 0x80, 0x88, 0xAA,
0x00, 0x80, 0x88, 0xAA,
0x00, 0x80, 0x88, 0xAA,
0x00, 0x80, 0x88, 0xAA,
0x00, 0x80, 0x88, 0xAA,
0x00, 0x80, 0x88, 0xAA,
0x00, 0x80, 0x88, 0xAA,
0x00, 0x80, 0x88, 0xAA,
0x00, 0x80, 0x88, 0xAA
}),
MonochromeCube<4, 4, 4>::Frame(MonochromeCube<4, 4, 4>::Buffer{
0x00, 0x00, 0x80, 0x88,
0x00, 0x00, 0x80, 0x88,
0x00, 0x00, 0x80, 0x88,
0x00, 0x00, 0x80, 0x88,
0x00, 0x00, 0x80, 0x88,
0x00, 0x00, 0x80, 0x88,
0x00, 0x00, 0x80, 0x88,
0x00, 0x00, 0x80, 0x88,
0x00, 0x00, 0x80, 0x88,
0x00, 0x00, 0x80, 0x88,
0x00, 0x00, 0x80, 0x88,
0x00, 0x00, 0x80, 0x88,
0x00, 0x00, 0x80, 0x88,
0x00, 0x00, 0x80, 0x88,
0x00, 0x00, 0x80, 0x88,
0x00, 0x00, 0x80, 0x88
}),
MonochromeCube<4, 4, 4>::Frame(MonochromeCube<4, 4, 4>::Buffer{
0x00, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x80
}),
MonochromeCube<4, 4, 4>::Frame(MonochromeCube<4, 4, 4>::Buffer{
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
}),
MonochromeCube<4, 4, 4>::Frame(MonochromeCube<4, 4, 4>::Buffer{
0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
}),
MonochromeCube<4, 4, 4>::Frame(MonochromeCube<4, 4, 4>::Buffer{
0xAA, 0xAA, 0xAA, 0xAA,
0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0xAA, 0xAA, 0xAA, 0xAA,
0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0xAA, 0xAA, 0xAA, 0xAA,
0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0xAA, 0xAA, 0xAA, 0xAA,
0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
}),
MonochromeCube<4, 4, 4>::Frame(MonochromeCube<4, 4, 4>::Buffer{
0x88, 0x88, 0x88, 0x88,
0xAA, 0xAA, 0xAA, 0xAA,
0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0x00, 0x00, 0x00,
0x88, 0x88, 0x88, 0x88,
0xAA, 0xAA, 0xAA, 0xAA,
0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0x00, 0x00, 0x00,
0x88, 0x88, 0x88, 0x88,
0xAA, 0xAA, 0xAA, 0xAA,
0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0x00, 0x00, 0x00,
0x88, 0x88, 0x88, 0x88,
0xAA, 0xAA, 0xAA, 0xAA,
0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0x00, 0x00, 0x00
}),
MonochromeCube<4, 4, 4>::Frame(MonochromeCube<4, 4, 4>::Buffer{
0x88, 0x88, 0x88, 0x88,
0xAA, 0xAA, 0xAA, 0xAA,
0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0x00, 0x00, 0x00,
0x88, 0x88, 0x88, 0x88,
0xAA, 0xAA, 0xAA, 0xAA,
0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0x00, 0x00, 0x00,
0x88, 0x88, 0x88, 0x88,
0xAA, 0xAA, 0xAA, 0xAA,
0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0x00, 0x00, 0x00,
0x88, 0x88, 0x88, 0x88,
0xAA, 0xAA, 0xAA, 0xAA,
0xFF, 0xFF, 0xFF, 0xFF,
0x00, 0x00, 0x00, 0x00
}),
MonochromeCube<4, 4, 4>::Frame(MonochromeCube<4, 4, 4>::Buffer{
0x80, 0x80, 0x80, 0x80,
0x88, 0x88, 0x88, 0x88,
0xAA, 0xAA, 0xAA, 0xAA,
0xFF, 0xFF, 0xFF, 0xFF,
0x80, 0x80, 0x80, 0x80,
0x88, 0x88, 0x88, 0x88,
0xAA, 0xAA, 0xAA, 0xAA,
0xFF, 0xFF, 0xFF, 0xFF,
0x80, 0x80, 0x80, 0x80,
0x88, 0x88, 0x88, 0x88,
0xAA, 0xAA, 0xAA, 0xAA,
0xFF, 0xFF, 0xFF, 0xFF,
0x80, 0x80, 0x80, 0x80,
0x88, 0x88, 0x88, 0x88,
0xAA, 0xAA, 0xAA, 0xAA,
0xFF, 0xFF, 0xFF, 0xFF
}),
MonochromeCube<4, 4, 4>::Frame(MonochromeCube<4, 4, 4>::Buffer{
0x00, 0x00, 0x00, 0x00,
0x80, 0x80, 0x80, 0x80,
0x88, 0x88, 0x88, 0x88,
0xAA, 0xAA, 0xAA, 0xAA,
0x00, 0x00, 0x00, 0x00,
0x80, 0x80, 0x80, 0x80,
0x88, 0x88, 0x88, 0x88,
0xAA, 0xAA, 0xAA, 0xAA,
0x00, 0x00, 0x00, 0x00,
0x80, 0x80, 0x80, 0x80,
0x88, 0x88, 0x88, 0x88,
0xAA, 0xAA, 0xAA, 0xAA,
0x00, 0x00, 0x00, 0x00,
0x80, 0x80, 0x80, 0x80,
0x88, 0x88, 0x88, 0x88,
0xAA, 0xAA, 0xAA, 0xAA
}),
MonochromeCube<4, 4, 4>::Frame(MonochromeCube<4, 4, 4>::Buffer{
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x80, 0x80, 0x80, 0x80,
0x88, 0x88, 0x88, 0x88,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x80, 0x80, 0x80, 0x80,
0x88, 0x88, 0x88, 0x88,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x80, 0x80, 0x80, 0x80,
0x88, 0x88, 0x88, 0x88,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x80, 0x80, 0x80, 0x80,
0x88, 0x88, 0x88, 0x88
}),
MonochromeCube<4, 4, 4>::Frame(MonochromeCube<4, 4, 4>::Buffer{
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x80, 0x80, 0x80, 0x80,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x80, 0x80, 0x80, 0x80,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x80, 0x80, 0x80, 0x80,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x80, 0x80, 0x80, 0x80
}),
MonochromeCube<4, 4, 4>::Frame(MonochromeCube<4, 4, 4>::Buffer{
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
}),
};
#endif//LEDCUBE_PATTERNS_HPP
| 33.987179 | 71 | 0.419615 | [
"vector"
] |
2fd8ad327fa2b93c58ec945a05cccedb02d1ec79 | 2,781 | cpp | C++ | KernelSDK/src/coredrivers/KernelFileLogDriver/cTextLogDriver.cpp | rodrigomr/VFS | 6b68b00df8cb668106c2d0841cbcd46138298717 | [
"Apache-2.0"
] | 38 | 2018-09-24T09:37:41.000Z | 2022-02-21T04:16:43.000Z | KernelSDK/src/coredrivers/KernelFileLogDriver/cTextLogDriver.cpp | rodrigomr/VFS | 6b68b00df8cb668106c2d0841cbcd46138298717 | [
"Apache-2.0"
] | 1 | 2018-10-02T17:57:44.000Z | 2018-10-07T06:55:44.000Z | KernelSDK/src/coredrivers/KernelFileLogDriver/cTextLogDriver.cpp | rodrigomr/VFS | 6b68b00df8cb668106c2d0841cbcd46138298717 | [
"Apache-2.0"
] | 6 | 2018-10-02T17:12:38.000Z | 2021-01-27T10:01:30.000Z | // Copyright 2018 Grass Valley, A Belden Brand
// 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 "stdafx.h"
using namespace vfs;
//{{{
const std::string cTextLogDriver::getPrefix(const iLogDriver::cMsg& msg) const
{
if (msg.m_Type == iLogDriver::cMsg::eBreak)
return "\r\n\r\n\r\n\r\n\r\n";
std::stringstream prefix;
// output the time
{
char buffer[32];
sprintf(buffer, "%02d:%02d:%02d.%03d %5d", msg.m_LocalTime.getHour(), msg.m_LocalTime.getMinute(), msg.m_LocalTime.getSecond(), msg.m_LocalTime.getMillisec(), msg.m_ThreadID);
prefix << buffer;
}
prefix << (msg.m_NumInjectedIndents > 0 ? "-> " : " ");
for (UInt32 i = 0; i < msg.m_NumIndents; ++i)
prefix << " ";
// output the module info
char singleChar[2] = " "; // the + - or space for thread indenting
switch (msg.m_Type)
{
case iLogDriver::cMsg::eLazyIndent:
return prefix.str() + " {";
case iLogDriver::cMsg::eOutdent:
return prefix.str() + " }";
case iLogDriver::cMsg::eCollapsedIndent:
singleChar[0] = '+';
break;
case iLogDriver::cMsg::eExpandedIndent:
singleChar[0] = '-';
break;
}
{
const bool isMainThread = (msg.m_ThreadName.substr(0, 4) == L"Krnl"); // backwards compatible with KernelFileLogDriver
std::string name = narrow(isMainThread ?
msg.m_ModuleName.substr(0, msg.m_ModuleName.find_first_of(L'.')) : // remove the ".dll"
msg.m_ThreadName);
std::transform(name.begin(), name.end(), name.begin(), ::toupper);
prefix << singleChar << name << " ";
}
return prefix.str();
}
const String cTextLogDriver::getBody(const iLogDriver::cMsg& msg) const
{
switch (msg.m_Type)
{
case iLogDriver::cMsg::eBreak:
return L" " + msg.m_Text + L"\r\n\r\n";
case iLogDriver::cMsg::eLazyIndent:
case iLogDriver::cMsg::eOutdent:
return L"";
default:
return msg.m_Text + (msg.m_Type == iLogDriver::cMsg::eCollapsedIndent ? L"..." : L"");
}
}
//}}}
//{{{
void cTextLogDriver::handleMsg(const iLogDriver::cMsg& msg) const
{
// The reason for the getPrefix and getBody functions was that cHtmlLogDriver
// was originally going derive from cTextLogDriver to reduce duplication.
write(getPrefix(msg));
write(getBody(msg));
write("\r\n");
}
//}}}
| 28.670103 | 179 | 0.665228 | [
"transform"
] |
2fd8e9828961f7d050b42cea252f14c75966fd85 | 4,819 | tpp | C++ | Core/src.tpp/Range$en-us.tpp | koz4k/soccer | 7bceea654b50c5c0e18effd38e79249bd295e0a4 | [
"MIT"
] | 1 | 2018-09-28T17:04:11.000Z | 2018-09-28T17:04:11.000Z | Core/src.tpp/Range$en-us.tpp | koz4k/soccer | 7bceea654b50c5c0e18effd38e79249bd295e0a4 | [
"MIT"
] | 1 | 2021-04-06T21:57:39.000Z | 2021-04-06T21:57:39.000Z | Core/src.tpp/Range$en-us.tpp | koz4k/soccer | 7bceea654b50c5c0e18effd38e79249bd295e0a4 | [
"MIT"
] | 3 | 2017-08-26T12:06:05.000Z | 2019-11-22T16:57:47.000Z | topic "Range";
[2 $$0,0#00000000000000000000000000000000:Default]
[i448;a25;kKO9;2 $$1,0#37138531426314131252341829483380:class]
[l288;2 $$2,2#27521748481378242620020725143825:desc]
[0 $$3,0#96390100711032703541132217272105:end]
[H6;0 $$4,0#05600065144404261032431302351956:begin]
[i448;a25;kKO9;2 $$5,0#37138531426314131252341829483370:item]
[l288;a4;*@5;1 $$6,6#70004532496200323422659154056402:requirement]
[l288;i1121;b17;O9;~~~.1408;2 $$7,0#10431211400427159095818037425705:param]
[i448;b42;O9;2 $$8,8#61672508125594000341940100500538:tparam]
[b42;2 $$9,9#13035079074754324216151401829390:normal]
[{_}%EN-US
[ {{10000@(113.42.0) [s0; [*@7;4 Range]]}}&]
[s1;O_; &]
[s0; U`+`+ algorithms are designed to work on [*/ Ranges]. Range is
a type that has (at minimum)&]
[s0; &]
[s0;i150;O0; Standard begin() / end() methods.&]
[s0;i150;O0; GetCount() that returns the number of elements in Range
(can be implemented as end `- begin)&]
[s0;i150;O0; operator`[`] (can be implemented as begin()`[i`])&]
[s0; &]
[s0; Standard Ranges usually also implement ToString and comparisons
(if it is possible).&]
[s0; &]
[s0; Usually, Range is either U`+`+ container or just some part of
it.&]
[s0; &]
[s0; U`+`+ provides these Range related typedefs and template functions:&]
[s3; &]
[s4;%- &]
[s5;:Upp`:`:ValueTypeOf`:`:typedef:%- [@(0.0.255) template <class ][*@4 Range][@(0.0.255) >
using]_[* ValueTypeOf];&]
[s2; Returns the type of elements of Range.&]
[s3;%- &]
[s4;%- &]
[s5;:Upp`:`:IteratorOf`:`:typedef:%- [@(0.0.255) template <class ][*@4 Range][@(0.0.255) >
using]_[* IteratorOf];&]
[s5;:Upp`:`:ConstIteratorOf`:`:typedef:%- [@(0.0.255) template <class
][*@4 Range][@(0.0.255) > using]_[* ConstIteratorOf]`'&]
[s2; Returns the type of Iterator / ConstIterator of range.&]
[s3; &]
[s4;%- &]
[s5;:Upp`:`:SubRange`(I`,I`):%- [@(0.0.255) template]_<[@(0.0.255) class]_[*@4 I]>_&]
[s5;:Upp`:`:SubRange`(I`,I`):%- [_^Upp`:`:SubRangeClass^ SubRangeClass]<[*@4 I]>_[* SubRang
e]([*@4 I]_[*@3 begin], [*@4 I]_[*@3 end])&]
[s2; Makes a Range based on begin/end iterators.&]
[s3; &]
[s4;%- &]
[s5;:Upp`:`:SubRange`(I`,int`):%- [@(0.0.255) template]_<[@(0.0.255) class]_[*@4 I]>_&]
[s5;:Upp`:`:SubRange`(I`,int`):%- [_^Upp`:`:SubRangeClass^ SubRangeClass]<[*@4 I]>_[* SubRa
nge]([*@4 I]_[*@3 begin], [@(0.0.255) int]_[*@3 count])&]
[s2; Makes a Range based on begin iterator and count.&]
[s3; &]
[s4;%- &]
[s5;:Upp`:`:SubRange`(C`&`,int`,int`):%- [@(0.0.255) template]_<[@(0.0.255) class]_[*@4 C]>
_&]
[s5;:Upp`:`:SubRange`(C`&`,int`,int`):%- [@(0.0.255) auto]_[* SubRange]([*@4 C][@(0.0.255) `&
]_[*@3 c], [@(0.0.255) int]_[*@3 pos], [@(0.0.255) int]_[*@3 count]);&]
[s5;:Upp`:`:SubRange`(const C`&`,int`,int`):%- [@(0.0.255) template]_<[@(0.0.255) class]_
[*@4 C]>_&]
[s5;:Upp`:`:SubRange`(const C`&`,int`,int`):%- [@(0.0.255) auto]_[* SubRange]([@(0.0.255) c
onst]_[*@4 C][@(0.0.255) `&]_[*@3 c], [@(0.0.255) int]_[*@3 pos], [@(0.0.255) int]_[*@3 count])
;&]
[s2; Makes a Range as subrange of some other Range (e.g. container).&]
[s3; &]
[s4;%- &]
[s5;:Upp`:`:SubRangeOf`:`:typedef:%- [@(0.0.255) template <class ][*@4 Range][@(0.0.255) >
using]_[* SubRangeOf];&]
[s2; Returns the type of SubRange of some Range.&]
[s3; &]
[s4;%- &]
[s5;:Upp`:`:ConstRange`(const T`&`,int`):%- [@(0.0.255) template]_<[@(0.0.255) class]_[*@4 T
]>_&]
[s5;:Upp`:`:ConstRange`(const T`&`,int`):%- [_^Upp`:`:ConstRangeClass^ ConstRangeClass]<
[*@4 T]>_[* ConstRange]([@(0.0.255) const]_[*@4 T][@(0.0.255) `&]_[*@3 value],
[@(0.0.255) int]_[*@3 count])&]
[s2; Creates a Range of [%-*@3 count] elements equal to [%-*@3 value].&]
[s3; &]
[s4;%- &]
[s5;:Upp`:`:ViewRange`(BaseRange`&`,Upp`:`:Vector`<int`>`&`&`):%- [@(0.0.255) template]_
<[@(0.0.255) class]_[*@4 BaseRange]>_&]
[s5;:Upp`:`:ViewRange`(BaseRange`&`,Upp`:`:Vector`<int`>`&`&`):%- [_^Upp`:`:ViewRangeClass^ V
iewRangeClass]<[*@4 BaseRange]>_[* ViewRange]([*@4 BaseRange][@(0.0.255) `&]_[*@3 r],
[_^Upp`:`:Vector^ Vector]<[@(0.0.255) int]>`&`&_[*@3 ndx])&]
[s2; Creates a view of [%-*@4 BaseRange ][%-*@3 r] based on mapping [%-*@3 ndx].
Element at [%-*@3 ndx]`[0`] becomes a first element of a new Range,
[%-*@3 ndx]`[1`] second etc..&]
[s3; &]
[s4;%- &]
[s5;:Upp`:`:FilterRange`(BaseRange`&`,Predicate`):%- [@(0.0.255) template]_<[@(0.0.255) c
lass]_[*@4 BaseRange], [@(0.0.255) class]_[*@4 Predicate]>_&]
[s5;:Upp`:`:FilterRange`(BaseRange`&`,Predicate`):%- [_^Upp`:`:ViewRangeClass^ ViewRang
eClass]<[*@4 BaseRange]>_[* FilterRange]([*@4 BaseRange][@(0.0.255) `&]_[*@3 r],
[*@4 Predicate]_[*@3 p])&]
[s2; Same as ViewRangeClass<BaseRange>([%-*@3 r], FindAll([%-*@3 r],
[%-*@3 p])). Creates a view of elements of master Range that satisfy
condition [%-*@3 p].&]
[s3; &]
[s0; ]] | 48.19 | 96 | 0.584146 | [
"vector"
] |
7c7f630ecddb87582c89aae4947b20d350ed4cfb | 829 | cc | C++ | algorithm/test.cc | zhangxuhuizju/cpp-primer-5th | e85b8493cc53157b0d1edac45d0c5b57e9a322b5 | [
"OLDAP-2.2.1"
] | 1 | 2019-10-15T08:39:56.000Z | 2019-10-15T08:39:56.000Z | algorithm/test.cc | zhangxuhuizju/cpp-primer-5th | e85b8493cc53157b0d1edac45d0c5b57e9a322b5 | [
"OLDAP-2.2.1"
] | null | null | null | algorithm/test.cc | zhangxuhuizju/cpp-primer-5th | e85b8493cc53157b0d1edac45d0c5b57e9a322b5 | [
"OLDAP-2.2.1"
] | null | null | null |
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
//返回两部分的差值
int diff(vector<int>& vec)
{
int len = vec.size();
int sum = 0;
for (int i = 0; i < len; ++i) {
sum += vec[i];
}
vector<vector<int>> dp;
for (int i = 0; i <= len; i++) {
vector<int>tmp;
for (int j = 0; j <= sum / 2; ++j) {
tmp.push_back(0);
}
dp.push_back(tmp);
}
for (int i = 1; i <= len; ++i) {
for (int j = 1; j <= sum / 2; ++j) {
if(j>=vec[i-1])dp[i][j] = max(dp[i-1][j],dp[i-1][j-vec[i-1]]+vec[i-1]);
else dp[i][j] = dp[i - 1][j];
}
}
return sum - 2*dp[len][sum / 2];
}
int main()
{
vector<int> vec = { 1,2,3 ,4,5};
cout << diff(vec) << endl;
system("pause");
return 0;
} | 18.840909 | 83 | 0.436671 | [
"vector"
] |
7c82c70955b6bb701c7cce0c10433c1ce00e2e1f | 2,694 | cpp | C++ | src/SearchOptV.cpp | PaCoders/SAT-to-CNF-Reductor | 38fc699997fe58120c183711abea4888748a9292 | [
"MIT"
] | null | null | null | src/SearchOptV.cpp | PaCoders/SAT-to-CNF-Reductor | 38fc699997fe58120c183711abea4888748a9292 | [
"MIT"
] | null | null | null | src/SearchOptV.cpp | PaCoders/SAT-to-CNF-Reductor | 38fc699997fe58120c183711abea4888748a9292 | [
"MIT"
] | null | null | null | /*
==============================================================================
Search and Optimisation problem
Francisco Chanivet Sanchez
==============================================================================
*/
#include <iostream>
#include <list>
#include <cstdlib>
#include <vector>
#include <fstream>
#include <string.h>
#include <algorithm>
#include "reduction.h"
#include "graphs.h"
#include "translator.h"
using namespace std;
//Optimisation problem
void optimisationProblem(){
vector< vector<int> > mat;
translator("file/graph.txt",mat);
size_t nClique = mat.size() + 1;
int isClique = 0;
while(nClique > 0 && isClique != 2560){
--nClique;
reductorCNF("file/graph.txt",nClique);
isClique = system("picosat file/cnf_file.cnf > /dev/null");
if(isClique != 2560){
cout<<"There is not a solution for k = "<<nClique<<endl;
}
}
if(isClique == 2560){
cout<<"There is a solution for k = "<<nClique<<"!"<<endl;
}
}
//Search problem
void searchProblem(){
vector< vector<int> > mat;
translator("file/graph.txt",mat);
list<unsigned int> set;
list<unsigned int> vertex;
for(unsigned int i = 0; i < mat.size(); i++){
vertex.push_back(i);
}
string file = "file/subgraph.txt";
int isClique = 0;
size_t nClique = 0;
while(nClique < 1 || nClique > mat.size()){
cout<<"Insert a clique number: ";
cin>>nClique;
}
cout<<"Searching the combination...."<<endl;
while(next_permutation(vertex.begin(),vertex.end()) && isClique != 2560){
set = vertex;
set.resize(nClique);
generateDimacsSG(file,set,mat);
//We execute the reductor here
reductorCNF(file,nClique);
isClique = system("picosat file/cnf_file.cnf > /dev/null");
}
cout<<"The nodes that make a "<<nClique<<"-clique are: "<<endl;
list<unsigned int>::iterator it = set.begin();
while(it != set.end()){
cout<<(*it) + 1<<", ";
++it;
}
cout<<endl;
}
int main(){
//We create the DIMACS file
vector< vector<int> > mat = {{0,1,1,1,1,0,0},{1,0,1,0,0,1,1},{1,1,0,1,0,1,0},{1,0,1,0,1,1,1},{1,0,0,1,0,1,1},{0,1,1,1,1,0,1},{0,1,0,1,1,1,0}};
generateDimacsG("file/graph.txt",mat);
int opt = 10;
while(opt > 0){
cout<<"\n============================================================="<<endl;
cout<<"What type of problem do you want to execute? "<<endl;
cout<<"\t 1. Optimisation problem"<<endl;
cout<<"\t 2. Search problem"<<endl;
cout<<"------ Introduce 0 if you want to exit. ------";
cout<<"\n============================================================="<<endl;
cout<<"Option: ";
cin>>opt;
cout<<endl;
if(opt == 1){
optimisationProblem();
cout<<endl;
}
if(opt == 2){
searchProblem();
cout<<endl;
}
}
}
| 24.27027 | 143 | 0.556422 | [
"vector"
] |
7c8609e49f81e4082823ba1ec0ef0a354cf51ea4 | 7,178 | cpp | C++ | src/Persistence/src/Dao/SQLite/SQLiteHandleDao.cpp | till213/SkyDolly | 75caa54fa9fcbaae04b6605c3c1a68e0cb9a0c16 | [
"MIT"
] | 21 | 2021-03-01T00:19:41.000Z | 2022-02-22T02:57:19.000Z | src/Persistence/src/Dao/SQLite/SQLiteHandleDao.cpp | till213/SkyDolly | 75caa54fa9fcbaae04b6605c3c1a68e0cb9a0c16 | [
"MIT"
] | 11 | 2021-06-20T20:16:56.000Z | 2022-03-28T19:03:34.000Z | src/Persistence/src/Dao/SQLite/SQLiteHandleDao.cpp | till213/SkyDolly | 75caa54fa9fcbaae04b6605c3c1a68e0cb9a0c16 | [
"MIT"
] | 3 | 2021-04-06T19:06:16.000Z | 2022-01-20T21:22:39.000Z | /**
* Sky Dolly - The Black Sheep for your Flight Recordings
*
* Copyright (c) Oliver Knoll
* All rights reserved.
*
* 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 <memory>
#include <vector>
#include <iterator>
#include <QString>
#include <QSqlQuery>
#include <QVariant>
#include <QSqlError>
#include <QSqlRecord>
#include "../../../../Model/src/AircraftHandleData.h"
#include "../../ConnectionManager.h"
#include "SQLiteHandleDao.h"
// PUBLIC
SQLiteHandleDao::SQLiteHandleDao() noexcept
{}
SQLiteHandleDao::~SQLiteHandleDao() noexcept
{}
bool SQLiteHandleDao::add(qint64 aircraftId, const AircraftHandleData &aircraftHandleData) noexcept
{
QSqlQuery query;
query.prepare(
"insert into handle ("
" aircraft_id,"
" timestamp,"
" brake_left_position,"
" brake_right_position,"
" water_rudder_handle_position,"
" tail_hook_position,"
" canopy_open,"
" left_wing_folding,"
" right_wing_folding,"
" gear_handle_position,"
" smoke_enable"
") values ("
" :aircraft_id,"
" :timestamp,"
" :brake_left_position,"
" :brake_right_position,"
" :water_rudder_handle_position,"
" :tail_hook_position,"
" :canopy_open,"
" :left_wing_folding,"
" :right_wing_folding,"
" :gear_handle_position,"
" :smoke_enable"
");"
);
query.bindValue(":aircraft_id", aircraftId);
query.bindValue(":timestamp", aircraftHandleData.timestamp);
query.bindValue(":brake_left_position", aircraftHandleData.brakeLeftPosition);
query.bindValue(":brake_right_position", aircraftHandleData.brakeRightPosition);
query.bindValue(":water_rudder_handle_position", aircraftHandleData.waterRudderHandlePosition);
query.bindValue(":tail_hook_position", aircraftHandleData.tailhookPosition);
query.bindValue(":canopy_open", aircraftHandleData.canopyOpen);
query.bindValue(":left_wing_folding", aircraftHandleData.leftWingFolding);
query.bindValue(":right_wing_folding", aircraftHandleData.rightWingFolding);
query.bindValue(":gear_handle_position", aircraftHandleData.gearHandlePosition ? 1 : 0);
query.bindValue(":smoke_enable", aircraftHandleData.smokeEnabled ? 1 : 0);
bool ok = query.exec();
#ifdef DEBUG
if (!ok) {
qDebug("SQLiteHandleDao::add: SQL error: %s", qPrintable(query.lastError().databaseText() + " - error code: " + query.lastError().nativeErrorCode()));
}
#endif
return ok;
}
bool SQLiteHandleDao::getByAircraftId(qint64 aircraftId, std::insert_iterator<std::vector<AircraftHandleData>> insertIterator) const noexcept
{
QSqlQuery query;
query.setForwardOnly(true);
query.prepare(
"select * "
"from handle h "
"where h.aircraft_id = :aircraft_id "
"order by h.timestamp asc;"
);
query.bindValue(":aircraft_id", aircraftId);
bool ok = query.exec();
if (ok) {
QSqlRecord record = query.record();
const int timestampIdx = record.indexOf("timestamp");
const int brakeLeftPositionIdx = record.indexOf("brake_left_position");
const int brakeRightPositionIdx = record.indexOf("brake_right_position");
const int waterRudderHandlePositionIdx = record.indexOf("water_rudder_handle_position");
const int tailHookPositionIdx = record.indexOf("tail_hook_position");
const int canopyOpenIdx = record.indexOf("canopy_open");
const int leftWingFoldingIdx = record.indexOf("left_wing_folding");
const int rightWingFoldingIdx = record.indexOf("right_wing_folding");
const int gearHandlePositionIdx = record.indexOf("gear_handle_position");
const int smokeEnablePositionIdx = record.indexOf("smoke_enable");
while (query.next()) {
AircraftHandleData data;
data.timestamp = query.value(timestampIdx).toLongLong();
data.brakeLeftPosition = query.value(brakeLeftPositionIdx).toInt();
data.brakeRightPosition = query.value(brakeRightPositionIdx).toInt();
data.waterRudderHandlePosition = query.value(waterRudderHandlePositionIdx).toInt();
data.tailhookPosition = query.value(tailHookPositionIdx).toInt();
data.canopyOpen = query.value(canopyOpenIdx).toInt();
data.leftWingFolding = query.value(leftWingFoldingIdx).toInt();
data.rightWingFolding = query.value(rightWingFoldingIdx).toInt();
data.gearHandlePosition = query.value(gearHandlePositionIdx).toBool();
data.smokeEnabled = query.value(smokeEnablePositionIdx).toBool();
insertIterator = std::move(data);
}
#ifdef DEBUG
} else {
qDebug("SQLiteHandleDao::getByAircraftId: SQL error: %s", qPrintable(query.lastError().databaseText() + " - error code: " + query.lastError().nativeErrorCode()));
#endif
}
return ok;
}
bool SQLiteHandleDao::deleteByFlightId(qint64 flightId) noexcept
{
QSqlQuery query;
query.prepare(
"delete "
"from handle "
"where aircraft_id in (select a.id "
" from aircraft a"
" where a.flight_id = :flight_id"
" );"
);
query.bindValue(":flight_id", flightId);
bool ok = query.exec();
#ifdef DEBUG
if (!ok) {
qDebug("SQLiteHandleDao::deleteByFlightId: SQL error: %s", qPrintable(query.lastError().databaseText() + " - error code: " + query.lastError().nativeErrorCode()));
}
#endif
return ok;
}
bool SQLiteHandleDao::deleteByAircraftId(qint64 aircraftId) noexcept
{
QSqlQuery query;
query.prepare(
"delete "
"from handle "
"where aircraft_id = :aircraft_id;"
);
query.bindValue(":aircraft_id", aircraftId);
bool ok = query.exec();
#ifdef DEBUG
if (!ok) {
qDebug("SQLiteHandleDao::deleteByAircraftId: SQL error: %s", qPrintable(query.lastError().databaseText() + " - error code: " + query.lastError().nativeErrorCode()));
}
#endif
return true;
}
| 37.778947 | 173 | 0.678462 | [
"vector",
"model"
] |
7c937fa4fd82b7a1a46a47c26b1ee6369a18001d | 3,607 | cpp | C++ | aws-cpp-sdk-acm-pca/source/model/CertificateAuthorityStatus.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-acm-pca/source/model/CertificateAuthorityStatus.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-acm-pca/source/model/CertificateAuthorityStatus.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/acm-pca/model/CertificateAuthorityStatus.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>
using namespace Aws::Utils;
namespace Aws
{
namespace ACMPCA
{
namespace Model
{
namespace CertificateAuthorityStatusMapper
{
static const int CREATING_HASH = HashingUtils::HashString("CREATING");
static const int PENDING_CERTIFICATE_HASH = HashingUtils::HashString("PENDING_CERTIFICATE");
static const int ACTIVE_HASH = HashingUtils::HashString("ACTIVE");
static const int DELETED_HASH = HashingUtils::HashString("DELETED");
static const int DISABLED_HASH = HashingUtils::HashString("DISABLED");
static const int EXPIRED_HASH = HashingUtils::HashString("EXPIRED");
static const int FAILED_HASH = HashingUtils::HashString("FAILED");
CertificateAuthorityStatus GetCertificateAuthorityStatusForName(const Aws::String& name)
{
int hashCode = HashingUtils::HashString(name.c_str());
if (hashCode == CREATING_HASH)
{
return CertificateAuthorityStatus::CREATING;
}
else if (hashCode == PENDING_CERTIFICATE_HASH)
{
return CertificateAuthorityStatus::PENDING_CERTIFICATE;
}
else if (hashCode == ACTIVE_HASH)
{
return CertificateAuthorityStatus::ACTIVE;
}
else if (hashCode == DELETED_HASH)
{
return CertificateAuthorityStatus::DELETED;
}
else if (hashCode == DISABLED_HASH)
{
return CertificateAuthorityStatus::DISABLED;
}
else if (hashCode == EXPIRED_HASH)
{
return CertificateAuthorityStatus::EXPIRED;
}
else if (hashCode == FAILED_HASH)
{
return CertificateAuthorityStatus::FAILED;
}
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
overflowContainer->StoreOverflow(hashCode, name);
return static_cast<CertificateAuthorityStatus>(hashCode);
}
return CertificateAuthorityStatus::NOT_SET;
}
Aws::String GetNameForCertificateAuthorityStatus(CertificateAuthorityStatus enumValue)
{
switch(enumValue)
{
case CertificateAuthorityStatus::CREATING:
return "CREATING";
case CertificateAuthorityStatus::PENDING_CERTIFICATE:
return "PENDING_CERTIFICATE";
case CertificateAuthorityStatus::ACTIVE:
return "ACTIVE";
case CertificateAuthorityStatus::DELETED:
return "DELETED";
case CertificateAuthorityStatus::DISABLED:
return "DISABLED";
case CertificateAuthorityStatus::EXPIRED:
return "EXPIRED";
case CertificateAuthorityStatus::FAILED:
return "FAILED";
default:
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
}
return {};
}
}
} // namespace CertificateAuthorityStatusMapper
} // namespace Model
} // namespace ACMPCA
} // namespace Aws
| 34.028302 | 100 | 0.630995 | [
"model"
] |
7c9b93759a822f5ed8c382fb9e3fa79c730f2bfd | 1,049 | cpp | C++ | aws-cpp-sdk-forecast/source/model/Baseline.cpp | Nexuscompute/aws-sdk-cpp | e7ef485e46e6962c9e084b8c9b104c1bfcceaf26 | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-forecast/source/model/Baseline.cpp | Nexuscompute/aws-sdk-cpp | e7ef485e46e6962c9e084b8c9b104c1bfcceaf26 | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-forecast/source/model/Baseline.cpp | Nexuscompute/aws-sdk-cpp | e7ef485e46e6962c9e084b8c9b104c1bfcceaf26 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/forecast/model/Baseline.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace ForecastService
{
namespace Model
{
Baseline::Baseline() :
m_predictorBaselineHasBeenSet(false)
{
}
Baseline::Baseline(JsonView jsonValue) :
m_predictorBaselineHasBeenSet(false)
{
*this = jsonValue;
}
Baseline& Baseline::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("PredictorBaseline"))
{
m_predictorBaseline = jsonValue.GetObject("PredictorBaseline");
m_predictorBaselineHasBeenSet = true;
}
return *this;
}
JsonValue Baseline::Jsonize() const
{
JsonValue payload;
if(m_predictorBaselineHasBeenSet)
{
payload.WithObject("PredictorBaseline", m_predictorBaseline.Jsonize());
}
return payload;
}
} // namespace Model
} // namespace ForecastService
} // namespace Aws
| 17.483333 | 74 | 0.734032 | [
"model"
] |
7ca8b56a9d25b3a3b4e5b5f5a9e3f61cf08c5727 | 3,993 | hpp | C++ | include/lastfmpp/detail/transform.hpp | chrismanning/lastfmpp | 59439e62d2654359a48f8244a4b69b95d398beb3 | [
"MIT"
] | null | null | null | include/lastfmpp/detail/transform.hpp | chrismanning/lastfmpp | 59439e62d2654359a48f8244a4b69b95d398beb3 | [
"MIT"
] | null | null | null | include/lastfmpp/detail/transform.hpp | chrismanning/lastfmpp | 59439e62d2654359a48f8244a4b69b95d398beb3 | [
"MIT"
] | null | null | null | /**************************************************************************
** Copyright (C) 2015 Christian Manning
**
** This software may be modified and distributed under the terms
** of the MIT license. See the LICENSE file for details.
**************************************************************************/
#ifndef LASTFM_TRANSFORM
#define LASTFM_TRANSFORM
#include <algorithm>
#include <type_traits>
#include <jbson/element.hpp>
#include <jbson/document.hpp>
#include <jbson/path.hpp>
namespace lastfmpp {
namespace detail {
template <typename T> struct deserialise_ {
template <typename ElemT> T operator()(ElemT&& elem) const {
return jbson::get<T>(elem);
}
};
} // namespace detail
template <typename T> constexpr auto deserialise = detail::deserialise_<T>{};
namespace detail {
template <typename T> struct _convert {
template <typename U> constexpr T operator()(U&& u) const {
return static_cast<T>(u);
}
};
} // namespace detail
template <typename T> constexpr auto convert = detail::_convert<T>{};
namespace detail {
struct transform_copy_ {
template <typename V, typename F> auto operator()(V&& v, F&& f) const {
using U = std::remove_cv_t<std::remove_reference_t<decltype(f(*v.begin()))>>;
using Alloc = typename std::remove_reference_t<V>::allocator_type;
using NewAlloc = typename std::allocator_traits<Alloc>::template rebind_alloc<U>;
std::vector<U, NewAlloc> result;
result.reserve(v.size());
std::transform(move_begin(v), move_end(v), std::back_inserter(result), std::forward<F>(f));
return result;
}
private:
template <typename V>
using iterator_type = std::conditional_t<std::is_rvalue_reference<V>::value,
std::move_iterator<decltype(std::begin(std::declval<V>()))>,
decltype(std::begin(std::declval<V>()))>;
template <typename V> static auto move_begin(V&& v) {
return iterator_type<V>{std::begin(v)};
}
template <typename V> static auto move_end(V&& v) {
return iterator_type<V>{std::end(v)};
}
};
} // namespace detail
constexpr auto transform_copy = detail::transform_copy_{};
namespace detail {
struct vector_to_optional_ {
template <typename T, typename... Args>
std::experimental::optional<T> operator()(std::vector<T, Args...>&& vec) const {
return vec.empty() ? std::experimental::nullopt : std::experimental::make_optional(std::move(vec.front()));
}
template <typename T, typename... Args>
std::experimental::optional<T> operator()(const std::vector<T, Args...>& vec) const {
return vec.empty() ? std::experimental::nullopt : std::experimental::make_optional(vec.front());
}
};
} // namespace detail
constexpr auto vector_to_optional = detail::vector_to_optional_{};
namespace detail {
template <typename T> struct transform_select_ {
auto operator()(std::experimental::string_view path) const {
return [path = path.to_string()](jbson::document doc) {
if(auto elem = vector_to_optional(jbson::path_select(std::move(doc), path))) {
return jbson::get<T>(*elem);
}
throw std::runtime_error("invalid response");
};
}
};
template <typename T> struct transform_select_<std::vector<T>> {
auto operator()(std::experimental::string_view path) const {
return [path = path.to_string()](jbson::document doc) {
auto elems = jbson::path_select(std::move(doc), path);
return transform_copy(elems, deserialise<T>);
};
}
};
} // namespace detail
template <typename T> constexpr auto transform_select = detail::transform_select_<T>{};
namespace detail {
struct _ignore_impl {
template <typename... Args> constexpr void operator()(Args&&...) const {
}
};
constexpr _ignore_impl ignore{};
}
} // namespace lastfm
#endif // LASTFM_TRANSFORM
| 30.25 | 115 | 0.627348 | [
"vector",
"transform"
] |
7ca9c2945735811419b10d52832490e5df3d88d5 | 432 | cpp | C++ | unix/phasor.cpp | kybr/MAT240B-2019 | d3a875f90e12df195a172b4f4f485153d4251086 | [
"MIT"
] | null | null | null | unix/phasor.cpp | kybr/MAT240B-2019 | d3a875f90e12df195a172b4f4f485153d4251086 | [
"MIT"
] | null | null | null | unix/phasor.cpp | kybr/MAT240B-2019 | d3a875f90e12df195a172b4f4f485153d4251086 | [
"MIT"
] | null | null | null | #include "everything.h"
using namespace diy;
int main(int argc, char* argv[]) {
float frequency = 220;
float phase = 0;
std::vector<std::string> a(argv, argv + argc);
if (argc > 2) phase = fmod(stof(a[2]), 2.0f);
if (argc > 1) frequency = stof(a[1]);
float perSampleIncrement = frequency / SAMPLE_RATE;
while (true) {
phase += perSampleIncrement;
if (phase > 1) phase -= 1;
printf("%f\n", phase);
}
}
| 22.736842 | 53 | 0.613426 | [
"vector"
] |
7cab89e54e13cc555b0b5c4f34193c12514c5bdf | 737 | cc | C++ | cpp/leetcode/78.subsets.cc | liubang/laboratory | 747f239a123cd0c2e5eeba893b9a4d1536555b1e | [
"MIT"
] | 3 | 2021-03-03T13:18:23.000Z | 2022-02-09T07:49:24.000Z | cpp/leetcode/78.subsets.cc | liubang/laboratory | 747f239a123cd0c2e5eeba893b9a4d1536555b1e | [
"MIT"
] | null | null | null | cpp/leetcode/78.subsets.cc | liubang/laboratory | 747f239a123cd0c2e5eeba893b9a4d1536555b1e | [
"MIT"
] | 1 | 2021-03-29T15:21:42.000Z | 2021-03-29T15:21:42.000Z | #include <gtest/gtest.h>
#include <vector>
namespace {
class Solution {
public:
std::vector<std::vector<int>> subsets(const std::vector<int>& nums) {
std::vector<std::vector<int>> ret;
ret.push_back({});
for (int i = 0; i < nums.size(); ++i) {
int all = ret.size();
for (int j = 0; j < all; ++j) {
std::vector<int> retj = ret[j];
retj.push_back(nums[i]);
ret.emplace_back(std::move(retj));
}
}
return ret;
}
};
} // namespace
TEST(Leetcode, subsets) {
Solution s;
std::vector<std::vector<int>> exp = {{}, {1}, {2}, {1, 2},
{3}, {1, 3}, {2, 3}, {1, 2, 3}};
auto ret = s.subsets({1, 2, 3});
EXPECT_EQ(exp, ret);
}
| 23.774194 | 71 | 0.497965 | [
"vector"
] |
7cb09314fb98548d046fa5fd48db52a44e26349f | 7,254 | cpp | C++ | File.cpp | gochaorg/zipsfx-cpp | bcfa69f3bf5009f1e4c3e426feb176268312d340 | [
"MIT"
] | 1 | 2020-03-30T05:13:09.000Z | 2020-03-30T05:13:09.000Z | File.cpp | gochaorg/zipsfx-cpp | bcfa69f3bf5009f1e4c3e426feb176268312d340 | [
"MIT"
] | null | null | null | File.cpp | gochaorg/zipsfx-cpp | bcfa69f3bf5009f1e4c3e426feb176268312d340 | [
"MIT"
] | null | null | null | /*
* File: File.cpp
* Author: User
*
* Created on 14 Январь 2012 г., 23:35
*/
#include "File.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <libgen.h>
#include <stdlib.h>
#include <io.h>
#include <iostream>
#include <direct.h>
#include <dirent.h>
#include <string.h>
#include <winbase.h>
#include "IOError.h"
File::File(const String& name) {
this->name.assign(name);
}
File::File(const File& orig) {
name.assign(orig.name);
}
File::File(const File& parent,const String& childName){
name.assign(parent.name);
name = name.trimEnd("/");
name = name.trimEnd("\\");
String cn(childName.c_str());
cn.assign(cn.trimEnd("/"));
cn.assign(cn.trimEnd("\\"));
cn.assign(cn.trimStart("/"));
cn.assign(cn.trimStart("\\"));
name = name.append("\\");
name = name.append(cn);
}
File::~File() {
}
bool File::isExists(){
struct stat s;
if( stat(name.c_str(),&s)==0 ){
return true;
}
return false;
}
bool File::isFile(){
struct stat s;
if( stat(name.c_str(),&s)!=0 ){
return false;
}
return S_ISREG(s.st_mode);
}
bool File::isDir(){
struct stat s;
if( stat(name.c_str(),&s)!=0 ){
return false;
}
return S_ISDIR(s.st_mode);
}
String File::getPath(){
return String(name);
}
String File::getName(){
char* res = (char *)malloc(strlen(name.c_str())+1);
char* res2 = 0;
strcpy(res,name.c_str());
res2 = basename(res);
String res3 = String(res2);
free(res);
return String(res3);
}
File File::getParent(){
char* res = (char *)malloc(strlen(name.c_str())+1);
char* res2 = 0;
strcpy(res,name.c_str());
res2 = dirname(res);
String res3 = String(res2);
free(res);
return File(res3);
}
long File::getSize(){
struct stat s;
if( stat(name.c_str(),&s)!=0 ){
return -1;
}
return s.st_size;
}
//using namespace std;
bool File::mkdir(bool withParents){
// cout << "mkdir " << name << endl;
if( isDir() ){
// cout << "is already created" << endl;
// cout << "success" << endl;
return true;
}
File fParent = getParent();
if( fParent.getPath().equals(".") ){
// cout << name << " is root" << endl;
// cout << "failed" << endl;
return false;
}
if( fParent.isDir() ){
// cout << "parent exists" << endl;
if( _mkdir( name.c_str() )==0 ){
// cout << "must be created" << endl;
return true;
}
// cout << "failed" << endl;
return false;
}else{
// cout << "parent not exists" << endl;
if( withParents ){
if( fParent.mkdir(true) ){
if( _mkdir( name.c_str() )==0 ){
// cout << "must be created" << endl;
// cout << "success" << endl;
return true;
}
}
}else{
// cout << "failed" << endl;
return false;
}
}
// cout << "failed" << endl;
return false;
}
RandomAccessFile File::open(const String& mode) throw (IOError) {
//RandomAccessFile rafile(name.replaceAll("\\","/").c_str());
RandomAccessFile rafile(name.c_str());
rafile.open(mode);
return rafile;
}
void File::copy(const File& target){
File trgt(target);
// std::cout << "copy " << name.c_str() << " to " << trgt.getPath() << std::endl;
if( isFile() ){
File tarDir = trgt.getParent();
if( !tarDir.isExists() ){
if( !tarDir.mkdir(true) ){
String mess("can't create dir: ");
mess = mess.append(tarDir.getPath());
throw new IOError(-1,mess);
}
}
RandomAccessFile rSrc = open("r");
RandomAccessFile rTarget = trgt.open("w+");
char buff[4096];
while(true){
bool eof = rSrc.isEOF();
if( eof ){
break;
}
size_t rd = rSrc.read(buff,sizeof(buff));
// std::cout << "readed " << rd << " bytes" << std::endl;
if( rd>0 ){
rTarget.write(buff,rd);
}
if( rd<0 )break;
}
rTarget.flush();
rTarget.close();
rSrc.close();
return;
}
if( isDir() ){
if( !trgt.isExists() ){
if( !trgt.mkdir(true) ){
String mess("can't create dir: ");
mess = mess.append(trgt.getPath());
throw new IOError(-1,mess);
}
}
if( !trgt.isDir() ){
String mess("is not dir: ");
mess = mess.append(trgt.getPath());
throw new IOError(-1,mess);
}
std::vector<File> files = readdir();
for( int idx=0; idx<files.size(); idx++ ){
File srcFile = files[idx];
File tFile = File(*this,srcFile.getName());
srcFile.copy(tFile);
}
}
}
std::vector<File> File::readdir(){
std::vector<File> files;
DIR *dir=0;
dir = opendir(name.c_str());
if( !dir ){
String mess("can't open dir");
mess.append(name.c_str());
throw new IOError(-1,mess);
}
dirent* dirEntry;
while(true){
dirEntry = ::readdir(dir);
if( dirEntry==NULL )break;
char* _entryName = (char *)malloc(dirEntry->d_namlen+1);
for( int is=0; is<dirEntry->d_namlen; is++ ){
_entryName[is] = dirEntry->d_name[is];
}
_entryName[dirEntry->d_namlen] = 0;
String fileName(_entryName);
free( _entryName );
if( fileName.equals(".") )continue;
if( fileName.equals("..") )continue;
File fDir(name.c_str());
File f(fDir,fileName);
files.push_back(f);
}
closedir(dir);
return files;
}
File File::getTempDir(){
String tmpDirString( getenv("TEMP") );
File tmpDir(tmpDirString);
return tmpDir;
}
File File::getCurrentDir(){
char currentDir[16384];
if( getcwd( currentDir,16384 )==0 ){
String mess("can't read current dir (getcwd)");
throw new IOError(-1,mess);
}
String curDirString( currentDir );
File curDir(curDirString);
return curDir;
}
bool File::setCurrentDir(File& file){
String p = file.getPath();
return chdir( p.c_str() )==0;
}
bool File::remove(){
if( isFile() ){
if( DeleteFile( name.c_str() )==0 ){
std::cout << "error delete file " << name << std::endl;
std::cout << "GetLastError()=" << GetLastError() << std::endl;
return false;
}
return true;
}
if( isDir() ){
std::vector<File> content = readdir();
bool succDel = true;
for( int i=0; i<content.size(); i++ ){
if( !content[i].remove() )succDel = false;
}
if( succDel ){
if( RemoveDirectory( name.c_str() )==0 ){
std::cout << "error delete dir " << name << std::endl;
std::cout << "GetLastError()=" << GetLastError() << std::endl;
return false;
}
}
return true;
}
std::cout << "can't delete " << name << std::endl;
return false;
} | 24.673469 | 84 | 0.506479 | [
"vector"
] |
7cb38b0619783dda7afbefa6413b74ca03bc2381 | 1,376 | cpp | C++ | src/GraphTheory/Kruskal.cpp | Rabbytr/Algorithm-Cpp | 1723ae9e522358a16faeccf7f61324ba95b9d602 | [
"MIT"
] | 1 | 2018-11-19T05:11:44.000Z | 2018-11-19T05:11:44.000Z | src/GraphTheory/Kruskal.cpp | Rabbytr/Algorithm-Cpp | 1723ae9e522358a16faeccf7f61324ba95b9d602 | [
"MIT"
] | null | null | null | src/GraphTheory/Kruskal.cpp | Rabbytr/Algorithm-Cpp | 1723ae9e522358a16faeccf7f61324ba95b9d602 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#pragma GCC optimize("O3")
#pragma GCC diagnostic error "-std=c++11"
//#pragma comment(linker, "/STACK:102400000,102400000")
#define REP(i, a, b) for(int i = a; i < b; ++i)
#define debug(x) { cerr << #x << '=' << x << "\n"; }
#define Arr(a, l, r) { cerr << #a << " = {"; REP(_, l, r) cerr << ' ' << a[_]; cerr << " }\n"; }
#define mset(a,b) memset(a,b,sizeof(a))
#define mkpr make_pair
#define ll long long
using namespace std;
const int maxn = 100;
struct Edge{int fro,to,w;};
vector<Edge> edges;
vector<int> G[maxn];
int n,ans,p[maxn];
void addEdge(int fro,int to,int w){ //无向图
edges.push_back((Edge){fro,to,w});
edges.push_back((Edge){to,fro,w});
int m = edges.size();
G[fro].push_back(m-2);
G[to].push_back(m-1);
}
int find(int x){return !p[x]?x:p[x]=find(p[x]);}
int Kruskal(){
sort(edges.begin(),edges.end(),[](Edge i,Edge j){return i.w<j.w;});
REP(i,0,edges.size()){
int x = find(edges[i].fro);int y = find(edges[i].to);
if(x!=y){
ans += edges[i].w;
p[y] = x;
}
}
return ans;
}
int main(){
ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
n = 6;
addEdge(1,2,6);
addEdge(1,4,5);
addEdge(1,3,1);
addEdge(2,3,5);
addEdge(3,4,5);
addEdge(2,5,3);
addEdge(3,5,6);
addEdge(3,6,4);
addEdge(4,6,2);
addEdge(5,6,6);
cout<<Kruskal()<<"\n";
Arr(p,1,n+1);
return 0;
}
| 22.557377 | 96 | 0.572674 | [
"vector"
] |
7cc24ee321d52be7a7d3031bcdc65609c263d4f3 | 975 | hpp | C++ | program/ode_solver/include/hypercubes/leaf.hpp | statphysandml/ODEVisualisation | cadc8f9b1e2adeaf1ce702197af7119e9f3b1ede | [
"MIT"
] | null | null | null | program/ode_solver/include/hypercubes/leaf.hpp | statphysandml/ODEVisualisation | cadc8f9b1e2adeaf1ce702197af7119e9f3b1ede | [
"MIT"
] | null | null | null | program/ode_solver/include/hypercubes/leaf.hpp | statphysandml/ODEVisualisation | cadc8f9b1e2adeaf1ce702197af7119e9f3b1ede | [
"MIT"
] | null | null | null | //
// Created by lukas on 13.03.19.
//
#ifndef PROJECT_LEAF_HPP
#define PROJECT_LEAF_HPP
#include "param_helper/json.hpp"
using json = nlohmann::json;
class Leaf
{
public:
Leaf(const std::vector< int > cube_indices_) :
cube_indices(cube_indices_), depth(cube_indices_.size() - 1)
{}
void info() const {
std::cout << "\nSolution: " << std::endl;
std::cout << "\tDepth: " << depth << std::endl;
std::cout << "\tCube indices:";
for(const auto& cube_index: cube_indices)
std::cout << " " << cube_index;
std::cout << std::endl;
}
int get_ith_cube_depth_index(int i) const
{
return cube_indices[i];
}
json to_json() const
{
return json {{"depth", depth},
{"cube_indices", cube_indices}};
}
private:
const int depth;
const std::vector< int > cube_indices; // root, first cube, second cube, usw.
};
#endif //PROJECT_LEAF_HPP
| 21.666667 | 81 | 0.580513 | [
"vector"
] |
7cc40e829d5c1ea459e3571647b9d41e8238aa47 | 7,426 | cpp | C++ | FilePersistence/src/SystemClipboard.cpp | dimitar-asenov/Envision | 1ab5c846fca502b7fe73ae4aff59e8746248446c | [
"BSD-3-Clause"
] | 75 | 2015-01-18T13:29:43.000Z | 2022-01-14T08:02:01.000Z | FilePersistence/src/SystemClipboard.cpp | dimitar-asenov/Envision | 1ab5c846fca502b7fe73ae4aff59e8746248446c | [
"BSD-3-Clause"
] | 364 | 2015-01-06T10:20:21.000Z | 2018-12-17T20:12:28.000Z | FilePersistence/src/SystemClipboard.cpp | dimitar-asenov/Envision | 1ab5c846fca502b7fe73ae4aff59e8746248446c | [
"BSD-3-Clause"
] | 14 | 2015-01-09T00:44:24.000Z | 2022-02-22T15:01:44.000Z | /***********************************************************************************************************************
**
** Copyright (c) 2011, 2014 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
** disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich 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 "SystemClipboard.h"
#include "FilePersistenceException.h"
#include "XMLModel.h"
#include "ModelBase/src/model/TreeManager.h"
#include "ModelBase/src/nodes/Node.h"
#include "Core/src/EnvisionException.h"
using namespace Model;
namespace FilePersistence {
static const QString CLIPBOARD_TAG = "clipboard";
const QString SystemClipboard::NULL_STRING = "____NULL____";
SystemClipboard::SystemClipboard() :
xml{nullptr}, numNodes_{0}
{
readClipboard();
}
SystemClipboard::~SystemClipboard()
{
SAFE_DELETE(xml);
}
SystemClipboard* SystemClipboard::clone() const
{
return new SystemClipboard{};
}
void SystemClipboard::saveTree(TreeManager* manager, const QString &name)
{
if (manager->root())
{
SAFE_DELETE(xml);
xml = new XMLModel{};
xml->beginSaveChildNode(CLIPBOARD_TAG);
manager_ = manager;
saveNode(manager->root(), name);
xml->endSaveChildNode();
QApplication::clipboard()->setText(xml->documentText());
SAFE_DELETE(xml);
numNodes_ = 0;
}
}
void SystemClipboard::saveStringValue(const QString &value)
{
xml->saveStringValue(value);
}
void SystemClipboard::saveIntValue(int value)
{
xml->saveIntValue(value);
}
void SystemClipboard::saveDoubleValue(double value)
{
xml->saveDoubleValue(value);
}
void SystemClipboard::saveReferenceValue(const QString &name, const Node* target)
{
QString nameString = name.isNull() ? (target && target->definesSymbol() ? target->symbolName() : NULL_STRING) : name;
xml->saveStringValue(nameString);
}
void SystemClipboard::saveNode(const Node *node, const QString &name)
{
// Do not require a fully loaded node.
xml->beginSaveChildNode(node->typeName());
xml->setName(name);
xml->setId(manager_->nodeIdMap().id(node));
node->save(*this);
xml->endSaveChildNode();
}
Node* SystemClipboard::loadTree(TreeManager*, const QString &, bool)
{
throw FilePersistenceException{"The clipboard does not support the loadTree() method."};
}
QList<LoadedNode> SystemClipboard::loadAllSubNodes(Node* parent, const QSet<QString>&)
{
QList<LoadedNode> result;
if ( xml->hasChildren() )
{
if (auto manager = parent->manager())
manager_ = manager;
xml->goToFirstChild();
while ( true )
{
LoadedNode ln = loadNode(nullptr);
result.append(ln);
if ( xml->hasNext() ) xml->loadNext();
else break;
}
xml->goToParent();
}
return result;
}
Node* SystemClipboard::loadSubNode(Node* parent, const QString& name, bool)
{
if (!xml->hasChild(name)) return nullptr;
if (auto manager = parent->manager())
manager_ = manager;
xml->beginLoadChildNode(name);
LoadedNode ln = loadNode(parent);
xml->endLoadChildNode();
return ln.node;
}
LoadedNode SystemClipboard::loadNode(Node* parent)
{
LoadedNode node;
node.name = xml->getName();
node.node = Node::createNewNode(xml->getType(), parent, *this, false);
if (!manager_->nodeIdMap().node(xml->getId()))
manager_->nodeIdMap().setId(node.node, xml->getId());
return node;
}
QString SystemClipboard::currentNodeType() const
{
return xml->getType();
}
Model::NodeIdType SystemClipboard::currentNodeID() const
{
return xml->getId();
}
int SystemClipboard::loadIntValue()
{
return xml->loadIntValue();
}
QString SystemClipboard::loadStringValue()
{
return xml->loadStringValue();
}
double SystemClipboard::loadDoubleValue()
{
return xml->loadDoubleValue();
}
QString SystemClipboard::loadReferenceValue(Reference*)
{
QString name = xml->loadStringValue();
if (name == NULL_STRING) name = QString{};
return name;
}
void SystemClipboard::putNode(const Node* node)
{
QList<const Node*> nodes;
nodes.append(node);
putNodes(nodes);
}
void SystemClipboard::putNodes(const QList<const Node*>& nodes)
{
if (nodes.size() > 0)
{
// Assume that there is only one manager for all these nodes
manager_ = nodes.first()->manager();
SAFE_DELETE(xml);
xml = new XMLModel{};
xml->beginSaveChildNode(CLIPBOARD_TAG);
for (int i = 0; i<nodes.size(); ++i)
{
xml->beginSaveChildNode(nodes[i]->typeName());
xml->setName(QString::number(i));
xml->setId(manager_->nodeIdMap().id(nodes[i]));
nodes[i]->save(*this);
xml->endSaveChildNode();
}
xml->endSaveChildNode();
QApplication::clipboard()->setText(xml->documentText());
SAFE_DELETE(xml);
numNodes_ = 0;
}
}
bool SystemClipboard::readClipboard()
{
numNodes_ = 0;
SAFE_DELETE(xml);
bool clipboardContainsEnvisionData = false;
if (!QApplication::clipboard()->text().isEmpty())
{
bool oldAssertOnThrow = Core::EnvisionException::assertOnThrow();
Core::EnvisionException::assertOnThrow() = false;
try
{
xml = new XMLModel{};
xml->setDocumentText(QApplication::clipboard()->text());
xml->goToRoot();
numNodes_ = xml->getChildrenNames().size();
xml->goToFirstChild();
clipboardContainsEnvisionData = true;
}
catch (FilePersistenceException&)
{
SAFE_DELETE(xml);
clipboardContainsEnvisionData = false;
}
Core::EnvisionException::assertOnThrow() = oldAssertOnThrow;
}
return clipboardContainsEnvisionData && numNodes_ > 0;
}
int SystemClipboard::numNodes() const
{
return numNodes_;
}
bool SystemClipboard::hasNext() const
{
return xml->hasNext();
}
void SystemClipboard::next()
{
if (xml->hasNext()) xml->loadNext();
else throw FilePersistenceException{"Could not find next clipboard element."};
}
Node* SystemClipboard::create(TreeManager* manager, Node* parent)
{
manager_ = manager;
Node* node = Node::createNewNode(xml->getType(), parent, *this, false);
if (manager) manager->nodeIdMap().setId(node, xml->getId());
return node;
}
bool SystemClipboard::isLoadingPartially() const
{
return false;
}
}
| 25.258503 | 120 | 0.702936 | [
"model"
] |
7cc538ec5aefefe18afddfcd016cda2c5fe459ac | 7,865 | cpp | C++ | VC/NotUsedCpps/CSAFuncs.cpp | hkujy/VC | 54b79fac4ecf4ac225b54325d879a580a9b17be6 | [
"MIT"
] | null | null | null | VC/NotUsedCpps/CSAFuncs.cpp | hkujy/VC | 54b79fac4ecf4ac225b54325d879a580a9b17be6 | [
"MIT"
] | null | null | null | VC/NotUsedCpps/CSAFuncs.cpp | hkujy/VC | 54b79fac4ecf4ac225b54325d879a580a9b17be6 | [
"MIT"
] | null | null | null | #include "CommonHeaders.h"
#include <assert.h>
#include <math.h> /* pow */
#include "RandomFuncs.h"
using namespace std;
void GenerateCloneSet(const vector<CHROME> &Chroms, const int NumPop, const int NumClone,
vector<int> &CloneSet);
// the compare class is from http://www.cplusplus.com/reference/algorithm/sort/
struct CompareStruct {
bool operator() (const CHROME &A, CHROME &B) { return (A.Fitness > B.Fitness); }
} SortDecent;
void SetDofAndProb(const std::vector<pair<double, double>> &Vec,
double &setdof, double &setdofprob, bool isExlcudeZero = false);
//double GenRandomFloat(const std::vector<pair<double,double>> &Vec);
Algorithms::Algorithms(int NumPop, int NumClone, int NumRep)
{
//Pop solution
CHROME ts;
int idCount = 0;
for (int i = 0; i < NumPop; i++)
{
ts.ID = idCount;
this->Chroms.push_back(ts);
idCount++;
}
// clone
for (int i = 0; i < NumPop / 2; i++)
{
for (int j = 0; j < NumClone; j++)
{
ts.ID = idCount;
this->Chroms.push_back(ts);
idCount++;
}
}
// Rep
for (int i = 0; i < NumRep; i++)
{
ts.ID = idCount;
this->Chroms.push_back(ts);
idCount++;
}
//NodeVarSet.reserve(NumNodes);
//NodeDofVarSet.reserve(NumNodes);
LinkVarSet.reserve(NumLinks);
LinkDofSet.reserve(NumLinks);
AlgorithmIndex = CSA;
};
Algorithms::Algorithms(int NumPop, int NumChild){
//Pop solution
CHROME ts;
int idCount = 0;
for (int i = 0; i < NumPop; i++)
{
ts.ID = idCount;
this->Chroms.push_back(ts);
idCount++;
}
// child
for (int i = 0; i < NumChild; i++)
{
ts.ID = idCount;
this->Chroms.push_back(ts);
idCount++;
}
LinkVarSet.reserve(NumLinks);
AlgorithmIndex = GA;
}
/*Cound the number of solution variables that requires to be recorded*/
void RecordSolVal(double &SolFit, double &CurrentBest,int &NumCount,ofstream &fout){
if (SolFit>CurrentBest)
{
CurrentBest = SolFit;
}
NumCount++;
if (WriteOutTo==screen)
cout <<"------NumSolCount = "<<NumCount << ", CurrentBest = " << CurrentBest << endl;
if (isWriteConverge==file&&isWriteConverge) fout << NumCount << "," << CurrentBest << endl;
if (WriteOutTo==both)
{
cout <<"------NumSolCount = "<<NumCount << ", CurrentBest = " << CurrentBest << endl;
if (isWriteConverge) fout << NumCount << "," << CurrentBest << endl;
}
}
Algorithms::~Algorithms(){
this->Chroms.clear();
//NodeVarSet.clear();
//NodeDofVarSet.clear();
};
void Algorithms::SortSol(unsigned int Num)
{
//cout << (this->Chroms.begin() + Num)->ID << endl;
std::sort(this->Chroms.begin(), this->Chroms.begin() + Num, SortDecent);
MaxFitValue = Chroms.begin()->Fitness;
MinFitValue = (Chroms.begin() + Num - 1)->Fitness;
bool allZero = true;
for each (auto val in this->Chroms.at(0).VulnerableLinkDof)
{
if (val > 0) allZero = false;
}
if (allZero)
cout << "problem id = " << Chroms[0].ID<< endl;
for (int i = 0; i < Chroms.size(); i++)
{
Chroms[i].ID = i;
}
//assert(MinFitValue >= -10.0);
};
int Algorithms::GenerateSol(int ChromIndex)
{
#pragma region OldGenerationMethod
/******************Random generation procedure***************/
//vector<int> CandiSet(NodeVarSet);
//int pos = -1;
///*this->Chroms.at(ChromIndex).Nodes.clear();
//this->Chroms.at(ChromIndex).Dof.clear();*/
//for (unsigned int i = 0; i < NodeVarSet.size(); i++)
//{
// pos = GenRandomPos((unsigned int)CandiSet.size());
// //this->Chroms.at(ChromIndex).Nodes.push_back(NodeVarSet.at(pos));
// this->Chroms.at(ChromIndex).Nodes.push_back(CandiSet.at(pos));
// CandiSet.erase(CandiSet.begin() + pos);
// this->Chroms.at(ChromIndex).NodeDof.push_back(GenRandomdouble(NodeDofVarSet));
//}
/*******************************************/
/******************Secquence***************/
//vector<int> CandiSet(NodeVarSet);
// for (size_t i = 0; i < NodeVarSet.size(); i++)
// {
// //cout << "************This is for debug purpose and need to be revised afterwards***********" << endl;
// this->Chroms.at(ChromIndex).VulnerableNodes.push_back(NodeVarSet.at(i));
// this->Chroms.at(ChromIndex).VulnerableNodeDof.push_back(GenRandomFloat(NodeDofVarSet));
// }
#pragma endregion O
double dof,dofprob;
for (size_t i = 0; i < LinkVarSet.size(); i++)
{
this->Chroms.at(ChromIndex).ID = ChromIndex;
this->Chroms.at(ChromIndex).VulnerableLinks.push_back(LinkVarSet.at(i));
SetDofAndProb(LinkDofSet[i],dof,dofprob);
this->Chroms.at(ChromIndex).VulnerableLinkDof.push_back(dof);
this->Chroms.at(ChromIndex).VulnerableLinkDofProb.push_back(dofprob);
}
return 1;
};
//Original Colone section
void Algorithms::CSAmain(GRAPH &Graph, int NumPop, int NumClone, int NumRep, ofstream &ConvergeFile,
ObjectManager &manager)
{
//phase 1
ofstream fsolconv; // converge based on the solution count
fsolconv.open("c://GitCodes//VC//OutPut//CSAConvergeBasedOnSol.txt",ios::app);
double CurrentBestFitness = -1.0f;
int NumSolEvaluated = 0;
int IdCount = NumPop;
for (int i = 0; i < NumPop; i++)
{
//cout << "Evaluate solution " << i << endl;
bool isRepeat = false;
do
{
this->Chroms.at(i).clear();
GenerateSol(i);
isRepeat = false;
for (int j = 0; j <= i; j++)
{
if (j == i) break;
if (this->Chroms.at(i).isSame(this->Chroms.at(j)))
{
isRepeat = true;
break;
}
}
} while (isRepeat);
this->Chroms.at(i).getSolProb();
Chroms.at(i).EvaluateSol(Graph, BaseUNPM, manager);
RecordSolVal(Chroms.at(i).Fitness, CurrentBestFitness, NumSolEvaluated, fsolconv);
}
int IterCounter = 0;
this->SortSol((unsigned int)NumPop);
vector<int> CloneSet(NumClone, -1);
Repeat:
IterCounter++;
IdCount = NumPop;
GenerateCloneSet(this->Chroms, NumPop, NumClone, CloneSet);
//phase 2
// clone: for half solution each colon
for (size_t i = 0; i < CloneSet.size();i++)
{
Chroms.at(IdCount).Copy(Chroms.at(CloneSet.at(i)));
bool isRepeat;
do
{
isRepeat = false;
this->HyperMutateMain(Chroms.at(IdCount));
for (int kk = 0; kk <= IdCount; kk++)
{
if (kk == IdCount) break;
if (this->Chroms.at(IdCount).isSame(this->Chroms.at(kk)))
{
isRepeat = true;
break;
}
}
} while (isRepeat);
Chroms.at(IdCount).getSolProb();
Chroms.at(IdCount).EvaluateSol(Graph, BaseUNPM, manager);
RecordSolVal(Chroms.at(IdCount).Fitness, CurrentBestFitness, NumSolEvaluated, fsolconv);
if (StopCriteria == 1&& NumSolEvaluated >= MaxNumSolEval)
{
goto FinalSort;
}
IdCount++;
}
for (int i = 0; i < NumRep; i++)
{
bool isRepeat = false;
do
{
this->Chroms.at(IdCount).clear();
GenerateSol(IdCount);
isRepeat = false;
for (int j = 0; j <= IdCount; j++)
{
if (j == IdCount) break;
if (this->Chroms.at(IdCount).isSame(this->Chroms.at(j)))
{
isRepeat = true;
break;
}
}
} while (isRepeat);
Chroms.at(IdCount).EvaluateSol(Graph, BaseUNPM, manager);
this->Chroms.at(IdCount).getSolProb();
RecordSolVal(Chroms.at(IdCount).Fitness, CurrentBestFitness, NumSolEvaluated, fsolconv);
if (StopCriteria == 1&& NumSolEvaluated >= MaxNumSolEval)
{
goto FinalSort;
}
IdCount++;
}
FinalSort:
this->SortSol((unsigned int)Chroms.size());
if (WriteOutTo == screen)
{
cout <<"CasIter = "<<IterCounter << ", CurrentBest = " << this->Chroms.at(0).Fitness << endl;
}
if (isWriteConverge == file&&isWriteConverge)
{
ConvergeFile << IterCounter << "," << this->Chroms.at(0).Fitness << endl;
}
if (WriteOutTo == both)
{
if (isWriteConverge) ConvergeFile << IterCounter << "," << this->Chroms.at(0).Fitness << endl;
cout <<"CasIter = "<<IterCounter << ", CurrentBest = " << this->Chroms.at(0).Fitness << endl;
}
if (StopCriteria == 1)
{
if (NumSolEvaluated >= MaxNumSolEval)
{
fsolconv.close();
return;
}
else goto Repeat;
}
if (StopCriteria == 0)
{
if (IterCounter < MaxCsaIter) goto Repeat;
else
{
fsolconv.close();
return;
}
}
}
| 26.129568 | 108 | 0.641322 | [
"vector"
] |
7cd78a6cb9a8341a395212db9b4c4ba4f376599e | 8,864 | cc | C++ | tool/SecVerilog-1.0/SecVerilog/tgt-vhdl/cast.cc | gokulprasath7c/secure_i2c_using_ift | 124384983ba70e8164b7217db70c43dfdf302d4b | [
"MIT"
] | 1 | 2019-01-28T21:23:37.000Z | 2019-01-28T21:23:37.000Z | tool/SecVerilog-1.0/SecVerilog/tgt-vhdl/cast.cc | gokulprasath7c/secure_i2c_using_ift | 124384983ba70e8164b7217db70c43dfdf302d4b | [
"MIT"
] | null | null | null | tool/SecVerilog-1.0/SecVerilog/tgt-vhdl/cast.cc | gokulprasath7c/secure_i2c_using_ift | 124384983ba70e8164b7217db70c43dfdf302d4b | [
"MIT"
] | null | null | null | /*
* Generate code to convert between VHDL types.
*
* Copyright (C) 2008-2009 Nick Gasson (nick@nickg.me.uk)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "vhdl_syntax.hh"
#include "vhdl_target.h"
#include "support.hh"
#include <cassert>
#include <iostream>
vhdl_expr *vhdl_expr::cast(const vhdl_type *to)
{
//std::cout << "Cast: from=" << type_->get_string()
// << " (" << type_->get_width() << ") "
// << " to=" << to->get_string() << " ("
// << to->get_width() << ")" << std::endl;
// If this expression hasn't been given a type then
// we can't generate any type conversion code
if (NULL == type_)
return this;
if (to->get_name() == type_->get_name()) {
if (to->get_width() == type_->get_width())
return this; // Identical
else
return resize(to->get_width());
}
else {
switch (to->get_name()) {
case VHDL_TYPE_BOOLEAN:
return to_boolean();
case VHDL_TYPE_INTEGER:
return to_integer();
case VHDL_TYPE_UNSIGNED:
case VHDL_TYPE_SIGNED:
case VHDL_TYPE_STD_LOGIC_VECTOR:
return to_vector(to->get_name(), to->get_width());
case VHDL_TYPE_STD_LOGIC:
return to_std_logic();
default:
assert(false);
}
}
assert(false);
return NULL;
}
/*
* Generate code to cast an expression to a vector type (std_logic_vector,
* signed, unsigned).
*/
vhdl_expr *vhdl_expr::to_vector(vhdl_type_name_t name, int w)
{
if (type_->get_name() == VHDL_TYPE_STD_LOGIC) {
vhdl_expr *others = w == 1 ? NULL : new vhdl_const_bit('0');
vhdl_bit_spec_expr *bs =
new vhdl_bit_spec_expr(new vhdl_type(name, w - 1, 0), others);
bs->add_bit(0, this);
return bs;
}
else {
// We have to cast the expression before resizing or the
// wrong sign bit may be extended (i.e. when casting between
// signed/unsigned *and* resizing)
vhdl_type *t = new vhdl_type(name, w - 1, 0);
vhdl_fcall *conv = new vhdl_fcall(t->get_string().c_str(), t);
conv->add_expr(this);
if (w != type_->get_width())
return conv->resize(w);
else
return conv;
}
}
/*
* Convert a generic expression to an Integer.
*/
vhdl_expr *vhdl_expr::to_integer()
{
vhdl_fcall *conv;
if (type_->get_name() == VHDL_TYPE_STD_LOGIC) {
require_support_function(SF_LOGIC_TO_INTEGER);
conv = new vhdl_fcall(support_function::function_name(SF_LOGIC_TO_INTEGER),
vhdl_type::integer());
}
else
conv = new vhdl_fcall("To_Integer", vhdl_type::integer());
conv->add_expr(this);
return conv;
}
/*
* Convert a generic expression to a Boolean.
*/
vhdl_expr *vhdl_expr::to_boolean()
{
if (type_->get_name() == VHDL_TYPE_STD_LOGIC) {
// '1' is true all else are false
vhdl_const_bit *one = new vhdl_const_bit('1');
return new vhdl_binop_expr
(this, VHDL_BINOP_EQ, one, vhdl_type::boolean());
}
else if (type_->get_name() == VHDL_TYPE_UNSIGNED) {
// Need to use a support function for this conversion
require_support_function(SF_UNSIGNED_TO_BOOLEAN);
vhdl_fcall *conv =
new vhdl_fcall(support_function::function_name(SF_UNSIGNED_TO_BOOLEAN),
vhdl_type::boolean());
conv->add_expr(this);
return conv;
}
else if (type_->get_name() == VHDL_TYPE_SIGNED) {
require_support_function(SF_SIGNED_TO_BOOLEAN);
vhdl_fcall *conv =
new vhdl_fcall(support_function::function_name(SF_SIGNED_TO_BOOLEAN),
vhdl_type::boolean());
conv->add_expr(this);
return conv;
}
assert(false);
return NULL;
}
/*
* Generate code to convert and expression to std_logic.
*/
vhdl_expr *vhdl_expr::to_std_logic()
{
if (type_->get_name() == VHDL_TYPE_BOOLEAN) {
require_support_function(SF_BOOLEAN_TO_LOGIC);
vhdl_fcall *ah =
new vhdl_fcall(support_function::function_name(SF_BOOLEAN_TO_LOGIC),
vhdl_type::std_logic());
ah->add_expr(this);
return ah;
}
else if (type_->get_name() == VHDL_TYPE_SIGNED) {
require_support_function(SF_SIGNED_TO_LOGIC);
vhdl_fcall *ah =
new vhdl_fcall(support_function::function_name(SF_SIGNED_TO_LOGIC),
vhdl_type::std_logic());
ah->add_expr(this);
return ah;
}
else if (type_->get_name() == VHDL_TYPE_UNSIGNED) {
require_support_function(SF_UNSIGNED_TO_LOGIC);
vhdl_fcall *ah =
new vhdl_fcall(support_function::function_name(SF_UNSIGNED_TO_LOGIC),
vhdl_type::std_logic());
ah->add_expr(this);
return ah;
}
assert(false);
return NULL;
}
/*
* Change the width of a signed/unsigned type.
*/
vhdl_expr *vhdl_expr::resize(int newwidth)
{
vhdl_type *rtype;
assert(type_);
if (type_->get_name() == VHDL_TYPE_SIGNED)
rtype = vhdl_type::nsigned(newwidth);
else if (type_->get_name() == VHDL_TYPE_UNSIGNED)
rtype = vhdl_type::nunsigned(newwidth);
else if (type_->get_name() == VHDL_TYPE_STD_LOGIC) {
// Pad it with zeros
vhdl_expr* zeros = new vhdl_const_bits(string(newwidth - 1, '0').c_str(),
newwidth - 1, false, true);
vhdl_binop_expr* concat =
new vhdl_binop_expr(zeros, VHDL_BINOP_CONCAT, this,
vhdl_type::nunsigned(newwidth));
return concat;
}
else
return this; // Doesn't make sense to resize non-vector type
vhdl_fcall *resizef = new vhdl_fcall("Resize", rtype);
resizef->add_expr(this);
resizef->add_expr(new vhdl_const_int(newwidth));
return resizef;
}
vhdl_expr *vhdl_const_int::to_vector(vhdl_type_name_t name, int w)
{
if (name == VHDL_TYPE_SIGNED || name == VHDL_TYPE_UNSIGNED) {
const char *fname = name == VHDL_TYPE_SIGNED
? "To_Signed" : "To_Unsigned";
vhdl_fcall *conv = new vhdl_fcall(fname, new vhdl_type(name, w - 1, 0));
conv->add_expr(this);
conv->add_expr(new vhdl_const_int(w));
return conv;
}
else
return vhdl_expr::to_vector(name, w);
}
int64_t vhdl_const_bits::bits_to_int() const
{
char msb = value_[value_.size() - 1];
int64_t result = 0, bit;
for (int i = sizeof(int64_t)*8 - 1; i >= 0; i--) {
if (i > (int)value_.size() - 1)
bit = (msb == '1' && signed_) ? 1 : 0;
else
bit = value_[i] == '1' ? 1 : 0;
result = (result << 1) | bit;
}
return result;
}
vhdl_expr *vhdl_const_bits::to_std_logic()
{
// VHDL won't let us cast directly between a vector and
// a scalar type
// But we don't need to here as we have the bits available
// Take the least significant bit
char lsb = value_[0];
return new vhdl_const_bit(lsb);
}
char vhdl_const_bits::sign_bit() const
{
return signed_ ? value_[value_.length()-1] : '0';
}
vhdl_expr *vhdl_const_bits::to_vector(vhdl_type_name_t name, int w)
{
if (name == VHDL_TYPE_STD_LOGIC_VECTOR) {
// Don't need to do anything
return this;
}
else if (name == VHDL_TYPE_SIGNED || name == VHDL_TYPE_UNSIGNED) {
// Extend with sign bit
value_.resize(w, sign_bit());
return this;
}
assert(false);
return NULL;
}
vhdl_expr *vhdl_const_bits::to_integer()
{
return new vhdl_const_int(bits_to_int());
}
vhdl_expr *vhdl_const_bits::resize(int w)
{
// Rather than generating a call to Resize, when can just sign-extend
// the bits here. As well as looking better, this avoids any ambiguity
// between which of the signed/unsigned versions of Resize to use.
value_.resize(w, sign_bit());
return this;
}
vhdl_expr *vhdl_const_bit::to_integer()
{
return new vhdl_const_int(bit_ == '1' ? 1 : 0);
}
vhdl_expr *vhdl_const_bit::to_boolean()
{
return new vhdl_const_bool(bit_ == '1');
}
vhdl_expr *vhdl_const_bit::to_vector(vhdl_type_name_t name, int w)
{
// Zero-extend this bit to the correct width
return (new vhdl_const_bits(&bit_, 1, name == VHDL_TYPE_SIGNED))->resize(w);
}
| 28.410256 | 81 | 0.636169 | [
"vector"
] |
7cd92af0471be84f1d0e329000807ad93400a43e | 1,190 | cpp | C++ | recursion-and-dp/towers-of-hanoi.cpp | mayankamencherla/cracking-the-coding-interview-solutions | 3cccad728cd4d41154eed9e93dd0546923a23fda | [
"MIT"
] | 3 | 2018-12-04T09:41:01.000Z | 2020-10-05T17:30:49.000Z | recursion-and-dp/towers-of-hanoi.cpp | mayankamencherla/cracking-the-coding-interview-solutions | 3cccad728cd4d41154eed9e93dd0546923a23fda | [
"MIT"
] | null | null | null | recursion-and-dp/towers-of-hanoi.cpp | mayankamencherla/cracking-the-coding-interview-solutions | 3cccad728cd4d41154eed9e93dd0546923a23fda | [
"MIT"
] | 1 | 2018-12-04T09:41:05.000Z | 2018-12-04T09:41:05.000Z | /**
* Given 2 numbers, recursively multiply them
* Without using *, use +, -, >>, <<
* Minimize the operations listed above
*/
#include <vector>
#include <iostream>
#include <stack>
using namespace std;
void initializeMain(stack<int>& main, int n)
{
for (int i=n; i>=1; i--)
{
main.push(i);
}
}
void moveStacks(stack<int>& main, stack<int>& buffer, int n)
{
while (n > 0)
{
buffer.push(main.top());
main.pop();
n--;
}
}
void moveLargestElement(stack<int>& main, stack<int>& target)
{
int top = main.top();
main.pop();
target.push(top);
}
void towersOfHanoi(stack<int>& main, stack<int>& buffer, stack<int>& target, int n)
{
if (n <= 0) return;
towersOfHanoi(main, target, buffer, n-1);
moveLargestElement(main, target);
towersOfHanoi(buffer, main, target, n-1);
}
int main()
{
stack<int> main;
stack<int> buffer;
stack<int> target;
int n;
printf("Enter any number : ");
cin >> n;
initializeMain(main, n);
towersOfHanoi(main, buffer, target, n);
while (!target.empty())
{
cout << target.top() << endl;
target.pop();
}
}
| 15.25641 | 83 | 0.569748 | [
"vector"
] |
7ce52c51f24fc7fbd797674f7fe29ea32f1f5459 | 359 | cpp | C++ | Leetcode/0406. Queue Reconstruction by Height/0406.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | Leetcode/0406. Queue Reconstruction by Height/0406.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | Leetcode/0406. Queue Reconstruction by Height/0406.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | class Solution {
public:
vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
vector<vector<int>> ans;
sort(begin(people), end(people), [](const auto& a, const auto& b) {
return a[0] == b[0] ? a[1] < b[1] : a[0] > b[0];
});
for (const auto& p : people)
ans.insert(begin(ans) + p[1], p);
return ans;
}
};
| 22.4375 | 71 | 0.554318 | [
"vector"
] |
7cf02038bbd99599cd784c5266df28efea9156d3 | 60,523 | cpp | C++ | demoMain.cpp | TheMagnat/Demo-Graphique-OpenGL | af1d21df44ce23bf272829e87417c771b4eaef77 | [
"MIT"
] | null | null | null | demoMain.cpp | TheMagnat/Demo-Graphique-OpenGL | af1d21df44ce23bf272829e87417c771b4eaef77 | [
"MIT"
] | null | null | null | demoMain.cpp | TheMagnat/Demo-Graphique-OpenGL | af1d21df44ce23bf272829e87417c771b4eaef77 | [
"MIT"
] | null | null | null |
/*
Projet programmation Graphique Guillaume Magniadas
Note : Il y à certaine partie du code qui aurait pu être mieux écrite pour mieux tirer profit des avantage du C++,
En commencant ce projet je me suis trop vite lancé, je pense que j'aurais pu ecrire plus de classe pour améliorer la lisibilité du code,
et le rendre plus maléable.
*/
#include "head.hpp"
//Le Chrono
#include <chrono>
//Mes fichiers
#include "SlowCube.hpp"
#include "Particles.hpp"
#include "Mobiles.hpp"
//Les fonction 3D
#include "3Dfunction.hpp"
//Temps
std::chrono::time_point<std::chrono::system_clock> last, now, startAnim, startProg;
//Taille de fenetre
static unsigned int width_f, height_f;
//Shader
static GLuint _pId = 0;
static GLuint _pidSky = 0;
static GLuint _pidSpace = 0;
static GLuint _pidSpaceMonte = 0;
static GLuint _pidStars = 0;
static GLuint _blurV = 0;
static GLuint _blurH = 0;
static GLuint _postProd = 0;
static GLuint _particuleShad = 0;
static GLuint _creditShad = 0;
static GLuint _voronoiShad = 0;
static GLuint _pidSphere = 0;
static GLuint _pidBlack = 0;
static GLuint _godLight = 0;
static GLuint _godLight2 = 0;
//static Shader testShad;
//Frame buffer
unsigned int fbo1 = 0, fbo2 = 0;
//Texture de framebuffer color
unsigned int texColBuff = 0, texColBuff2 = 0;
//Depth et stencil buffer tempon buffer
unsigned int rbo = 0;
//Couleurs
GLfloat cyan[] = {50.f/255.f, 1, 1, 1};
static std::array<float, 3> colors {1.0f, 0.0f, 1.0f};
//Objet GL4D
static GLuint sphere_ = 0;
//vertices
static float skyboxVertices[] = {
// positions
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, 1.0f
};
//Fond square
static float spaceVertices[] = {
//Position, Texture
-1.f, -1.f, 0.f, 0.f, 0.f,
-1.f, 1.f, 0.f, 0.f, 1.f,
1.f, 1.f, 0.f, 1.f, 1.f,
1.f, 1.f, 0.f, 1.f, 1.f,
1.f, -1.f, 0.f, 1.f, 0.f,
-1.f, -1.f, 0.f, 0.f, 0.f
};
//Variable Global OpenGL
//Save VAO VBO
static unsigned int VBO, VAO, skyVBO, skyVAO, spaceVBO, spaceVAO;
//data de forme
static std::array<float, 216> maForme;
//save des formes
static std::vector<unsigned int> allFormes;
static std::vector<unsigned int> allFormesVBO;
//Variable Global Texture
static unsigned int cubemapTexture;
static std::vector<std::string> faces{
"texture/right.tga",
"texture/left.tga",
"texture/top.tga",
"texture/bottom.tga",
"texture/front.tga",
"texture/back.tga"
};
static unsigned int textureSpace;
static std::string fileSpace = "texture/bottom.tga";
//Texture des mobiles 1D
static unsigned int textureMobiles;
//Variable Global Music
#define ECHANTILLONS 1024
static Sint16 _hauteurs[ECHANTILLONS];
/*!\brief pointeur vers la musique chargée par SDL_Mixer */
static Mix_Music * _mmusic = NULL;
/*!\brief données entrées/sorties pour la lib fftw */
static fftw_complex * _in4fftw = NULL, * _out4fftw = NULL;
/*!\brief donnée à précalculée utile à la lib fftw */
static fftw_plan _plan4fftw = NULL;
//Variable Global Fonts
static unsigned int _textTexId = 0;
//Fonctions
static Point p1(50, 50, 0.25, 0.5, 0.4);
static Point p2(50, 500, 0.25, 0.5, 0.4);
static Point p3(500, 500, 0.25, 0.5, 0.4);
static Point p4(500, 50, 0.25, 0.5, 0.4);
/**
* Fonction exécuté à la fin du programme.
**/
static void quitte(void) {
//Je ne suis pas sur de bien delete tout ce qu'il faut par defaut de temps..
glDeleteVertexArrays(1, &skyVAO);
glDeleteBuffers(1, &skyVBO);
glDeleteVertexArrays(1, &spaceVAO);
glDeleteBuffers(1, &spaceVBO);
glDeleteFramebuffers(1, &fbo1);
glDeleteFramebuffers(1, &fbo2);
glDeleteRenderbuffers(1, &rbo);
//On libère les texture des fonts
if(_textTexId) {
glDeleteTextures(1, &_textTexId);
_textTexId = 0;
}
if(textureMobiles){
glDeleteTextures(1, &textureMobiles);
textureMobiles = 0;
}
if(textureSpace){
glDeleteTextures(1, &textureSpace);
textureSpace = 0;
}
if(cubemapTexture){
glDeleteTextures(1, &cubemapTexture);
cubemapTexture = 0;
}
for(size_t i(0); i < allFormes.size(); ++i){
glDeleteVertexArrays(1, &allFormes[i]);
}
for(size_t i(0); i < allFormesVBO.size(); ++i){
glDeleteBuffers(1, &allFormesVBO[i]);
}
gl4duClean(GL4DU_ALL);
}
static size_t pourcentActual = 0;
static std::array<bool, 4> pourcentAuto;
static std::array<float, 4> pourcent;
/**
* Fonction servant à dessin, permetant de faire grandire le pourcentage affiché de chaque coté de la forme 2D jusqu'a tous les avoir à 100%.
**/
static void growPourcent(float step){
for(size_t i(0); i < 4; ++i){
if(pourcent[i] != 1.f){
pourcent[i] += step;
if(pourcent[i] >= 1.0f){
pourcent[i] = 1.0f;
pourcentActual = i+1;
}
break;
}
}
}
/**
* Fonction qui génère un quadrilatère 2D de facon aléatoire.
**/
static void newPoint(Point& a1, Point& a2, Point& a3, Point& a4){
/*
a1 = Point(rand()%(width_f/2) + width_f/4, rand()%(height_f/2) + height_f/4, 1, 1, 1);
a2 = Point(rand()%(width_f/2) + width_f/4, rand()%(height_f/2) + height_f/4, 1, 1, 1);
a3 = Point(rand()%(width_f/2) + width_f/4, rand()%(height_f/2) + height_f/4, 1, 1, 1);
a4 = Point(rand()%(width_f/2) + width_f/4, rand()%(height_f/2) + height_f/4, 1, 1, 1);
*/
a1 = Point(rand()%(width_f/4) + width_f/4, rand()%(height_f/4) + height_f/4, 1, 1, 1);
a2 = Point(rand()%(width_f/4) + width_f/4, rand()%(height_f/4) + height_f/2, 1, 1, 1);
a3 = Point(rand()%(width_f/4) + width_f/2, rand()%(height_f/4) + height_f/2, 1, 1, 1);
a4 = Point(rand()%(width_f/4) + width_f/2, rand()%(height_f/4) + height_f/4, 1, 1, 1);
}
//Les étoiles
static std::vector<glm::vec3> posStar;
static std::vector<glm::vec3> posStarTwo;
static std::vector<glm::vec3> posStarTree;
/**
* Fonction qui remplis les position de nb étoiles dans fillPosStar,
* le tout compris entre minWidth et maxWidth pour l'axe X, et pareil pour les 2 dernier axes.
**/
static void generateStars(std::vector<glm::vec3>& fillPosStar, int nb, int minWidth, int maxWidth, int minHeight, int maxHeight, int minDepth, int maxDepth){
for(size_t i(0); i < nb; ++i){
fillPosStar.emplace_back(rand()%(maxWidth - minWidth) + minWidth, rand()%(maxHeight - minHeight) + minHeight, rand()%(maxDepth - minDepth) + minDepth);
}
}
//Variable de calcul
static float accele = 0;
static float accele2 = 0;
static float hight = 0;
static float angle = 0;
//static std::array<float, 3> clearColor;
static glm::vec3 clearColor;
static glm::vec3 ambient = glm::vec3(0.1f);
static glm::vec3 specular = glm::vec3(0.1f);
static float transpa = 0.0f;
static Particles mesParticules;
static Mobiles mesMobiles;
/**
* Boucle graphique faisant office de crédit.
* Affiche les crédit sur un quadrilatère texturé par ces dernier qui bouge dans un framebuffer,
* puis traite la texture obtenue dans un shader affichant une certaine version de voronoi.
* La demo se termine une fois les crédit partie et quelque secondes après.
**/
static void dessinVoronoi(void){
//Calculs de temps
now = std::chrono::system_clock::now();
std::chrono::duration<double, std::ratio<1,1>> delta = now - last;
last = now;
float elapsedTime(delta.count());
float timeFromStart(std::chrono::duration<double, std::ratio<1,1>>(std::chrono::system_clock::now() - startAnim).count());
//
mesMobiles.move(elapsedTime);
//On change de frame buffer
glBindFramebuffer(GL_FRAMEBUFFER, fbo1);
glClearColor(0, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//Décommenter pour un effet sympathique
/*glDepthMask(GL_FALSE);
glUseProgram(_pidSpace);
glUniform1f(glGetUniformLocation(_pidSpace, "temps"), timeFromStart);
glUniform1f(glGetUniformLocation(_pidSpace, "angle2"), 0);
glUniform1f(glGetUniformLocation(_pidSpace, "hight"), 0);
clearColor[0] = 1.0f;
glUniform3fv(glGetUniformLocation(_pidSpace, "clearColor"), 1, &clearColor[0]);
glUniform1f(glGetUniformLocation(_pidSpace, "finAll"), 0.0f);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textureSpace);
glBindVertexArray(spaceVAO);
glDrawArrays(GL_TRIANGLES, 0, 6);
glDepthMask(GL_TRUE);*/
//
glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glUseProgram(_creditShad);
glm::mat4 projection = glm::perspective(glm::radians(45.0f), (float)width_f / (float)height_f, 0.1f, 50.0f);
glUniformMatrix4fv(glGetUniformLocation(_creditShad, "projection"), 1, GL_FALSE, &projection[0][0]);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, _textTexId);
glUniform1i(glGetUniformLocation(_creditShad, "tex"), 0);
gl4duBindMatrix("modelViewMatrix");
gl4duLoadIdentityf();
static bool end = false;
float scaleCoef = abs(tan(timeFromStart/10.0f))*2;
if(timeFromStart > 5.0f && scaleCoef < 0.01f){
if(!end){
end = true;
timeFromStart = 0.0f;
startAnim = now;
}
}
if(!end){
gl4duScalef(scaleCoef*2, scaleCoef, 1);
}
else{
gl4duScalef(0, 0, 0);
}
//gl4duTranslatef(0.033, 0.10, -5.0);
gl4duTranslatef(0.f, 0.f, -5.5f);
gl4duRotatef(abs(tan(timeFromStart/50.f)*360), 1, 1, 1);
gl4duSendMatrices();
glBindVertexArray(spaceVAO);
glDrawArrays(GL_TRIANGLES, 0, 6);
//On dessine maintenant sur l'écran
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glClear(GL_COLOR_BUFFER_BIT);
//Shaders pour le voronoi
glUseProgram(_voronoiShad);
std::vector<float> texture1Data;
size_t mobilesSize(mesMobiles.fillTexture(texture1Data));
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texColBuff);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_1D, textureMobiles);
glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA32F, mobilesSize, 0, GL_RGBA, GL_FLOAT, texture1Data.data());
glUniform1i(glGetUniformLocation(_voronoiShad, "screenTex"), 0);
glUniform1i(glGetUniformLocation(_voronoiShad, "mobileTex"), 1);
glUniform1f(glGetUniformLocation(_voronoiShad, "step"), (1.0f / mobilesSize));
glUniform1f(glGetUniformLocation(_voronoiShad, "time"), timeFromStart);
glBindVertexArray(spaceVAO);
glDrawArrays(GL_TRIANGLES, 0, 6);
if(end && timeFromStart > 3.0f){
float timeFromStartProg(std::chrono::duration<double, std::ratio<1,1>>(std::chrono::system_clock::now() - startProg).count());
std::cout << "Temps total : " << timeFromStartProg << std::endl;
exit(0);
}
}
static float mode = -1;
static bool finAll = false;
static size_t finVal;
/**
* Boucle graphique finale qui reprend toute les formes déssiné au cours de dessin3D (les version 3D de dessin)
* et les affiche à la chaine sous la forme d'une spirale infini. 3 paques de sphere sont aussi déssiné.
* La camera de cette boucle avance à l'infini et a chaque fois qu'un paques de sphère passe dérière, ses spheres sont régénéré derriere les deux autres.
* Une fois que l'angle de vue atteint une valeur fixé, commence à effacer certaint element de la scene jisqi'a obtenir un ecran noire.
* Une fois l'ecran noire obtenue, après quelque secondes lance la boucle dessinVoronoi.
**/
static void dessinAll(void){
//Calculs de temps
now = std::chrono::system_clock::now();
std::chrono::duration<double, std::ratio<1,1>> delta = now - last;
last = now;
float elapsedTime(delta.count());
float timeFromStart(std::chrono::duration<double, std::ratio<1,1>>(std::chrono::system_clock::now() - startAnim).count());
Sint16 tempo = _hauteurs[2];
if(!finAll){
//Constante en fonction des basses
if(tempo > 40){
//Couleur du clear
clearColor[0] = 1.0f;
clearColor[1] = 0.0f;
clearColor[2] = 1.0f;
//Couleur de la lumière ambient
ambient[0] = 1.0f;
ambient[1] = 0.0f;
ambient[2] = 1.0f;
specular[0] = 0.35f;
specular[1] = 0.0f;
specular[2] = 0.5f;
//Transparence de la piece centrale
transpa = 0.75f;
}
for(size_t i(0); i < 3; ++i){
clearColor[i] += 0.015f;
if(clearColor[i] > 1.0f) clearColor[i] = 1.0f;
ambient[i] -= 0.010f;
if(ambient[i] < 0.1f) ambient[i] = 0.1f;
specular[i] += 0.015f;
if(specular[i] > 1.0f) specular[i] = 1.0f;
}
transpa -= 0.025f;
if(transpa < 0) transpa = 0.0f;
}
else{
for(size_t i(0); i < 3; ++i){
clearColor[i] -= 0.015f;
if(clearColor[i] < 0.0f) clearColor[i] = 0.0f;
ambient[i] -= 0.010f;
if(ambient[i] < 0.1f) ambient[i] = 0.1f;
specular[i] += 0.015f;
if(specular[i] > 1.0f) specular[i] = 1.0f;
}
}
//Scale de la forme
tempo = _hauteurs[2];
if(tempo > 0 && hight < (0.5*sqrt(tempo)*(0.5*0.5)*16)){
accele = sqrt(tempo);
}
accele -= elapsedTime * 6.f;
hight = 0.5*accele*(0.5*0.5)+hight;
if(hight <= 0.5) hight = 0;
if(hight == 0) accele = 0;
//Rotation de la forme
tempo = _hauteurs[32];
if(tempo > 0 && accele2 < (0.5*tempo/3*(0.5*0.5)*16)){
accele2 = tempo/3;
}
accele2 -= elapsedTime * 0.75f;
if(accele2 <= 0) accele2 = 0;
angle += 0.5*accele2*(0.5*0.5);
glClearColor(clearColor[0], clearColor[1], clearColor[2], 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//On s'occupe du fond
glDepthMask(GL_FALSE);
glUseProgram(_pidSpace);
glUniform1f(glGetUniformLocation(_pidSpace, "temps"), timeFromStart);
glUniform1f(glGetUniformLocation(_pidSpace, "angle2"), angle);
glUniform1f(glGetUniformLocation(_pidSpace, "hight"), hight);
glUniform3fv(glGetUniformLocation(_pidSpace, "clearColor"), 1, &clearColor[0]);
glUniform1f(glGetUniformLocation(_pidSpace, "finAll"), finAll == true ? 1.0f : 0.0f);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textureSpace);
glBindVertexArray(spaceVAO);
glDrawArrays(GL_TRIANGLES, 0, 6);
glDepthMask(GL_TRUE);
//Dessin des pieces
glUseProgram(_pId);
glUniform1f(glGetUniformLocation(_pId, "time"), timeFromStart);
glUniform1f(glGetUniformLocation(_pId, "mode"), -1.0f);
//Lumière
glUniform3fv(glGetUniformLocation(_pId, "light.ambient"), 1, &ambient[0]);
glUniform3f(glGetUniformLocation(_pId, "light.specular"), 1.0f, 1.0f, 1.0f);
glUniform3f(glGetUniformLocation(_pId, "light.diffuse"), 1.f, 1.f, 1.f);
//Attenuation
glUniform1f(glGetUniformLocation(_pId, "light.constant"), 1.0f);
glUniform1f(glGetUniformLocation(_pId, "light.linear"), 0.00045f);
glUniform1f(glGetUniformLocation(_pId, "light.quadratic"), 0.000075f);
glUniform4fv(glGetUniformLocation(_pId, "couleur"), 1, cyan);
//Camera
static float tempoY = -15.f;
tempoY -= elapsedTime * 60.f;
glm::vec3 viewPos(0.f, tempoY, 0.f);
glm::mat4 view = glm::lookAt(viewPos, glm::vec3(0.0, -1.0, 0.0) + viewPos, glm::vec3(0.0, 0.0, -1.0));
glUniformMatrix4fv(glGetUniformLocation(_pId, "view"), 1, GL_FALSE, &view[0][0]);
glUniform3fv(glGetUniformLocation(_pId, "viewPos"), 1, &viewPos[0]);
glUniform3fv(glGetUniformLocation(_pId, "light.position"), 1, &viewPos[0]);
//Projection
static float viewAngle = 0.f;
viewAngle += elapsedTime * 3.f;
if(viewAngle >= 175.f){
viewAngle = 175.f;
if(finAll == false){
finAll = true;
finVal = static_cast<size_t>(((-1*(tempoY+15))+1000)/(allFormes.size() * 2)) - 25;
}
}
glm::mat4 projection = glm::perspective(glm::radians(viewAngle), (float)width_f / (float)height_f, 0.1f, 5000.0f);
glUniformMatrix4fv(glGetUniformLocation(_pId, "projection"), 1, GL_FALSE, &projection[0][0]);
//Uniform
glUniform4fv(glGetUniformLocation(_pId, "couleur"), 1, cyan);
glUniform1f(glGetUniformLocation(_pId, "transpa"), 1.f);
//Model
gl4duBindMatrix("modelViewMatrix");
gl4duLoadIdentityf();
size_t taille(allFormes.size());
size_t prof1Ite(taille*2);
size_t maxIte;
if(finAll){
maxIte = finVal;
}
else{
maxIte = static_cast<size_t>(((-1*(tempoY+15))+1000)/prof1Ite);
}
for(size_t i(static_cast<size_t>(((-1*(tempoY+15))/prof1Ite))), it(i*taille); i < maxIte; ++i){
for(; it < taille * (i+1); ++it){
gl4duPushMatrix();
gl4duTranslatef(0, -2.f * it, 0.f);
gl4duRotatef(360 * ((((it) - taille * i) + 0.f)/((float)taille)), 0.f, 1.f, 0.f);
gl4duTranslatef(0, 0, (-5.f - hight));
gl4duRotatef(-angle, -1, 1, 0);
gl4duRotatef(timeFromStart*75.0f, -1, 0, 0);
glBindVertexArray(allFormes[(it - taille * i)]);
gl4duScalef(2.f, 2.f, 2.f);
gl4duSendMatrices();
glUniform1f(glGetUniformLocation(_pId, "transpa"), transpa);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glDrawArrays(GL_TRIANGLES, 0, 36);
gl4duScalef(hight/30.f + 1.f, hight/30.f + 1.f, hight/30.f + 1.f);
gl4duSendMatrices();
glUniform1f(glGetUniformLocation(_pId, "transpa"), 1.f);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glDrawArrays(GL_TRIANGLES, 0, 36);
gl4duPopMatrix();
}
}
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
//Etoiles
glUseProgram(_pidStars);
//Lumière
glUniform3fv(glGetUniformLocation(_pId, "light.ambient"), 1, &ambient[0]);
glUniform3f(glGetUniformLocation(_pId, "light.specular"), 1.0f, 1.0f, 1.0f);
glUniform3f(glGetUniformLocation(_pId, "light.diffuse"), 1.f, 1.f, 1.f);
//Attenuation
glUniform1f(glGetUniformLocation(_pId, "light.constant"), 1.0f);
glUniform1f(glGetUniformLocation(_pId, "light.linear"), 0.022f);
glUniform1f(glGetUniformLocation(_pId, "light.quadratic"), 0.0019f);
static uint8_t lowest = 0;
static int nextStep = -100;
if(!finAll){
if(tempoY <= nextStep){
if(lowest == 0){
posStar.clear();
generateStars(posStar, 500, -50, 50, nextStep - 200, nextStep - 300, -50, 50);
lowest = 1;
}
else if(lowest == 1){
posStarTwo.clear();
generateStars(posStarTwo, 500, -50, 50, nextStep - 200, nextStep - 300, -50, 50);
lowest = 2;
}
else{
posStarTree.clear();
generateStars(posStarTree, 500, -50, 50, nextStep - 200, nextStep - 300, -50, 50);
lowest = 0;
}
nextStep -= 100;
}
}
glUniformMatrix4fv(glGetUniformLocation(_pId, "view"), 1, GL_FALSE, &view[0][0]);
glUniform3fv(glGetUniformLocation(_pId, "viewPos"), 1, &viewPos[0]);
glUniform3fv(glGetUniformLocation(_pId, "light.position"), 1, &viewPos[0]);
glUniformMatrix4fv(glGetUniformLocation(_pId, "projection"), 1, GL_FALSE, &projection[0][0]);
//Uniform
glUniform4f(glGetUniformLocation(_pId, "couleur"), 1, 1, 1, 1);
glUniform1f(glGetUniformLocation(_pId, "transpa"), 1.f);
//Model
gl4duBindMatrix("modelViewMatrix");
for(size_t i(0), taille(posStar.size()); i < taille; ++i){
gl4duLoadIdentityf();
gl4duTranslatef(posStar[i].x, posStar[i].y, posStar[i].z);
gl4duScalef(0.15f, 0.15f, 0.15f);
gl4duSendMatrices();
gl4dgDraw(sphere_);
gl4duLoadIdentityf();
gl4duTranslatef(posStarTwo[i].x, posStarTwo[i].y, posStarTwo[i].z);
gl4duScalef(0.15f, 0.15f, 0.15f);
gl4duSendMatrices();
gl4dgDraw(sphere_);
gl4duLoadIdentityf();
gl4duTranslatef(posStarTree[i].x+10, posStarTree[i].y+10, posStarTree[i].z+10);
gl4duScalef(0.15f, 0.15f, 0.15f);
gl4duSendMatrices();
gl4dgDraw(sphere_);
}
static float transpa2 = 1.0f;
transpa2 -= elapsedTime * 1.0f;
if(transpa2 < 0.0f) transpa2 = 0.0f;
//On dissine un ecran noir pour les transitions
glUseProgram(_pidBlack);
glBindVertexArray(spaceVAO);
glUniform4f(glGetUniformLocation(_pidBlack, "color"), 0, 0, 0, transpa2);
glDrawArrays(GL_TRIANGLES, 0, 6);
if(timeFromStart > 66.0f){
startAnim = std::chrono::system_clock::now();
gl4duwDisplayFunc(dessinVoronoi);
}
}
/**
* Ancienne boucle graphique plus utilisé, elle était prévu à la base a la place de dessinAllStars,
* Mais ressemble trop à dessinAll avec des choses en moins, reste intéréssante.
**/
static void dessinMonte(void){
//Calculs de temps
now = std::chrono::system_clock::now();
std::chrono::duration<double, std::ratio<1,1>> delta = now - last;
last = now;
float elapsedTime(delta.count());
float timeFromStart(std::chrono::duration<double, std::ratio<1,1>>(std::chrono::system_clock::now() - startAnim).count());
Sint16 tempo = _hauteurs[2];
//Constante en fonction des basses
if(tempo > 40){
//Couleur du clear
clearColor[0] = 1.0f;
clearColor[1] = 0.0f;
clearColor[2] = 1.0f;
//Couleur de la lumière ambient
ambient[0] = 1.0f;
ambient[1] = 0.0f;
ambient[2] = 1.0f;
//Transparence de la piece centrale
transpa = 0.75f;
}
for(size_t i(0); i < 3; ++i){
clearColor[i] += 0.015f;
if(clearColor[i] > 1.0f) clearColor[i] = 1.0f;
ambient[i] -= 0.010f;
if(ambient[i] < 0.1f) ambient[i] = 0.1f;
specular[i] += 0.015f;
if(specular[i] > 1.0f) specular[i] = 1.0f;
}
transpa -= 0.025f;
if(transpa < 0) transpa = 0.0f;
//Scale de la forme
tempo = _hauteurs[2];
if(tempo > 0 && hight < (0.5*sqrt(tempo)*(0.5*0.5)*16)){
accele = sqrt(tempo);
}
accele -= elapsedTime * 6.f;
hight = 0.5*accele*(0.5*0.5)+hight;
if(hight <= 0.5) hight = 0;
if(hight == 0) accele = 0;
//Rotation de la forme
tempo = _hauteurs[32];
if(tempo > 0 && accele2 < (0.5*tempo/3*(0.5*0.5)*16)){
accele2 = tempo/3;
}
accele2 -= elapsedTime * 1.5f;
if(accele2 <= 0) accele2 = 0;
angle += 0.5*accele2*(0.5*0.5);
glClearColor(clearColor[0], clearColor[1], clearColor[2], 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//On s'occupe du fond
glDepthMask(GL_FALSE);
glUseProgram(_pidSpaceMonte);
glUniform1f(glGetUniformLocation(_pidSpaceMonte, "temps"), 40.f - timeFromStart);
glUniform1f(glGetUniformLocation(_pidSpaceMonte, "angle2"), angle);
glUniform1f(glGetUniformLocation(_pidSpaceMonte, "hight"), hight);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textureSpace);
glBindVertexArray(spaceVAO);
glDrawArrays(GL_TRIANGLES, 0, 6);
glDepthMask(GL_TRUE);
//Dessin des pieces
glUseProgram(_pidSpaceMonte);
//Lumière
glUniform3fv(glGetUniformLocation(_pId, "light.ambient"), 1, &ambient[0]);
glUniform3f(glGetUniformLocation(_pId, "light.specular"), 1.0f, 1.0f, 1.0f);
glUniform3f(glGetUniformLocation(_pId, "light.diffuse"), 1.f, 1.f, 1.f);
//Attenuation
glUniform1f(glGetUniformLocation(_pId, "light.constant"), 1.0f);
glUniform1f(glGetUniformLocation(_pId, "light.linear"), 0.0045f);
glUniform1f(glGetUniformLocation(_pId, "light.quadratic"), 0.00075f);
glUniform4fv(glGetUniformLocation(_pId, "couleur"), 1, cyan);
//CALCUL POUR LES DEPLACEMENT
//FIN CALCULS
static float tempoY = -15.f;
tempoY -= elapsedTime * 60.f;
glm::vec3 viewPos(0.f, tempoY, 0.f);
glm::mat4 view = glm::lookAt(viewPos, glm::vec3(0.0, -1.0, 0.0) + viewPos, glm::vec3(0.0, 0.0, -1.0));
glUniformMatrix4fv(glGetUniformLocation(_pId, "view"), 1, GL_FALSE, &view[0][0]);
glUniform3fv(glGetUniformLocation(_pId, "viewPos"), 1, &viewPos[0]);
glUniform3fv(glGetUniformLocation(_pId, "light.position"), 1, &viewPos[0]);
//Projection
static float viewAngle = 0.f;
viewAngle += elapsedTime * 3.f;
if(viewAngle >= 175.f) viewAngle = 175.f;
glm::mat4 projection = glm::perspective(glm::radians(viewAngle), (float)width_f / (float)height_f, 0.1f, 5000.0f);
glUniformMatrix4fv(glGetUniformLocation(_pId, "projection"), 1, GL_FALSE, &projection[0][0]);
//Uniform
glUniform4fv(glGetUniformLocation(_pId, "couleur"), 1, cyan);
glUniform1f(glGetUniformLocation(_pId, "transpa"), 1.f);
//Model
gl4duBindMatrix("modelViewMatrix");
gl4duLoadIdentityf();
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
if(timeFromStart >= 40.f){
startAnim = std::chrono::system_clock::now();
gl4duwDisplayFunc(dessin);
}
}
/**
* Boucle graphique qui dessine 3 paques de plusieurs sphere dispersé de manière aléatoire,
* La camera de cette boucle recule perpetuellement, et a chaque fois qu'un des paque est assez éloigné, regenère ses sphere et le replace en avant.
* Des particules sont aussi généré au cours de cette boucle.
* Le tout est ensuité flouté et mixé avec un avant après pour donner un effet de brillance.
* Une fois un temps fixé passé, commence à ne plus rien generer, puis passe à la boucle dessin.
**/
static void dessinAllStars(void){
//Calculs de temps
now = std::chrono::system_clock::now();
std::chrono::duration<double, std::ratio<1,1>> delta = now - last;
last = now;
float elapsedTime(delta.count());
float timeFromStart(std::chrono::duration<double, std::ratio<1,1>>(std::chrono::system_clock::now() - startAnim).count());
Sint16 tempo = _hauteurs[2];
//Constante en fonction des basses
if(tempo > 40){
//Couleur de la lumière ambient
ambient[0] = 1.0f;
ambient[1] = 0.0f;
ambient[2] = 1.0f;
//Transparence de la piece centrale
transpa = 0.75f;
}
for(size_t i(0); i < 3; ++i){
ambient[i] -= 0.010f;
if(ambient[i] < 0.1f) ambient[i] = 0.1f;
specular[i] += 0.015f;
if(specular[i] > 1.0f) specular[i] = 1.0f;
}
transpa -= 0.025f;
if(transpa < 0) transpa = 0.0f;
//On change de framebuffer avant tout
glBindFramebuffer(GL_FRAMEBUFFER, fbo1);
glClearColor(clearColor[0], clearColor[1], clearColor[2], 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//Dessin des pieces
glUseProgram(_pidStars);
//Lumière
glUniform3fv(glGetUniformLocation(_pidStars, "light.ambient"), 1, &ambient[0]);
glUniform3f(glGetUniformLocation(_pidStars, "light.specular"), 1.0f, 1.0f, 1.0f);
glUniform3f(glGetUniformLocation(_pidStars, "light.diffuse"), 1.f, 1.f, 1.f);
//Attenuation
glUniform1f(glGetUniformLocation(_pidStars, "light.constant"), 1.0f);
glUniform1f(glGetUniformLocation(_pidStars, "light.linear"), 0.022f);
glUniform1f(glGetUniformLocation(_pidStars, "light.quadratic"), 0.0019f);
static uint8_t lowest = 0;
static int nextStep = 100;
static float tempoZ = 0.f;
float tempoX = cos(timeFromStart)*10.f;
float tempoY = sin(timeFromStart)*10.f;
tempoZ += elapsedTime * 30.f;
glm::vec3 viewPos(tempoX, tempoY, tempoZ);
if(timeFromStart >= 12.5f){
}
else{
if(tempoZ >= nextStep){
if(lowest == 0){
posStar.clear();
generateStars(posStar, 500, -50, 50, -50, 50, nextStep, nextStep + 100);
lowest = 1;
}
else if(lowest == 1){
posStarTwo.clear();
generateStars(posStarTwo, 500, -50, 50, -50, 50, nextStep, nextStep + 100);
lowest = 2;
}
else{
posStarTree.clear();
generateStars(posStarTree, 500, -50, 50, -50, 50, nextStep, nextStep + 100);
lowest = 0;
}
nextStep += 100;
}
}
if(timeFromStart < 15.0f){
//Ajout de particules
int nbNewParticles = (int)(elapsedTime*150.0);
//Pour eviter les paté de particules en cas de petit freeze
if(nbNewParticles > (int)(0.016f*150.0)) nbNewParticles = (int)(0.016f*150.0);
for(size_t i(0); i < nbNewParticles; ++i){
//Dispertion des particules inspiré des cours de http://www.opengl-tutorial.org sur les particules
float spread = 1.5f;
glm::vec3 maindir = glm::vec3(0.0f, 0.0f, 2.5f);
glm::vec3 randomdir = glm::vec3(
(rand()%2000 - 1000.0f)/250.0f,
(rand()%2000 - 1000.0f)/250.0f,
(rand()%2000 - 1000.0f)/1000.0f
);
glm::vec3 pos(glm::vec3(rand()%40 - 20, rand()%40 - 20, tempoZ - 5.f));
glm::vec4 color((rand()%256)/256.f, (rand()%256)/256.f, (rand()%256)/256.f, (rand()%256)/256.f);
mesParticules.add(pos, maindir + randomdir*spread, color, (rand()%100)/100.f * 0.3f + 0.05f, 0, 0, 5.0f);
}
}
glm::mat4 view = glm::lookAt(viewPos, glm::vec3(0.0, 0.0, -40.0f + tempoZ), glm::vec3(0.0, 1.f, 0.0f));
glUniformMatrix4fv(glGetUniformLocation(_pidStars, "view"), 1, GL_FALSE, &view[0][0]);
glUniform3fv(glGetUniformLocation(_pidStars, "viewPos"), 1, &viewPos[0]);
glUniform3fv(glGetUniformLocation(_pidStars, "light.position"), 1, &viewPos[0]);
//Projection
glm::mat4 projection = glm::perspective(glm::radians(45.0f), (float)width_f / (float)height_f, 0.1f, 5000.0f);
glUniformMatrix4fv(glGetUniformLocation(_pidStars, "projection"), 1, GL_FALSE, &projection[0][0]);
//Uniform
glUniform4f(glGetUniformLocation(_pidStars, "couleur"), 1, 1, 1, 1);
glUniform1f(glGetUniformLocation(_pidStars, "transpa"), 1.f);
//Model
gl4duBindMatrix("modelViewMatrix");
for(size_t i(0), taille(posStar.size()); i < taille; ++i){
gl4duLoadIdentityf();
gl4duTranslatef(posStar[i].x, posStar[i].y, posStar[i].z);
gl4duScalef(0.25f, 0.25f, 0.25f);
gl4duSendMatrices();
gl4dgDraw(sphere_);
gl4duLoadIdentityf();
gl4duTranslatef(posStarTwo[i].x, posStarTwo[i].y, posStarTwo[i].z);
gl4duScalef(0.25f, 0.25f, 0.25f);
gl4duSendMatrices();
gl4dgDraw(sphere_);
gl4duLoadIdentityf();
gl4duTranslatef(posStarTree[i].x+10, posStarTree[i].y+10, posStarTree[i].z+10);
gl4duScalef(0.25f, 0.25f, 0.25f);
gl4duSendMatrices();
gl4dgDraw(sphere_);
}
// ----Particules
mesParticules.update(elapsedTime, viewPos);
mesParticules.draw(view, projection);
//Une fois tout déssiné, on produit le resultat final
glDisable(GL_DEPTH_TEST);
//On utilise finalement le flou de gl4d, parfait pour notre utilisation
gl4dfBlur(texColBuff, texColBuff2, 15, 1, 0, GL_FALSE);
//On bind une fois la forme, ca suffi.
glBindVertexArray(spaceVAO);
//Flou verticale
/*
glBindFramebuffer(GL_FRAMEBUFFER, fbo2);
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
//Shaders pour le flou verti
glUseProgram(_blurV);
glUniform1f(glGetUniformLocation(_blurV, "sigma"), 3);
glUniform1f(glGetUniformLocation(_blurV, "blurSize"), 1.f/height_f);
glBindTexture(GL_TEXTURE_2D, texColBuff);
glDrawArrays(GL_TRIANGLES, 0, 6);
//Flou horizontale
glUseProgram(_blurH);
glUniform1f(glGetUniformLocation(_blurH, "sigma"), 3);
glUniform1f(glGetUniformLocation(_blurH, "blurSize"), 1.f/width_f);
glBindTexture(GL_TEXTURE_2D, texColBuff2);
glDrawArrays(GL_TRIANGLES, 0, 6);*/
// ----- Ecran -----
//Et on déssine sur l'ecran
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glClear(GL_COLOR_BUFFER_BIT);
//Shaders pour le quad
glUseProgram(_postProd);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texColBuff);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, texColBuff2);
glUniform1i(glGetUniformLocation(_postProd, "screenTexture"), 0);
glUniform1i(glGetUniformLocation(_postProd, "blurTexture"), 1);
glDrawArrays(GL_TRIANGLES, 0, 6);
glEnable(GL_DEPTH_TEST);
if(timeFromStart >= 20.f){
startAnim = std::chrono::system_clock::now();
gl4duwDisplayFunc(dessin);
}
}
static float camePos2 = 0.f;
/**
* Boucle de graphique de transition entre dessin3D et dessinAll.
* Dessine une sphere texturé avec un fond spacial et agrandi la sphere jusqu'a atteindre l'intérieur de celle ci.
* Passe à dessinAll quand celui ci est atteint.
**/
static void dessinTransition(void){
static float transpa2 = 1.0f;
static bool intro = true;
//Calculs de temps
now = std::chrono::system_clock::now();
std::chrono::duration<float, std::ratio<1,1>> delta = now - last;
last = now;
float elapsedTime(delta.count());
float timeFromStart(std::chrono::duration<float, std::ratio<1,1>>(now - startAnim).count());
//On change de framebuffer avant tout
glBindFramebuffer(GL_FRAMEBUFFER, fbo1);
//
Sint16 tempo = _hauteurs[2];
if(tempo > 40){
//Couleur de la lumière ambient
ambient[0] = colors[0];
ambient[1] = colors[1];
ambient[2] = colors[2];
}
float toAdd(elapsedTime * 0.90f);
for(size_t i(0); i < 3; ++i){
ambient[i] -= toAdd;
if(ambient[i] < 0.1f) ambient[i] = 0.1f;
}
//Scale de la forme
if(tempo > 0 && hight < (0.5*sqrt(tempo)*(0.5*0.5)*16)){
accele = sqrt(tempo);
}
accele -= elapsedTime * 30.f;
hight = 0.5*accele*(0.5*0.5)+hight;
if(hight <= 0.5) hight = 0;
if(hight == 0) accele = 0;
//Rotation de la forme
tempo = _hauteurs[32];
if(tempo > 0 && accele2 < (0.5*tempo/3*(0.5*0.5)*16)){
accele2 = tempo/3;
}
accele2 -= elapsedTime * 1.0f;
if(accele2 <= 0) accele2 = 0;
angle += 0.5*accele2;
glUseProgram(_pidSphere);
glUniform3fv(glGetUniformLocation(_pidSphere, "light.ambient"), 1, &ambient[0]);
glUniform3f(glGetUniformLocation(_pidSphere, "light.specular"), 0.5f, 0.5f, 0.5f);
glUniform3f(glGetUniformLocation(_pidSphere, "light.diffuse"), 1.f, 1.f, 1.f);
//Attenuation
glUniform1f(glGetUniformLocation(_pidSphere, "light.constant"), 1.0f);
glUniform1f(glGetUniformLocation(_pidSphere, "light.linear"), 0.022f);
glUniform1f(glGetUniformLocation(_pidSphere, "light.quadratic"), 0.0019f);
glClearColor(0, 0, 0, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//Camera
camePos2 += elapsedTime * 30.f;
float radius = 10.0f;
float camX = sin((camePos2)/50.f) * radius;
float camZ = cos((camePos2)/50.f) * radius;
glm::vec3 viewPos(camX, 0.0, camZ);
glUniform3fv(glGetUniformLocation(_pidSphere, "light.position"), 1, &viewPos[0]);
glm::mat4 view = glm::lookAt(viewPos, glm::vec3(0.0, 0.0, 0.0), glm::vec3(0.0, 1.f, 0.0f));
glUniformMatrix4fv(glGetUniformLocation(_pidSphere, "view"), 1, GL_FALSE, &view[0][0]);
glUniform3fv(glGetUniformLocation(_pidSphere, "viewPos"), 1, &viewPos[0]);
glUniform3fv(glGetUniformLocation(_pidSphere, "light.position"), 1, &viewPos[0]);
//Projection
glm::mat4 projection = glm::perspective(glm::radians(45.0f), (float)width_f / (float)height_f, 0.1f, 5000.0f);
glUniformMatrix4fv(glGetUniformLocation(_pidSphere, "projection"), 1, GL_FALSE, &projection[0][0]);
//Uniform
glUniform4f(glGetUniformLocation(_pidSphere, "couleur"), cyan[0], cyan[1], cyan[2], 1);
glUniform1f(glGetUniformLocation(_pidSphere, "transpa"), 1.f);
//Model
gl4duBindMatrix("modelViewMatrix");
gl4duLoadIdentityf();
//float scaleCoef(abs(cos(timeFromStart/5.f))*3.0f);
//float scaleCoef(timeFromStart*2 - 1.0f);
//float scaleCoef(abs(tan(timeFromStart/4.0f))/2.0f - 0.1f);
static std::vector<glm::vec3> allVelocity;
static std::vector<glm::vec3> allPos;
static int endScale = 0;
static float endTime = 0;
float actualTime(timeFromStart - endTime);
float scaleCoef(abs(cos(timeFromStart/5.0f)));
//std::cout << "Scale coef : " << scaleCoef << std::endl;
if(scaleCoef < 0.01f && !endScale){
endScale = true;
endTime = timeFromStart;
}
if(endScale == 1){
scaleCoef = 0.0f;
if(timeFromStart - endTime > 1.0f){
endScale = 2;
endTime = timeFromStart;
for(size_t i(0), taille(allFormes.size()*6); i < taille; ++i){
float vX((rand()%200 - 100) / 100.0f), vY((rand()%300 - 150) / 100.0f), vZ((rand()%200 - 100) / 100.0f);
allVelocity.emplace_back(vX, vY, vZ);
}
}
}
else if(endScale == 2){
scaleCoef = actualTime*10;
}
gl4duRotatef(angle, 1, -1, 0);
gl4duScalef(scaleCoef, scaleCoef, scaleCoef);
gl4duSendMatrices();
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textureSpace);
if(endScale == 0){
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
gl4dgDraw(sphere_);
}
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
for(size_t i(0), taille(allFormes.size()); i < taille*6; ++i){
size_t j(i%taille);
gl4duLoadIdentityf();
if(!endScale){
gl4duScalef(scaleCoef, scaleCoef, scaleCoef);
}
else if(endScale == 1){
gl4duScalef(0, 0, 0);
}
else if(endScale == 2){
if(scaleCoef < 1){
gl4duScalef(scaleCoef, scaleCoef, scaleCoef);
}
glm::vec3& velocity(allVelocity[i]);
gl4duTranslatef(velocity.x*5 * actualTime, velocity.y*2 * actualTime, velocity.z*5 * actualTime);
}
gl4duSendMatrices();
glBindVertexArray(allFormes[j]);
glDrawArrays(GL_TRIANGLES, 0, 36);
}
if(timeFromStart >= 18.5f) intro = false;
if(intro){
transpa2 -= elapsedTime * 0.5f;
if(transpa2 < 0.0f) transpa2 = 0.0f;
}
else{
transpa2 += elapsedTime * 1.0f;
if(transpa2 > 1.0f) transpa2 = 1.0f;
}
//On dissine un ecran noir pour les transitions
glUseProgram(_pidBlack);
glBindVertexArray(spaceVAO);
glUniform4f(glGetUniformLocation(_pidBlack, "color"), 0, 0, 0, transpa2);
glDrawArrays(GL_TRIANGLES, 0, 6);
//Une fois tout déssiné, on produit le resultat final
glDisable(GL_DEPTH_TEST);
//On utilise finalement le flou de gl4d, parfait pour notre utilisation
//gl4dfBlur(texColBuff, texColBuff2, 15, 1, 0, GL_FALSE);
//On bind une fois la forme, ca suffi.
glBindVertexArray(spaceVAO);
// ----- Ecran -----
//Et on déssine sur l'ecran
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glClear(GL_COLOR_BUFFER_BIT);
//Shaders pour le quad
glUseProgram(_godLight2);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texColBuff);
glUniform1i(glGetUniformLocation(_godLight2, "screenTexture"), 0);
glDrawArrays(GL_TRIANGLES, 0, 6);
glEnable(GL_DEPTH_TEST);
if(timeFromStart >= 20.0f){
generateStars(posStar, 500, -50, 50, 0, -100, -50, 50);
generateStars(posStarTwo, 500, -50, 50, -100, -200, -50, 50);
generateStars(posStarTree, 500, -50, 50, -200, -300, -50, 50);
startAnim = std::chrono::system_clock::now();
gl4duwDisplayFunc(dessinAll);
}
}
//Static de dessin3D
static float camePos = 0.f;
std::chrono::time_point<std::chrono::system_clock> lastClear;
static int modePlus = 0.0f;
/**
* Fonction qui dessine la forme precedemment déssiné dans dessin mais en 3D,
* avec un fond texturé en 3D et des effets sur la forme en fonction des fréquence de la musique.
* Si un temps total d'animation est atteint, passe a dessinTransition, sinon revien à dessin et genere une nouvelle forme 2D.
**/
static void dessin3D(void){
//Calculs de temps
now = std::chrono::system_clock::now();
std::chrono::duration<float, std::ratio<1,1>> delta = now - last;
last = now;
float elapsedTime(delta.count());
float timeFromStart(std::chrono::duration<float, std::ratio<1,1>>(now - startAnim).count());
float timeFromStartProg(std::chrono::duration<double, std::ratio<1,1>>(std::chrono::system_clock::now() - startProg).count());
glUseProgram(_pId);
glUniform1f(glGetUniformLocation(_pId, "time"), timeFromStartProg);
glUniform1f(glGetUniformLocation(_pId, "mode"), modePlus%7);
//Clear color
Sint16 tempo = _hauteurs[2];
//Constante en fonction des basses
if(tempo > 40){
//Couleur du clear
clearColor[0] = colors[0];
clearColor[1] = colors[1];
clearColor[2] = colors[2];
//Couleur de la lumière ambient
ambient[0] = colors[0];
ambient[1] = colors[1];
ambient[2] = colors[2];
//Transparence de la piece centrale
transpa = 0.75f;
}
float toAdd(elapsedTime * 0.9f);
for(size_t i(0); i < 3; ++i){
clearColor[i] += toAdd;
if(clearColor[i] > 1.0f) clearColor[i] = 1.0f;
ambient[i] -= toAdd;
if(ambient[i] < 0.1f) ambient[i] = 0.1f;
}
transpa -= elapsedTime * 0.75f;
if(transpa < 0) transpa = 0.0f;
//Lumière
//glUniform3f(glGetUniformLocation(_pId, "light.direction"), -1.f, 0.f, -1.f);
glUniform3fv(glGetUniformLocation(_pId, "light.ambient"), 1, &ambient[0]);
glUniform3f(glGetUniformLocation(_pId, "light.specular"), 0.5f, 0.5f, 0.5f);
glUniform3f(glGetUniformLocation(_pId, "light.diffuse"), 1.f, 1.f, 1.f);
//Attenuation
glUniform1f(glGetUniformLocation(_pId, "light.constant"), 1.0f);
glUniform1f(glGetUniformLocation(_pId, "light.linear"), 0.09f);
glUniform1f(glGetUniformLocation(_pId, "light.quadratic"), 0.032f);
//Position de la lumiere constante
glUniform3f(glGetUniformLocation(_pId, "light.position"), 0, 0, 1);
//Clear
glClearColor(clearColor[0], clearColor[1], clearColor[2], 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//Uutilisation des shaders
glUseProgram(_pId);
//CALCUL POUR LES DEPLACEMENT
//Scale de la forme
tempo = _hauteurs[2];
if(tempo > 0 && hight < (0.5*sqrt(tempo)*(0.5*0.5)*16)){
accele = sqrt(tempo);
}
accele -= elapsedTime * 30.f;
hight = 0.5*accele*(0.5*0.5)+hight;
if(hight <= 0.5) hight = 0;
if(hight == 0) accele = 0;
//Rotation de la forme
tempo = _hauteurs[32];
if(tempo > 0 && accele2 < (0.5*tempo/3*(0.5*0.5)*16)){
accele2 = tempo/3;
}
accele2 -= elapsedTime * 0.75f;
if(accele2 <= 0) accele2 = 0;
angle += 0.5*accele2*(0.5*0.5);
//FIN CALCULS
//Camera
camePos += elapsedTime * 30.f;
float radius = 10.0f;
float camX = sin((angle + camePos)/50.f) * radius;
float camZ = cos((angle + camePos)/50.f) * radius;
glm::mat4 view(1.0f);
glm::vec3 viewPos(camX, 0.0, camZ);
view = glm::lookAt(viewPos, glm::vec3(0.0, 0.0, 0.0), glm::vec3(0.0, 1.0, 0.0));
glUniformMatrix4fv(glGetUniformLocation(_pId, "view"), 1, GL_FALSE, &view[0][0]);
glUniform3fv(glGetUniformLocation(_pId, "viewPos"), 1, &viewPos[0]);
//SKY
glDepthMask(GL_FALSE);
glUseProgram(_pidSky);
glm::mat4 projection = glm::perspective(glm::radians(hight*2.5f + 45.f), (float)width_f / (float)height_f, 0.1f, 50.0f);
glUniformMatrix4fv(glGetUniformLocation(_pidSky, "projection"), 1, GL_FALSE, &projection[0][0]);
glm::mat4 viewNoTranslate = glm::mat4(glm::mat3(view));
glUniformMatrix4fv(glGetUniformLocation(_pidSky, "view"), 1, GL_FALSE, &viewNoTranslate[0][0]);
glBindVertexArray(skyVAO);
glBindTexture(GL_TEXTURE_CUBE_MAP, cubemapTexture);
glDrawArrays(GL_TRIANGLES, 0, 36);
glDepthMask(GL_TRUE);
//FIN SKY
glUseProgram(_pId);
//On active le VAO de notre forme
glBindVertexArray(VAO);
//Matrice de model
gl4duBindMatrix("modelViewMatrix");
gl4duLoadIdentityf();
gl4duRotatef(-angle, 1, 1, 0);
gl4duPushMatrix();
gl4duScalef(hight/15.f + 1.f, hight/15.f + 1.f, hight/15.f + 1.f);
gl4duSendMatrices();
gl4duPopMatrix();
//gl4duRotatef(180 * sin(noStop/100.f), 0, 1, 0);
glUniform4fv(glGetUniformLocation(_pId, "couleur"), 1, cyan);
glUniform1f(glGetUniformLocation(_pId, "transpa"), 1.f);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glDrawArrays(GL_TRIANGLES, 0, 36);
glUniform1f(glGetUniformLocation(_pId, "transpa"), transpa);
//A changer ?
//gl4duScalef(1.0f/(hight/30.f + 0.25f), 1.0f/(hight/30.f + 0.25f), 1.0f/(hight/30.f + 0.25f));
gl4duScalef((sqrt(hight/30.0f) + 1.0f), (sqrt(hight/30.0f) + 1.0f), (sqrt(hight/30.0f) + 1.0f));
gl4duSendMatrices();
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glDrawArrays(GL_TRIANGLES, 0, 36);
if(timeFromStart >= 3.f){
transpa = 0.f;
newPoint(p1, p2, p3, p4);
pourcentActual = 0;
pourcent = std::array<float, 4>();
pourcentAuto = std::array<bool, 4>();
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
startAnim = std::chrono::system_clock::now();
gl4duwDisplayFunc(dessin);
if(timeFromStartProg >= 82.f){
clearColor[0] = 0.0f;
clearColor[1] = 0.0f;
clearColor[2] = 0.0f;
startAnim = std::chrono::system_clock::now();
gl4duwDisplayFunc(dessinTransition);
}
}
}
float lastStrongest = 1.0f;
/**
* Boucle graphique qui dessine une forme 2D de facon procedurale
* et passe à la fonction dessin3D une fois le dessin complet
**/
static void dessin(void) {
//Calculs de temps
now = std::chrono::system_clock::now();
std::chrono::duration<float, std::ratio<1,1>> delta = now - last;
last = now;
float elapsedTime(delta.count());
//Calcul
Sint16 tempo = _hauteurs[2];
if(tempo > 0 && hight < (0.5*sqrt(tempo)*(0.5*0.5)*16)){
accele = sqrt(tempo);
}
accele -= 0.5;
hight = 0.5*accele*(0.5*0.5)+hight;
if(hight <= 0.5) hight = 0;
if(hight == 0) accele = 0;
for(size_t i(0); i < 3; ++i){
clearColor[i] -= 0.05f;
if(clearColor[i] < 0) clearColor[i] = 0.0f;
}
//Clear
glClearColor(clearColor[0], clearColor[1], clearColor[2], 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
gl4dpClearScreenWith(RGB(255*clearColor[0], 255*clearColor[1], 255*clearColor[2]));
tempo = _hauteurs[2];
lastStrongest = hight/1000.0f + elapsedTime * 1.8f;
if(tempo > 40){
if(pourcent[pourcentActual] == 0.f){
pourcentAuto[pourcentActual] = true;
}
}
SlowCube myCube(p1, p2, p3, p4);
gl4dpSetColor(RGB(50, 255, 255));
growPourcent(lastStrongest);
for(size_t i(0); i < 4; ++i){
std::vector<Point> const& tempo(myCube.getSide(i));
for(size_t j(0), maxSize(tempo.size()*pourcent[i]); j < maxSize; ++j){
gl4dpPutPixel(tempo[j].x, tempo[j].y);
}
}
if(pourcent[3] == 1.f){
//On genere le cube en fonction des nouveaux points...
generateCube(p1, p2, p3, p4, maForme);
//On genere Array et buffer
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
//Et on bind le buffer sur ce nouvel array
bindNewBuffer(maForme, VAO, VBO);
allFormes.push_back(VAO);
//On stoque le VBO seulement pour pouvoir le supprimer plus tard
allFormesVBO.push_back(VBO);
//On remet tout à 0
accele = 0;
accele2 = 0;
hight = 0;
angle = 0;
//On remet à 0 le timer de debut d'animation a chaque changement d'animation
startAnim = std::chrono::system_clock::now();
//On remet les static de dessin3D a 0
camePos = 0.f;
mode = rand()%7;
++modePlus;
gl4duwDisplayFunc(dessin3D);
}
gl4dpUpdateScreen(NULL);
}
///Fonction d'initialisation
static void init(){
//Partie musicale
_in4fftw = (fftw_complex*) fftw_malloc(ECHANTILLONS * sizeof *_in4fftw);
memset(_in4fftw, 0, ECHANTILLONS * sizeof *_in4fftw);
assert(_in4fftw);
_out4fftw = (fftw_complex*) fftw_malloc(ECHANTILLONS * sizeof *_out4fftw);
assert(_out4fftw);
_plan4fftw = fftw_plan_dft_1d(ECHANTILLONS, _in4fftw, _out4fftw, FFTW_FORWARD, FFTW_ESTIMATE);
assert(_plan4fftw);
//Partie GL
glEnable(GL_DEPTH_TEST);
//Transparence
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glClearColor(0.f, 0.f, 0.f, 0.0f);
//Charge texture cube
cubemapTexture = loadCubemap(faces);
//Charge texture space
textureSpace = loadTexture(fileSpace);
//On genere les frameBuffer
glGenFramebuffers(1, &fbo1);
glGenFramebuffers(1, &fbo2);
//Pour le premier frame buffer
//On bind
glBindFramebuffer(GL_FRAMEBUFFER, fbo1);
//On genere la texture
texColBuff = genTexture();
//On bind le (texture) tempon de couleur sur le framebuffer
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texColBuff, 0);
rbo = genDepthStencil();
//On bind le render buffer pour le depth et stencil
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbo);
//On verifie si c'est good
if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
std::cout << "Erreur framebuffer 1 incomplet" << std::endl;
//Pour le deuxieme frame buffer
glBindFramebuffer(GL_FRAMEBUFFER, fbo2);
texColBuff2 = genTexture();
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texColBuff2, 0);
if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
std::cout << "Erreur framebuffer 2 incomplet" << std::endl;
glBindFramebuffer(GL_FRAMEBUFFER, 0);
//Sky
//On genere Array et buffer
glGenVertexArrays(1, &skyVAO);
glGenBuffers(1, &skyVBO);
glBindVertexArray(skyVAO);
glBindBuffer(GL_ARRAY_BUFFER, skyVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(skyboxVertices), skyboxVertices, GL_STATIC_DRAW);
//attribue de position
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*) 0);
glEnableVertexAttribArray(0);
//FIN SKY
//VAO ET VBO SPACE
//On genere Array et buffer
glGenVertexArrays(1, &spaceVAO);
glGenBuffers(1, &spaceVBO);
glBindVertexArray(spaceVAO);
glBindBuffer(GL_ARRAY_BUFFER, spaceVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(spaceVertices), spaceVertices, GL_STATIC_DRAW);
//Position attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
//Vecteur Texture
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3*sizeof(float)));
glEnableVertexAttribArray(1);
glBindVertexArray(0);
//Fin Space
//Charge les shader
_pId = gl4duCreateProgram("<vs>shaders/vertex.vs", "<fs>shaders/fragment.fs", NULL);
_pidSky = gl4duCreateProgram("<vs>shaders/skybox.vs", "<fs>shaders/skybox.fs", NULL);
_pidSpace = gl4duCreateProgram("<vs>shaders/space.vs", "<fs>shaders/space.fs", NULL);
_pidSpaceMonte = gl4duCreateProgram("<vs>shaders/spaceMonte.vs", "<fs>shaders/spaceMonte.fs", NULL);
_pidStars = gl4duCreateProgram("<vs>shaders/stars.vs", "<fs>shaders/stars.fs", NULL);
_blurV = gl4duCreateProgram("<vs>shaders/prod/after.vs", "<fs>shaders/prod/blursVert.fs", NULL);
_blurH = gl4duCreateProgram("<vs>shaders/prod/after.vs", "<fs>shaders/prod/blursHori.fs", NULL);
_postProd = gl4duCreateProgram("<vs>shaders/prod/after.vs", "<fs>shaders/prod/after.fs", NULL);
_particuleShad = gl4duCreateProgram("<vs>shaders/particule/particle.vs", "<fs>shaders/particule/particle.fs", NULL);
_creditShad = gl4duCreateProgram("<vs>shaders/credit/credits.vs", "<fs>shaders/credit/credits.fs", NULL);
_voronoiShad = gl4duCreateProgram("<vs>shaders/voronoi.vs", "<fs>shaders/voronoi.fs", NULL);
_pidSphere = gl4duCreateProgram("<vs>shaders/spaceSphere.vs", "<fs>shaders/spaceSphere.fs", NULL);
_pidBlack = gl4duCreateProgram("<vs>shaders/transi/black.vs", "<fs>shaders/transi/black.fs", NULL);
_godLight = gl4duCreateProgram("<vs>shaders/prod/god.vs", "<fs>shaders/prod/god.fs", NULL);
_godLight2 = gl4duCreateProgram("<vs>shaders/prod/god2.vs", "<fs>shaders/prod/god2.fs", NULL);
mesParticules.init("texture/atlas.png", _particuleShad, 10000);
//Mobiles
textureMobiles = gen1DTexture();
mesMobiles.init(30, width_f, height_f);
//Generation matrice gl4d
gl4duGenMatrix(GL_FLOAT, "modelViewMatrix");
//Objet GL4D
sphere_ = gl4dgGenSpheref(30, 30);
glViewport(0, 0, width_f, height_f);
glUseProgram(_pId);
glm::mat4 projection = glm::ortho(-1.0f, 1.f, -1.0f, 1.f, -50.f, 50.f);
glUniformMatrix4fv(glGetUniformLocation(_pId, "projection"), 1, GL_FALSE, &projection[0][0]);
glUseProgram(_pidSky);
glUniformMatrix4fv(glGetUniformLocation(_pidSky, "projection"), 1, GL_FALSE, &projection[0][0]);
//InitiAudio
initAudio("audio/Arsonist - Discovery — No Copyright Music.ogg");
//Init textes
initText(&_textTexId,
"Développé par\n"
"Guillaume Magniadas\n\n\n"
"Musique :\n"
"Arsonist - Discovery (No Copyright)\n\n\n"
"Merci d'avoir regardé !");
//On démarre le chrono de départ
startProg = std::chrono::system_clock::now();
last = std::chrono::system_clock::now();
lastClear = std::chrono::system_clock::now();
}
///Fonction d'initialisation de l'audio reprises des samples GL4D
static void initAudio(const char * filename) {
//Car apple = chiant
#if defined(__APPLE__)
int mult = 1;
#else
int mult = 2;
#endif
int mixFlags = MIX_INIT_MP3, res;
res = Mix_Init(mixFlags);
if( (res & mixFlags) != mixFlags ) {
fprintf(stderr, "Mix_Init: Erreur lors de l'initialisation de la bibliotheque SDL_Mixer\n");
fprintf(stderr, "Mix_Init: %s\n", Mix_GetError());
//exit(3); commenté car ne réagit correctement sur toutes les architectures
}
if(Mix_OpenAudio(44100, AUDIO_S16LSB, 1, mult * ECHANTILLONS) < 0) exit(4);
if(!(_mmusic = Mix_LoadMUS(filename))) {
fprintf(stderr, "Erreur lors du Mix_LoadMUS: %s\n", Mix_GetError());
exit(5);
}
Mix_SetPostMix(mixCallback, NULL);
if(!Mix_PlayingMusic()) Mix_PlayMusic(_mmusic, 1);
}
///Fonction de traitement de l'audio reprise des samples GL4D
static void mixCallback(void *udata, Uint8 *stream, int len) {
if(_plan4fftw) {
int i, j, l = MIN(len >> 1, ECHANTILLONS);
Sint16 *d = (Sint16 *)stream;
for(i = 0; i < l; i++)
_in4fftw[i][0] = d[i] / ((1 << 15) - 1.0);
fftw_execute(_plan4fftw);
for(i = 0; i < l >> 2; i++) {
_hauteurs[4 * i] = (int)(sqrt(_out4fftw[i][0] * _out4fftw[i][0] + _out4fftw[i][1] * _out4fftw[i][1]) * exp(2.0 * i / (double)(l / 4.0)));
for(j = 1; j < 4; j++)
_hauteurs[4 * i + j] = MIN(_hauteurs[4 * i], 255);
}
}
}
//Fonction generation de texte via fonts reprise des samples GL4D
static void initText(GLuint * ptId, const char * text){
static int firstTime = 1;
SDL_Color c = {255, 255, 0, 255};
SDL_Surface * d, * s;
TTF_Font * font = NULL;
if(firstTime) {
/* initialisation de la bibliothèque SDL2 ttf */
if(TTF_Init() == -1) {
fprintf(stderr, "TTF_Init: %s\n", TTF_GetError());
exit(2);
}
firstTime = 0;
}
if(*ptId == 0) {
/* initialisation de la texture côté OpenGL */
glGenTextures(1, ptId);
glBindTexture(GL_TEXTURE_2D, *ptId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}
/* chargement de la font */
if( !(font = TTF_OpenFont("font/Obesum-Caps-FFP.ttf", 128)) ) {
fprintf(stderr, "TTF_OpenFont: %s\n", TTF_GetError());
return;
}
/* création d'une surface SDL avec le texte */
d = TTF_RenderUTF8_Blended_Wrapped(font, text, c, 2048);
if(d == NULL) {
TTF_CloseFont(font);
fprintf(stderr, "Erreur lors du TTF_RenderText\n");
return;
}
/* copie de la surface SDL vers une seconde aux spécifications qui correspondent au format OpenGL */
s = SDL_CreateRGBSurface(0, d->w, d->h, 32, R_MASK, G_MASK, B_MASK, A_MASK);
assert(s);
SDL_BlitSurface(d, NULL, s, NULL);
SDL_FreeSurface(d);
/* transfert vers la texture OpenGL */
glBindTexture(GL_TEXTURE_2D, *ptId);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, s->w, s->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, s->pixels);
fprintf(stderr, "Dimensions de la texture : %d %d\n", s->w, s->h);
SDL_FreeSurface(s);
TTF_CloseFont(font);
glBindTexture(GL_TEXTURE_2D, 0);
}
int main(int argc, char ** argv) {
int seed(time(NULL));
std::cout << "Seed : " << seed << std::endl;
srand(seed);
//Des tailles qui vont bien
//1024 768
//1200 924
//1280 1024
//1280 800
//1366 768
if(!gl4duwCreateWindow(0, NULL, /* args du programme */
"Demo - Guillaume Magniadas", /* titre */
0, 0, 1366, 768, /* x,y, largeur, hauteur */
GL4DW_FULLSCREEN | GL4DW_SHOWN) /* état visible */) {
return 1;
}
GLint vp[4];
glGetIntegerv(GL_VIEWPORT, vp);
width_f = vp[2];
height_f = vp[3];
//std::cout << "WIDTH : " << width_f << " HEIGHT : " << height_f << std::endl;
//Limiter a 60fps
SDL_GL_SetSwapInterval(1);
gl4dpInitScreenWithDimensions(width_f, height_f);
init();
atexit(quitte);
newPoint(p1, p2, p3, p4);
generateCube(p1, p2, p3, p4, maForme);
bindNewBuffer(maForme, VAO, VBO);
startAnim = std::chrono::system_clock::now();
generateStars(posStar, 500, -50, 50, -50, 50, -200, -100);
generateStars(posStarTwo, 500, -50, 50, -50, 50, -100, 0);
generateStars(posStarTree, 500, -50, 50, -50, 50, 0, 100);
/*
Pour commencer avec une autre animation il suffi de commenter
celle avec dessin et decommenter celle que vous voulez
*/
gl4duwDisplayFunc(dessinAllStars);
//gl4duwDisplayFunc(dessinTransition);
//gl4duwDisplayFunc(dessinVoronoi);
//gl4duwDisplayFunc(dessin);
gl4duwMainLoop();
/*
Pour lancer dessinAll ou dessinTransition, decommentez ces lignes en commentant celles au dessus
*/
/*generateStars(posStar, 500, -50, 50, 0, -100, -50, 50);
generateStars(posStarTwo, 500, -50, 50, -100, -200, -50, 50);
generateStars(posStarTree, 500, -50, 50, -200, -300, -50, 50);
for(int i = 0; i < 15; ++i){
newPoint(p1, p2, p3, p4);
//On genere le cube en fonction des nouveaux points...
generateCube(p1, p2, p3, p4, maForme);
//On genere Array et buffer
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
//Et on bind le buffer sur ce nouvel array
bindNewBuffer(maForme, VAO, VBO);
allFormes.push_back(VAO);
}
//Choisir une des deux
gl4duwDisplayFunc(dessinTransition);
//gl4duwDisplayFunc(dessinAll);
gl4duwMainLoop();*/
return 0;
}
| 27.610858 | 157 | 0.632685 | [
"render",
"vector",
"model",
"3d"
] |
7cf68c4bf2a50c7b40c11b1c52fbb7c9e8750f30 | 2,355 | hpp | C++ | LinaPhysics/include/Core/PhysicsCommon.hpp | moonantonio/LinaEngine | fe5a91a85c64dd0719656eb38e2fb37037bacfc1 | [
"MIT"
] | 10 | 2018-09-30T22:29:27.000Z | 2018-10-08T14:04:42.000Z | LinaPhysics/include/Core/PhysicsCommon.hpp | moonantonio/LinaEngine | fe5a91a85c64dd0719656eb38e2fb37037bacfc1 | [
"MIT"
] | 15 | 2018-10-02T22:14:17.000Z | 2018-10-12T08:01:36.000Z | LinaPhysics/include/Core/PhysicsCommon.hpp | moonantonio/LinaEngine | fe5a91a85c64dd0719656eb38e2fb37037bacfc1 | [
"MIT"
] | 1 | 2018-09-30T16:37:10.000Z | 2018-09-30T16:37:10.000Z | /*
This file is a part of: Lina Engine
https://github.com/inanevin/LinaEngine
Author: Inan Evin
http://www.inanevin.com
Copyright (c) [2018-2020] [Inan Evin]
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.
*/
/*
Class: PhysicsCommon
Timestamp: 12/20/2021 1:05:42 PM
*/
#pragma once
#ifndef PhysicsCommon_HPP
#define PhysicsCommon_HPP
// Headers here.
#include "Math/Quaternion.hpp"
#include "Math/Vector.hpp"
#ifdef LINA_PHYSICS_BULLET
#include "btBulletDynamicsCommon.h"
#elif LINA_PHYSICS_PHYSX
#include "PxPhysicsAPI.h"
#endif
namespace Lina::Physics
{
#ifdef LINA_PHYSICS_BULLET
extern btVector3 ToBtVector(const Vector3& v);
extern btQuaternion ToBtQuat(const Quaternion& q);
extern Vector3 ToLinaVector(const btVector3& v);
extern Quaternion ToLinaQuat(const btQuaternion& q);
#endif
#ifdef LINA_PHYSICS_PHYSX
extern physx::PxVec2 ToPxVector2(const Vector2& v);
extern physx::PxVec3 ToPxVector3(const Vector3& v);
extern physx::PxVec4 ToPxVector4(const Vector4& v);
extern physx::PxQuat ToPxQuat(const Quaternion& q);
extern Vector2 ToLinaVector2(const physx::PxVec2& v);
extern Vector3 ToLinaVector3(const physx::PxVec3& v);
extern Vector4 ToLinaVector4(const physx::PxVec4& v);
extern Quaternion ToLinaQuat(const physx::PxQuat& q);
#endif
} // namespace Lina::Physics
#endif
| 30.192308 | 78 | 0.763907 | [
"vector"
] |
7cf9d671896e053c4560217c938595ba0eeaf027 | 6,239 | hpp | C++ | include/Roadmap.hpp | TobiasLundby/ROVI2 | d2666abf12196930074db910488e33d6fc43f7cc | [
"BSD-3-Clause"
] | 1 | 2019-01-07T14:33:00.000Z | 2019-01-07T14:33:00.000Z | include/Roadmap.hpp | TobiasLundby/ROVI2 | d2666abf12196930074db910488e33d6fc43f7cc | [
"BSD-3-Clause"
] | 1 | 2017-05-14T20:28:44.000Z | 2017-05-18T07:50:48.000Z | include/Roadmap.hpp | TobiasLundby/ROVI2 | d2666abf12196930074db910488e33d6fc43f7cc | [
"BSD-3-Clause"
] | null | null | null | #ifndef ROADMAP_ROS
#define ROADMAP_ROS
#include "ros/ros.h"
#include <rw/models/WorkCell.hpp>
#include <rw/kinematics/State.hpp>
#include <rw/models/Device.hpp>
#include <rw/rw.hpp>
#include <rw/math/Q.hpp>
#include "rovi2/Q.h"
#include "rovi2/Plan.h"
#include "rovi2/path.h"
#include "rovi2/Conf.h"
//#include <rw/math/QMetric.hpp>
#include <rwlibs/proximitystrategies/ProximityStrategyPQP.hpp>
#include <rw/pathplanning/PlannerConstraint.hpp>
#include <rw/pathplanning/QConstraint.hpp>
#include <rw/pathplanning/QEdgeConstraint.hpp>
#include <rw/proximity/CollisionDetector.hpp>
#include <rw/proximity/CollisionStrategy.hpp>
#include <rw/common.hpp>
#include <rw/pathplanning/QSampler.hpp>
#include <rwlibs/algorithms/kdtree/KDTreeQ.hpp>
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
//#include <boost/thread/lock_guard.hpp>
#include <boost/bind.hpp>
#define SINGLE_THREAD false
class Astar;
class Node
{
public:
Node(rw::math::Q p, int nodeid){ q_val = p; edges = std::vector<Node*>(0); edge_cost = std::vector<double>(0); nodenum = nodeid;}
~Node(){}
rw::math::Q q_val;
std::vector<Node*> edges;
std::vector<double> edge_cost;
bool connected_component = false;
bool usable = false;
int nodenum;
unsigned int astar_run = 0;
double g_score;
double f_score;
bool closed;
bool open;
Node* cameFrom;
};
class Roadmap
{
public:
Roadmap(ros::NodeHandle h, int size, double resolution, double connection_radius, double max_density);
Roadmap(ros::NodeHandle h,std::string path);
virtual ~Roadmap();
bool create_roadmap();
void save_roadmap(std::string path);
rw::math::Q toRw(const rovi2::Q& q);
rovi2::Q toRos(const rw::math::Q& q);
// ROS topics
// We probably need to implement the graph search in here, givin the transfer time for ros topics will slow it down
void find_path(rw::math::Q init, rw::math::Q goal);
// If the distance is small enough, do not start a graph search, insted make graping using RRT (seperate ROS topic!)
// Always check with this one before calling find_path
void distance_to_goal(rw::math::Q init, rw::math::Q goal);
void connectedComponents();
bool start_plan(rovi2::Plan::Request & request, rovi2::Plan::Response &res);
bool check_plan(rovi2::Conf::Request & request, rovi2::Conf::Response &res);
protected:
void initWorkCell();
void initRobworkStuff();
// Find connection node for init and goal from a Q position
Node* find_connection_node(rw::math::Q);
bool inCollision(Node *n);
bool inCollision(Node *a, Node *b);
void threadAdd1(Node* A, Node* B);
void threadAdd2(Node* A, Node* B);
void threadAdd3(Node* A, Node* B);
void threadAdd4(Node* A, Node* B);
bool distanceTooClose(rw::math::Q a);
// These are not checked for collision!
void addNode(rw::math::Q n, int nodeid, bool c, bool u);
void addNode(rw::math::Q n, int nodeid);
void addEdges(int nodeidA, int nodeidB);
// Add a new samples node
bool addNode();
std::vector<Node*> nodesInRange(Node *a);
int nodesInRange(rw::math::Q a);
void addEdges(std::vector<Node*> n, Node *a, bool check, std::vector<double> _cost = std::vector<double>(0));
void connectGraph();
int nonConnectedNodes();
void load_roadmap(std::string path);
static bool Sorting(const std::vector<Node*> i, const std::vector<Node*> j) { return i.size() > j.size(); }
public:
rw::models::WorkCell::Ptr _workcell1 = nullptr;
rw::models::WorkCell::Ptr _workcell2 = nullptr;
rw::models::WorkCell::Ptr _workcell3 = nullptr;
rw::models::WorkCell::Ptr _workcell4 = nullptr;
rw::models::WorkCell::Ptr _workcellAstar = nullptr;
rw::kinematics::State _state1;
rw::kinematics::State _state2;
rw::kinematics::State _state3;
rw::kinematics::State _state4;
rw::kinematics::State _stateAstar;
rw::models::Device::Ptr _device1;
rw::models::Device::Ptr _device2;
rw::models::Device::Ptr _device3;
rw::models::Device::Ptr _device4;
rw::models::Device::Ptr _deviceAstar;
rw::proximity::CollisionDetector::Ptr _detector1;
rw::proximity::CollisionDetector::Ptr _detector2;
rw::proximity::CollisionDetector::Ptr _detector3;
rw::proximity::CollisionDetector::Ptr _detector4;
rw::proximity::CollisionDetector::Ptr _detectorAstar;
rw::common::Ptr<rw::pathplanning::QConstraint> _constraint1;
rw::common::Ptr<rw::pathplanning::QConstraint> _constraint2;
rw::common::Ptr<rw::pathplanning::QConstraint> _constraint3;
rw::common::Ptr<rw::pathplanning::QConstraint> _constraint4;
rw::common::Ptr<rw::pathplanning::QConstraint> _constraintAstar;
rw::common::Ptr<rw::pathplanning::QEdgeConstraint> _edgeConstraint1;
rw::common::Ptr<rw::pathplanning::QEdgeConstraint> _edgeConstraint2;
rw::common::Ptr<rw::pathplanning::QEdgeConstraint> _edgeConstraint3;
rw::common::Ptr<rw::pathplanning::QEdgeConstraint> _edgeConstraint4;
rw::common::Ptr<rw::pathplanning::QEdgeConstraint> _edgeConstraintAstar;
rw::proximity::CollisionStrategy::Ptr _strategy1;
rw::proximity::CollisionStrategy::Ptr _strategy2;
rw::proximity::CollisionStrategy::Ptr _strategy3;
rw::proximity::CollisionStrategy::Ptr _strategy4;
rw::proximity::CollisionStrategy::Ptr _strategyAstar;
rw::pathplanning::QSampler::Ptr _sampler;
rw::math::Q _metricWeights;
rw::math::QMetric::Ptr _metric = nullptr;
rw::math::Q _radi;
rw::math::Q _radi2;
// KdTree for nearest neighbor search.
rwlibs::algorithms::KDTreeQ<Node*>::Ptr _kdtree;
std::list<const rwlibs::algorithms::KDTreeQ<Node*>::KDNode*> _kdnodesSearchResult;
// The graph is just a container for the node pointers.
std::vector<Node*> *_graph;
double _resolution;
double _size;
double _actualSize = 0;
double _connectedEdgePairs = 0;
double _connection_radius;
double _max_density;
double _usable_nodes;
double _largestConnected = 0;
int t1Usage = 0;
int t2Usage = 0;
int t3Usage = 0;
int t4Usage = 0;
boost::mutex push_lock;
//boost::mutex astar_lock;
//bool astar_running = false;
Astar *planner = nullptr;
boost::thread* astar_thread = nullptr;
std::vector<boost::thread*> threads;
ros::ServiceServer service_start_plan;
ros::ServiceServer service_next_conf;
ros::Publisher path_publisher;
ros::NodeHandle _nodehandle;
};
#endif
| 27.606195 | 131 | 0.729604 | [
"vector"
] |
cfb3272cdd9294edf782382362a0a08084e877ff | 3,458 | cpp | C++ | cpp_concepts/code/multi_threading_v1.cpp | filippo82/cpp_programming | 56e8046aadbebf1f8a883f990c31300e56522011 | [
"Apache-2.0"
] | null | null | null | cpp_concepts/code/multi_threading_v1.cpp | filippo82/cpp_programming | 56e8046aadbebf1f8a883f990c31300e56522011 | [
"Apache-2.0"
] | null | null | null | cpp_concepts/code/multi_threading_v1.cpp | filippo82/cpp_programming | 56e8046aadbebf1f8a883f990c31300e56522011 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <vector>
#include <thread>
#include <chrono>
// using namespace std;
// Function
void accumulator_function2(const std::vector<int> &v, unsigned long long &acm,
unsigned int beginIndex, unsigned int endIndex)
{
acm = 0;
for (unsigned int i = beginIndex; i < endIndex; ++i)
{
acm += v[i];
}
};
// Functor
class CAccumulatorFunctor3
{
public:
void operator()(const std::vector<int> &v,
unsigned int beginIndex, unsigned int endIndex)
{
_acm = 0;
for (unsigned int i = beginIndex; i < endIndex; ++i)
{
_acm += v[i];
}
}
unsigned long long _acm;
};
int main(int argc, char * argv[])
{
unsigned int c = std::thread::hardware_concurrency();
std::cout << "Number of available cores: " << c << std::endl;
std::vector<int> v;
v.resize(1000000000, 2);
std::size_t pos;
int choice = std::stoi(argv[1], &pos);
// Record start time
auto start = std::chrono::high_resolution_clock::now();
switch (choice)
{
case 0:
{
// Serial
unsigned long long acm;
accumulator_function2(v, acm, 0, v.size());
std::cout << "The sum of all elements is " << acm << std::endl;
break;
}
case 1:
{
// Function
unsigned long long acm1 = 0;
unsigned long long acm2 = 0;
std::thread t1(accumulator_function2, std::ref(v), std::ref(acm1), 0, v.size() / 2);
std::thread t2(accumulator_function2, std::ref(v), std::ref(acm2), v.size() / 2, v.size());
t1.join();
t2.join();
std::cout << "The sum of all elements is " << acm1 + acm2 << std::endl;
break;
}
case 2:
{
// Functor
CAccumulatorFunctor3 accumulator1 = CAccumulatorFunctor3();
CAccumulatorFunctor3 accumulator2 = CAccumulatorFunctor3();
std::thread t1(std::ref(accumulator1), std::ref(v), 0, v.size() / 2);
std::thread t2(std::ref(accumulator2), std::ref(v), v.size() / 2, v.size());
t1.join();
t2.join();
std::cout << "The sum of all elements is " << accumulator1._acm + accumulator2._acm << std::endl;
break;
}
case 3:
{
// Lambda function
unsigned long long acm1 = 0;
unsigned long long acm2 = 0;
// Two ways for using lambda functions
// First case: parameters are passed using std::ref()
std::thread t1([](std::vector<int> &v, unsigned long long &acm){
for (unsigned int i = 0; i < v.size() / 2; ++i)
{
acm += v[i];
}
}, std::ref(v), std::ref(acm1));
// Second case: parameters are captured
std::thread t2([&acm2, &v](){
for (unsigned int i = v.size() / 2; i < v.size(); ++i)
{
acm2 += v[i];
}
});
t1.join();
t2.join();
std::cout << "The sum of all elements is " << acm1 + acm2 << std::endl;
break;
}
}
// std::thread t1([&acm1, &v](){
// for (unsigned int i = 0; i < v.size() / 2; ++i)
// {
// acm1 += v[i];
// }
// });
// std::thread t2([&acm2, &v](){
// for (unsigned int i = v.size() / 2; i < v.size(); ++i)
// {
// acm2 += v[i];
// }
// });
// Record end time
auto finish = std::chrono::high_resolution_clock::now();
// Duration
std::chrono::duration<double> elapsed = finish - start;
std::cout << "Elapsed time: " << elapsed.count() << " s" << std::endl;
return 0;
}
| 26.6 | 103 | 0.539618 | [
"vector"
] |
cfb3a87a5bf51c285a618fbc224e26927c68d057 | 8,098 | cpp | C++ | game_2048_v2/Chessboard.cpp | trionfordring/CppGames | b6e5882df55e3ff0a432b8432f0d7063a101f0f4 | [
"Apache-2.0"
] | null | null | null | game_2048_v2/Chessboard.cpp | trionfordring/CppGames | b6e5882df55e3ff0a432b8432f0d7063a101f0f4 | [
"Apache-2.0"
] | null | null | null | game_2048_v2/Chessboard.cpp | trionfordring/CppGames | b6e5882df55e3ff0a432b8432f0d7063a101f0f4 | [
"Apache-2.0"
] | null | null | null | //
// Created by fordring on 2020/5/3.
//
#include "Chessboard.h"
using std::vector;
Chessboard::Chessboard(int width, int height) : board(height, vector<Cell>(width)), maxNum(0) {
}
bool Chessboard::insertPiece(Point point, int num) {
if(isEmpty(point)){
setPiece(point,num);
return true;
}
return false;
}
bool Chessboard::isEmpty(Point point) {
int piece = getPiece(point);
return piece==0;
}
int Chessboard::getHeight() {
return board.size();
}
int Chessboard::getWidth() {
return board[0].size();
}
int Chessboard::getPieceCount() {
int cnt=0;
for(int y=0;y<board.size();y++)
for(int x=0;x<board[0].size();x++){
if(getPiece({x,y})!=0){
cnt++;
}
}
return cnt;
}
int Chessboard::getPiece(Point point) {
if(point.x<getWidth()&&point.x>=0&&point.y<getHeight()&&point.y>=0)
return board[point.y][point.x].num;
else
return -1;
}
int Chessboard::setPiece(Point point, int num) {
int last = getPiece(point);
if(last!=-1){
board[point.y][point.x].num=num;
}
return last;
}
///////////////////
bool Chessboard::merge_UP() {
bool ans = false;
for(int y=1;y<getHeight();y++){
for(int x=0;x<getWidth();x++){
int piece = getPiece({x,y});
if(piece!=0&&piece!=-1){
int i=1,next = getPiece({x,y-i});
for(;next==0;i++,next = getPiece({x,y-i}));
if(next==piece&&board[y-i][x].flag== false){
board[y-i][x].num+=piece;
board[y-i][x].flag= true;
board[y][x].num=0;
ans= true;
}
}
}
}
return ans;
}
bool Chessboard::canSlide_UP() {
for(int y=1;y<getHeight();y++){
for(int x=0;x<getWidth();x++){
int piece = getPiece({x,y});
if(piece!=0&&piece!=-1){
int next = getPiece({x,y-1});
if(next==piece||next==0){
return true;
}
}
}
}
return false;
}
bool Chessboard::land_UP() {
bool ans = false;
for(int y=1;y<getHeight();y++){
for(int x=0;x<getWidth();x++){
board[y][x].flag= false;
int piece = getPiece({x,y});
if(piece!=0&&piece!=-1){
int i=1,next = getPiece({x,y-i});
for(;next==0;i++,next = getPiece({x,y-i}));
if(i>1){
ans = true;
board[y][x].num=0;
board[y-(i-1)][x].num=piece;
}
}
}
}
return ans;
}
bool Chessboard::merge_DOWN() {
bool ans = false;
for(int y=getHeight()-1;y>=0;y--){
for(int x=0;x<getWidth();x++){
int piece = getPiece({x,y});
if(piece!=0&&piece!=-1){
int i=1,next = getPiece({x,y+i});
for(;next==0;i++,next = getPiece({x,y+i}));
if(next==piece&&board[y+i][x].flag== false){
board[y+i][x].num+=piece;
board[y+i][x].flag= true;
board[y][x].num=0;
ans= true;
}
}
}
}
return ans;
}
bool Chessboard::canSlide_DOWN() {
for(int y=getHeight()-1;y>=0;y--){
for(int x=0;x<getWidth();x++){
int piece = getPiece({x,y});
if(piece!=0&&piece!=-1){
int next = getPiece({x,y+1});
if(next==piece||next==0){
return true;
}
}
}
}
return false;
}
bool Chessboard::land_DOWN() {
bool ans = false;
for(int y=getHeight()-1;y>=0;y--){
for(int x=0;x<getWidth();x++){
board[y][x].flag= false;
int piece = getPiece({x,y});
if(piece!=0&&piece!=-1){
int i=1,next = getPiece({x,y+i});
for(;next==0;i++,next = getPiece({x,y+i}));
if(i>1){
ans = true;
board[y][x].num=0;
board[y+(i-1)][x].num=piece;
}
}
}
}
return ans;
}
bool Chessboard::merge_LEFT() {
bool ans = false;
for(int x=0;x<getWidth();x++){
for(int y=0;y<getHeight();y++){
int piece = getPiece({x,y});
if(piece!=0&&piece!=-1){
int i=1,next = getPiece({x-i,y});
for(;next==0;i++,next = getPiece({x-i,y}));
if(next==piece&&board[y][x-i].flag== false){
board[y][x-i].num+=piece;
board[y][x-i].flag= true;
board[y][x].num=0;
ans= true;
}
}
}
}
return ans;
}
bool Chessboard::canSlide_LEFT() {
for(int x=0;x<getWidth();x++){
for(int y=0;y<getHeight();y++){
int piece = getPiece({x,y});
if(piece!=0&&piece!=-1){
int next = getPiece({x-1,y});
if(next==piece&&board[y][x-1].flag== false){
return true;
}
}
}
}
return false;
}
bool Chessboard::land_LEFT() {
bool ans = false;
for(int x=0;x<getWidth();x++){
for(int y=0;y<getHeight();y++){
board[y][x].flag= false;
int piece = getPiece({x,y});
if(piece!=0&&piece!=-1){
int i=1,next = getPiece({x-i,y});
for(;next==0;i++,next = getPiece({x-i,y}));
if(i>1){
ans = true;
board[y][x].num=0;
board[y][x-(i-1)].num=piece;
}
}
}
}
return ans;
}
bool Chessboard::merge_RIGHT() {
bool ans = false;
for(int x=getWidth()-1;x>=0;x--){
for(int y=0;y<getHeight();y++){
int piece = getPiece({x,y});
if(piece!=0&&piece!=-1){
int i=1,next = getPiece({x+i,y});
for(;next==0;i++,next = getPiece({x+i,y}));
if(next==piece&&board[y][x+i].flag== false){
board[y][x+i].num+=piece;
board[y][x+i].flag= true;
board[y][x].num=0;
ans= true;
}
}
}
}
return ans;
}
bool Chessboard::canSlide_RIGHT() {
for(int x=getWidth()-1;x>=0;x--){
for(int y=0;y<getHeight();y++){
int piece = getPiece({x,y});
if(piece!=0&&piece!=-1){
int next = getPiece({x+1,y});
if(next==piece&&board[y][x+1].flag== false){
return true;
}
}
}
}
return false;
}
bool Chessboard::land_RIGHT() {
bool ans = false;
for(int x=getWidth()-1;x>=0;x--){
for(int y=0;y<getHeight();y++){
board[y][x].flag= false;
int piece = getPiece({x,y});
if(piece!=0&&piece!=-1){
int i=1,next = getPiece({x+i,y});
for(;next==0;i++,next = getPiece({x+i,y}));
if(i>1){
ans = true;
board[y][x].num=0;
board[y][x+(i-1)].num=piece;
}
}
}
}
return ans;
}
bool Chessboard::canSlide() {
return canSlide_UP()||canSlide_DOWN()||canSlide_LEFT()||canSlide_RIGHT();
}
bool Chessboard::slide_UP() {
bool ans = merge_UP();
return land_UP()||ans;
}
bool Chessboard::slide_DOWN() {
bool ans = merge_DOWN();
return land_DOWN()||ans;
}
bool Chessboard::slide_LEFT() {
bool ans = merge_LEFT();
return land_LEFT()||ans;
}
bool Chessboard::slide_RIGHT() {
bool ans = merge_RIGHT();
return land_RIGHT()||ans;
}
int Chessboard::getMaxPiece() {
int ans=0;
for(int y=0;y<getHeight();y++){
for(int x=0;x<getWidth();x++){
ans = std::max(ans,getPiece({x,y}));
}
}
return ans;
} | 25.872204 | 95 | 0.431959 | [
"vector"
] |
cfc1cf14746ce3e3585ee61262a24cb5423c98b4 | 4,275 | hpp | C++ | src/Externals/spire/es-render/comp/CommonUniforms.hpp | Haydelj/SCIRun | f7ee04d85349b946224dbff183438663e54b9413 | [
"MIT"
] | 92 | 2015-02-09T22:42:11.000Z | 2022-03-25T09:14:50.000Z | src/Externals/spire/es-render/comp/CommonUniforms.hpp | Haydelj/SCIRun | f7ee04d85349b946224dbff183438663e54b9413 | [
"MIT"
] | 1,618 | 2015-01-05T19:39:13.000Z | 2022-03-27T20:28:45.000Z | src/Externals/spire/es-render/comp/CommonUniforms.hpp | Haydelj/SCIRun | f7ee04d85349b946224dbff183438663e54b9413 | [
"MIT"
] | 64 | 2015-02-20T17:51:23.000Z | 2021-11-19T07:08:08.000Z | /*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2020 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#ifndef SPIRE_RENDER_COMPONENT_COMMON_UNIFORMS_HPP
#define SPIRE_RENDER_COMPONENT_COMMON_UNIFORMS_HPP
#include <es-log/trace-log.h>
#include <gl-platform/GLPlatform.hpp>
#include <es-cereal/ComponentSerialize.hpp>
#include <es-general/comp/StaticCamera.hpp>
#include <es-general/comp/CameraSelect.hpp>
#include <spire/scishare.h>
namespace ren {
struct SCISHARE CommonUniforms
{
// -- Data --
static const int MaxNumCommonUniforms = 5;
enum COMMON_UNIFORMS
{
U_MODEL_VIEW_PROJECTION, // uModelViewProjection - Object -> World -> View -> Projection
U_MODEL_VIEW, // uModelView - Object -> World -> View
U_MODEL, // uModel - Object -> World transform
U_VIEW_PROJECTION, // uViewProjection - Inverse view projection matrix
U_PROJECTION, // uProj - Projection matrix
U_INVERSE_VIEW, // uInverseView - View to World
U_CAM_VIEW_VEC, // uCamViewVec - Viewing vector for the camera. Depends on projection matrix
U_VIEW, // uView - Inverse view
U_CAM_UP, // uCamUp - 'Up' vector for the camera in world space
U_CAM_POS, // uCamPos - Camera position in world space.
U_GLOBAL_TIME, // uGlobalTime - Global time of the game. Used for animation.
U_ASPECT_RATIO, // uAspectRatio - The window aspect ratio
U_WINDOW_WIDTH, // uWindowWidth - The window's width
UNIFORM_NONE,
};
int uniformSize; ///< How many elements in 'uniformType' and 'uniformLocation' are valid.
COMMON_UNIFORMS uniformType[MaxNumCommonUniforms];
GLint uniformLocation[MaxNumCommonUniforms];
// -- Functions --
CommonUniforms() {uniformSize = -1;}
// Checks, and constructs if necessary, a uniform array covering
// common uniforms for the given shaderID. You will have to const-cast
// this CommonUniforms component in order to use this function, is it
// modifies this component in-place.
void checkUniformArray(GLuint shaderID);
/// This function assumes that you have already bound the appropriate
/// shader. It will apply all common uniforms with the given parameters.
void applyCommonUniforms(const glm::mat4& objectToWorld,
const gen::StaticCameraData& cam,
double globalTime) const;
void setAsUnitialized()
{
uniformSize = -1;
}
static const char* getName() {return "ren:CommonUniforms";}
bool serialize(spire::ComponentSerialize& /* s */, uint64_t /* entityID */)
{
// This component will be populated in real-time and doesn't need to be
// serialized since the values will be dependent on this running
// OpenGL instance.
return true;
}
};
} // namespace ren
#endif
| 40.714286 | 123 | 0.663626 | [
"object",
"vector",
"transform"
] |
cfca57262a2aeb326cc49511e2c5eebb5de26fe1 | 11,845 | cpp | C++ | src/async_engine.cpp | quarkslab/nodescan | 2c9f14ed4cb1e1548a73c6a565b96d5618bd4c0a | [
"BSD-3-Clause"
] | 11 | 2015-01-01T05:37:01.000Z | 2021-11-15T10:45:00.000Z | src/async_engine.cpp | quarkslab/nodescan | 2c9f14ed4cb1e1548a73c6a565b96d5618bd4c0a | [
"BSD-3-Clause"
] | null | null | null | src/async_engine.cpp | quarkslab/nodescan | 2c9f14ed4cb1e1548a73c6a565b96d5618bd4c0a | [
"BSD-3-Clause"
] | 4 | 2015-04-20T01:28:28.000Z | 2021-11-14T03:26:49.000Z | /*
* Copyright (c) 2014, Quarkslab
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the {organization} 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.
*/
#define _BSD_SOURCE
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/epoll.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <iostream>
#include <ns/async_engine.h>
#include <ns/host_state_machine.h>
#include <ns/ipstr.h>
#include <ns/target.h>
#include <ns/log.h>
#include <ns/errors.h>
#define MAX_EVENTS 1024
static uint32_t socket_bytes_avail(int s)
{
int ret;
ioctl(s, FIONREAD, &ret);
return ret;
}
static int new_socket(int type, int proto)
{
int s = socket(AF_INET, type, proto);
fcntl(s, F_SETFL, fcntl(s, F_GETFL) | O_NONBLOCK);
return s;
}
ns::AsyncEngine::AsyncEngine(TargetSet& targets, uint32_t nsockets, uint32_t timeout):
Engine(targets),
_nsockets(nsockets),
_timeout(timeout),
_timeout_status_display(0)
{
init_sockets();
}
void ns::AsyncEngine::init_sockets()
{
_avail_socks = nsockets();
/*
free_socks().reserve(nsockets());
for (uint32_t i = 0; i < nsockets(); i++) {
const int s = new_socket();
_lvl4_sms.insert(std::make_pair(s, Lvl4SM()));
free_socks().push_back(s);
}
*/
}
void ns::AsyncEngine::remove_connected_socket(int s)
{
struct epoll_event ev;
ev.events = EPOLLIN;
ev.data.fd = s;
epoll_ctl(epoll(), EPOLL_CTL_DEL, s, &ev);
}
void ns::AsyncEngine::free_socket(int s)
{
remove_connecting_socket(s);
remove_connected_socket(s);
close(s);
del_lvl4_sm(s);
_avail_socks++;
_sockets_targets.erase(s);
}
void ns::AsyncEngine::socket_finished(int s, int err)
{
_ndone++;
Target t = target_from_socket(s);
Lvl4SM& lvl4sm = lvl4_sm(s);
Lvl4Buffer const& buf = lvl4sm.buffer();
callback_finish(t, buf, err);
lvl4sm.free_buffer();
if (target_finished(t, host_sm(t.ipv4()))) {
del_host_sm(t);
}
free_socket(s);
}
void ns::AsyncEngine::process_connecting_ready(int s, Lvl4SM& lvl4sm)
{
_D(BOOST_LOG_NAMED_SCOPE("AsyncEngine::process_connecting_ready"));
int err;
socklen_t size = sizeof(int);
getsockopt(s, SOL_SOCKET, SO_ERROR, &err, &size);
if (err != 0) {
//BOOST_LOG_TRIVIAL(trace) << "Error with " << ipstr(ipv4) << ": " << strerror(err) << std::endl;
socket_finished(s, err);
return;
}
Target target = target_from_socket(s);
const uint32_t ipv4 = target.ipv4();
_D(BOOST_LOG_TRIVIAL(trace) << "Connected to " << ipstr(ipv4) << std::endl);
const bool ret = lvl4sm.on_connect(s, target, host_sm(ipv4));
if (ret == false) {
// The end for him
socket_finished(s, 0);
_D(BOOST_LOG_TRIVIAL(trace) << "on_connect action returned false for " << ipstr(ipv4) << std::endl);
}
else {
remove_connecting_socket(s);
add_connected_socket(s);
lvl4sm.update_ts();
}
}
void ns::AsyncEngine::reconnect(int s, Target const& target, Lvl4SM const& lvl4sm)
{
_D(BOOST_LOG_TRIVIAL(trace) << "reconnect" << std::endl);
Lvl4Action cur_action = lvl4sm.get_on_connect();
remove_connected_socket(s);
close(s);
_avail_socks++;
create_socket(s, target);
lvl4_sm(s).set_on_connect(cur_action);
add_connecting_socket(s);
}
int ns::AsyncEngine::create_socket(int& s, Target const& target)
{
assert(_avail_socks > 0);
/*struct in_addr addr_;
addr_.s_addr = htonl(target.ipv4());
std::cerr << "Connecting to " << inet_ntoa(addr_) << "..." << std::endl;*/
leeloo::port port = target.port();
s = new_socket(port.socket_type(), port.socket_proto());
if (s == -1) {
return errno;
}
_avail_socks--;
sockaddr_in addr = target.to_sockaddr_in();
int ret = connect(s, (const sockaddr*) &addr, sizeof(struct sockaddr_in));
Lvl4SM& lvl4sm = new_lvl4_sm(s);
lvl4sm.set_valid(true);
lvl4sm.set_on_connect(_callback_lvl4_connected);
lvl4sm.update_ts();
_sockets_targets.insert(std::make_pair(s, target));
return ret;
}
void ns::AsyncEngine::process_connected_ready(int s, Target const& target, Lvl4SM& lvl4sm)
{
_D(BOOST_LOG_NAMED_SCOPE("AsyncEngine::process_connected_ready"));
uint32_t navail = socket_bytes_avail(s);
const uint32_t ipv4 = target.ipv4();
if (navail == 0) {
_D(BOOST_LOG_TRIVIAL(trace) << ipstr(ipv4) << " remote host deconnected" << std::endl);
if (lvl4sm.reconnect()) {
Lvl4Buffer const& buf = lvl4sm.buffer();
callback_finish(target, buf, (int) errors::WILL_RECONNECT);
lvl4sm.free_buffer();
reconnect(s, target, lvl4sm);
return;
}
socket_finished(s, ECONNRESET);
return;
}
// Returns true to go on
// false to remove
bool ret = lvl4sm.process_lvl4_data(s, navail, target, host_sm(ipv4));
_D(BOOST_LOG_TRIVIAL(trace) << ipstr(ipv4) << " process_lvl4_data returned " << ret << std::endl);
lvl4sm.update_ts();
if (ret == false) {
_D(BOOST_LOG_TRIVIAL(trace) << ipstr(ipv4) << " free socket!" << std::endl);
// Free socket, this is the end for this one!
socket_finished(s, 0);
}
}
void ns::AsyncEngine::add_connecting_socket(int s)
{
struct epoll_event ev;
ev.events = EPOLLOUT;
ev.data.fd = s;
epoll_ctl(epoll(), EPOLL_CTL_ADD, s, &ev);
}
void ns::AsyncEngine::add_connected_socket(int s)
{
struct epoll_event ev;
ev.events = EPOLLIN;
ev.data.fd = s;
epoll_ctl(epoll(), EPOLL_CTL_ADD, s, &ev);
}
void ns::AsyncEngine::remove_connecting_socket(int s)
{
struct epoll_event ev;
// &ev isn't mandatory, but there is a bug before 2.6.9 that
// makes epoll crashes if &ev == nullptr
epoll_ctl(epoll(), EPOLL_CTL_DEL, s, &ev);
}
void ns::AsyncEngine::launch()
{
init_scan();
do_async_scan();
}
void ns::AsyncEngine::launch_shrd(uint32_t, uint32_t)
{
//init_shrd_scan(idx, total);
do_async_scan();
}
bool ns::AsyncEngine::process_free_socks()
{
std::vector<int>::const_iterator it_socks;
_D(BOOST_LOG_TRIVIAL(trace) << "begin free socks" << std::endl);
const uint32_t avail_socks = _avail_socks;
try {
for (uint32_t i = 0; i < avail_socks; i++) {
int ret, s;
Target cur_target;
while (true) {
cur_target = next_target();
if (cur_target.is_end()) {
return false;
}
_nlaunched++;
ret = create_socket(s, cur_target);
if (ret == 0) {
break;
}
else {
if (errno == EINPROGRESS) {
break;
}
socket_finished(s, errno);
_D(BOOST_LOG_TRIVIAL(trace) << s << " Error connecting to " << ipstr(cur_target.ipv4()) << ": " << errno << " " << strerror(errno) << std::endl);
}
}
_D(BOOST_LOG_TRIVIAL(trace) << "Connecting to " << ipstr(cur_target.ipv4()) << std::endl);
HostSM& hsm = host_sm(cur_target.ipv4());
init_host_sm(cur_target, hsm);
add_connecting_socket(s);
}
}
catch (NextTargetWouldBlock const&) {
return true;
}
return true;
}
int ns::AsyncEngine::process_events()
{
static struct epoll_event events[MAX_EVENTS];
_D(BOOST_LOG_TRIVIAL(trace) << "begin epoll" << std::endl);
// Poll this
const int nfds = epoll_wait(epoll(), events, MAX_EVENTS, 1);
for (int i = 0; i < nfds; i++) {
struct epoll_event& ev = events[i];
const int fd = ev.data.fd;
if ((ev.events & EPOLLOUT) == EPOLLOUT) {
process_connecting_ready(fd, lvl4_sm(fd));
}
else
if ((ev.events & EPOLLIN) == EPOLLIN) {
process_connected_ready(fd, target_from_socket(fd), lvl4_sm(fd));
}
}
return nfds;
}
bool ns::AsyncEngine::has_watch_timedout(time_t ts, int s, Lvl4SM& lvl4sm) const
{
if (!_watch_timeout_cb || (_watch_timeout == 0)) {
return false;
}
if ((ts-lvl4sm.watch_ts()) >= watch_timeout()) {
if (!_watch_timeout_cb(ConnectedTarget(s, Target::from_socket(s)))) {
return true;
}
lvl4sm.update_watch_ts(ts);
}
return false;
}
size_t ns::AsyncEngine::process_dirty_and_timeouts()
{
_D(BOOST_LOG_TRIVIAL(trace) << "begin timeouts" << std::endl);
lvl4_sms_type::iterator it;
const time_t ts = timestamp();
size_t n_lvl4_sms_valid = 0;
std::vector<std::pair<int, Lvl4SM*>> to_process;
std::vector<int> timeouted;
for (it = _lvl4_sms.begin(); it != _lvl4_sms.end(); it++) {
Lvl4SM& p = it->second;
if (p.valid()) {
const int s = it->first;
if (p.should_process_buffer()) {
to_process.push_back(std::make_pair(s, &p));
}
const uint32_t timeout_target = timeout_of_target(Target::from_socket(s));
if (((ts-p.ts()) >= timeout_target) || has_watch_timedout(ts, it->first, p)) {
const int s = it->first;
timeouted.push_back(s);
}
else {
n_lvl4_sms_valid++;
}
}
}
// Do this out of this loop as some Lvl4SM can be deleted in the way.
for (auto const& tp: to_process) {
const int s = tp.first;
Target target = target_from_socket(s);
bool ret = tp.second->process_buffer(s, target, host_sm(target.ipv4()));
if (!ret) {
socket_finished(s, 0);
continue;
}
}
for (int s: timeouted) {
socket_finished(s, (int) errors::NS_TIMEOUT);
}
return n_lvl4_sms_valid;
}
bool ns::AsyncEngine::should_call_status_display()
{
if (!_callback_status || _timeout_status_display == 0) {
return false;
}
const time_t now = timestamp();
if (now-_last_time_status_display >= _timeout_status_display) {
_last_time_status_display = now;
return true;
}
return false;
}
void ns::AsyncEngine::do_async_scan()
{
_D(BOOST_LOG_NAMED_SCOPE("AsyncEngine::do_async_scan"));
epoll() = epoll_create(nsockets());
_nlaunched = 0;
_ndone = 0;
_last_time_status_display = 0;
process_free_socks();
while (true) {
// Events processing
const int nfds = process_events();
// Dirties and timeouts
const size_t n_lvl4_sms_valid = process_dirty_and_timeouts();
// IP connect. It is done after the events processing because some of
// them might have add new targets into the original set.
const bool end_targets = !process_free_socks();
_D(BOOST_LOG_TRIVIAL(trace) << "nfds == " << nfds << " "
<< "n_lvl4_sms_valid == " << n_lvl4_sms_valid << " "
<< "end_targets == " << end_targets << std::endl);
// Check for the end
if (nfds == 0 && n_lvl4_sms_valid == 0 && end_targets) {
break;
}
if (should_call_status_display()) {
_callback_status(_nlaunched, _ndone);
}
if (should_save_state()) {
save_state(file_autosave());
}
}
}
ns::Lvl4SM& ns::AsyncEngine::lvl4_sm(epoll_event const& ev)
{
return lvl4_sm(ev.data.fd);
}
void ns::AsyncEngine::ensure_available_sockets(const size_t n)
{
if (_avail_socks < n) {
_avail_socks += (n-_avail_socks);
}
}
| 26.322222 | 150 | 0.688729 | [
"vector"
] |
cfcf326e019905df191a038a5c0674252cd20379 | 1,423 | cpp | C++ | Kickstart/KickStart20B/gen.cpp | Shahraaz/CP_P_S5 | b068ad02d34338337e549d92a14e3b3d9e8df712 | [
"MIT"
] | null | null | null | Kickstart/KickStart20B/gen.cpp | Shahraaz/CP_P_S5 | b068ad02d34338337e549d92a14e3b3d9e8df712 | [
"MIT"
] | null | null | null | Kickstart/KickStart20B/gen.cpp | Shahraaz/CP_P_S5 | b068ad02d34338337e549d92a14e3b3d9e8df712 | [
"MIT"
] | null | null | null | // Optimise
#include <bits/stdc++.h>
using namespace std;
#ifdef LOCAL
#include "/home/shahraaz/bin/debug.h"
#else
#define db(...)
#endif
using ll = long long;
#define f first
#define s second
#define pb push_back
#define all(v) v.begin(), v.end()
const int NAX = 9999, MOD = 1000000007;
// double prob[NAX][NAX];
// int vis[NAX][NAX];
class Solution
{
private:
public:
Solution() {}
~Solution() {}
void solveCase()
{
srand(time(NULL));
int t = 100;
cout << t << '\n';
while (t--)
{
vector<int> l{rand() % NAX, rand() % NAX, rand() % NAX};
vector<int> r{rand() % NAX, rand() % NAX, rand() % NAX};
sort(all(l));
sort(all(r));
cout << l[2] + 1 << ' ' << r[2] + 1 << ' ';
cout << l[0] + 1 << ' ' << r[0] + 1 << ' ';
cout << l[1] + 1 << ' ' << r[1] + 1 << ' ';
cout << '\n';
}
}
};
int32_t main()
{
#ifndef LOCAL
ios_base::sync_with_stdio(0);
cin.tie(0);
#endif
int t = 1;
// cin >> t;
Solution mySolver;
for (int i = 1; i <= t; ++i)
{
// cout << "Case #" << i << ": ";
mySolver.solveCase();
#ifdef LOCAL
cerr << "Case #" << i << ": Time " << chrono::duration<double>(chrono::steady_clock::now() - TimeStart).count() << " s.\n";
TimeStart = chrono::steady_clock::now();
#endif
}
return 0;
} | 21.892308 | 131 | 0.471539 | [
"vector"
] |
cfcf9f429b223d0ba5ed35e3d784d41f420be145 | 20,745 | cpp | C++ | branch/old_angsys/angsys_beta1/source/angsys/angsys.shared/source/collections/vector.cpp | ChuyX3/angsys | 89b2eaee866bcfd11e66efda49b38acc7468c780 | [
"Apache-2.0"
] | null | null | null | branch/old_angsys/angsys_beta1/source/angsys/angsys.shared/source/collections/vector.cpp | ChuyX3/angsys | 89b2eaee866bcfd11e66efda49b38acc7468c780 | [
"Apache-2.0"
] | null | null | null | branch/old_angsys/angsys_beta1/source/angsys/angsys.shared/source/collections/vector.cpp | ChuyX3/angsys | 89b2eaee866bcfd11e66efda49b38acc7468c780 | [
"Apache-2.0"
] | null | null | null | /*********************************************************************************************************************/
/* File Name: vector.cpp */
/* Author: Ing. Jesus Rocha <chuyangel.rm@gmail.com>, July 2016. */
/* Copyright (C) Angsys, - All Rights Reserved */
/* Confidential Information of Angsys. Not for disclosure or distribution without the author's prior written */
/* consent. This file contains code, techniques and know-how which is confidential and proprietary to Jesus Rocha */
/* */
/*********************************************************************************************************************/
#include "pch.h"
#include <angsys.h>
#include <ang/collections/vector.h>
#include <ang/core/async.h>
using namespace ang;
ang::object_wrapper<ang::collections::vector_buffer<string>>::object_wrapper()
: _ptr(null)
{
}
ang::object_wrapper<ang::collections::vector_buffer<string>>::object_wrapper(ang::collections::vector_buffer<string>* ptr)
: object_wrapper<ang::collections::vector_buffer<string>>()
{
set(ptr);
}
ang::object_wrapper<ang::collections::vector_buffer<string>>::object_wrapper(ang::initializer_list_t<string> list)
: object_wrapper<ang::collections::vector_buffer<string>>()
{
set(new collections::vector_buffer<string>(ang::move(list)));
}
ang::object_wrapper<ang::collections::vector_buffer<string>>::object_wrapper(ang::static_array<string> list)
: object_wrapper<ang::collections::vector_buffer<string>>()
{
set(new collections::vector_buffer<string>(list.size(), list.get()));
}
ang::object_wrapper<ang::collections::vector_buffer<string>>::object_wrapper(ang::initializer_list_t<cstr_t> list)
: object_wrapper<ang::collections::vector_buffer<string>>()
{
set(new collections::vector_buffer<string>((uint)list.size()));
auto data = get();
for (auto it = list.begin(); it != list.end(); ++it)
data->append(*it);
}
ang::object_wrapper<ang::collections::vector_buffer<string>>::object_wrapper(ang::initializer_list_t<cwstr_t> list)
: object_wrapper<ang::collections::vector_buffer<string>>()
{
set(new collections::vector_buffer<string>((uint)list.size()));
auto data = get();
for (auto it = list.begin(); it != list.end(); ++it)
data->append(*it);
}
ang::object_wrapper<ang::collections::vector_buffer<string>>::object_wrapper(const ang::collections::ienum<string>* store)
: object_wrapper<ang::collections::vector_buffer<string>>()
{
set(new collections::vector_buffer<string>(store));
}
ang::object_wrapper<ang::collections::vector_buffer<string>>::object_wrapper(ang::object_wrapper<ang::collections::vector_buffer<string>> && other)
: object_wrapper<collections::vector_buffer<string>>()
{
collections::vector_buffer<string> * temp = other._ptr;
other._ptr = null;
_ptr = temp;
}
ang::object_wrapper<ang::collections::vector_buffer<string>>::object_wrapper(ang::object_wrapper<ang::collections::vector_buffer<string>> const& other)
: object_wrapper<collections::vector_buffer<string>>()
{
set(other.get());
}
ang::object_wrapper<ang::collections::vector_buffer<string>>::object_wrapper(ang::nullptr_t const& other)
: object_wrapper<collections::vector_buffer<string>>() { }
ang::object_wrapper<ang::collections::vector_buffer<string>>::~object_wrapper()
{
clean();
}
void ang::object_wrapper<ang::collections::vector_buffer<string>>::clean()
{
if (_ptr)_ptr->release();
_ptr = null;
}
void ang::object_wrapper<ang::collections::vector_buffer<string>>::clean_unsafe()
{
_ptr = null;
}
bool ang::object_wrapper<ang::collections::vector_buffer<string>>::is_empty()const
{
return _ptr == null;
}
ang::collections::vector_buffer<string>* ang::object_wrapper<ang::collections::vector_buffer<string>>::get(void)const
{
return _ptr;
}
void ang::object_wrapper<ang::collections::vector_buffer<string>>::set(ang::collections::vector_buffer<string>* ptr)
{
ang::collections::vector_buffer<string> * temp = _ptr;
if (ptr == _ptr) return;
_ptr = ptr;
if (_ptr)_ptr->add_ref();
if (temp)temp->release();
}
ang::collections::vector_buffer<string>** ang::object_wrapper<ang::collections::vector_buffer<string>>::addres_of(void)
{
return &_ptr;
}
ang::object_wrapper<ang::collections::vector_buffer<string>>& ang::object_wrapper<ang::collections::vector_buffer<string>>::operator = (ang::collections::vector_buffer<string>* ptr)
{
set(ptr);
return*this;
}
ang::object_wrapper<ang::collections::vector_buffer<string>>& ang::object_wrapper<ang::collections::vector_buffer<string>>::operator = (const ang::nullptr_t&)
{
clean();
return*this;
}
ang::object_wrapper<ang::collections::vector_buffer<string>>& ang::object_wrapper<ang::collections::vector_buffer<string>>::operator = (ang::collections::ienum<string> const* items)
{
if (_ptr == null)
set(new collections::vector_buffer<string>(items));
else
_ptr->copy(items);
return *this;
}
ang::object_wrapper<ang::collections::vector_buffer<string>>& ang::object_wrapper<ang::collections::vector_buffer<string>>::operator = (ang::object_wrapper<ang::collections::vector_buffer<string>> && other)
{
if (this == &other)
return *this;
clean();
_ptr = other._ptr;
other._ptr = null;
return*this;
}
ang::object_wrapper<ang::collections::vector_buffer<string>>& ang::object_wrapper<ang::collections::vector_buffer<string>>::operator = (ang::object_wrapper<ang::collections::vector_buffer<string>> const& other)
{
set(other._ptr);
return*this;
}
ang::object_wrapper<ang::collections::vector_buffer<string>>& ang::object_wrapper<ang::collections::vector_buffer<string>>::operator += (string value)
{
if (is_empty())
set(new ang::collections::vector_buffer<string>());
get()->append(ang::move(value));
return*this;
}
ang::object_wrapper_ptr<ang::collections::vector_buffer<string>> ang::object_wrapper<ang::collections::vector_buffer<string>>::operator & (void)
{
return this;
}
ang::collections::vector_buffer<string> * ang::object_wrapper<ang::collections::vector_buffer<string>>::operator -> (void)
{
return get();
}
ang::collections::vector_buffer<string> const* ang::object_wrapper<ang::collections::vector_buffer<string>>::operator -> (void)const
{
return get();
}
ang::object_wrapper<ang::collections::vector_buffer<string>>::operator ang::collections::vector_buffer<string> * (void)
{
return get();
}
ang::object_wrapper<ang::collections::vector_buffer<string>>::operator ang::collections::vector_buffer<string> const* (void)const
{
return get();
}
string const& ang::object_wrapper<ang::collections::vector_buffer<string>>::operator[](int idx)const
{
#ifdef DEBUG_SAFE_CODE
if (is_empty()) throw(exception_t(except_code::invalid_memory));
if (((uint)idx >= _ptr->size()) || (idx < 0)) throw(exception_t(except_code::array_overflow));
#endif
return _ptr->data()[idx];
}
string & ang::object_wrapper<ang::collections::vector_buffer<string>>::operator[](int idx)
{
#ifdef DEBUG_SAFE_CODE
if (is_empty()) throw(exception_t(except_code::invalid_memory));
if (((uint)idx >= _ptr->size()) || (idx < 0)) throw(exception_t(except_code::array_overflow));
#endif
return _ptr->data()[idx];
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
ang::object_wrapper<ang::collections::vector_buffer<wstring>>::object_wrapper()
: _ptr(null)
{
}
ang::object_wrapper<ang::collections::vector_buffer<wstring>>::object_wrapper(ang::collections::vector_buffer<wstring>* ptr)
: object_wrapper<ang::collections::vector_buffer<wstring>>()
{
set(ptr);
}
ang::object_wrapper<ang::collections::vector_buffer<wstring>>::object_wrapper(ang::initializer_list_t<wstring> list)
: object_wrapper<ang::collections::vector_buffer<wstring>>()
{
set(new collections::vector_buffer<wstring>(ang::move(list)));
}
ang::object_wrapper<ang::collections::vector_buffer<wstring>>::object_wrapper(ang::initializer_list_t<cwstr_t> list)
: object_wrapper<ang::collections::vector_buffer<wstring>>()
{
set(new collections::vector_buffer<wstring>((uint)list.size()));
auto data = get();
for (auto it = list.begin(); it != list.end(); ++it)
data->append(*it);
}
ang::object_wrapper<ang::collections::vector_buffer<wstring>>::object_wrapper(ang::static_array<wstring> list)
: object_wrapper<ang::collections::vector_buffer<wstring>>()
{
set(new collections::vector_buffer<wstring>(list.size(), list.get()));
}
ang::object_wrapper<ang::collections::vector_buffer<wstring>>::object_wrapper(ang::initializer_list_t<cstr_t> list)
: object_wrapper<ang::collections::vector_buffer<wstring>>()
{
set(new collections::vector_buffer<wstring>((uint)list.size()));
auto data = get();
for (auto it = list.begin(); it != list.end(); ++it)
data->append(*it);
}
ang::object_wrapper<ang::collections::vector_buffer<wstring>>::object_wrapper(const ang::collections::ienum<wstring>* store)
: object_wrapper<ang::collections::vector_buffer<wstring>>()
{
set(new collections::vector_buffer<wstring>(store));
}
ang::object_wrapper<ang::collections::vector_buffer<wstring>>::object_wrapper(ang::object_wrapper<ang::collections::vector_buffer<wstring>> && other)
: object_wrapper<collections::vector_buffer<wstring>>()
{
collections::vector_buffer<wstring> * temp = other._ptr;
other._ptr = null;
_ptr = temp;
}
ang::object_wrapper<ang::collections::vector_buffer<wstring>>::object_wrapper(ang::object_wrapper<ang::collections::vector_buffer<wstring>> const& other)
: object_wrapper<collections::vector_buffer<wstring>>()
{
set(other.get());
}
ang::object_wrapper<ang::collections::vector_buffer<wstring>>::object_wrapper(ang::nullptr_t const& other)
: object_wrapper<collections::vector_buffer<wstring>>() { }
ang::object_wrapper<ang::collections::vector_buffer<wstring>>::~object_wrapper()
{
clean();
}
void ang::object_wrapper<ang::collections::vector_buffer<wstring>>::clean()
{
if (_ptr)_ptr->release();
_ptr = null;
}
void ang::object_wrapper<ang::collections::vector_buffer<wstring>>::clean_unsafe()
{
_ptr = null;
}
bool ang::object_wrapper<ang::collections::vector_buffer<wstring>>::is_empty()const
{
return _ptr == null;
}
ang::collections::vector_buffer<wstring>* ang::object_wrapper<ang::collections::vector_buffer<wstring>>::get(void)const
{
return _ptr;
}
void ang::object_wrapper<ang::collections::vector_buffer<wstring>>::set(ang::collections::vector_buffer<wstring>* ptr)
{
ang::collections::vector_buffer<wstring> * temp = _ptr;
if (ptr == _ptr) return;
_ptr = ptr;
if (_ptr)_ptr->add_ref();
if (temp)temp->release();
}
ang::collections::vector_buffer<wstring>** ang::object_wrapper<ang::collections::vector_buffer<wstring>>::addres_of(void)
{
return &_ptr;
}
ang::object_wrapper<ang::collections::vector_buffer<wstring>>& ang::object_wrapper<ang::collections::vector_buffer<wstring>>::operator = (ang::collections::vector_buffer<wstring>* ptr)
{
set(ptr);
return*this;
}
ang::object_wrapper<ang::collections::vector_buffer<wstring>>& ang::object_wrapper<ang::collections::vector_buffer<wstring>>::operator = (const ang::nullptr_t&)
{
clean();
return*this;
}
ang::object_wrapper<ang::collections::vector_buffer<wstring>>& ang::object_wrapper<ang::collections::vector_buffer<wstring>>::operator = (ang::collections::ienum<wstring> const* items)
{
if (_ptr == null)
set(new collections::vector_buffer<wstring>(items));
else
_ptr->copy(items);
return *this;
}
ang::object_wrapper<ang::collections::vector_buffer<wstring>>& ang::object_wrapper<ang::collections::vector_buffer<wstring>>::operator = (ang::object_wrapper<ang::collections::vector_buffer<wstring>> && other)
{
if (this == &other)
return *this;
clean();
_ptr = other._ptr;
other._ptr = null;
return*this;
}
ang::object_wrapper<ang::collections::vector_buffer<wstring>>& ang::object_wrapper<ang::collections::vector_buffer<wstring>>::operator = (ang::object_wrapper<ang::collections::vector_buffer<wstring>> const& other)
{
set(other._ptr);
return*this;
}
ang::object_wrapper<ang::collections::vector_buffer<wstring>>& ang::object_wrapper<ang::collections::vector_buffer<wstring>>::operator += (wstring value)
{
if (is_empty())
set(new ang::collections::vector_buffer<wstring>());
get()->append(ang::move(value));
return*this;
}
ang::object_wrapper_ptr<ang::collections::vector_buffer<wstring>> ang::object_wrapper<ang::collections::vector_buffer<wstring>>::operator & (void)
{
return this;
}
ang::collections::vector_buffer<wstring> * ang::object_wrapper<ang::collections::vector_buffer<wstring>>::operator -> (void)
{
return get();
}
ang::collections::vector_buffer<wstring> const* ang::object_wrapper<ang::collections::vector_buffer<wstring>>::operator -> (void)const
{
return get();
}
ang::object_wrapper<ang::collections::vector_buffer<wstring>>::operator ang::collections::vector_buffer<wstring> * (void)
{
return get();
}
ang::object_wrapper<ang::collections::vector_buffer<wstring>>::operator ang::collections::vector_buffer<wstring> const* (void)const
{
return get();
}
wstring const& ang::object_wrapper<ang::collections::vector_buffer<wstring>>::operator[](int idx)const
{
#ifdef DEBUG_SAFE_CODE
if (is_empty()) throw(exception_t(except_code::invalid_memory));
if (((uint)idx >= _ptr->size()) || (idx < 0)) throw(exception_t(except_code::array_overflow));
#endif
return _ptr->data()[idx];
}
wstring & ang::object_wrapper<ang::collections::vector_buffer<wstring>>::operator[](int idx)
{
#ifdef DEBUG_SAFE_CODE
if (is_empty()) throw(exception_t(except_code::invalid_memory));
if (((uint)idx >= _ptr->size()) || (idx < 0)) throw(exception_t(except_code::array_overflow));
#endif
return _ptr->data()[idx];
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
ang::object_wrapper<ang::collections::vector_buffer<objptr>>::object_wrapper()
: _ptr(null)
{
}
ang::object_wrapper<ang::collections::vector_buffer<objptr>>::object_wrapper(ang::collections::vector_buffer<objptr>* ptr)
: object_wrapper<ang::collections::vector_buffer<objptr>>()
{
set(ptr);
}
ang::object_wrapper<ang::collections::vector_buffer<objptr>>::object_wrapper(ang::initializer_list_t<objptr> list)
: object_wrapper<ang::collections::vector_buffer<objptr>>()
{
set(new collections::vector_buffer<objptr>(ang::move(list)));
}
ang::object_wrapper<ang::collections::vector_buffer<objptr>>::object_wrapper(ang::static_array<objptr> list)
: object_wrapper<ang::collections::vector_buffer<objptr>>()
{
set(new collections::vector_buffer<objptr>(list.size(), list.get()));
}
ang::object_wrapper<ang::collections::vector_buffer<objptr>>::object_wrapper(const ang::collections::ienum<objptr>* store)
: object_wrapper<ang::collections::vector_buffer<objptr>>()
{
set(new collections::vector_buffer<objptr>(store));
}
ang::object_wrapper<ang::collections::vector_buffer<objptr>>::object_wrapper(ang::object_wrapper<ang::collections::vector_buffer<objptr>> && other)
: object_wrapper<collections::vector_buffer<objptr>>()
{
collections::vector_buffer<objptr> * temp = other._ptr;
other._ptr = null;
_ptr = temp;
}
ang::object_wrapper<ang::collections::vector_buffer<objptr>>::object_wrapper(ang::object_wrapper<ang::collections::vector_buffer<objptr>> const& other)
: object_wrapper<collections::vector_buffer<objptr>>()
{
set(other.get());
}
ang::object_wrapper<ang::collections::vector_buffer<objptr>>::object_wrapper(ang::nullptr_t const& other)
: object_wrapper<collections::vector_buffer<objptr>>() { }
ang::object_wrapper<ang::collections::vector_buffer<objptr>>::~object_wrapper()
{
clean();
}
void ang::object_wrapper<ang::collections::vector_buffer<objptr>>::clean()
{
if (_ptr)_ptr->release();
_ptr = null;
}
void ang::object_wrapper<ang::collections::vector_buffer<objptr>>::clean_unsafe()
{
_ptr = null;
}
bool ang::object_wrapper<ang::collections::vector_buffer<objptr>>::is_empty()const
{
return _ptr == null;
}
ang::collections::vector_buffer<objptr>* ang::object_wrapper<ang::collections::vector_buffer<objptr>>::get(void)const
{
return _ptr;
}
void ang::object_wrapper<ang::collections::vector_buffer<objptr>>::set(ang::collections::vector_buffer<objptr>* ptr)
{
ang::collections::vector_buffer<objptr> * temp = _ptr;
if (ptr == _ptr) return;
_ptr = ptr;
if (_ptr)_ptr->add_ref();
if (temp)temp->release();
}
ang::collections::vector_buffer<objptr>** ang::object_wrapper<ang::collections::vector_buffer<objptr>>::addres_of(void)
{
return &_ptr;
}
ang::object_wrapper<ang::collections::vector_buffer<objptr>>& ang::object_wrapper<ang::collections::vector_buffer<objptr>>::operator = (ang::collections::vector_buffer<objptr>* ptr)
{
set(ptr);
return*this;
}
ang::object_wrapper<ang::collections::vector_buffer<objptr>>& ang::object_wrapper<ang::collections::vector_buffer<objptr>>::operator = (const ang::nullptr_t&)
{
clean();
return*this;
}
ang::object_wrapper<ang::collections::vector_buffer<objptr>>& ang::object_wrapper<ang::collections::vector_buffer<objptr>>::operator = (ang::collections::ienum<objptr> const* items)
{
if (_ptr == null)
set(new collections::vector_buffer<objptr>(items));
else
_ptr->copy(items);
return *this;
}
ang::object_wrapper<ang::collections::vector_buffer<objptr>>& ang::object_wrapper<ang::collections::vector_buffer<objptr>>::operator = (ang::object_wrapper<ang::collections::vector_buffer<objptr>> && other)
{
if (this == &other)
return *this;
clean();
_ptr = other._ptr;
other._ptr = null;
return*this;
}
ang::object_wrapper<ang::collections::vector_buffer<objptr>>& ang::object_wrapper<ang::collections::vector_buffer<objptr>>::operator = (ang::object_wrapper<ang::collections::vector_buffer<objptr>> const& other)
{
set(other._ptr);
return*this;
}
ang::object_wrapper<ang::collections::vector_buffer<objptr>>& ang::object_wrapper<ang::collections::vector_buffer<objptr>>::operator += (objptr value)
{
if (is_empty())
set(new ang::collections::vector_buffer<objptr>());
get()->append(ang::move(value));
return*this;
}
ang::object_wrapper_ptr<ang::collections::vector_buffer<objptr>> ang::object_wrapper<ang::collections::vector_buffer<objptr>>::operator & (void)
{
return this;
}
ang::collections::vector_buffer<objptr> * ang::object_wrapper<ang::collections::vector_buffer<objptr>>::operator -> (void)
{
return get();
}
ang::collections::vector_buffer<objptr> const* ang::object_wrapper<ang::collections::vector_buffer<objptr>>::operator -> (void)const
{
return get();
}
ang::object_wrapper<ang::collections::vector_buffer<objptr>>::operator ang::collections::vector_buffer<objptr> * (void)
{
return get();
}
ang::object_wrapper<ang::collections::vector_buffer<objptr>>::operator ang::collections::vector_buffer<objptr> const* (void)const
{
return get();
}
objptr const& ang::object_wrapper<ang::collections::vector_buffer<objptr>>::operator[](int idx)const
{
#ifdef DEBUG_SAFE_CODE
if (is_empty()) throw(exception_t(except_code::invalid_memory));
if (((uint)idx >= _ptr->size()) || (idx < 0)) throw(exception_t(except_code::array_overflow));
#endif
return _ptr->data()[idx];
}
objptr & ang::object_wrapper<ang::collections::vector_buffer<objptr>>::operator[](int idx)
{
#ifdef DEBUG_SAFE_CODE
if (is_empty()) throw(exception_t(except_code::invalid_memory));
if (((uint)idx >= _ptr->size()) || (idx < 0)) throw(exception_t(except_code::array_overflow));
#endif
return _ptr->data()[idx];
}
#include "vector_specialization.inl"
ANG_IMPLEMENT_VECTOR_DATA_SPECIALIZATION(short)
ANG_IMPLEMENT_VECTOR_DATA_SPECIALIZATION(ushort)
ANG_IMPLEMENT_VECTOR_DATA_SPECIALIZATION(int)
ANG_IMPLEMENT_VECTOR_DATA_SPECIALIZATION(uint)
ANG_IMPLEMENT_VECTOR_DATA_SPECIALIZATION(long)
ANG_IMPLEMENT_VECTOR_DATA_SPECIALIZATION(ulong)
ANG_IMPLEMENT_VECTOR_DATA_SPECIALIZATION(long64)
ANG_IMPLEMENT_VECTOR_DATA_SPECIALIZATION(ulong64)
ANG_IMPLEMENT_VECTOR_DATA_SPECIALIZATION(float)
ANG_IMPLEMENT_VECTOR_DATA_SPECIALIZATION(double)
ANG_IMPLEMENT_INTERFACE_VECTOR_SPECIALIZATION(ang::core::async::iasync_task)
ANG_IMPLEMENT_OBJECT_VECTOR_SPECIALIZATION(ang::core::delegates::function_data<dword(pointer)>)
ANG_IMPLEMENT_OBJECT_VECTOR_SPECIALIZATION(ang::core::delegates::function_data<void(objptr, pointer)>)
| 30.417889 | 213 | 0.708797 | [
"vector"
] |
cfd03337362251f6bc4848dbe00885498bde51b2 | 3,765 | cpp | C++ | src/util/helper.cpp | raphaelsulzer/mesh-tools | 73150bec58813e2b9b750205807002a1c3f18884 | [
"MIT"
] | 1 | 2022-02-24T03:39:05.000Z | 2022-02-24T03:39:05.000Z | src/util/helper.cpp | raphaelsulzer/mesh-tools | 73150bec58813e2b9b750205807002a1c3f18884 | [
"MIT"
] | 1 | 2022-02-24T06:59:59.000Z | 2022-03-04T01:25:09.000Z | src/util/helper.cpp | raphaelsulzer/mesh-tools | 73150bec58813e2b9b750205807002a1c3f18884 | [
"MIT"
] | null | null | null | #include <base/cgal_typedefs.h>
#include <util/helper.h>
//#include <processing/tetIntersection.h>
#include <random>
#include <iterator>
using namespace std;
#ifdef RECONBENCH
#include <modeling/Vector3.h>
const Vector3RB point2Vector3RB(const Point p){
return Vector3RB(p.x(),p.y(),p.z());
}
#endif
const Eigen::Vector3d cgal2Eigen(const Point p){
return Eigen::Vector3d(p.x(), p.y(), p.z());
}
const Point eigen2Cgal(const Eigen::Vector3f p){
return Point(p.x(), p.y(), p.z());
}
vector<Eigen::Vector3d> cgal2Eigen(vector<Point> in){
vector<Eigen::Vector3d> out;
for(const auto& point : in){
Eigen::Vector3d p(point.x(), point.y(), point.z());
out.push_back(p);
}
return out;
}
vector<Point> eigen2Cgal(const vector<Eigen::Vector3d> in){
vector<Point> out;
for(const auto& point : in){
Point p(point.x(), point.y(), point.z());
out.push_back(p);
}
return out;
}
#include <CGAL/Polyhedron_copy_3.h>
Polyhedron_Exact inexact2exactPolyhedron(Polyhedron in){
CGAL::Polyhedron_copy_3<Polyhedron, Polyhedron_Exact::HalfedgeDS> modifier(in);
Polyhedron_Exact ex;
ex.delegate(modifier);
return ex;
}
Polyhedron exact2inexactPolyhedron(Polyhedron_Exact ex){
CGAL::Polyhedron_copy_3<Polyhedron_Exact, Polyhedron::HalfedgeDS> modifier(ex);
Polyhedron in;
in.delegate(modifier);
return in;
}
size_t splitString(const std::string &txt, std::vector<std::string> &strs, char ch)
{
size_t pos = txt.find( ch );
size_t initialPos = 0;
strs.clear();
// Decompose statement
while( pos != std::string::npos ) {
strs.push_back( txt.substr( initialPos, pos - initialPos ) );
initialPos = pos + 1;
pos = txt.find( ch, initialPos );
}
// Add the last one
strs.push_back( txt.substr( initialPos, std::min( pos, txt.size() ) - initialPos + 1 ) );
return strs.size();
}
string double2string(double regularization_weight){
ostringstream out;
if(regularization_weight == 0.0)
out.precision(0);
else if(regularization_weight >= 10)
out.precision(0);
else if(regularization_weight >= 1)
out.precision(1);
else if(regularization_weight >= 0.1)
out.precision(1);
else if(regularization_weight >= 0.01)
out.precision(2);
else
out.precision(3);
out << std::fixed << regularization_weight;
string rw_string = "_"+out.str();
return rw_string;
}
template<typename Iter, typename RandomGenerator>
Iter select_randomly(Iter start, Iter end, RandomGenerator& g) {
std::uniform_int_distribution<> dis(0, std::distance(start, end) - 1);
std::advance(start, dis(g));
return start;
}
template<typename Iter>
Iter select_randomly(Iter start, Iter end) {
static std::random_device rd;
static std::mt19937 gen(rd());
return select_randomly(start, end, gen);
}
//string getCurrentPath(){
// char szTmp[32];
// sprintf(szTmp, "/proc/%d/exe", getpid());
// char pBuf[256];
// size_t len = sizeof(pBuf);
// int bytes = MIN(readlink(szTmp, pBuf, len), len - 1);
// if(bytes >= 0)
// pBuf[bytes] = '\0';
// return pBuf;
//}
string whichOS()
{
#ifdef _WIN32
return "Windows 32-bit";
#elif _WIN64
return "Windows 64-bit";
#elif __APPLE__ || __MACH__
return "Mac OSX";
#elif __linux__
return "Linux";
#elif __FreeBSD__
return "FreeBSD";
#elif __unix || __unix__
return "Unix";
#else
return "Other";
#endif
}
//void remove(std::vector<Point> &v)
//{
// auto end = v.end();
// for (auto it = v.begin(); it != end; ++it) {
// end = std::remove(it + 1, end, *it);
// }
// v.erase(end, v.end());
//}
| 22.54491 | 93 | 0.630013 | [
"vector"
] |
cfd4375c61897d5ed439c1b5ee8362a617ff04a7 | 2,066 | cc | C++ | libs/core/src/core/image_canvas.cc | madeso/euphoria | 59b72d148a90ae7a19e197e91216d4d42f194fd5 | [
"MIT"
] | 24 | 2015-07-27T14:32:18.000Z | 2021-11-15T12:11:31.000Z | libs/core/src/core/image_canvas.cc | madeso/euphoria | 59b72d148a90ae7a19e197e91216d4d42f194fd5 | [
"MIT"
] | 27 | 2021-07-09T21:18:40.000Z | 2021-07-14T13:39:56.000Z | libs/core/src/core/image_canvas.cc | madeso/euphoria | 59b72d148a90ae7a19e197e91216d4d42f194fd5 | [
"MIT"
] | null | null | null | #include "core/image_canvas.h"
#include "core/image.h"
#include "core/assert.h"
#include "core/numeric.h"
#include "core/mat2.h"
#include "core/image_draw.h"
#include "core/stringutils.h"
#include "core/stringmerger.h"
#include "core/log.h"
namespace euphoria::core
{
Vec2f
Canvas::transform_position(const Vec2f& v) const
{
const auto vv = transform * Vec3f {v, 1};
return Vec2f {vv.x, static_cast<float>(target_image->height) - vv.y};
}
Canvas::Canvas(Image* i)
: fill_style(NamedColor::black)
, target_image(i)
, transform(Mat3f::identity())
, building_path(false)
{
}
void
Canvas::fill_rect(int x, int y, int w, int h) const
{
ASSERTX(w > 0, w);
ASSERTX(h > 0, h);
draw_rect(
target_image,
fill_style,
Recti::from_top_left_width_height(Vec2i{x, target_image->height - y}, w, h));
}
void
Canvas::translate(float x, float y)
{
const auto m = Mat3f::from_translation2d(Vec2f {x, y});
transform = transform * m;
}
void
Canvas::rotate(float r)
{
transform = transform * Mat3f{Mat2f::from_rotation(Angle::from_radians(r))};
}
void
Canvas::begin_path()
{
ASSERT(!building_path);
path.resize(0);
building_path = true;
}
void
Canvas::close_path()
{
ASSERT(building_path);
building_path = false;
}
void
Canvas::move_to(float x, float y)
{
ASSERT(building_path);
ASSERT(path.empty());
path.push_back(transform_position(Vec2f(x, y)));
}
void
Canvas::line_to(float dx, float dy)
{
ASSERT(building_path);
if(path.empty())
{
path.push_back(transform_position(Vec2f::zero()));
}
path.push_back(transform_position(Vec2f(dx, dy)));
}
void
Canvas::fill() const
{
ASSERT(!building_path);
fill_poly(target_image, fill_style, path);
}
}
| 21.081633 | 93 | 0.5697 | [
"transform"
] |
cfd78d3bbc2247041caf84455670701e0e613962 | 5,403 | cpp | C++ | hard/4_median_of_two_sorted_arrays.cpp | pdu/leetcode_cpp | c487df7561f92562b20a31317957f47e0a20c485 | [
"Apache-2.0"
] | 4 | 2019-07-22T03:53:23.000Z | 2019-10-17T01:37:41.000Z | hard/4_median_of_two_sorted_arrays.cpp | pdu/leetcode_cpp | c487df7561f92562b20a31317957f47e0a20c485 | [
"Apache-2.0"
] | null | null | null | hard/4_median_of_two_sorted_arrays.cpp | pdu/leetcode_cpp | c487df7561f92562b20a31317957f47e0a20c485 | [
"Apache-2.0"
] | 2 | 2020-03-10T03:30:41.000Z | 2020-11-10T06:51:34.000Z | // step 1: clarify
//
// 1. it's two sorted array
// 2. if there're two medium numbers, get the average value
// 3. the arrays cannot be both empty but maybe empty
//
// step 2: solutions
//
// the problem is: find the kth number in two sorted array
//
// the first solution:
// 1. get 2 indexes starting from the beginnings of the two arrays: i1 = 0, i2 = 0
// 2. loop forward: if num1[i1] <= num2[i2]: i1++ else: i2++
// 3. so as to find the medium numbers
// time complexity: O(m + n)
// space complexity: O(1)
//
// the second solution:
// 1. binary search the target in the range of min(num1, num2) to max(num1, num2)
// 2. then binary search in num1 and num2 to checkout how many numbers are smaller the target
// 3. so as to find the kth number, k = (m+n+1)/2 or (m+n+1)/2+1
// time complexity: O(log(INT_MAX) * log(m + n))
// space complexity: O(1)
//
// the third solution:
// 1. binary search num1 and num2 together, to find the kth number
// 2. so the situation is like the following:
// num1: ---t1---|---t2---
// num2: ---t3---|---t4---
// t1, t2, t3, t4 is the length of each part
// in the case of num1[mid] <= num2[mid]:
// if k <= t1: search kth number in t1 + t3
// else if k <= t1 + t3: search kth number in t1 + t2 + t3
// else: search (k-t1)th number in t2 + t3 + t4
// 3. the terminate case is any of the arrays is empty or both of the arrays are size 1
// time complexity: O(log(m + n))
// space complexity: O(1)
// it's more convenient to implement in c using pointer
#include <vector>
using namespace std;
// solution 2
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
if (nums1.empty())
return median(nums2);
else if (nums2.empty())
return median(nums1);
int total_num = nums1.size() + nums2.size();
if (total_num % 2 == 1)
return kthNumber(nums1, nums2, total_num / 2 + 1);
else
return (kthNumber(nums1, nums2, total_num / 2) + kthNumber(nums1, nums2, total_num / 2 + 1)) / 2.0;
}
private:
double median(vector<int>& nums) {
int n = nums.size();
if (n % 2 == 0)
return (nums[n / 2] + nums[n / 2 - 1]) / 2.0;
else
return nums[n / 2];
}
int kthNumber(vector<int>& nums1, vector<int>& nums2, int kth) {
int left = min(nums1[0], nums2[0]);
int right = max(nums1.back(), nums2.back());
while (left <= right) {
int mid = left + (right - left) / 2;
int index = lowerBound(nums1, mid) + lowerBound(nums2, mid);
if (index > kth)
right = mid - 1;
else if (index < kth)
left = mid + 1;
else
right = mid - 1;
}
return left;
}
int lowerBound(vector<int>& num, int target) {
int left = 0;
int right = num.size() - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (target >= num[mid])
left = mid + 1;
else
right = mid - 1;
}
return left;
}
};
// solution 3
double median(int* nums, int numsSize) {
if (numsSize % 2 == 0)
return (nums[numsSize / 2] + nums[numsSize / 2 - 1]) / 2.0;
else
return nums[numsSize / 2];
}
void swap2(int **nums1, int **nums2) {
int* tmp = *nums1;
*nums1 = *nums2;
*nums2 = tmp;
}
void swap(int *num1, int *num2) {
int tmp = *num1;
*num1 = *num2;
*num2 = tmp;
}
int min(int a, int b) {
return a < b ? a : b;
}
int max(int a, int b) {
return a > b ? a : b;
}
int kthNumber(int* nums1, int nums1Size, int* nums2, int nums2Size, int k) {
if (nums1Size == 0)
return nums2[k - 1];
else if (nums2Size == 0)
return nums1[k - 1];
else if (nums1Size == 1 && nums2Size == 1)
return k == 1 ? min(nums1[0], nums2[0]) : max(nums1[0], nums2[0]);
int nums1Left = (nums1Size + 1) / 2;
int nums1Right = nums1Size - nums1Left;
int nums2Left = (nums2Size + 1) / 2;
int nums2Right = nums2Size - nums2Left;
if (nums1[nums1Left - 1] > nums2[nums2Left - 1]) {
swap2(&nums1, &nums2);
swap(&nums1Size, &nums2Size);
swap(&nums1Left, &nums2Left);
swap(&nums1Right, &nums2Right);
}
// should be care that every recursive should decrease the array size
if (k <= nums1Left)
return kthNumber(nums1, nums1Left, nums2, nums2Left, k);
else if (k <= nums1Left + nums2Left) {
if (nums2Left == 1)
return kthNumber(nums1 + nums1Left, nums1Right, nums2, nums2Left, k - nums1Left);
else
return kthNumber(nums1, nums1Size, nums2, nums2Left, k);
}
else
return kthNumber(nums1 + nums1Left, nums1Right, nums2, nums2Size, k - nums1Left);
}
double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) {
if (nums1Size == 0)
return median(nums2, nums2Size);
else if (nums2Size == 0)
return median(nums1, nums1Size);
int total = nums1Size + nums2Size;
if (total % 2 == 0)
return (kthNumber(nums1, nums1Size, nums2, nums2Size, total / 2) + kthNumber(nums1, nums1Size, nums2, nums2Size, total / 2 + 1)) / 2.0;
else
return kthNumber(nums1, nums1Size, nums2, nums2Size, total / 2 + 1);
}
| 32.160714 | 143 | 0.568388 | [
"vector"
] |
cfd95648aedf7fddba8c4f3b43b3f14a49aa2ada | 2,001 | cpp | C++ | out/production/leetcode/io/github/zhengyhn/leetcode/advantage_shuffle/advantage-shuffle.cpp | zhengyhn/leetcode | 2e5e618dd7c964c8e983b187c6b1762cbe1764de | [
"MIT"
] | null | null | null | out/production/leetcode/io/github/zhengyhn/leetcode/advantage_shuffle/advantage-shuffle.cpp | zhengyhn/leetcode | 2e5e618dd7c964c8e983b187c6b1762cbe1764de | [
"MIT"
] | null | null | null | out/production/leetcode/io/github/zhengyhn/leetcode/advantage_shuffle/advantage-shuffle.cpp | zhengyhn/leetcode | 2e5e618dd7c964c8e983b187c6b1762cbe1764de | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <vector>
#include <algorithm>
#include <random>
#include <chrono>
using namespace std;
class Solution {
public:
vector<int> advantageCount(vector<int>& A, vector<int>& B) {
srand(time(NULL));
float temperature = 1000000.0;
float cool = 0.99;
int best_adavatage = A.size();
vector<int> best = A;
while (temperature > 0.001) {
vector<int> current = best;
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
shuffle(current.begin(), current.end(), std::default_random_engine(seed));
// int left = rand() % current.size();
// int right = rand() % current.size();
// int temp = current[left];
// current[left] = current[right];
// current[right] = temp;
int adavantage = 0;
for (int i = 0; i < current.size(); ++i) {
if (current[i] > B[i]) {
adavantage += 1;
}
}
adavantage = current.size() - adavantage;
std::cout << adavantage << " " << best_adavatage << " " << rand() / double(RAND_MAX) << " " << exp(-(adavantage - best_adavatage + 1.0) / temperature) << std::endl;
if (adavantage < best_adavatage || (rand() / double(RAND_MAX) < exp(-(adavantage - best_adavatage + 1.0) / temperature))) {
best = current;
best_adavatage = adavantage;
}
temperature *= cool;
}
return best;
}
};
int main() {
Solution sln;
// vector<int> A = {2,7,11,15};
// vector<int> B = {1,10,4,11};
// vector<int> A = {12,24,8,32};
// vector<int> B = {13,25,32,11};
// vector<int> A = {2,5,4,1,8};
// vector<int> B = {4,1,5,8,2};
vector<int> A = {11,18,7,8,3,17,12,16,0,13};
vector<int> B = {18,16,3,9,0,11,13,8,7,17};
vector<int> ret = sln.advantageCount(A, B);
for (int item: ret) {
std::cout << item << " ";
}
std::cout << std::endl;
return 0;
}
| 29.865672 | 172 | 0.549225 | [
"vector"
] |
cfdd33cff0e659056c34246a879e311aa9c25ffa | 10,530 | cpp | C++ | source/src/microapp/cs_MicroappStorage.cpp | Mergon/bluenet | d6eadc3a3e0c8abc112df70780669a5739fe11bd | [
"Apache-2.0",
"MIT"
] | null | null | null | source/src/microapp/cs_MicroappStorage.cpp | Mergon/bluenet | d6eadc3a3e0c8abc112df70780669a5739fe11bd | [
"Apache-2.0",
"MIT"
] | null | null | null | source/src/microapp/cs_MicroappStorage.cpp | Mergon/bluenet | d6eadc3a3e0c8abc112df70780669a5739fe11bd | [
"Apache-2.0",
"MIT"
] | null | null | null | /*
* Store "micro" apps in flash.
*
* Author: Crownstone Team
* Copyright: Crownstone (https://crownstone.rocks)
* Date: April 4, 2020
* License: LGPLv3+, Apache License 2.0, and/or MIT (triple-licensed)
*/
#include "nrf_fstorage_sd.h"
#include <algorithm>
#include <ble/cs_UUID.h>
#include <cfg/cs_AutoConfig.h>
#include <cfg/cs_Config.h>
#include <common/cs_Types.h>
#include <logging/cs_Logger.h>
#include <drivers/cs_Storage.h>
#include <events/cs_EventDispatcher.h>
#include <ipc/cs_IpcRamData.h>
#include <microapp/cs_MicroappProtocol.h>
#include <microapp/cs_MicroappStorage.h>
#include <protocol/cs_ErrorCodes.h>
#include <storage/cs_State.h>
#include <storage/cs_StateData.h>
#include <util/cs_BleError.h>
#include <util/cs_Error.h>
#include <util/cs_Hash.h>
#include <util/cs_Utils.h>
void fs_evt_handler_sched(void *data, uint16_t size) {
nrf_fstorage_evt_t * evt = (nrf_fstorage_evt_t*) data;
MicroappStorage::getInstance().handleFileStorageEvent(evt);
}
static void fs_evt_handler(nrf_fstorage_evt_t * p_evt) {
uint32_t retVal = app_sched_event_put(p_evt, sizeof(*p_evt), fs_evt_handler_sched);
APP_ERROR_CHECK(retVal);
}
NRF_FSTORAGE_DEF(nrf_fstorage_t microapp_storage) =
{
.evt_handler = fs_evt_handler,
.start_addr = g_FLASH_MICROAPP_BASE,
.end_addr = g_FLASH_MICROAPP_BASE + (0x1000*(g_FLASH_MICROAPP_PAGES)) - 1,
};
MicroappStorage::MicroappStorage() { //: EventListener() {
// EventDispatcher::getInstance().addListener(this);
_prevMessage.protocol = 0;
_prevMessage.app_id = 0;
_prevMessage.payload = 0;
_prevMessage.repeat = 0;
_enabled = false;
_debug = true;
}
uint16_t MicroappStorage::init() {
_buffer = new uint8_t[MICROAPP_CHUNK_SIZE];
uint32_t err_code;
err_code = nrf_fstorage_init(µapp_storage, &nrf_fstorage_sd, NULL);
switch(err_code) {
case NRF_SUCCESS:
LOGi("Sucessfully initialized from 0x%08X to 0x%08X", microapp_storage.start_addr, microapp_storage.end_addr);
break;
default:
LOGw("Error code %i", err_code);
break;
}
return err_code;
}
uint16_t MicroappStorage::erasePages() {
uint32_t err_code;
err_code = nrf_fstorage_erase(µapp_storage, microapp_storage.start_addr, g_FLASH_MICROAPP_PAGES, NULL);
return err_code;
}
uint16_t MicroappStorage::checkAppSize(uint16_t size) {
uint32_t start = microapp_storage.start_addr;
if ((start + size) > microapp_storage.end_addr) {
LOGw("Microapp binary too large. Application can not be written");
return ERR_NO_SPACE;
}
return ERR_SUCCESS;
}
/**
* We assume that the checksum of the particular chunk is already performed. It would be a waste to send an event with
* incorrect checksum. If other sources for microapp code (e.g. UART) are added, the checksum should also be checked
* early in the process. We also assume that all data buffers are of size MICROAPP_CHUNK_SIZE. The last one should be
* appended with 0xFF values to make it the right size.
*/
uint16_t MicroappStorage::writeChunk(uint8_t index, const uint8_t *data, uint16_t size) {
uint32_t err_code;
uint32_t start = microapp_storage.start_addr + (MICROAPP_CHUNK_SIZE * index);
LOGi("Write chunk: %i at 0x%08X of size %i", index, start, size);
LOGi("Start with data [%02X,%02X,%02X]", data[0], data[1], data[2]);
// check chunk size
if ((start + size) > microapp_storage.end_addr) {
LOGw("Microapp binary too large. Chunk not written");
return ERR_NO_SPACE;
}
// Make a copy of the data object
memcpy(_buffer, data, size);
err_code = nrf_fstorage_write(µapp_storage, start, _buffer, size, NULL);
switch(err_code) {
case NRF_ERROR_NULL:
LOGw("Error code %i, NRF_ERROR_NULL", err_code);
break;
case NRF_ERROR_INVALID_STATE:
LOGw("Error code %i, NRF_ERROR_INVALID_STATE", err_code);
break;
case NRF_ERROR_INVALID_LENGTH:
LOGw("Error code %i, NRF_ERROR_INVALID_LENGTH", err_code);
LOGw(" start %i, data [%02X,%02X,%02X], size, %i", start, data[0], data[1], data[2], size);
break;
case NRF_ERROR_INVALID_ADDR:
LOGw("Error code %i, NRF_ERROR_INVALID_ADDR", err_code);
LOGw(" at 0x%08X (start at 0x%08X)", start, microapp_storage.start_addr);
LOGw(" is 0x%08X word-aligned as well?", data);
break;
case NRF_ERROR_NO_MEM:
LOGw("Error code %i, NRF_ERROR_NO_MEM", err_code);
break;
case NRF_SUCCESS:
LOGi("Sucessfully written");
break;
}
return err_code;
}
/**
* For now only allow one app.
*/
void MicroappStorage::storeAppMetadata(uint8_t id, uint16_t checksum, uint16_t size) {
LOGi("Store app %i, checksum %i, size %i, start address %x", id, checksum, size, microapp_storage.start_addr);
TYPIFY(STATE_MICROAPP) state_microapp;
state_microapp.start_addr = microapp_storage.start_addr;
state_microapp.size = size;
state_microapp.checksum = checksum;
state_microapp.id = id;
state_microapp.validation = static_cast<uint8_t>(CS_MICROAPP_VALIDATION_NONE);
cs_state_data_t data(CS_TYPE::STATE_MICROAPP, id, (uint8_t*)&state_microapp, sizeof(state_microapp));
uint32_t err_code = State::getInstance().set(data);
if (err_code != ERR_SUCCESS) {
LOGi("Error: remove state microapp");
Storage::getInstance().remove(CS_TYPE::STATE_MICROAPP);
}
}
/**
* Validate a chunk of data given a checksum to compare with.
*/
uint16_t MicroappStorage::validateChunk(const uint8_t * const data, uint16_t size, uint16_t compare) {
uint32_t checksum = 0;
checksum = Fletcher(data, size, checksum);
LOGi("Chunk checksum %04X (versus %04X)", (uint16_t)checksum, compare);
if ((uint16_t)checksum == compare) {
return ERR_SUCCESS;
} else {
return ERR_INVALID_MESSAGE;
}
}
/**
* This function validates the app in flash. It can only be used when the state is written and all flash operations
* have finished. Only use it when all chunks, also the last chunk has been written successfully.
*
* The checksum is calculated iteratively, by using the chunk size. For the last chunk we will only use the part
* up to the total size of the binary. By doing it iteratively we can keep the local buffer relatively small.
*/
uint16_t MicroappStorage::validateApp() {
TYPIFY(STATE_MICROAPP) state_microapp;
cs_state_id_t id = 0;
cs_state_data_t data(CS_TYPE::STATE_MICROAPP, id, (uint8_t*)&state_microapp, sizeof(state_microapp));
State::getInstance().get(data);
uint8_t buf[MICROAPP_CHUNK_SIZE];
// read from flash with fstorage, calculate checksum
uint8_t count = state_microapp.size / MICROAPP_CHUNK_SIZE;
uint16_t remain = state_microapp.size - (count * MICROAPP_CHUNK_SIZE);
uint32_t checksum_iterative = 0;
uint32_t addr = microapp_storage.start_addr;
for (int i = 0; i < count; ++i) {
nrf_fstorage_read(µapp_storage, addr, &buf, MICROAPP_CHUNK_SIZE);
checksum_iterative = Fletcher(buf, MICROAPP_CHUNK_SIZE, checksum_iterative);
addr += MICROAPP_CHUNK_SIZE;
}
// last chunk of alternative size
if (remain) {
nrf_fstorage_read(µapp_storage, addr, &buf, remain);
checksum_iterative = Fletcher(buf, remain, checksum_iterative);
}
uint16_t checksum = (uint16_t)checksum_iterative;
// compare checksum
if (state_microapp.checksum != checksum) {
LOGw("Microapp %i has checksum 0x%04X, but calculation shows 0x%04X", state_microapp.id,
state_microapp.checksum, checksum);
return ERR_INVALID_MESSAGE;
}
LOGi("Yes, microapp %i has proper checksum", state_microapp.id);
return ERR_SUCCESS;
}
/**
* Set the app to be "valid". This is normally done after the checksum has been checked and considered correct.
* This information is written to flash.
*/
void MicroappStorage::setAppValid() {
TYPIFY(STATE_MICROAPP) state_microapp;
cs_state_id_t app_id = 0;
cs_state_data_t data(CS_TYPE::STATE_MICROAPP, app_id, (uint8_t*)&state_microapp, sizeof(state_microapp));
State::getInstance().get(data);
// write validation = VALIDATION_CHECKSUM to fds record
state_microapp.validation = static_cast<uint8_t>(CS_MICROAPP_VALIDATION_CHECKSUM);
State::getInstance().set(data);
}
/**
* Get if the app is actually valid. If not available from memory it will be obtained from flash.
*/
bool MicroappStorage::isAppValid() {
TYPIFY(STATE_MICROAPP) state_microapp;
cs_state_id_t app_id = 0;
cs_state_data_t data(CS_TYPE::STATE_MICROAPP, app_id, (uint8_t*)&state_microapp, sizeof(state_microapp));
State::getInstance().get(data);
return (state_microapp.validation == static_cast<uint8_t>(CS_MICROAPP_VALIDATION_CHECKSUM));
}
/**
* After an app has been considered "valid" it is possible to enable it. It is also possible to disable an app
* afterwards (without invalidating it). The app can be enabled later on again.
*/
uint16_t MicroappStorage::enableApp(bool flag) {
TYPIFY(STATE_MICROAPP) state_microapp;
cs_state_id_t app_id = 0;
cs_state_data_t data(CS_TYPE::STATE_MICROAPP, app_id, (uint8_t*)&state_microapp, sizeof(state_microapp));
State::getInstance().get(data);
if (state_microapp.validation >= static_cast<uint8_t>(CS_MICROAPP_VALIDATION_CHECKSUM)) {
if (flag) {
state_microapp.validation = static_cast<uint8_t>(CS_MICROAPP_VALIDATION_ENABLED);
_enabled = true;
} else {
state_microapp.validation = static_cast<uint8_t>(CS_MICROAPP_VALIDATION_DISABLED);
_enabled = false;
}
} else {
// Not allowed to enable/disable app that did not pass checksum valid state.
return ERR_INVALID_MESSAGE;
}
State::getInstance().set(data);
return ERR_SUCCESS;
}
/**
* Check if an app is enabled.
*/
bool MicroappStorage::isEnabled() {
TYPIFY(STATE_MICROAPP) state_microapp;
cs_state_id_t app_id = 0;
cs_state_data_t data(CS_TYPE::STATE_MICROAPP, app_id, (uint8_t*)&state_microapp, sizeof(state_microapp));
State::getInstance().get(data);
return (state_microapp.validation == static_cast<uint8_t>(CS_MICROAPP_VALIDATION_ENABLED));
}
/**
* Return result of fstorage operation to sender. We only send this event after fstorage returns to pace the
* incoming messages. In this way it is also possible to resend a particular chunk.
*/
void MicroappStorage::handleFileStorageEvent(nrf_fstorage_evt_t *evt) {
uint16_t error;
if (evt->result != NRF_SUCCESS) {
LOGe("Flash error");
error = ERR_UNSPECIFIED;
} else {
LOGi("Flash event successful");
error = ERR_SUCCESS;
}
switch (evt->id) {
case NRF_FSTORAGE_EVT_WRITE_RESULT: {
LOGi("Flash written");
_prevMessage.repeat = number_of_notifications;
_prevMessage.error = error;
event_t event(CS_TYPE::EVT_MICROAPP, &_prevMessage, sizeof(_prevMessage));
event.dispatch();
break;
}
case NRF_FSTORAGE_EVT_ERASE_RESULT: {
LOGi("Flash erased");
break;
}
default:
break;
}
}
| 33.75 | 118 | 0.751092 | [
"object"
] |
cfe92144f5fcdbdd5756d433c328f22f8d2275dd | 1,798 | cpp | C++ | src/tools.cpp | ChenKuanSun/CarND-Extended-Kalman-Filter | 33363a355823c285588a2385f133ddbeeb6df49d | [
"MIT"
] | null | null | null | src/tools.cpp | ChenKuanSun/CarND-Extended-Kalman-Filter | 33363a355823c285588a2385f133ddbeeb6df49d | [
"MIT"
] | null | null | null | src/tools.cpp | ChenKuanSun/CarND-Extended-Kalman-Filter | 33363a355823c285588a2385f133ddbeeb6df49d | [
"MIT"
] | null | null | null | #include <iostream>
#include "tools.h"
using Eigen::VectorXd;
using Eigen::MatrixXd;
using std::vector;
//initialize paramater
Tools::Tools() {}
Tools::~Tools() {}
VectorXd Tools::CalculateRMSE(const vector<VectorXd> &estimations,
const vector<VectorXd> &ground_truth) {
/**
TODO:
* Calculate the RMSE here.
*/
VectorXd rmse(4);
rmse << 0, 0, 0, 0;
if (estimations.size() == 0) {
cout << "ERROR - The estimations vector is empty!" << endl;
return rmse;
if (estimations.size() == 0)
cout << "ERROR - The estimations vector is empty!" << endl;
return rmse;
}
if (ground_truth.size() == 0) {
cout << "ERROR - The ground-truth vector is empty!" << endl;
return rmse;
}
float t = estimations.size();
if (t != ground_truth.size()) {
cout << "ERROR - The ground-truth and estimations vectors must have the same size!" << endl;
return rmse;
}
for (float i = 0; i < estimations.size(); ++i) {
VectorXd dif = estimations[i] - ground_truth[i];
dif = dif.array() * dif.array();
rmse += dif;
}
rmse /= t;
rmse = rmse.array().sqrt();;
return rmse;
}
MatrixXd Tools::CalculateJacobian(const VectorXd& x_state) {
/**
TODO:
* Calculate a Jacobian here.
*/
MatrixXd Hj(3, 4);
if (x_state.size() != 4) {
cout << "ERROR - The state vector must size 4!" << endl;
return Hj;
}
float px = x_state(0);
float py = x_state(1);
float vx = x_state(2);
float vy = x_state(3);
//Calculate the Jacobian
float rho = px * px + py * py;
float rho2 = sqrt(rho); //sqrtrho
float rho3 = rho2 * rho;//sqrt rho * rho
//4*3
Hj << px / rho2, py / rho2, 0, 0,
-py / rho, px / rho, 0, 0,
py*(vx*py - vy * px) / rho3, px*(vy*px - vx * py) / rho3, px / rho2, py / rho2;
return Hj;
}
| 22.475 | 94 | 0.5901 | [
"vector"
] |
cff6c6b539ce97723b22717ec5d4a86d5d8718a4 | 21,795 | cc | C++ | src/MapsMesh.cc | 45degree/MAPS | aa2aacdda97ab67cc3e80aca3251000eed49d1e3 | [
"MIT"
] | null | null | null | src/MapsMesh.cc | 45degree/MAPS | aa2aacdda97ab67cc3e80aca3251000eed49d1e3 | [
"MIT"
] | null | null | null | src/MapsMesh.cc | 45degree/MAPS | aa2aacdda97ab67cc3e80aca3251000eed49d1e3 | [
"MIT"
] | null | null | null | #include "MapsMesh.h"
#include <igl/gaussian_curvature.h>
#include <poly2tri.h>
#include <tbb/tbb.h>
#include <Eigen/Dense>
#include <algorithm>
#include <limits>
#include <progressbar/progressbar.hpp>
namespace Maps {
template <class Mesh>
static void OpenMesh2IGL(const Mesh *mesh, Eigen::MatrixX3d &V, Eigen::MatrixX3i &F) {
assert(mesh->is_trimesh());
auto verticesCount = std::distance(mesh->vertices_sbegin(), mesh->vertices_end());
auto facesCount = std::distance(mesh->faces_sbegin(), mesh->faces_end());
V.resize(verticesCount, 3);
F.resize(facesCount, 3);
std::map<typename Mesh::VertexHandle, int> newVertexHandleMap;
int j = 0;
for (auto i = mesh->vertices_sbegin(); i != mesh->vertices_end(); i++, j++) {
auto p = mesh->point(*i);
V(j, 0) = p[0];
V(j, 1) = p[1];
V(j, 2) = p[2];
newVertexHandleMap[*i] = j;
}
j = 0;
for (auto i = mesh->faces_sbegin(); i != mesh->faces_end(); i++, j++) {
auto fh = *i;
int vi = 0;
for (typename Mesh::ConstFaceVertexCCWIter fvi = mesh->cfv_ccwbegin(fh);
vi < 3 && fvi != mesh->cfv_ccwend(fh); ++fvi) {
F(j, vi) = newVertexHandleMap[*fvi];
vi++;
}
}
}
int MapMesh::CDTTrangle(const Coordinate2DPair &coordinates,
std::vector<std::array<VertexHandle, 3>> &faces,
BaryCoor &barycentricCoordinates) {
faces.clear();
std::vector<p2t::Point *> points(coordinates.size());
for (int i = 0; i < coordinates.size(); i++) {
double x = coordinates[i].second[0];
double y = coordinates[i].second[1];
points[i] = new p2t::Point(x, y);
}
p2t::CDT cdt(points);
try {
cdt.Triangulate();
} catch (const std::runtime_error &exception) {
std::cout << exception.what() << std::endl;
throw exception;
}
auto triangles = cdt.GetTriangles();
if (!p2t::IsDelaunay(triangles)) {
return -1;
}
int trangleIdx = -1;
for (int j = 0; j < triangles.size(); j++) {
auto &triangle = triangles[j];
std::array<Point2D, 3> triangle2D;
triangle2D[0] = Point2D(triangle->GetPoint(0)->x, triangle->GetPoint(0)->y);
triangle2D[1] = Point2D(triangle->GetPoint(1)->x, triangle->GetPoint(1)->y);
triangle2D[2] = Point2D(triangle->GetPoint(2)->x, triangle->GetPoint(2)->y);
std::array<VertexHandle, 3> face;
for (int i = 0; i < 3; i++) {
auto position = std::find(points.begin(), points.end(), triangle->GetPoint(i));
if (position == points.end()) return -1;
face[i] = coordinates[position - points.begin()].first;
}
faces.push_back(face);
/**
* 计算原点的重心坐标
*/
if (!IsInTriangle(Point2D(0, 0), triangle2D)) continue;
auto [alpha, beta, gamma] = CalculateBaryCoor(Point2D(0, 0), triangle2D);
barycentricCoordinates[0] = std::make_pair(face[0], alpha);
barycentricCoordinates[1] = std::make_pair(face[1], beta);
barycentricCoordinates[2] = std::make_pair(face[2], gamma);
trangleIdx = j;
}
for (auto &point : points) {
delete point;
}
return trangleIdx;
}
int MapMesh::MVTTrangle(const Coordinate2DPair &coordinates, int startIdx,
std::vector<std::array<VertexHandle, 3>> &faces,
BaryCoor &barycentricCoordinates) {
faces.clear();
int trangleIdx = -1;
for (size_t i = 0, ii = 1; i < coordinates.size(); i++, ii++, ii %= coordinates.size()) {
if (i == startIdx || ii == startIdx) continue;
std::array<VertexHandle, 3> face(
{coordinates[i].first, coordinates[ii].first, coordinates[startIdx].first});
faces.push_back(face);
std::array<Point2D, 3> triangle;
triangle[0] = coordinates[startIdx].second;
triangle[1] = coordinates[i].second;
triangle[2] = coordinates[ii].second;
/**
* 计算原点的重心坐标
*/
if (!IsInTriangle(Point2D(0, 0), triangle)) continue;
auto [alpha, beta, gamma] = CalculateBaryCoor(Point2D(0, 0), triangle);
barycentricCoordinates[0] = std::make_pair(coordinates[startIdx].first, alpha);
barycentricCoordinates[1] = std::make_pair(coordinates[i].first, beta);
barycentricCoordinates[2] = std::make_pair(coordinates[ii].first, gamma);
trangleIdx = static_cast<int>(faces.size() - 1);
}
return trangleIdx;
}
std::optional<MapMesh::Point2D> MapMesh::ReCalculate2DCoordinates(
std::map<VertexHandle, Point2D> &originCoor, VertexHandle deleteVertex) const {
if (!IsVertexDeleted(deleteVertex)) return std::nullopt;
auto baryCoor = data(deleteVertex).baryCoor.value();
return originCoor[baryCoor[0].first] * baryCoor[0].second +
originCoor[baryCoor[1].first] * baryCoor[1].second +
originCoor[baryCoor[2].first] * baryCoor[2].second;
}
void MapMesh::ReTrangleAndAddFace(const VertexHandle &deleteVertex) {
// 记录1领域面中所有包含的点, 并更新这些点的参数
// 假设1领域面f上记录了一个点v, v中记录了v在f上的重心坐标(a, b, c), 面f在经过2维映射变成了f'
// 更新过程: 1. 根据f'和(a, b, c)计算v的二维映射点v'
// 2. 重新计算包含v'的三角形p‘, 并根据p’重新计算坐标(a', b', c')
// 3. 删除f, 添加面p, 更新v的重心坐标, 建立p与v的关联
std::vector<FaceHandle> ringFaces(vf_begin(deleteVertex), vf_end(deleteVertex));
Coordinate2DPair coordinates;
Calculate2D(deleteVertex, coordinates);
// 重新计算1领域面上所有包含的点的二维坐标
std::map<VertexHandle, Point2D> currentPoint2DMap(coordinates.begin(), coordinates.end());
std::map<VertexHandle, Point2D> deletePoint2DMap;
for (auto &face : ringFaces) {
for (auto &vertex : data(face).vertrices) {
auto newCoor = ReCalculate2DCoordinates(currentPoint2DMap, vertex);
if (!newCoor.has_value()) break;
deletePoint2DMap[vertex] = newCoor.value();
}
}
delete_vertex(deleteVertex, false);
BaryCoor barycentricCoordinates;
std::vector<std::array<VertexHandle, 3>> newFaces;
int trangleIdx = CDTTrangle(coordinates, newFaces, barycentricCoordinates);
std::vector<FaceHandle> facesHandle;
if (trangleIdx != -1 && TryToAddFaces(newFaces, facesHandle)) {
data(facesHandle[trangleIdx]).vertrices.push_back(deleteVertex);
data(deleteVertex).baryCoor = barycentricCoordinates;
// 判断被删除的点在那个三角形内部, 并计算重心坐标
for (auto &[vertex, point2D] : deletePoint2DMap) {
auto newParma = UpdateParam(newFaces, currentPoint2DMap, point2D);
if (!newParma.has_value()) continue;
auto [idx, alpha, beta, gamma] = newParma.value();
data(facesHandle[idx]).vertrices.push_back(vertex);
BaryCoor baryCoor;
baryCoor[0].first = newFaces[idx][0], baryCoor[0].second = alpha;
baryCoor[1].first = newFaces[idx][1], baryCoor[1].second = beta;
baryCoor[2].first = newFaces[idx][2], baryCoor[2].second = gamma;
data(vertex).baryCoor = baryCoor;
}
return;
}
for (int i = 0; i < coordinates.size(); i++) {
newFaces.clear();
trangleIdx = MVTTrangle(coordinates, i, newFaces, barycentricCoordinates);
if (TryToAddFaces(newFaces, facesHandle)) {
data(facesHandle[trangleIdx]).vertrices.push_back(deleteVertex);
data(deleteVertex).baryCoor = barycentricCoordinates;
for (auto &[vertex, point2D] : deletePoint2DMap) {
auto newParma = UpdateParam(newFaces, currentPoint2DMap, point2D);
if (!newParma.has_value()) continue;
auto [idx, alpha, beta, gamma] = newParma.value();
data(facesHandle[idx]).vertrices.push_back(vertex);
BaryCoor baryCoor;
baryCoor[0].first = newFaces[idx][0], baryCoor[0].second = alpha;
baryCoor[1].first = newFaces[idx][1], baryCoor[1].second = beta;
baryCoor[2].first = newFaces[idx][2], baryCoor[2].second = gamma;
data(vertex).baryCoor = baryCoor;
}
return;
}
}
throw std::runtime_error("can't add face");
}
void MapMesh::Initialize() {
originFaces = std::vector<FaceHandle>(faces_sbegin(), faces_end());
for (const auto &face : originFaces) {
originFaceVertices[face] = std::vector<VertexHandle>(fv_begin(face), fv_end(face));
}
}
void MapMesh::CalculateCurvature() {
Eigen::MatrixX3d V;
Eigen::MatrixX3i F;
Eigen::VectorXd K;
OpenMesh2IGL(this, V, F);
igl::gaussian_curvature(V, F, K);
int j = 0;
maxCurvature = (std::numeric_limits<double>::min)();
for (auto i = vertices_sbegin(); i != vertices_end(); i++, j++) {
data(*i).curvature = K[j];
if (K[j] > maxCurvature) {
maxCurvature = K[j];
}
}
}
void MapMesh::CalculateWeight(double lambda) {
while (!curvatureQueue.empty()) {
curvatureQueue.pop();
}
for (auto i = vertices_sbegin(); i != vertices_end(); i++) {
data(*i).weight = lambda * data(*i).curvature / maxCurvature +
(1 - lambda) * data(*i).ringArea / maxRingArea;
curvatureQueue.push(*i);
}
}
void MapMesh::CalculateAreas() {
maxRingArea = (std::numeric_limits<double>::min)();
for (auto faceIter = faces_sbegin(); faceIter != faces_end(); faceIter++) {
double area = CalculateArea(*faceIter);
data(*faceIter).area = area;
}
for (auto vertexIter = vertices_sbegin(); vertexIter != vertices_end(); vertexIter++) {
double ringArea = 0;
for (auto faceIter = vf_begin(*vertexIter); faceIter != vf_end(*vertexIter); faceIter++) {
ringArea += data(*faceIter).area;
}
if (ringArea > maxRingArea) {
maxRingArea = ringArea;
}
data(*vertexIter).ringArea = ringArea;
}
}
void MapMesh::MapFaceFromOriginMesh(const FaceHandle &face, std::array<Point, 3> &mapFace) const {
if (originFaceVertices.find(face) == originFaceVertices.end()) return;
const std::vector<VertexHandle> &vertices = originFaceVertices.at(face);
assert(vertices.size() == 3);
for (int i = 0; i < 3; i++) {
auto vertexHandle = vertices[i];
if (!IsVertexDeleted(vertexHandle)) {
mapFace[i] = point(vertexHandle);
continue;
}
auto baryCoor = data(vertexHandle).baryCoor.value();
mapFace[i] = point(baryCoor[0].first) * baryCoor[0].second +
point(baryCoor[1].first) * baryCoor[1].second +
point(baryCoor[2].first) * baryCoor[2].second;
}
}
void MapMesh::FaceSubDivision() {
std::vector<FaceHandle> originFaceHandle(faces_sbegin(), faces_end());
for (const auto &faceHandle : originFaceHandle) {
std::vector<VertexHandle> vertices(fv_begin(faceHandle), fv_end(faceHandle));
assert(vertices.size() == 3);
for (int i = 0, ii = 1; i < 3; i++, ii++, ii %= 3) {
auto newPoint = (point(vertices[i]) + point(vertices[ii])) / 2.0;
auto newPointHandle = add_vertex(newPoint);
data(newPointHandle).isNew = true;
vertices.push_back(newPointHandle);
}
delete_face(faceHandle);
add_face({vertices[0], vertices[3], vertices[5]});
add_face({vertices[3], vertices[1], vertices[4]});
add_face({vertices[5], vertices[4], vertices[2]});
add_face({vertices[3], vertices[4], vertices[5]});
}
}
void MapMesh::DownSampling() {
request_face_status();
request_vertex_status();
request_edge_status();
for (auto vertexIter = vertices_sbegin(); vertexIter != vertices_end(); vertexIter++) {
data(*vertexIter).canBeDeleted = true;
}
CalculateCurvature();
CalculateAreas();
CalculateWeight(0.5);
while (!curvatureQueue.empty()) {
auto vertexHandle = curvatureQueue.top();
curvatureQueue.pop();
if (!data(vertexHandle).canBeDeleted) continue;
for (auto ringVertex = vv_begin(vertexHandle); ringVertex != vv_end(vertexHandle);
ringVertex++) {
data(*ringVertex).canBeDeleted = false;
}
ReTrangleAndAddFace(vertexHandle);
}
SaveBaseLevelMesh();
}
void MapMesh::Remesh() {
int N = static_cast<int>(std::distance(vertices_sbegin(), vertices_end()));
progressbar bar(N);
std::mutex _mutex;
auto IsMapedInASingleFace = [&](const FaceHandle &faceHandle) -> bool {
std::set<VertexHandle> verticesHandle;
for (const auto &vertexHandle : originFaceVertices[faceHandle]) {
if (data(vertexHandle).baryCoor.has_value()) {
auto baryCoor = data(vertexHandle).baryCoor.value();
verticesHandle.insert(baryCoor[0].first);
verticesHandle.insert(baryCoor[1].first);
verticesHandle.insert(baryCoor[2].first);
} else {
verticesHandle.insert(vertexHandle);
}
}
return verticesHandle.size() == 3;
};
auto findMaxCommonVertex = [&](const std::vector<FaceHandle> &facesHandle) {
std::multiset<VertexHandle> verticesHandle;
for (const auto &faceHandle : facesHandle) {
for (const auto &vertexHandle : baseLevelMesh->fv_range(faceHandle)) {
verticesHandle.insert(vertexHandle);
}
}
VertexHandle maxCommonVertex;
int maxCount = -1;
for (const auto &vertex : verticesHandle) {
int count = static_cast<int>(verticesHandle.count(vertex));
if (count > maxCount) {
maxCount = static_cast<int>(verticesHandle.count(vertex));
maxCommonVertex = vertex;
}
}
return maxCommonVertex;
};
auto isRingFace = [&](const VertexHandle &vertexHandle, const FaceHandle &faceHandle) {
for (const auto &face : baseLevelMesh->vf_range(vertexHandle)) {
if (face == faceHandle) return true;
}
return false;
};
auto isRingPoint =
[&](const VertexHandle &vertexHandle, const std::vector<VertexHandle> &ringVertices) {
for (const auto &ringVertex : ringVertices) {
bool found = false;
for (const auto &realRingVertex : baseLevelMesh->vv_range(vertexHandle)) {
if (realRingVertex == ringVertex) {
found = true;
}
}
if (!found) return false;
}
return true;
};
oneapi::tbb::parallel_for_each(vertices_sbegin(), vertices_end(),
[&](const VertexHandle &vertex) {
if (!data(vertex).isNew) {
_mutex.lock();
bar.update();
_mutex.unlock();
/* continue; */
return;
}
// 在基面上找到公共顶点,并展开到2维平面计算重心坐标
auto vertexFaceOption = baseLevelMesh->FindFace(point(vertex));
if (!vertexFaceOption.has_value()) {
_mutex.lock();
bar.update();
_mutex.unlock();
/* continue; */
return;
}
auto vertexFace = vertexFaceOption.value();
for (const auto &face : originFaces) {
std::array<Point, 3> mapFace;
const std::vector<VertexHandle> &fv = originFaceVertices[face];
if (IsMapedInASingleFace(face)) { // 原面能够完全映射到基面上
MapFaceFromOriginMesh(face, mapFace);
if (IsInTriangle(point(vertex), mapFace)) {
auto [alpha, beta, gamma] = CalculateBaryCoor(point(vertex), mapFace);
Point newPoint =
alpha * point(fv[0]) + beta * point(fv[1]) + gamma * point(fv[2]);
point(vertex) = newPoint;
break;
}
} else {
std::vector<FaceHandle> baseFaces;
std::vector<VertexHandle> fixVertex;
for (const auto &vertexHandle : fv) {
if (!IsVertexDeleted(vertexHandle)) {
fixVertex.push_back(vertexHandle);
continue;
}
auto baryCoor = data(vertexHandle).baryCoor.value();
auto face = baseLevelMesh->FindFace(
{baryCoor[0].first, baryCoor[1].first, baryCoor[2].first});
if (face.has_value()) {
baseFaces.push_back(face.value());
}
}
VertexHandle commonVertex;
if (baseFaces.size() == 3) {
if (std::find(baseFaces.begin(), baseFaces.end(), vertexFace) ==
baseFaces.end()) {
continue;
}
commonVertex = findMaxCommonVertex(baseFaces);
} else {
bool foundCommonVertex = false;
for (const auto &baseFace : baseFaces) {
for (const auto &baseVert : baseLevelMesh->fv_range(baseFace)) {
if (isRingFace(baseVert, vertexFace) &&
isRingPoint(baseVert, fixVertex)) {
commonVertex = baseVert;
foundCommonVertex = true;
break;
}
}
if (foundCommonVertex) break;
}
if (!foundCommonVertex) continue;
}
Coordinate2DPair coorPair;
baseLevelMesh->Calculate2D(commonVertex, coorPair);
Coordinate2DMap coorMap(coorPair.begin(), coorPair.end());
Point2D vertex2D(0, 0);
auto vertex2DBaryCoor = baseLevelMesh->CalculateBaryCoor(point(vertex), vertexFace);
for (const auto &vertex2DBaryCoorItem : vertex2DBaryCoor) {
if (coorMap.find(vertex2DBaryCoorItem.first) == coorMap.end()) {
continue;
}
vertex2D +=
coorMap.at(vertex2DBaryCoorItem.first) * vertex2DBaryCoorItem.second;
}
std::array<std::pair<VertexHandle, Point2D>, 3> face2D;
bool canMapTo2D = true;
for (int i = 0; i < 3; i++) {
face2D[i].first = fv[i];
face2D[i].second = Point2D(0, 0);
if (!IsVertexDeleted(fv[i])) {
face2D[i].second = coorMap[fv[i]];
continue;
}
auto baryCoor = data(fv[i]).baryCoor.value();
for (const auto &baryCoorItem : baryCoor) {
if (baryCoorItem.first == commonVertex) continue;
if (coorMap.find(baryCoorItem.first) == coorMap.end()) {
canMapTo2D = false;
break;
/* throw std::runtime_error("can't found item"); */
}
face2D[i].second += coorMap.at(baryCoorItem.first) * baryCoorItem.second;
}
}
if (!canMapTo2D) continue;
std::array<Point2D, 3> triangle{face2D[0].second, face2D[1].second,
face2D[2].second};
if (!IsInTriangle(vertex2D, triangle)) continue;
auto [alpha, beta, gamma] = CalculateBaryCoor(vertex2D, triangle);
point(vertex) = alpha * point(face2D[0].first) + beta * point(face2D[1].first) +
gamma * point(face2D[2].first);
break;
}
}
_mutex.lock();
bar.update();
_mutex.unlock();
});
}
std::optional<std::tuple<int, double, double, double>> MapMesh::UpdateParam(
const std::vector<std::array<VertexHandle, 3>> &faces,
const std::map<VertexHandle, Point2D> &point2DMap, const Point2D &point) {
for (int i = 0; i < faces.size(); i++) {
const auto &face = faces[i];
std::array<Point2D, 3> triangle;
triangle[0] = point2DMap.at(face[0]);
triangle[1] = point2DMap.at(face[1]);
triangle[2] = point2DMap.at(face[2]);
if (!IsInTriangle(point, triangle)) continue;
auto [alpha, beta, gamma] = CalculateBaryCoor(point, triangle);
return std::make_tuple(i, alpha, beta, gamma);
}
return std::nullopt;
}
void MapMesh::Calculate2D(VertexHandle vertex, Coordinate2DPair &coordinates) const {
coordinates.clear();
auto vertex3D = point(vertex);
double K_i = 0;
for (const auto &face : vf_range(vertex)) {
K_i += CalculateAngle(vertex, face);
}
double a = 2 * M_PI / K_i;
K_i = 0;
VertexHandle lastVertex;
int i = 0;
for (const auto &ringPoint : vv_range(vertex)) {
if (i != 0) {
auto Vec1 = point(lastVertex) - point(vertex);
auto Vec2 = point(ringPoint) - point(vertex);
K_i += std::acos(Vec1.normalized().dot(Vec2.normalized()));
}
auto point3D = point(ringPoint);
double r_k = (point3D - vertex3D).norm();
Point2D point2D{std::pow(r_k, a) * std::cos(K_i * a), std::pow(r_k, a) * std::sin(K_i * a)};
coordinates.emplace_back(ringPoint, point2D);
lastVertex = ringPoint;
i++;
}
}
} // namespace Maps
| 36.204319 | 100 | 0.560633 | [
"mesh",
"vector"
] |
cffbe54c78e5c439b26405a670651ecdadade0f1 | 1,624 | cpp | C++ | 51.cpp | pengzhezhe/LeetCode | 305ec0c5b4cb5ea7cd244b3308132dee778138bc | [
"Apache-2.0"
] | null | null | null | 51.cpp | pengzhezhe/LeetCode | 305ec0c5b4cb5ea7cd244b3308132dee778138bc | [
"Apache-2.0"
] | null | null | null | 51.cpp | pengzhezhe/LeetCode | 305ec0c5b4cb5ea7cd244b3308132dee778138bc | [
"Apache-2.0"
] | null | null | null | //
// Created by pzz on 2021/12/10.
//
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
class Solution {
private:
vector<vector<string>> result;
vector<string> chessBoard;
void backtracing(int n, int row) {
if (row == n) {
result.push_back(chessBoard);
return;
}
for (int i = 0; i < n; i++) {
if (isValid(row, i, n)) {
chessBoard[row][i] = 'Q';
backtracing(n, row + 1);
chessBoard[row][i] = '.';
}
}
}
bool isValid(int row, int col, int n) {
//Check col
for (int i = 0; i < n; i++) {
if (chessBoard[i][col] == 'Q') {
return false;
}
}
//Check 45
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
if (chessBoard[i][j] == 'Q') {
return false;
}
}
//Check 135
for (int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) {
if (chessBoard[i][j] == 'Q') {
return false;
}
}
return true;
}
public:
vector<vector<string>> solveNQueens(int n) {
chessBoard.insert(chessBoard.begin(), n, string(n, '.'));
backtracing(n, 0);
return result;
}
};
int main() {
Solution solution;
vector<vector<string>> result = solution.solveNQueens(4);
for (const auto &vec: result) {
for (const auto &s: vec) {
cout << s << endl;
}
}
return 0;
} | 22.246575 | 72 | 0.439655 | [
"vector"
] |
321501cb1fc9cd77f3d82ded5ec528787e89f7a6 | 9,426 | cpp | C++ | src/obj_to_ps2icon.cpp | bignaux/ps2iconsys | ec5cdc56d53bcfc7d79277f76c0ed2233da9ff9d | [
"MIT"
] | 10 | 2019-11-29T00:31:18.000Z | 2022-01-29T22:02:34.000Z | src/obj_to_ps2icon.cpp | bignaux/ps2iconsys | ec5cdc56d53bcfc7d79277f76c0ed2233da9ff9d | [
"MIT"
] | 2 | 2021-04-16T23:57:59.000Z | 2021-08-18T21:27:40.000Z | src/obj_to_ps2icon.cpp | bignaux/ps2iconsys | ec5cdc56d53bcfc7d79277f76c0ed2233da9ff9d | [
"MIT"
] | 4 | 2021-04-11T12:42:03.000Z | 2022-02-13T13:22:43.000Z | /**
* @file src/obj_to_ps2icon.cpp
*
* @brief A tool for converting Wavefront OBJ to PS2 Iconsbuild_header/
*/
#include <iostream>
#include "../include/ps2_ps2icon.hpp"
#include "../include/obj_loader.hpp"
#include "../gbLib/include/gbException.hpp"
#include "../gbLib/include/gbImageLoader.hpp"
char const* obj_input_file = NULL; ///< path to the input file
int obj_mesh_index = 0; ///< 0-based index of the mesh to use
char const* ps2_output_file = NULL; ///< path to the output file
char const* texture_input_file = NULL; ///< path to the texture file (tga or bmp)
bool verbose_output = false; ///< flag for verbose output
bool list_obj_file = false; ///< flag for obj content listing
float obj_scale_factor = 0.0f; ///< geometric scale factor for conversion
/** Print a help text on screen
* @param[in] self Name of the executable (e.g. obtained from argv[0])
*/
void PrintHelp(char* self)
{
std::cout << "********************************************************" << "\n"
<< " *** OBJ to PS2Icon Converter V-1.0 ***" << "\n"
<< " ** by Ghulbus Inc. (http://www.ghulbus-inc.de/) **" << "\n"
<< " **************************************************" << "\n"
<< "\n"
<< " Usage: " << self << " [OPTION]..." << "\n"
<< "Build a PS2Icon from a Wavefront OBJ file." << "\n"
<< "\n"
<< " -h, --help display this help" << "\n"
<< " -f, --input-file Wavefront OBJ file used as input" << "\n"
<< " -o, --output-file Name of the destination file" << "\n"
<< " -t, --input-texture Texture file used as input (must be BMP or TGA)" << "\n"
<< " -m, --mesh-index Index of the OBJ mesh to use (0-based)" << "\n"
<< " -s, --scale-factor Scale factor that is applied to geometry" << "\n"
<< " -v, --verbose activate verbose output" << "\n"
<< " -l, --list-obj-file list the meshes contained in input" << "\n"
<< "\n"
<< " Examples:" << "\n"
<< " " << self << " -f foo.obj" << "\n"
<< "Converts the first mesh in file foo.obj to an icon file default.icn" << "\n"
<< "using a default texture." << "\n"
<< "\n"
<< " " << self << " -f foo.obj -m 3 -s 0.5 -t bar.tga -o out.icn" << "\n"
<< "Converts the fourth mesh in file foo.obj to an icon file out.icn" << "\n"
<< "using the image from bar.tga as a texture and scaling the geometry" << "\n"
<< "to half the size before writing." << "\n"
<< "\n"
<< " " << self << " -f foo.obj -l" << "\n"
<< "Prints a list of all meshes in foo.obj. No files are written." << "\n"
<< std::endl;
}
/** Parse the command line arguments and set globals accordingly
* @param[in] argc argc
* @param[in] argv argv
*/
void ParseCommandLine(int argc, char* argv[])
{
for(int i=1; i<argc; i++) {
//Flag parameters:
if( (strcmp( argv[i], "-h" ) == 0) || (strcmp( argv[i], "--help" ) == 0) ) {
PrintHelp(argv[0]);
exit(0);
} else if( (strcmp( argv[i], "-l" ) == 0) || (strcmp( argv[i], "--list-obj-file" ) == 0) ) {
list_obj_file = true;
} else if( (strcmp( argv[i], "-v" ) == 0) || (strcmp( argv[i], "--verbose" ) == 0) ) {
verbose_output = true;
} else if(i < argc-1) {
//Parameters with 1 argument
if( (strcmp( argv[i], "-f" ) == 0) || (strcmp( argv[i], "--input-file" ) == 0) ) {
obj_input_file = argv[++i];
} else if( (strcmp( argv[i], "-t" ) == 0) || (strcmp( argv[i], "--input-texture" ) == 0) ) {
texture_input_file = argv[++i];
} else if( (strcmp( argv[i], "-o" ) == 0) || (strcmp( argv[i], "--output-file" ) == 0) ) {
ps2_output_file = argv[++i];
} else if( (strcmp( argv[i], "-m" ) == 0) || (strcmp( argv[i], "--mesh-index" ) == 0) ) {
obj_mesh_index = atoi(argv[++i]);
} else if( (strcmp( argv[i], "-s" ) == 0) || (strcmp( argv[i], "--scale-factor" ) == 0) ) {
obj_scale_factor = static_cast<float>(atof(argv[++i]));
} else {
std::cout << "Invalid argument." << std::endl << std::endl;
PrintHelp(argv[0]);
exit(1);
}
} else {
std::cout << "Invalid argument." << std::endl << std::endl;
PrintHelp(argv[0]);
exit(1);
}
}
}
/** Load the obj file
*/
OBJ_FileLoader* LoadOBJFile()
{
OBJ_FileLoader* ret = NULL;
if(verbose_output)
std::cout << " * Reading OBJ file \"" << obj_input_file << "\"...";
try {
ret = new OBJ_FileLoader(obj_input_file);
} catch(Ghulbus::gbException e) {
std::cout << "\nFile read error: \"" << obj_input_file << "\"" << std::endl;
exit(1);
}
if(verbose_output)
std::cout << "done." << std::endl;
if(obj_mesh_index >= ret->GetNMeshes()) {
std::cout << "Invalid mesh index. Index given: " << obj_mesh_index << "; Maximum allowed for \""
<< obj_input_file << "\": " << (ret->GetNMeshes() - 1) << std::endl;
exit(1);
}
return ret;
}
/** Print a list of all meshes contained in an obj file
* @param[in] obj_file Working loader to the file to list
*/
void ListOBJFile(OBJ_FileLoader const* obj_file)
{
std::cout << " * Parsing OBJ file \"" << obj_input_file << "\" contents...\n";
std::cout << " ** Found " << obj_file->GetNMeshes() << " meshes: " << std::endl;
for(int i=0; i<obj_file->GetNMeshes(); ++i) {
OBJ_Mesh const* tmp = obj_file->GetMesh(i);
std::cout << " ** #" << i << ": " << tmp->GetName() << " - "
<< tmp->GetNFaces() << " Triangles, " << tmp->GetNVertices() << " Vertices\n";
}
std::cout << " * done." << std::endl;
}
/** Helper function: Is f a path to a BMP file?
*/
bool IsBMP(char const* f)
{
//check for .bmp ending:
int len = static_cast<int>(strlen(f));
if( (f[len-3] == 'B' || f[len-3] == 'b') &&
(f[len-2] == 'M' || f[len-2] == 'm') &&
(f[len-1] == 'P' || f[len-1] == 'p') ) {
GhulbusUtil::gbImageType_BMP_T checker;
std::ifstream tmp(f, std::ios_base::in | std::ios_base::binary);
return checker.CheckFile(tmp);
}
return false;
}
/** Load a texture file
*/
GhulbusUtil::gbImageLoader* LoadTexture()
{
GhulbusUtil::gbImageLoader* ret = NULL;
if(IsBMP(texture_input_file)) {
try {
ret = new GhulbusUtil::gbImageLoader( texture_input_file, GhulbusUtil::gbImageType_BMP() );
} catch( Ghulbus::gbException e ) {
std::cout << "\"" << texture_input_file << "\" is no valid BMP file." << std::endl;
exit(1);
}
} else {
try {
ret = new GhulbusUtil::gbImageLoader( texture_input_file, GhulbusUtil::gbImageType_TGA() );
} catch( Ghulbus::gbException e ) {
std::cout << "\"" << texture_input_file << "\" is no valid TGA file." << std::endl;
exit(1);
}
}
if( (ret->GetWidth() != 128) || (ret->GetHeight() != 128) ) {
std::cout << "Only Textures of size 128x128 allowed! \"" << texture_input_file << "\" has "
<< ret->GetWidth() << "x" << ret->GetHeight() << std::endl;
exit(1);
}
return ret;
}
/** Write a PS2Icon file
*/
void WriteOutputFile(OBJ_FileLoader const* obj_file, GhulbusUtil::gbImageLoader* img_loader)
{
PS2Icon ps2_icon;
if(img_loader) {
if(verbose_output)
std::cout << " * Copying texture data from \"" << texture_input_file << "\"...";
unsigned int* tmp = new unsigned int[img_loader->GetWidth() * img_loader->GetHeight()];
img_loader->FlipV();
img_loader->GetImageData32(tmp);
ps2_icon.SetTextureData(tmp);
delete[] tmp;
if(verbose_output)
std::cout << "done." << std::endl;
}
OBJ_Mesh const* tmp = obj_file->GetMesh(obj_mesh_index);
if(verbose_output)
std::cout << " * Copying geometry data from \"" << obj_input_file << "\": Mesh #" << obj_mesh_index
<< " - " << tmp->GetName() << "...";
if(obj_scale_factor != 0.0f) {
if(verbose_output)
std::cout << "\n Scale factor is " << obj_scale_factor << " ...";
if(obj_scale_factor < 0.0f) {
std::cout << "\n!WARNING! Scale factor is negative.\n ";
}
ps2_icon.SetGeometry(*tmp, obj_scale_factor);
} else {
ps2_icon.SetGeometry(*tmp);
}
if(verbose_output)
std::cout << "done." << std::endl;
if(verbose_output)
std::cout << " * Writing output to \"" << ps2_output_file << "\"...";
try {
ps2_icon.WriteFile(ps2_output_file);
} catch(Ghulbus::gbException e) {
std::cout << "\nError while writing to \"" << ps2_output_file << "\"" << std::endl;
exit(1);
}
if(verbose_output)
std::cout << "done." << std::endl;
}
int main(int argc, char* argv[])
{
ParseCommandLine(argc, argv);
if(!obj_input_file) {
std::cout << "No input file specified." << std::endl << std::endl;
PrintHelp(argv[0]);
exit(1);
}
std::cout << "OBJ to PS2Icon Converter V-1.0\n by Ghulbus Inc. (http://www.ghulbus-inc.de/)\n" << std::endl;
if((!list_obj_file) && (!ps2_output_file)) { ps2_output_file = "default.icn"; }
OBJ_FileLoader* obj_file = LoadOBJFile();
if(list_obj_file) {
ListOBJFile(obj_file);
}
GhulbusUtil::gbImageLoader* img_loader = NULL;
if(texture_input_file) {
img_loader = LoadTexture();
}
if(ps2_output_file) {
WriteOutputFile(obj_file, img_loader);
}
delete img_loader;
delete obj_file;
std::cout << "Success :)" << std::endl;
return 0;
}
| 36.393822 | 111 | 0.549226 | [
"mesh",
"geometry"
] |
321f4378b41a154118d0fd434c666388e11853a3 | 3,098 | cpp | C++ | RaytracerOpencl/host.cpp | sriravic/Raytracer | 7afb24d6a759362902b1c6f8c6ee29d43c179388 | [
"MIT"
] | 1 | 2018-05-16T20:47:21.000Z | 2018-05-16T20:47:21.000Z | RaytracerOpencl/host.cpp | sriravic/Raytracer | 7afb24d6a759362902b1c6f8c6ee29d43c179388 | [
"MIT"
] | null | null | null | RaytracerOpencl/host.cpp | sriravic/Raytracer | 7afb24d6a759362902b1c6f8c6ee29d43c179388 | [
"MIT"
] | null | null | null | #include <iostream>
#include <CL/cl.hpp>
#include <vector>
#include <fstream>
#include <iterator>
#include <string>
#include <memory>
int main(int argc, char** argv) {
std::cout << "OpenCL Raytracer" << std::endl;
std::cout << "Srinath Ravichandran" << std::endl;
// Step1 : initialize and get all available platforms
std::vector<cl::Platform> platforms;
cl::Platform::get(&platforms);
if (platforms.size() == 0) {
std::cout << "Did not find any available opencl platforms" << std::endl;
return -1;
}
// lets us the 1'st platform for now
cl::Platform platform = platforms[0];
std::cout << "Using OpenCL platform : " << platform.getInfo<CL_PLATFORM_NAME>() << std::endl;
// Step2 : Get a device first
std::vector<cl::Device> devices;
platform.getDevices(CL_DEVICE_TYPE_ALL, &devices);
if (devices.size() == 0) {
std::cout << "Did not find any devices" << std::endl;
return -1;
}
// let's use the 1st device
cl::Device device = devices[0];
std::cout << "Using OpenCL device : " << device.getInfo<CL_DEVICE_NAME>() << std::endl;
// Step3 : Create a context
cl::Context context(device);
// Step 4: Create a program
cl::Program::Sources sources;
// Step 5: Compose the opencl program string
std::ifstream inputSrc("raytracer.cl");
std::string srcCode(std::istreambuf_iterator<char>(inputSrc), (std::istreambuf_iterator<char>()));
sources.push_back(std::make_pair(srcCode.c_str(), srcCode.length()));
// Step 6: Create a program
cl::Program program(context, sources);
if (program.build({ device }) != CL_SUCCESS) {
std::cout << "Error building :" << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device) << std::endl;
return -1;
}
// Define the raytracing constants
int nx = 400;
int ny = 200;
int ns = 1;
// Write the output file
std::ofstream outfile("out.ppm");
outfile << "P3\n" << nx << " " << ny << "\n255\n"; // header for the pfm file
// create buffers on the device
cl::Buffer dColorBuffer(context, CL_MEM_READ_WRITE, sizeof(unsigned char) * 3 * nx * ny);
// create a command queue
cl::CommandQueue queue(context, device);
// run the kernel.
cl::Kernel kernel(program, "color");
kernel.setArg(0, dColorBuffer);
kernel.setArg(1, nx);
kernel.setArg(2, ny);
queue.enqueueNDRangeKernel(kernel, cl::NullRange, cl::NDRange(nx * ny), cl::NullRange);
queue.finish();
// get the reults
std::shared_ptr<unsigned char> hColorBuffer(new unsigned char[nx * ny * 3]);
queue.enqueueReadBuffer(dColorBuffer, CL_TRUE, 0, sizeof(unsigned char) * 3 * nx * ny, hColorBuffer.get());
// write the file out
std::cout << "Writing out image file.." << std::endl;
for (int i = 0; i < nx * ny; i++) {
outfile << (int)hColorBuffer.get()[3 * i + 0] << " " <<
(int)hColorBuffer.get()[3 * i + 1] << " " <<
(int)hColorBuffer.get()[3 * i + 2] << "\n";
}
return 0;
} | 34.043956 | 111 | 0.603938 | [
"vector"
] |
3221c3674a987cb451849ebc72b41149a3f097d4 | 931 | cpp | C++ | Dataset/Leetcode/train/56/79.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/train/56/79.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | Dataset/Leetcode/train/56/79.cpp | kkcookies99/UAST | fff81885aa07901786141a71e5600a08d7cb4868 | [
"MIT"
] | null | null | null | class Solution {
public:
vector<vector<int>> XXX(vector<vector<int>>& intervals) {
if(intervals.size()==1){
return intervals;
}
std::sort(intervals.begin(), intervals.end(),
[](const std::vector<int>& a, const std::vector<int>& b) {
return a[0] < b[0];
});
vector<vector<int>> result;
result.push_back(intervals[0]);
int curRight = intervals[0][1];
int cnt=0;
for(int i=1;i<intervals.size();i++){
if(intervals[i][0]<=curRight){
curRight = max(curRight, intervals[i][1]);
result[cnt][0] = min(result[cnt][0], intervals[i][0]);
result[cnt][1] = curRight;
}
else{
result.push_back(intervals[i]);
curRight = intervals[i][1];
cnt++;
}
}
return result;
}
};
| 26.6 | 70 | 0.46724 | [
"vector"
] |
32263d02108d8321294ddb643bf27d738509922d | 914 | cpp | C++ | src/IceRay/main/interface/python/core/geometry/rtss/list.cpp | dmilos/IceRay | 4e01f141363c0d126d3c700c1f5f892967e3d520 | [
"MIT-0"
] | 2 | 2020-09-04T12:27:15.000Z | 2022-01-17T14:49:40.000Z | src/IceRay/main/interface/python/core/geometry/rtss/list.cpp | dmilos/IceRay | 4e01f141363c0d126d3c700c1f5f892967e3d520 | [
"MIT-0"
] | null | null | null | src/IceRay/main/interface/python/core/geometry/rtss/list.cpp | dmilos/IceRay | 4e01f141363c0d126d3c700c1f5f892967e3d520 | [
"MIT-0"
] | 1 | 2020-09-04T12:27:52.000Z | 2020-09-04T12:27:52.000Z |
#include "../../../def_submodule.hpp"
#include "../../../../../../geometry/rtss/list.hpp"
typedef GS_DDMRM::S_IceRay::S_type::GT_size GTs_size;
typedef GS_DDMRM::S_IceRay::S_type::GT_scalar GTs_scalar;
typedef GS_DDMRM::S_IceRay::S_type::S_coord::GT_scalar3D GTs_coord3D;
typedef GS_DDMRM::S_IceRay::S_geometry::S__pure::GC__base GTs__base;
typedef GS_DDMRM::S_IceRay::S_geometry::S_RTSS::GC__pure GTs__rtss;
typedef GS_DDMRM::S_IceRay::S_geometry::S_RTSS::GC_list GTs_list;
void expose_IceRay_geometry_RTSS_list()
{
//MAKE_SUBMODULE( IceRay );
MAKE_SUBMODULE( core );
MAKE_SUBMODULE( geometry );
MAKE_SUBMODULE( rtss );
// just empty class, might be ::type()
// But not insert/add/push/size
boost::python::class_< GTs_list, boost::python::bases<GTs__rtss> >( "GeometryRTSSList" )
.def( boost::python::init<>() )
;
}
| 30.466667 | 91 | 0.669584 | [
"geometry"
] |
7a8c933e970a292fffabb3e9b00d4df3e3cc3f96 | 1,412 | cpp | C++ | CCF-CSP/201812-2.cpp | windcry1/My-ACM-ICPC | b85b1c83b72c6b51731dae946a0df57c31d3e7a1 | [
"MIT"
] | null | null | null | CCF-CSP/201812-2.cpp | windcry1/My-ACM-ICPC | b85b1c83b72c6b51731dae946a0df57c31d3e7a1 | [
"MIT"
] | null | null | null | CCF-CSP/201812-2.cpp | windcry1/My-ACM-ICPC | b85b1c83b72c6b51731dae946a0df57c31d3e7a1 | [
"MIT"
] | null | null | null | //Author:LanceYu
#include<iostream>
#include<string>
#include<cstring>
#include<cstdio>
#include<fstream>
#include<iosfwd>
#include<vector>
#include<cstdlib>
#include<queue>
#include<set>
#include<ctime>
#include<algorithm>
#include<complex>
#include<cmath>
#include<array>
#include<valarray>
#include<bitset>
#define ll long long
using namespace std;
const double clf=1e-8;
//const double e=2.718281828;
const double PI=3.141592653589793;
const int MMAX=2147483647;
const int mod=1e9+7;
//priority_queue<int>p;
//priority_queue<int,vector<int>,greater<int> >pq;
int main()
{
//freopen("C:\\Users\\LENOVO\\Desktop\\in.txt","r",stdin);
//freopen("C:\\Users\\LENOVO\\Desktop\\out.txt","w",stdout);
int r,y,g,n,a,b,t;
ll s=0;
scanf("%d%d%d%d",&r,&y,&g,&n);
while (n--)
{
scanf("%d%d",&a,&b);
if(a==0)
s=s+b;
else if (a==1)
{
t = (r - b + s) % (r + y + g);
if (t<r)
s=s+r-t;
if ((t>=r+g) && (t<r+g+y))
s=s+r+g+y-t+r;
}
else if (a==2)
{
t = (r+g+y - b + s) % (r + y + g);
if (t<r)
s=s+r-t;
if ((t>=r+g) && (t<r+g+y))
s=s+r+g+y-t+r;
}
else if (a==3)
{
t = (r + g - b + s) % (r + y + g);
if (t<r)
s=s+r-t;
if ((t>=r+g) && (t<r+g+y))
s=s+r+g+y-t+r;
}
}
printf("%lld\n",s);
return 0;
}
| 20.463768 | 61 | 0.497167 | [
"vector"
] |
7a8dd4776eccd1f00a2674499acad1379a233070 | 1,613 | cpp | C++ | E6-I/standard.cpp | Matrix53/algo | 7a176dac9ed9c6ad65d1514afb6388f7ee6b912a | [
"MIT"
] | 1 | 2021-12-14T08:54:11.000Z | 2021-12-14T08:54:11.000Z | E6-I/standard.cpp | Matrix53/algo | 7a176dac9ed9c6ad65d1514afb6388f7ee6b912a | [
"MIT"
] | null | null | null | E6-I/standard.cpp | Matrix53/algo | 7a176dac9ed9c6ad65d1514afb6388f7ee6b912a | [
"MIT"
] | 1 | 2021-12-13T09:31:40.000Z | 2021-12-13T09:31:40.000Z | // Author: Matrix53
#include <bits/stdc++.h>
using namespace std;
const double pi = acos(-1.0);
const double eps = 1e-6;
int sgn(double x) {
if (fabs(x) < eps) return 0;
return x > 0 ? 1 : -1;
}
struct Point {
double x, y;
Point() : x(0), y(0) {}
Point(double a, double b) : x(a), y(b) {}
Point operator-(Point a) { return Point(x - a.x, y - a.y); }
};
typedef Point Vector;
double dot(Vector a, Vector b) { return a.x * b.x + a.y * b.y; }
double det(Vector a, Vector b) { return a.x * b.y - a.y * b.x; }
//向量A逆时针旋转rad弧度
Vector rotate(Vector a, double rad) {
return Vector(a.x * cos(rad) - a.y * sin(rad),
a.x * sin(rad) + a.y * cos(rad));
}
struct Line {
Point p1, p2;
Line() {}
Line(Point a, Point b) : p1(a), p2(b) {}
};
typedef Line Segment;
//点和线段的关系:0为在线段延长线上,1为线段端点,2为在线段上,3为左侧,4为右侧
int relation(Point p, Segment s) {
int sign = sgn(det(s.p2 - s.p1, p - s.p1));
if (sign) return sign > 0 ? 3 : 4;
sign = sgn(dot(s.p2 - p, s.p1 - p));
if (sign) return sign > 0 ? 0 : 2;
return 1;
}
int main() {
// freopen("D:/Workspace/algo/E6-H/data/4.in", "r", stdin);
Point O, A, K, T1, T2;
int alpha;
scanf("%lf%lf", &O.x, &O.y);
scanf("%lf%lf%d", &A.x, &A.y, &alpha);
scanf("%lf%lf", &K.x, &K.y);
K = K - O;
A = A - O;
for (int count = 0; count < 365; ++count) {
T1 = rotate(A, ((alpha * 2 * count) % 360) * pi / 180);
T2 = rotate(A, ((alpha * 2 * (count + 1)) % 360) * pi / 180);
int res = relation(K, Segment(T1, T2));
if (res == 1 || res == 2) {
printf("%d", count);
return 0;
}
}
printf("-1");
return 0;
} | 24.815385 | 65 | 0.535028 | [
"vector"
] |
7a8ea1e5565a1de80eddd24e7008a6c05bc03b12 | 736 | hpp | C++ | include/loquat/graph/breadth_first_search.hpp | logicmachine/loquat | 162d22fb0098de37990bd469d7fbba8f990713aa | [
"MIT"
] | 1 | 2019-07-15T10:19:12.000Z | 2019-07-15T10:19:12.000Z | include/loquat/graph/breadth_first_search.hpp | logicmachine/loquat | 162d22fb0098de37990bd469d7fbba8f990713aa | [
"MIT"
] | null | null | null | include/loquat/graph/breadth_first_search.hpp | logicmachine/loquat | 162d22fb0098de37990bd469d7fbba8f990713aa | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include <queue>
#include "loquat/graph/adjacency_list.hpp"
namespace loquat {
template <typename EdgeType, typename F>
void breadth_first_search(
const adjacency_list<EdgeType>& g,
vertex_t root,
std::vector<bool>& vis,
F func)
{
std::queue<vertex_t> q;
q.push(root);
vis[root] = true;
while(!q.empty()){
const auto u = q.front();
q.pop();
for(const auto& e : g[u]){
const auto v = e.to;
if(vis[v]){ continue; }
func(u, e);
vis[v] = true;
q.push(v);
}
}
}
template <typename EdgeType, typename F>
void breadth_first_search(
const adjacency_list<EdgeType>& g,
vertex_t root,
F func)
{
std::vector<bool> vis(g.size());
breadth_first_search(g, root, vis, func);
}
}
| 17.52381 | 42 | 0.663043 | [
"vector"
] |
7a93003b201602b58e9f9b54110f0b250f0f2d44 | 1,670 | cc | C++ | asylo/crypto/sha256_hash.cc | kevin405/mosl_vsgx_migration | 76ddd438c8caad1051ea9a7e2040bf6ccee996a2 | [
"Apache-2.0"
] | 1 | 2019-01-13T21:39:32.000Z | 2019-01-13T21:39:32.000Z | asylo/crypto/sha256_hash.cc | kevin405/mosl_vsgx_migration | 76ddd438c8caad1051ea9a7e2040bf6ccee996a2 | [
"Apache-2.0"
] | null | null | null | asylo/crypto/sha256_hash.cc | kevin405/mosl_vsgx_migration | 76ddd438c8caad1051ea9a7e2040bf6ccee996a2 | [
"Apache-2.0"
] | 1 | 2019-01-02T22:04:21.000Z | 2019-01-02T22:04:21.000Z | /*
*
* Copyright 2017 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 "asylo/crypto/sha256_hash.h"
#include <openssl/sha.h>
#include "asylo/crypto/util/bssl_util.h"
#include "asylo/crypto/util/byte_container_view.h"
namespace asylo {
Sha256Hash::Sha256Hash() { Init(); }
HashAlgorithm Sha256Hash::GetHashAlgorithm() const {
return HashAlgorithm::SHA256;
}
size_t Sha256Hash::DigestSize() const { return SHA256_DIGEST_LENGTH; }
void Sha256Hash::Init() { SHA256_Init(&context_); }
void Sha256Hash::Update(ByteContainerView data) {
SHA256_Update(&context_, data.data(), data.size());
}
Status Sha256Hash::CumulativeHash(std::vector<uint8_t> *digest) const {
// Do not finalize the internally stored hash context. Instead, finalize a
// copy of the current context so that the current context can be updated in
// future calls to Update.
SHA256_CTX context_snapshot = context_;
digest->resize(SHA256_DIGEST_LENGTH);
if (SHA256_Final(digest->data(), &context_snapshot) != 1) {
return Status(error::GoogleError::INTERNAL, BsslLastErrorString());
}
return Status::OkStatus();
}
} // namespace asylo
| 30.363636 | 78 | 0.738323 | [
"vector"
] |
7a952c0122034c1038c87952dd8cb34e276315a3 | 2,538 | cpp | C++ | Contrib-Intel/RSD-PSME-RMM/application/src/rest/endpoints/account_service/account_service.cpp | opencomputeproject/Rack-Manager | e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a | [
"MIT"
] | 5 | 2019-11-11T07:57:26.000Z | 2022-03-28T08:26:53.000Z | Contrib-Intel/RSD-PSME-RMM/application/src/rest/endpoints/account_service/account_service.cpp | opencomputeproject/Rack-Manager | e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a | [
"MIT"
] | 3 | 2019-09-05T21:47:07.000Z | 2019-09-17T18:10:45.000Z | Contrib-Intel/RSD-PSME-RMM/application/src/rest/endpoints/account_service/account_service.cpp | opencomputeproject/Rack-Manager | e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a | [
"MIT"
] | 11 | 2019-07-20T00:16:32.000Z | 2022-01-11T14:17:48.000Z | /*!
* @copyright
* Copyright (c) 2018-2019 Intel Corporation
*
* @copyright
* 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
*
* @copyright
* http://www.apache.org/licenses/LICENSE-2.0
*
* @copyright
* 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.
*
* @file account_service.cpp
* */
#include "psme/rest/endpoints/account_service/account_service.hpp"
#include "psme/rest/constants/constants.hpp"
#include "psme/rest/utils/status_helpers.hpp"
#include "psme/rest/server/error/error_factory.hpp"
#include "agent-framework/module/enum/common.hpp"
using namespace psme::rest;
using namespace psme::rest::constants;
using namespace agent_framework::model;
namespace {
json::Json make_prototype() {
json::Json r(json::Json::value_t::object);
r[Common::ODATA_CONTEXT] = "/redfish/v1/$metadata#AccountService.AccountService";
r[Common::ODATA_ID] = json::Json::value_t::null;
r[Common::ODATA_TYPE] = "#AccountService.v1_3_0.AccountService";
r[Common::ID] = "AccountService";
r[Common::NAME] = "Account Service";
r[Common::DESCRIPTION] = "Account Service";
r[Common::STATUS][Common::STATE] = "Enabled";
r[Common::STATUS][Common::HEALTH] = "OK";
r[AccountService::SERVICE_ENABLED] = true;
r[AccountService::LOCAL_ACCOUNT_AUTH] = "Enabled";
r[AccountService::ACCOUNTS] = json::Json::value_t::object;
r[AccountService::ACCOUNTS][Common::ODATA_ID] = "/redfish/v1/AccountService/Accounts";
r[AccountService::ROLES] = json::Json::value_t::object;
r[AccountService::ROLES][Common::ODATA_ID] = "/redfish/v1/AccountService/Roles";
return r;
}
}
namespace psme {
namespace rest {
namespace endpoint {
AccountService::AccountService(const std::string& path) : EndpointBase(path) {}
AccountService::~AccountService() {}
void AccountService::get(const server::Request& req, server::Response& res) {
auto r = make_prototype();
r[Common::STATUS][Common::STATE] = enums::State(enums::State::Enabled).to_string();
r[constants::AccountService::SERVICE_ENABLED] = true;
r[Common::ODATA_ID] = PathBuilder(req).build();
set_response(res, r);
}
}
}
}
| 30.214286 | 90 | 0.715524 | [
"object",
"model"
] |
7a9696ddf62e5d38bcc89984dbc694fe337698c9 | 632 | cpp | C++ | codeforces/3/3A_ShortestPathOfTheKing.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 3 | 2015-05-25T06:24:37.000Z | 2016-09-10T07:58:00.000Z | codeforces/3/3A_ShortestPathOfTheKing.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | null | null | null | codeforces/3/3A_ShortestPathOfTheKing.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 5 | 2015-05-25T06:24:40.000Z | 2021-08-19T19:22:29.000Z | #include <cassert>
#include <vector>
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <string>
#include <cstring>
#include <queue>
#include <utility>
using namespace std;
int main() {
string s, t;
cin >> s >> t;
cout << max(abs(s[0]-t[0]), abs(s[1]-t[1])) << '\n';
while (s[0]!=t[0] || s[1]!=t[1]) {
if (s[0] < t[0]) { cout << 'R'; ++s[0]; }
else if (s[0] > t[0]) { cout << 'L'; --s[0]; }
if (s[1] < t[1]) { cout << 'U'; ++s[1]; }
else if (s[1] > t[1]) { cout << 'D'; --s[1]; }
cout << '\n';
}
return 0;
}
| 21.793103 | 56 | 0.46519 | [
"vector"
] |
7a9d18819e3eb772896a23a74a9d176547c49fac | 46,522 | cc | C++ | src/Graph/graph.cc | hgl71964/PET | 4cedb25c5dce0c49eebb693125235fc4ad1e26f8 | [
"Apache-2.0"
] | null | null | null | src/Graph/graph.cc | hgl71964/PET | 4cedb25c5dce0c49eebb693125235fc4ad1e26f8 | [
"Apache-2.0"
] | null | null | null | src/Graph/graph.cc | hgl71964/PET | 4cedb25c5dce0c49eebb693125235fc4ad1e26f8 | [
"Apache-2.0"
] | null | null | null | #include "graph.h"
#include "common.h"
#include "ffi.h"
#include "operator.h"
#include "tensor.h"
#include <string>
#include <unordered_map>
#include <unordered_set>
namespace tpm {
PYBIND11_EMBEDDED_MODULE(cpp_module, m) {
py::class_<Tensor>(m, "Tensor");
py::class_<Operator>(m, "Operator");
py::class_<PermItem>(m, "PermItem")
.def(py::init<int>())
.def(py::init<const std::vector<int> &>())
.def(py::init<std::initializer_list<int>>());
py::class_<Perm>(m, "Perm")
.def(py::init<const std::vector<PermItem> &>())
.def(py::init<std::initializer_list<PermItem>>());
py::class_<Graph>(m, "Graph")
.def("tensor",
static_cast<Tensor *(Graph::*)(const Dim &, const std::string &)>(
&Graph::tensor),
py::return_value_policy::reference_internal)
.def("conv",
static_cast<Operator *(Graph::*)(Tensor *, Tensor *, Tensor *, int,
int, int, int, int, int,
Tensor *)>(&Graph::conv),
py::return_value_policy::reference_internal)
.def("convTrans",
static_cast<Operator *(Graph::*)(Tensor *, Tensor *, Tensor *, int,
int, int, int, int, int,
Tensor *)>(&Graph::convTrans),
py::return_value_policy::reference_internal)
.def("pad",
static_cast<Operator *(Graph::*)(Tensor *, Tensor *, const Dim &,
const Dim &)>(&Graph::pad),
py::return_value_policy::reference_internal)
.def(
"concat",
static_cast<Operator *(Graph::*)(const TensorVec &, Tensor *, int)>(
&Graph::concat),
py::return_value_policy::reference_internal)
.def(
"matmul",
static_cast<Operator *(Graph::*)(Tensor *, Tensor *, Tensor *, bool,
bool, Tensor *)>(&Graph::matmul),
py::return_value_policy::reference_internal)
.def("g2bmm",
static_cast<Operator *(Graph::*)(Tensor *, Tensor *, Tensor *, int,
int, Tensor *)>(&Graph::g2bmm),
py::return_value_policy::reference_internal)
.def("gbmml",
static_cast<Operator *(Graph::*)(Tensor *, Tensor *, Tensor *, int,
Tensor *)>(&Graph::gbmml),
py::return_value_policy::reference_internal)
.def("split",
static_cast<Operator *(Graph::*)(Tensor *, const TensorVec &, int,
int)>(&Graph::split),
py::return_value_policy::reference_internal)
.def("transpose",
static_cast<Operator *(Graph::*)(Tensor *, Tensor *, int,
const Perm &, int)>(
&Graph::transpose),
py::return_value_policy::reference_internal)
.def("flatten",
static_cast<Operator *(Graph::*)(Tensor *, Tensor *, int)>(
&Graph::flatten),
py::return_value_policy::reference_internal)
.def("maxpool",
static_cast<Operator *(Graph::*)(Tensor *, Tensor *, int, int, int,
int, int, int, int, int)>(
&Graph::maxpool),
py::return_value_policy::reference_internal)
.def("avgpool",
static_cast<Operator *(Graph::*)(Tensor *, Tensor *, int, int, int,
int, int, int)>(&Graph::avgpool),
py::return_value_policy::reference_internal)
.def("avgpool",
static_cast<Operator *(Graph::*)(Tensor *, Tensor *)>(
&Graph::avgpool),
py::return_value_policy::reference_internal)
.def("add",
static_cast<Operator *(Graph::*)(const TensorVec &, Tensor *)>(
&Graph::add),
py::return_value_policy::reference_internal)
.def("sub",
static_cast<Operator *(Graph::*)(Tensor *, Tensor *, Tensor *)>(
&Graph::sub),
py::return_value_policy::reference_internal)
.def("mul",
static_cast<Operator *(Graph::*)(const TensorVec &, Tensor *)>(
&Graph::mul),
py::return_value_policy::reference_internal)
.def("div",
static_cast<Operator *(Graph::*)(Tensor *, Tensor *, Tensor *)>(
&Graph::div),
py::return_value_policy::reference_internal)
.def("pow",
static_cast<Operator *(Graph::*)(Tensor *, Tensor *, int)>(
&Graph::pow),
py::return_value_policy::reference_internal)
.def("gather",
static_cast<Operator *(Graph::*)(Tensor *, Tensor *, Tensor *,
int)>(&Graph::gather),
py::return_value_policy::reference_internal)
.def("reduceMean",
static_cast<Operator *(Graph::*)(Tensor *, Tensor *, int)>(
&Graph::reduceMean),
py::return_value_policy::reference_internal)
.def("softmax",
static_cast<Operator *(Graph::*)(Tensor *, Tensor *, int)>(
&Graph::softmax),
py::return_value_policy::reference_internal)
.def("reshape",
static_cast<Operator *(Graph::*)(Tensor *, Tensor *)>(
&Graph::reshape),
py::return_value_policy::reference_internal)
.def("sigmoid",
static_cast<Operator *(Graph::*)(Tensor *, Tensor *)>(
&Graph::sigmoid),
py::return_value_policy::reference_internal)
.def(
"relu",
static_cast<Operator *(Graph::*)(Tensor *, Tensor *)>(&Graph::relu),
py::return_value_policy::reference_internal)
.def(
"tanh",
static_cast<Operator *(Graph::*)(Tensor *, Tensor *)>(&Graph::tanh),
py::return_value_policy::reference_internal)
.def("batchnorm",
static_cast<Operator *(Graph::*)(Tensor *, Tensor *, Tensor *,
Tensor *, Tensor *, Tensor *,
float, float)>(&Graph::batchnorm),
py::return_value_policy::reference_internal)
.def("identity",
static_cast<Operator *(Graph::*)(Tensor *, Tensor *)>(
&Graph::identity),
py::return_value_policy::reference_internal)
.def("split",
static_cast<Operator *(Graph::*)(Tensor *, const TensorVec &, int,
std::vector<int>)>(&Graph::split),
py::return_value_policy::reference_internal);
}
GraphBase::~GraphBase() {
for (auto op : ops)
if (op != nullptr) {
delete op;
op = nullptr;
}
for (auto tensor : tensors)
if (tensor != nullptr) {
delete tensor; // tensor destructor will delete tensor's data ptr
tensor = nullptr;
}
// XXX it seems tensor from inputs or outputs also belong tensors,
// so free tensors actually free all tensor in this graph
}
void GraphBase::addTensor(Tensor *tensor) { tensors.emplace_back(tensor); }
TensorVec &GraphBase::getTensors() { return tensors; }
OpVec &GraphBase::getOperators() { return ops; }
const OpVec &GraphBase::getOperators() const { return ops; }
TensorVec &GraphBase::getInputs() { return inputs; }
const TensorVec &GraphBase::getInputs() const { return inputs; }
TensorVec &GraphBase::getOutputs() { return outputs; }
const TensorVec &GraphBase::getOutputs() const { return outputs; }
void GraphBase::updateConnection() {
// for each Op, update its tensor
for (auto op : ops) {
for (auto tensor : op->getInputs())
tensor->addInputOf(op);
for (auto tensor : op->getOutputs())
tensor->setOutputOf(op);
}
// update successors and predecessors for all ops
for (auto tensor : tensors) {
for (auto opNext : tensor->getInputOf()) {
auto opPrev = tensor->getOutputOf();
if (opPrev != nullptr) {
opNext->addPredecessors(opPrev);
opPrev->addSuccessors(opNext);
}
}
if (!tensor->getInputOf().empty() && tensor->getOutputOf() == nullptr)
inputs.emplace_back(tensor);
if (tensor->getInputOf().empty() && tensor->getOutputOf() != nullptr)
outputs.emplace_back(tensor);
}
}
Operator *Graph::conv(Tensor *input, Tensor *weight, Tensor *output, int ph,
int pw, int sh, int sw, int dh, int dw, Tensor *bias) {
auto op = new ConvOp(input, weight, output, ph, pw, sh, sw, dh, dw, bias);
ops.emplace_back(op);
return op;
}
Operator *Graph::conv(Tensor *input, Tensor *weight, int ph, int pw, int sh,
int sw, int dh, int dw, Tensor *bias) {
auto op = new ConvOp(input, weight, ph, pw, sh, sw, dh, dw, bias);
ops.emplace_back(op);
auto output = op->getOutputs()[0];
addTensor(output);
return op;
}
Operator *Graph::conv(Tensor *input, Tensor *weight, Tensor *output,
ConvOp::PaddingMode pm, int sh, int sw, int dh, int dw,
Tensor *bias) {
auto op = new ConvOp(input, weight, output, pm, sh, sw, dh, dw, bias);
ops.emplace_back(op);
return op;
}
Operator *Graph::conv(Tensor *input, Tensor *weight, ConvOp::PaddingMode pm,
int sh, int sw, int dh, int dw, Tensor *bias) {
auto op = new ConvOp(input, weight, pm, sh, sw, dh, dw, bias);
ops.emplace_back(op);
auto output = op->getOutputs()[0];
addTensor(output);
return op;
}
Operator *Graph::convTrans(Tensor *input, Tensor *weight, Tensor *output,
int ph, int pw, int sh, int sw, int dh, int dw,
Tensor *bias) {
{
auto dims = input->getDims();
input->setDims({dims[0], dims[2], dims[3], dims[1]});
}
{
auto dims = weight->getDims();
weight->setDims({dims[0], dims[2], dims[3], dims[1]});
}
auto op =
new ConvTransOp(input, weight, output, ph, pw, sh, sw, dh, dw, bias);
ops.emplace_back(op);
return op;
}
Operator *Graph::convTrans(Tensor *input, Tensor *weight, int ph, int pw,
int sh, int sw, int dh, int dw, Tensor *bias) {
auto op = new ConvTransOp(input, weight, ph, pw, sh, sw, dh, dw, bias);
ops.emplace_back(op);
auto output = op->getOutputs()[0];
addTensor(output);
return op;
}
Operator *Graph::convTrans(Tensor *input, Tensor *weight, Tensor *output,
ConvTransOp::PaddingMode pm, int sh, int sw, int dh,
int dw, Tensor *bias) {
auto op = new ConvTransOp(input, weight, output, pm, sh, sw, dh, dw, bias);
ops.emplace_back(op);
return op;
}
Operator *Graph::convTrans(Tensor *input, Tensor *weight,
ConvTransOp::PaddingMode pm, int sh, int sw, int dh,
int dw, Tensor *bias) {
auto op = new ConvTransOp(input, weight, pm, sh, sw, dh, dw, bias);
ops.emplace_back(op);
auto output = op->getOutputs()[0];
addTensor(output);
return op;
}
Operator *Graph::matmul(Tensor *A, Tensor *B, Tensor *C, bool transA,
bool transB, Tensor *bias) {
auto op = new MatmulOp(A, B, C, transA, transB, bias);
ops.emplace_back(op);
return op;
}
Operator *Graph::matmul(Tensor *A, Tensor *B, bool transA, bool transB,
Tensor *bias) {
auto op = new MatmulOp(A, B, transA, transB, bias);
ops.emplace_back(op);
auto output = op->getOutputs()[0];
addTensor(output);
return op;
}
Operator *Graph::g2bmm(Tensor *A, Tensor *B, Tensor *C, int width, int dilation,
Tensor *bias) {
auto op = new G2BMMOp(A, B, C, width, dilation, bias);
ops.emplace_back(op);
return op;
}
Operator *Graph::g2bmm(Tensor *A, Tensor *B, int width, int dilation,
Tensor *bias) {
auto op = new G2BMMOp(A, B, width, dilation, bias);
ops.emplace_back(op);
auto output = op->getOutputs()[0];
addTensor(output);
return op;
}
Operator *Graph::gbmml(Tensor *A, Tensor *B, Tensor *C, int dilation,
Tensor *bias) {
auto op = new GBMMLOp(A, B, C, dilation, bias);
ops.emplace_back(op);
return op;
}
Operator *Graph::gbmml(Tensor *A, Tensor *B, int dilation, Tensor *bias) {
auto op = new GBMMLOp(A, B, dilation, bias, Operator::ActType::None);
ops.emplace_back(op);
auto output = op->getOutputs()[0];
addTensor(output);
return op;
}
Operator *Graph::pad(Tensor *input, Tensor *output, const Dim &begin,
const Dim &end) {
auto op = new PadOp(input, output, begin, end);
ops.emplace_back(op);
return op;
}
Operator *Graph::pad(Tensor *input, const Dim &begin, const Dim &end) {
auto op = new PadOp(input, begin, end);
ops.emplace_back(op);
auto output = op->getOutputs()[0];
addTensor(output);
return op;
}
Operator *Graph::slice(Tensor *input, Tensor *output, const Dim &begin,
const Dim &end) {
auto op = new SliceOp(input, output, begin, end);
ops.emplace_back(op);
return op;
}
Operator *Graph::slice(Tensor *input, const Dim &begin, const Dim &end) {
auto op = new SliceOp(input, begin, end);
ops.emplace_back(op);
auto output = op->getOutputs()[0];
addTensor(output);
return op;
}
Operator *Graph::concat(const TensorVec &inputs, Tensor *output, int dim) {
auto op = new ConcatOp(inputs, output, dim);
ops.emplace_back(op);
return op;
}
Operator *Graph::concat(const TensorVec &inputs, int dim) {
auto op = new ConcatOp(inputs, dim);
ops.emplace_back(op);
auto output = op->getOutputs()[0];
addTensor(output);
return op;
}
Operator *Graph::split(Tensor *input, const TensorVec &outputs, int dim,
int num) {
auto op = new SplitOp(input, outputs, dim, num);
ops.emplace_back(op);
return op;
}
Operator *Graph::split(Tensor *input, int dim, int num) {
auto op = new SplitOp(input, dim, num);
ops.emplace_back(op);
auto outputs = op->getOutputs();
for (auto output : outputs)
addTensor(output);
return op;
}
Operator *Graph::split(Tensor *input, const TensorVec &outputs, int dim,
std::vector<int> sizes) {
auto op = new SplitOp(input, outputs, dim, sizes);
ops.emplace_back(op);
return op;
}
Operator *Graph::split(Tensor *input, int dim, std::vector<int> sizes) {
auto op = new SplitOp(input, dim, sizes);
ops.emplace_back(op);
auto outputs = op->getOutputs();
for (auto output : outputs)
addTensor(output);
return op;
}
Operator *Graph::transpose(Tensor *input, Tensor *output, int split,
const Perm &after, int factor) {
auto op = new TransposeOp(input, output, split, after, factor);
ops.emplace_back(op);
return op;
}
Operator *Graph::transpose(Tensor *input, int split, const Perm &after,
int factor) {
auto op = new TransposeOp(input, split, after, factor);
ops.emplace_back(op);
auto output = op->getOutputs()[0];
addTensor(output);
return op;
}
Operator *Graph::flatten(Tensor *input, Tensor *output, int axis) {
assert(axis > 0 && axis < (int)input->getDims().size());
Dim d1, d2;
for (size_t i = 0, iEnd = input->getDims().size(); i < iEnd; i++) {
((int)i < axis ? d1 : d2).emplace_back(i);
}
return transpose(input, output, -1, {d1, d2});
}
Operator *Graph::flatten(Tensor *input, int axis) {
assert(axis > 0 && axis < (int)input->getDims().size());
Dim d1, d2;
for (size_t i = 0, iEnd = input->getDims().size(); i < iEnd; i++) {
((int)i < axis ? d1 : d2).emplace_back(i);
}
return transpose(input, -1, {d1, d2});
}
Operator *Graph::extend(Tensor *input, Tensor *output, int dim, int num) {
auto op = new ExtendOp(input, output, dim, num);
ops.emplace_back(op);
return op;
}
Operator *Graph::extend(Tensor *input, int dim, int num) {
auto op = new ExtendOp(input, dim, num);
ops.emplace_back(op);
auto output = op->getOutputs()[0];
addTensor(output);
return op;
}
Operator *Graph::batchnorm(Tensor *input, Tensor *scale, Tensor *bias,
Tensor *mean, Tensor *var, Tensor *output,
float epsilon, float momentum) {
auto op = new BatchNormOp(input, scale, bias, mean, var, output, epsilon,
momentum);
ops.emplace_back(op);
return op;
}
Operator *Graph::batchnorm(Tensor *input, Tensor *scale, Tensor *bias,
Tensor *mean, Tensor *var, float epsilon,
float momentum) {
auto op = new BatchNormOp(input, scale, bias, mean, var, epsilon, momentum);
ops.emplace_back(op);
auto output = op->getOutputs()[0];
addTensor(output);
return op;
}
Operator *Graph::maxpool(Tensor *input, Tensor *output, int kh, int kw, int dh,
int dw, int ph, int pw, int sh, int sw) {
auto op = new MaxPoolOp(input, output, kh, kw, dh, dw, ph, pw, sh, sw);
ops.emplace_back(op);
return op;
}
Operator *Graph::maxpool(Tensor *input, int kh, int kw, int dh, int dw, int ph,
int pw, int sh, int sw) {
auto op = new MaxPoolOp(input, kh, kw, dh, dw, ph, pw, sh, sw);
ops.emplace_back(op);
auto output = op->getOutputs()[0];
addTensor(output);
return op;
}
Operator *Graph::avgpool(Tensor *input, Tensor *output) {
auto op = new AvgPoolOp(input, output);
ops.emplace_back(op);
return op;
}
Operator *Graph::avgpool(Tensor *input, Tensor *output, int kh, int kw, int ph,
int pw, int sh, int sw) {
auto op = new AvgPoolOp(input, output, kh, kw, ph, pw, sh, sw);
ops.emplace_back(op);
return op;
}
Operator *Graph::avgpool(Tensor *input, int kh, int kw, int ph, int pw, int sh,
int sw) {
auto op = new AvgPoolOp(input, kh, kw, ph, pw, sh, sw);
ops.emplace_back(op);
auto output = op->getOutputs()[0];
addTensor(output);
return op;
}
Operator *Graph::add(const TensorVec &inputs, Tensor *output) {
auto op = new AddOp(inputs, output);
ops.emplace_back(op);
return op;
}
Operator *Graph::add(const TensorVec &inputs) {
auto op = new AddOp(inputs);
ops.emplace_back(op);
auto output = op->getOutputs()[0];
addTensor(output);
return op;
}
Operator *Graph::sub(Tensor *input0, Tensor *input1, Tensor *output) {
auto op = new SubOp({input0, input1}, output);
ops.emplace_back(op);
return op;
}
Operator *Graph::sub(Tensor *input0, Tensor *input1) {
auto op = new SubOp({input0, input1});
ops.emplace_back(op);
auto output = op->getOutputs()[0];
addTensor(output);
return op;
}
Operator *Graph::mul(const TensorVec &inputs, Tensor *output) {
auto op = new MulOp(inputs, output);
ops.emplace_back(op);
return op;
}
Operator *Graph::mul(const TensorVec &inputs) {
auto op = new MulOp(inputs);
ops.emplace_back(op);
auto output = op->getOutputs()[0];
addTensor(output);
return op;
}
Operator *Graph::div(Tensor *input0, Tensor *input1, Tensor *output) {
auto op = new DivOp({input0, input1}, output);
ops.emplace_back(op);
return op;
}
Operator *Graph::div(Tensor *input0, Tensor *input1) {
auto op = new DivOp({input0, input1});
ops.emplace_back(op);
auto output = op->getOutputs()[0];
addTensor(output);
return op;
}
Operator *Graph::pow(Tensor *input, Tensor *output, int pow) {
auto op = new PowOp(input, output, pow);
ops.emplace_back(op);
return op;
}
Operator *Graph::pow(Tensor *input, int pow) {
auto op = new PowOp(input, pow);
ops.emplace_back(op);
auto output = op->getOutputs()[0];
addTensor(output);
return op;
}
Operator *Graph::gather(Tensor *data, Tensor *indices, Tensor *output,
int axis) {
auto op = new GatherOp(data, indices, output, axis);
ops.emplace_back(op);
return op;
}
Operator *Graph::gather(Tensor *data, Tensor *indices, int axis) {
auto op = new GatherOp(data, indices, axis);
ops.emplace_back(op);
auto output = op->getOutputs()[0];
addTensor(output);
return op;
}
Operator *Graph::reduceMean(Tensor *input, Tensor *output, int axis) {
auto op = new ReduceMeanOp(input, output, axis);
ops.emplace_back(op);
return op;
}
Operator *Graph::reduceMean(Tensor *input, int axis) {
auto op = new ReduceMeanOp(input, axis);
ops.emplace_back(op);
auto output = op->getOutputs()[0];
addTensor(output);
return op;
}
Operator *Graph::reshape(Tensor *input, Tensor *output) {
auto op = new ReshapeOp(input, output);
ops.emplace_back(op);
return op;
}
Operator *Graph::identity(Tensor *input, Tensor *output) {
auto op = new IdentityOp(input, output);
ops.emplace_back(op);
return op;
}
Operator *Graph::identity(Tensor *input) {
auto op = new IdentityOp(input);
ops.emplace_back(op);
auto output = op->getOutputs()[0];
addTensor(output);
return op;
}
Operator *Graph::relu(Tensor *input, Tensor *output) {
auto op = new ActivationOp(input, output, Operator::Relu);
ops.emplace_back(op);
return op;
}
Operator *Graph::relu(Tensor *input) {
auto op = new ActivationOp(input, Operator::Relu);
ops.emplace_back(op);
addTensor(op->getOutputs()[0]);
return op;
}
Operator *Graph::sigmoid(Tensor *input, Tensor *output) {
auto op = new ActivationOp(input, output, Operator::Sigmoid);
ops.emplace_back(op);
return op;
}
Operator *Graph::sigmoid(Tensor *input) {
auto op = new ActivationOp(input, Operator::Sigmoid);
ops.emplace_back(op);
addTensor(op->getOutputs()[0]);
return op;
}
Operator *Graph::softmax(Tensor *input, Tensor *output, int axis) {
auto op = new SoftmaxOp(input, output, axis);
ops.emplace_back(op);
return op;
}
Operator *Graph::softmax(Tensor *input, int axis) {
auto op = new SoftmaxOp(input, axis);
ops.emplace_back(op);
auto output = op->getOutputs()[0];
addTensor(output);
return op;
}
Operator *Graph::tanh(Tensor *input, Tensor *output) {
auto op = new TanhOp(input, output);
ops.emplace_back(op);
return op;
}
Operator *Graph::tanh(Tensor *input) {
auto op = new TanhOp(input);
ops.emplace_back(op);
auto output = op->getOutputs()[0];
addTensor(output);
return op;
}
Operator *Graph::membound(TensorVec &inputs, TensorVec &outputs,
nnet::Expr expr, double exec_time) {
auto op = new MemBoundOp(inputs, outputs, expr, exec_time);
ops.emplace_back(op);
return op;
}
Tensor *GraphBase::tensor(const Dim &dims, Tensor::DataType dtype) {
auto tensor = new Tensor(dims, Tensor::Input, dtype);
tensors.emplace_back(tensor);
return tensor;
}
Tensor *GraphBase::tensor(const Dim &dims, const std::string &dtype) {
if (dtype == "FLOAT")
return tensor(dims, Tensor::Float32);
if (dtype == "INT32")
return tensor(dims, Tensor::Int32);
if (dtype == "INT64") // FIXME: Treat int64 as int32
return tensor(dims, Tensor::Int32);
std::cout << "Unsupported data type: " + dtype << std::endl;
assert(false);
return nullptr;
}
void Graph::setInputs(TensorVec inputs_) { inputs = inputs_; }
void Graph::setOutputs(TensorVec outputs_) { outputs = outputs_; }
bool Graph::importOnnx(const char *net) {
start_interpreter();
try {
py::module::import("cpp_plugin").attr("import_onnx")(this, net);
} catch (py::error_already_set &e) {
if (e.matches(PyExc_ImportError)) {
std::cerr << "Import Error. Don't forget to set environment "
"variable PYTHONPATH to contain "
"<repo-root>/python"
<< std::endl;
}
throw;
}
if (mutateInceptionHead())
puts("Detecting inception head");
updateConnection();
return true;
}
// build manipulable graph from given oplist
// only consider Ops that are inside the oplist
// tensors are associated with Ops
//
SubGraph::SubGraph(OpVec oplist) {
hash = 2147483647;
std::map<size_t, Tensor *> tensorMap;
// clone to ops & tensors
for (auto originOp : oplist) {
auto op = originOp->clone();
ops.emplace_back(op);
for (auto tensor : originOp->getInputs()) {
Tensor *t;
if (tensorMap.find(tensor->getHash()) == tensorMap.end()) {
t = tensor->clone(); // inputOf and outputOf will not be cloned
tensors.emplace_back(t);
tensorMap.emplace(tensor->getHash(), t);
} else
t = tensorMap[tensor->getHash()];
t->addInputOf(op);
op->addInput(t);
}
for (auto tensor : originOp->getOutputs()) {
Tensor *t;
if (tensorMap.find(tensor->getHash()) == tensorMap.end()) {
t = tensor->clone();
tensors.emplace_back(t);
tensorMap.emplace(tensor->getHash(), t);
} else
t = tensorMap[tensor->getHash()];
t->setOutputOf(op);
op->addOutput(t);
}
}
for (auto tensor : tensors) {
for (auto opNext : tensor->getInputOf()) {
auto opPrev = tensor->getOutputOf();
if (opPrev != nullptr) {
opNext->addPredecessors(opPrev);
opPrev->addSuccessors(opNext);
}
}
// also populate inputs & outputs
if (!tensor->getInputOf().empty() && tensor->getOutputOf() == nullptr)
inputs.emplace_back(tensor);
if (tensor->getInputOf().empty() && tensor->getOutputOf() != nullptr)
outputs.emplace_back(tensor);
}
}
void SubGraph::cleanConnection() {
for (auto tensor : tensors) {
tensor->setOutputOf(nullptr);
tensor->setInputOf({});
}
for (auto op : ops) {
op->setPredecessors({});
op->setSuccessors({});
}
inputs.clear();
outputs.clear();
}
int SubGraph::findTensor(Tensor *tensor, int ntensor) {
ntensor = ntensor == 0 ? tensors.size() : ntensor;
for (int i = 0; i < ntensor; ++i)
if (tensors[i] == tensor)
return i;
return -1;
}
bool SubGraph::resetOps(OpVec oplist, size_t ntensor) {
ntensor = ntensor == 0 ? tensors.size() : ntensor;
hash = 2147483647;
// clear ops, inputs, outputs
ops.clear();
cleanConnection();
for (auto op : oplist) {
ops.emplace_back(op);
op->setPredecessors({});
op->setSuccessors({});
// op's input & output tensor must be in the graph already to find
for (auto tensor : op->getInputs()) {
auto idx = findTensor(
tensor); // search for idx of this tensor in graph's tensors
if (idx < 0)
return false;
auto t = tensors[idx];
t->addInputOf(op);
}
for (auto tensor : op->getOutputs()) {
auto idx = findTensor(tensor);
if (idx < 0)
return false;
auto t = tensors[idx];
t->setOutputOf(op);
}
}
for (size_t i = 0; i < ntensor; ++i) {
auto tensor = tensors[i];
for (auto opNext : tensor->getInputOf()) {
auto opPrev = tensor->getOutputOf();
if (opPrev != nullptr) {
opNext->addPredecessors(opPrev);
opPrev->addSuccessors(opNext);
}
}
if (!tensor->getInputOf().empty() && tensor->getOutputOf() == nullptr)
inputs.emplace_back(tensor);
if (tensor->getInputOf().empty() && tensor->getOutputOf() != nullptr)
outputs.emplace_back(tensor);
}
return true;
}
const std::pair<bool, VType>
SubGraph::compute(const Dim &point, size_t outputId, bool getAllPos) const {
if (outputId >= outputs.size()) {
return {false, 0};
}
std::unordered_map<const Tensor *, DimRange> drs;
for (auto output : outputs)
drs[output] = DimRange::getEmpty();
if (getAllPos)
drs[outputs[outputId]] = DimRange::getAllPos();
else
drs[outputs[outputId]] = DimRange(point);
// reversed DFS post-order is topo-order
std::unordered_set<const Operator *> flag;
// computing functions for operators
std::vector<std::function<bool()>> runners;
std::function<bool(Operator *)> dfs = [&](Operator *op) -> bool {
if (flag.count(op)) {
return true;
}
flag.insert(op);
for (auto &&next : op->getSuccessors()) {
if (!dfs(next)) {
return false;
}
}
std::vector<DimRange> inDrs;
std::function<bool()> runner;
Tensor *out = op->getOutput();
if (out != nullptr) {
std::tie(inDrs, runner) = op->compute(drs.at(out));
if (runner == nullptr) {
return false;
}
} else {
assert(op->isSplitOp());
out = op->getOutputs()[outputId];
std::tie(inDrs, runner) =
dynamic_cast<SplitOp *>(op)->compute(outputId, drs.at(out));
}
assert(op->isConcatOp() || (int)inDrs.size() == op->numInputs());
for (size_t i = 0, iEnd = inDrs.size(); i < iEnd; i++) {
const Tensor *t = op->getInputs()[i];
drs[t] = drs.count(t) ? unionRange(drs[t], inDrs[i]) : inDrs[i];
}
runners.push_back(runner);
return true;
};
// Operator *op = outputs[outputId]->getOutputOf();
for (auto &&op : ops) {
if (!dfs(op)) {
return {false, 0};
}
}
for (auto it = runners.rbegin(); it != runners.rend(); it++) {
if (!(*it)()) {
return {false, 0};
}
}
return {true, outputs[outputId]->getData(point)};
}
uint64_t SubGraph::getHash() {
if (hash != 2147483647) {
return hash;
}
// TODO: Replace string operations with int operations
auto &opList = getOperators();
std::vector<int> cnt(opList.size());
std::vector<uint64_t> nodeHash(opList.size());
std::unordered_map<int, int> nodeMap;
std::unordered_set<int> inputSet;
std::vector<int> q;
for (size_t i = 0; i < opList.size(); i++) {
auto &op = opList[i];
nodeMap.emplace(op->getGuid(), i);
cnt[i] = op->getPredecessors().size();
nodeHash[i] = hashPack(op->getHash());
}
for (auto t : getInputs()) {
inputSet.emplace(t->getGuid());
}
for (size_t i = 0; i < opList.size(); i++) {
auto &op = opList[i];
if (op->getPredecessors().size() == 0) {
q.emplace_back(i);
}
}
int st = 0, ed = q.size();
while (st < ed) {
int id = q[st];
st++;
auto &op = opList[id];
for (auto t : op->getInputs()) {
if (inputSet.find(t->getGuid()) != inputSet.end()) {
nodeHash[id] = hashAppend(nodeHash[id], t->getHash());
} else {
nodeHash[id] =
hashAppend(nodeHash[id],
nodeHash[nodeMap[t->getOutputOf()->getGuid()]]);
}
}
nodeHash[id] = hashPack(nodeHash[id]);
for (auto suc : op->getSuccessors()) {
int suc_id = nodeMap[suc->getGuid()];
cnt[suc_id]--;
if (cnt[suc_id] == 0) {
q.emplace_back(suc_id);
ed++;
}
}
}
hash = 0;
for (auto t : getOutputs()) {
int id = nodeMap[t->getOutputOf()->getGuid()];
hash =
hashAppend(hash, hashPack(hashAppend(t->getHash(), nodeHash[id])));
}
return hash;
}
int SubGraph::print() {
std::cout << "Subgraph[" << getHash() << "]" << std::endl;
std::cout << " op num: " << getOperators().size() << std::endl;
std::cout << " input: ";
for (auto input : getInputs()) {
std::cout << input->getHash() << " ";
}
std::cout << std::endl;
std::cout << " operator: " << std::endl;
for (auto op : getOperators()) {
std::cout << " ";
op->print();
std::cout << "[" << op->getGuid() << "]";
std::cout << " pre=[";
for (auto pre : op->getPredecessors()) {
std::cout << pre->getGuid() << ",";
}
std::cout << "], suc=[";
for (auto suc : op->getSuccessors()) {
std::cout << suc->getGuid() << ",";
}
std::cout << "]" << std::endl;
}
std::cout << " output: ";
for (auto output : getOutputs()) {
if (output->isNotCounted()) {
std::cout << "(" << output->getHash() << ") ";
} else {
std::cout << output->getHash() << " ";
}
}
std::cout << std::endl;
return 0;
}
int SubGraph::printBrief() {
std::cout << "Subgraph[" << getHash() << "] brief" << std::endl;
std::cout << " op num: " << getOperators().size() << std::endl;
std::cout << " input: ";
for (auto input : getInputs()) {
std::cout << input->getHash() << " ";
}
std::cout << std::endl;
std::cout << " output: ";
for (auto output : getOutputs()) {
if (output->isNotCounted()) {
std::cout << "(" << output->getHash() << ") ";
} else {
std::cout << output->getHash() << " ";
}
}
std::cout << std::endl;
return 0;
}
int SubGraph::getComputeOps(std::vector<Operator *> &opList) {
opList.clear();
for (auto op : ops) {
if (op->isComputeOp()) {
opList.emplace_back(op);
}
}
return 0;
};
int SubGraph::reset(std::vector<Tensor *> &input,
std::vector<Tensor *> &output) {
auto &origin_input = getInputs();
auto &origin_output = getOutputs();
std::unordered_map<int, int> map;
map.clear();
for (auto t : tensors) {
t->refresh();
}
if (origin_input.size() != input.size()) {
return 1;
}
for (size_t i = 0, iEnd = input.size(); i < iEnd; i++) {
origin_input[i]->replace(*input[i]);
}
if (origin_output.size() != output.size()) {
return 1;
}
for (size_t i = 0, iEnd = output.size(); i < iEnd; i++) {
origin_output[i]->replace(*output[i]);
}
return 0;
}
int SubGraph::split(std::shared_ptr<SubGraph> &master,
std::shared_ptr<SubGraph> &slave,
std::vector<Operator *> &slaveOps) {
std::unordered_set<Operator *> set, slaveSet;
for (auto op : getOperators()) {
set.emplace(op);
}
for (auto op : slaveOps) {
if (set.find(op) == set.end()) {
std::cout << "ERROR: [SubGraph::split] slave op not in subgraph."
<< std::endl;
return 1;
}
slaveSet.emplace(op);
}
std::vector<Operator *> masterOps;
for (auto op : getOperators()) {
if (slaveSet.find(op) == slaveSet.end()) {
masterOps.emplace_back(op);
}
}
master = std::make_shared<SubGraph>(masterOps);
slave = std::make_shared<SubGraph>(slaveOps);
return 0;
}
int SubGraph::merge(std::shared_ptr<SubGraph> &master,
std::shared_ptr<SubGraph> &slave) {
std::unordered_map<uint64_t, Tensor *> map;
std::vector<Operator *> ops;
for (auto t : getTensors()) {
map.emplace(t->getHash(), t);
}
for (auto op : getOperators()) {
ops.emplace_back(op);
}
for (auto op : slave->getOperators()) {
std::vector<Tensor *> inputs;
for (auto t : op->getInputs()) {
if (map.find(t->getHash()) != map.end()) {
inputs.emplace_back(map[t->getHash()]);
} else {
inputs.emplace_back(t);
}
}
std::vector<Tensor *> outputs;
for (auto t : op->getOutputs()) {
if (map.find(t->getHash()) != map.end()) {
outputs.emplace_back(map[t->getHash()]);
} else {
outputs.emplace_back(t);
}
}
op->setInputs(inputs);
op->setOutputs(outputs);
ops.emplace_back(op);
}
master = std::make_shared<SubGraph>(ops);
return 0;
}
bool Graph::mutateInceptionHead() {
const int max_dep = 4;
const std::vector<Operator::OpType> layer_ops{
Operator::Gather, Operator::Reshape, Operator::Mul, Operator::Add};
std::vector<std::vector<Tensor *>> layers_inputs(max_dep + 1);
std::vector<Operator *> head_ops;
Tensor *input = nullptr;
for (auto t : tensors) {
if (t->getType() == Tensor::Input) {
input = t;
break;
}
}
if (input == nullptr)
return false;
layers_inputs[0].push_back(input);
// TODO why there are more than 1 Input Tensor?
for (int i = 0; i < max_dep; ++i) {
int cnt = 0;
for (auto input : layers_inputs[i]) {
for (auto op : ops) {
if (std::find(op->getInputs().begin(), op->getInputs().end(),
input) == op->getInputs().end())
continue;
if (op->getType() != layer_ops[i] ||
op->getOutputs().size() != 1)
return false;
cnt++;
layers_inputs[i + 1].push_back(op->getOutputs()[0]);
head_ops.push_back(op);
}
}
if (cnt != 3)
return false;
}
// This model is inception
ConcatOp *concat_op = nullptr;
ConvOp *conv_op = nullptr;
for (auto op : ops) {
if (std::find(op->getInputs().begin(), op->getInputs().end(),
layers_inputs[max_dep][0]) != op->getInputs().end())
concat_op = dynamic_cast<ConcatOp *>(op);
}
for (auto op : ops) {
if (std::find(op->getInputs().begin(), op->getInputs().end(),
concat_op->getOutputs()[0]) != op->getInputs().end())
conv_op = dynamic_cast<ConvOp *>(op);
}
assert(concat_op && conv_op);
head_ops.push_back(concat_op);
Dim dim_weight{input->getDims()};
auto mul_weight = tensor(dim_weight, Tensor::Float32);
auto add_weight = tensor(dim_weight, Tensor::Float32);
auto mul_op = this->mul({input, mul_weight});
auto add_op = this->add({mul_op->getOutputs()[0], add_weight});
conv_op->setInputs({add_op->getOutputs()[0], conv_op->getInputs()[1]});
removeOps(head_ops);
return true;
}
void GraphBase::removeOps(OpVec &removed_ops) {
OpVec new_ops;
TensorVec new_tensors, removed_tensors;
for (Operator *op : ops) {
bool removed = std::find(removed_ops.begin(), removed_ops.end(), op) !=
removed_ops.end();
if (removed) {
for (auto t : op->getOutputs()) {
removed_tensors.push_back(t);
delete t;
}
delete op;
} else {
new_ops.push_back(op);
}
}
ops = new_ops;
for (auto *t : tensors) {
if (std::find(removed_tensors.begin(), removed_tensors.end(), t) !=
removed_tensors.end())
new_tensors.push_back(t);
}
tensors = new_tensors;
}
bool GraphBase::has_Ops(Operator *query) {
return std::find(ops.begin(), ops.end(), query) != ops.end();
}
bool GraphBase::exportOnnx(const char *path) {
std::vector<std::string> tensor_name;
std::map<std::string, std::string> tensor_dtype;
std::map<std::string, std::vector<int>> tensor_dim;
std::vector<std::string> initializer;
std::vector<std::string> op_name;
std::map<std::string, std::vector<std::string>> op_input, op_output;
std::map<std::string, std::map<std::string, std::string>> op_attr;
std::map<std::string, std::vector<int>> tensor_value;
auto &tensors = getTensors();
for (auto &tensor : tensors) {
size_t guid = tensor->getGuid();
Tensor::DataType dtype = tensor->getDType();
Dim dim = tensor->getDims();
Tensor::TensorType ttype = tensor->getType();
std::string name = "tensor_" + std::to_string(guid);
std::string dtype_str = "";
if (dtype == Tensor::DataType::Float32) {
dtype_str = "Float32";
} else {
dtype_str = "Int32";
}
tensor_name.emplace_back(name);
tensor_dtype[name] = dtype_str;
tensor_dim[name] = dim;
if (ttype == Tensor::TensorType::Weight) {
initializer.emplace_back(name);
} else {
if (ttype == Tensor::TensorType::Invalid) {
std::cout << "Invalid tensor founded!" << std::endl;
}
if (ttype == Tensor::TensorType::NotCounted) {
std::cout << "Notcounted tensor founded!" << std::endl;
}
}
}
std::cout << "Tensors Got." << std::endl;
auto &operators = getOperators();
for (auto &op : operators) {
if (op->isReshapeOp()) {
auto outp = op->getOutputs()[0];
std::vector<int> extra;
for (size_t i = 0, iEnd = (outp->getDims()).size(); i < iEnd; ++i) {
extra.emplace_back((outp->getDims())[i]);
}
std::string opname =
"Reshape_" + std::to_string(op->getGuid()) + "_shape";
tensor_value[opname] = extra;
}
if (op->isTransposeOp()) {
Tensor *inp = op->getInputs()[0];
Tensor *oup = op->getOutputs()[0];
std::string last = "tensor_" + std::to_string(inp->getGuid());
Dim last_dim = inp->getDims();
TransposeOp *trop = dynamic_cast<TransposeOp *>(op);
const std::vector<std::shared_ptr<TransBasic>> &totop =
trop->getTTParam();
for (size_t i = 0, iEnd = totop.size(); i < iEnd; ++i) {
std::string outp = "";
if (i == iEnd - 1) {
outp = "tensor_" + std::to_string(oup->getGuid());
} else {
outp = "tensor_tr_" + std::to_string(op->getGuid()) + "_" +
std::to_string(i);
tensor_name.emplace_back(outp);
tensor_dtype[outp] = tensor_dtype[last];
}
std::string optype = "";
std::vector<int> extra;
totop[i]->getOptypeDim(optype, last_dim, extra);
if (i < iEnd - 1)
tensor_dim[outp] = last_dim;
std::string opname = optype + "_tr_" +
std::to_string(op->getGuid()) + "_" +
std::to_string(i);
op_name.emplace_back(opname);
op_input[opname] = {last};
op_output[opname] = {outp};
last = outp;
if (optype == "Reshape") {
tensor_value[opname + "_shape"] = extra;
std::map<std::string, std::string> attr;
op_attr[opname] = attr;
}
if (optype == "Transpose") {
std::map<std::string, std::string> attr;
std::string perm = "";
for (auto x : extra)
perm += std::to_string(x) + ",";
perm.pop_back();
attr["perm"] = "[" + perm + "]";
op_attr[opname] = attr;
}
}
continue;
}
size_t guid = op->getGuid();
std::vector<std::string> inp, oup;
auto &inputtensors = op->getInputs();
for (auto &tensor : inputtensors) {
size_t guid = tensor->getGuid();
std::string name = "tensor_" + std::to_string(guid);
inp.emplace_back(name);
}
auto &outputtensors = op->getOutputs();
for (auto &tensor : outputtensors) {
size_t guid = tensor->getGuid();
std::string name = "tensor_" + std::to_string(guid);
oup.emplace_back(name);
}
std::string optype;
std::map<std::string, std::string> attr;
std::map<std::string, std::vector<int>> extra;
op->getOptypeAttr(optype, attr, extra);
for (auto it = extra.begin(); it != extra.end(); ++it) {
std::string name = it->first;
tensor_name.emplace_back(name);
tensor_dtype[name] = "Float32";
tensor_dim[name] = it->second;
initializer.emplace_back(name);
inp.emplace_back(name);
}
std::string opname = optype + "_" + std::to_string(guid);
op_name.emplace_back(opname);
op_input[opname] = inp;
op_output[opname] = oup;
op_attr[opname] = attr;
}
std::cout << "Operators Got." << std::endl;
start_interpreter();
try {
py::module::import("cpp_plugin")
.attr("export_onnx")(path, tensor_name, tensor_dtype, tensor_dim,
initializer, op_name, op_input, op_output,
op_attr, tensor_value);
} catch (py::error_already_set &e) {
if (e.matches(PyExc_ImportError)) {
std::cerr << "Import Error. Don't forget to set environment "
"variable PYTHONPATH to contain "
"<repo-root>/python"
<< std::endl;
}
throw;
}
return true;
}
} // namespace tpm
| 33.565657 | 80 | 0.540497 | [
"vector",
"model"
] |
7aa1180f4a6533b260d92f495ac184811ff69c73 | 9,150 | hpp | C++ | ccore/include/pyclustering/cluster/kmeans_plus_plus.hpp | JosephChataignon/pyclustering | bf4f51a472622292627ec8c294eb205585e50f52 | [
"BSD-3-Clause"
] | 1,013 | 2015-01-26T19:50:14.000Z | 2022-03-31T07:38:48.000Z | ccore/include/pyclustering/cluster/kmeans_plus_plus.hpp | peterlau0626/pyclustering | bf4f51a472622292627ec8c294eb205585e50f52 | [
"BSD-3-Clause"
] | 542 | 2015-01-20T16:44:32.000Z | 2022-01-29T14:57:20.000Z | ccore/include/pyclustering/cluster/kmeans_plus_plus.hpp | peterlau0626/pyclustering | bf4f51a472622292627ec8c294eb205585e50f52 | [
"BSD-3-Clause"
] | 262 | 2015-03-19T07:28:12.000Z | 2022-03-30T07:28:24.000Z | /*!
@authors Andrei Novikov (pyclustering@yandex.ru)
@date 2014-2020
@copyright BSD-3-Clause
*/
#pragma once
#include <random>
#include <unordered_set>
#include <pyclustering/definitions.hpp>
#include <pyclustering/cluster/center_initializer.hpp>
#include <pyclustering/cluster/cluster_data.hpp>
#include <pyclustering/utils/metric.hpp>
using namespace pyclustering::utils::metric;
namespace pyclustering {
namespace clst {
/**
*
* @brief K-Means++ center initializer algorithm.
*
*/
class kmeans_plus_plus : public center_initializer {
public:
/**
*
* @brief Denotes that the farthest center candidate (with highest probability) should be used as a center.
*
*/
static const std::size_t FARTHEST_CENTER_CANDIDATE;
/**
*
* @brief Non-existed index that represents non-initialized value.
*
*/
static const std::size_t INVALID_INDEX;
public:
/**
*
* @brief Metric that is used for distance calculation between two points.
*
*/
using metric = distance_functor<std::vector<double>>;
private:
using index_set = std::unordered_set<std::size_t>;
using center_description = std::tuple<point, std::size_t>;
enum { POINT, INDEX };
using store_result = std::function<void(center_description &)>;
private:
std::size_t m_amount = 0;
std::size_t m_candidates = 0;
metric m_dist_func;
long long m_random_state = RANDOM_STATE_CURRENT_TIME;
mutable std::mt19937 m_generator;
/* temporal members that are used only during initialization */
mutable dataset const * m_data_ptr = nullptr;
mutable index_sequence const * m_indexes_ptr = nullptr;
mutable index_set m_free_indexes;
mutable index_sequence m_allocated_indexes;
public:
/**
*
* @brief Default constructor to create initializer algorithm K-Means++.
*
*/
kmeans_plus_plus() = default;
/**
*
* @brief Constructor of center initializer algorithm K-Means++.
*
* @param[in] p_amount: amount of centers that should initialized.
* @param[in] p_candidates: amount of candidates that are considered to find the best center, if
* the farthest candidate is required (with highest probability) than static constant
* FARTHEST_CENTER_CANDIDATE can be specified.
* @param[in] p_random_state: seed for random state (by default is `RANDOM_STATE_CURRENT_TIME`, current system time is used).
*
* @see FARTHEST_CENTER_CANDIDATE
*
*/
kmeans_plus_plus(const std::size_t p_amount, const std::size_t p_candidates = 1, const long long p_random_state = RANDOM_STATE_CURRENT_TIME) noexcept;
/**
*
* @brief Constructor of center initializer algorithm K-Means++.
* @details By default algorithm uses square Euclidean distance as a metric.
*
* @param[in] p_amount: amount of centers that should initialized.
* @param[in] p_candidates: amount of candidates that are considered to find the best center, if
* the farthest candidate is required (with highest probability) than static constant
* FARTHEST_CENTER_CANDIDATE can be specified.
* @param[in] p_metric: metric for distance calculation between points.
* @param[in] p_random_state: seed for random state (by default is `RANDOM_STATE_CURRENT_TIME`, current system time is used).
*
* @see FARTHEST_CENTER_CANDIDATE
*
*/
kmeans_plus_plus(const std::size_t p_amount, const std::size_t p_candidates, const metric & p_metric, const long long p_random_state = RANDOM_STATE_CURRENT_TIME) noexcept;
/**
*
* @brief Default copy constructor to create initializer algorithm K-Means++.
*
*/
kmeans_plus_plus(const kmeans_plus_plus & p_other) = default;
/**
*
* @brief Default move constructor to create initializer algorithm K-Means++.
*
*/
kmeans_plus_plus(kmeans_plus_plus && p_other) = default;
/**
*
* @brief Default destructor to destroy initializer algorithm K-Means++.
*
*/
~kmeans_plus_plus() = default;
public:
/**
*
* @brief Performs center initialization process in line algorithm configuration.
*
* @param[in] p_data: data for that centers are calculated.
* @param[out] p_centers: initialized centers for the specified data.
*
*/
void initialize(const dataset & p_data, dataset & p_centers) const override;
/**
*
* @brief Performs center initialization process in line algorithm configuration for
* specific range of points.
*
* @param[in] p_data: data for that centers are calculated.
* @param[in] p_indexes: point indexes from data that are defines which points should be considered
* during calculation process. If empty then all data points are considered.
* @param[out] p_centers: initialized centers for the specified data.
*
*/
void initialize(const dataset & p_data, const index_sequence & p_indexes, dataset & p_centers) const override;
/**
*
* @brief Performs center initialization process in line algorithm configuration using real points from dataset as centers.
*
* @param[in] p_data: data for that centers are calculated.
* @param[out] p_center_indexes: initialized center indexes for the specified data where indexes correspond to points from the data.
*
*/
void initialize(const dataset & p_data, index_sequence & p_center_indexes) const;
private:
/**
*
* @brief Assigns seed to the random generator that is used by the algorithm.
*
*/
void initialize_random_generator();
/**
*
* @brief Performs center initialization process in line algorithm configuration.
*
* @param[in] p_data: data for that centers are calculated.
* @param[in] p_indexes: point indexes from data that are defines which points should be considered
* during calculation process. If empty then all data points are considered.
* @param[out] p_proc: function that defines how to store output result of the algorithm.
*
*/
void initialize(const dataset & p_data, const index_sequence & p_indexes, const store_result & p_proc) const;
/**
*
* @brief Store obtained center.
*
* @param[in] p_proc: function that defines how to store output result of the algorithm.
* @param[in] p_result: initialized center that should be stored.
*
*/
void store_center(const store_result & p_proc, center_description & p_result) const;
/**
*
* @brief Store pointers to data, indexes and centers to avoiding passing them between class methods.
* @details Pointers are reseted when center initialization is over.
*
* @param[in] p_data: data for that centers are calculated.
* @param[in] p_indexes: point indexes from data that are defines which points should be
* considered during calculation process.
*
* @return The first initialized center.
*
*/
void store_temporal_params(const dataset & p_data, const index_sequence & p_indexes) const;
/**
*
* @brief Reset (fill by nullptr) temporal points.
*
*/
void free_temporal_params() const;
/**
*
* @brief Calculates the first initial center using uniform distribution.
*
* @return The first initialized center.
*
*/
center_description get_first_center() const;
/**
*
* @brief Calculates the next most probable center in line with weighted distribution.
*
* @return The next initialized center.
*
*/
center_description get_next_center() const;
/**
*
* @brief Calculates distances from each point to closest center.
*
* @param[out] p_distances: the shortest distances from each point to center.
*
*/
void calculate_shortest_distances(std::vector<double> & p_distances) const;
/**
*
* @brief Calculates distance from the specified point to the closest center.
*
* @param[in] p_point: point for that the shortest distance is calculated.
*
*/
double get_shortest_distance(const point & p_point) const;
/**
*
* @brief Calculates center probability for each point using distances to closest centers.
*
* @param[in] p_distances: distances from each point to closest center.
* @param[out] p_probabilities: probability of each point to be next center.
*
*/
void calculate_probabilities(const std::vector<double> & p_distances, std::vector<double> & p_probabilities) const;
/**
*
* @brief Calculates most probable center.
*
* @param[in] p_distances: distances from each point to closest center.
* @param[in] p_probabilities: probability of each point to be next center.
*
*/
std::size_t get_probable_center(const std::vector<double> & p_distances, const std::vector<double> & p_probabilities) const;
};
}
}
| 31.6609 | 175 | 0.66929 | [
"vector"
] |
7aa54af63983238ffbcf8c1a984ffa60b7f6ed06 | 4,450 | cpp | C++ | GAME/gamemap/skybox.cpp | leogenot/IMACRUN | 9767a6f23d03d8ef61d3aa2bd7c5a8873f3d21b4 | [
"MIT"
] | null | null | null | GAME/gamemap/skybox.cpp | leogenot/IMACRUN | 9767a6f23d03d8ef61d3aa2bd7c5a8873f3d21b4 | [
"MIT"
] | null | null | null | GAME/gamemap/skybox.cpp | leogenot/IMACRUN | 9767a6f23d03d8ef61d3aa2bd7c5a8873f3d21b4 | [
"MIT"
] | 1 | 2021-11-10T13:52:22.000Z | 2021-11-10T13:52:22.000Z | #include "GAME_H/gamemap/skybox.hpp"
void Skybox::initSkybox()
{
Shader skyboxShader("GAME/shaders/skybox.vs", "GAME/shaders/skybox.fs");
m_skyboxShader = skyboxShader;
float skyboxVertices[] = {
// positions
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, 1.0f};
glGenVertexArrays(1, &m_VAO);
glGenBuffers(1, &m_VBO);
glBindVertexArray(m_VAO);
glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(skyboxVertices), &skyboxVertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
std::vector<std::string> faces{
"assets/textures/skybox/desert/right.png",
"assets/textures/skybox/desert/left.png",
"assets/textures/skybox/desert/top.png",
"assets/textures/skybox/desert/bottom.png",
"assets/textures/skybox/desert/front.png",
"assets/textures/skybox/desert/back.png"};
cubemapTexture = loadCubemap(faces);
m_skyboxShader.use();
m_skyboxShader.setInt("skybox", 0);
}
void Skybox::draw(glm::mat4 view, glm::mat4 projection, glm::mat4 model, glm::mat4 cameraViewMatrix) const
{
// draw skybox as last
glDepthFunc(GL_LEQUAL); // change depth function so depth test passes when values are equal to depth buffer's content
m_skyboxShader.use();
view = glm::mat4(glm::mat3(cameraViewMatrix)); // remove translation from the view matrix
//view = glm::mat4(glm::mat3(Trackcamera.GetViewMatrix())); // remove translation from the view matrix
m_skyboxShader.setMat4("view", view);
m_skyboxShader.setMat4("projection", projection);
// skybox cube
glBindVertexArray(m_VAO);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_CUBE_MAP, cubemapTexture);
glDrawArrays(GL_TRIANGLES, 0, 36);
glBindVertexArray(0);
glDepthFunc(GL_LESS); // set depth function back to default
}
// loads a cubemap texture from 6 individual texture faces
// order:
// +X (right)
// -X (left)
// +Y (top)
// -Y (bottom)
// +Z (front)
// -Z (back)
// -------------------------------------------------------
unsigned int Skybox::loadCubemap(std::vector<std::string> faces)
{
unsigned int textureID;
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);
int width, height, nrChannels;
for (unsigned int i = 0; i < faces.size(); i++) {
unsigned char* data = stbi_load(faces[i].c_str(), &width, &height, &nrChannels, 0);
if (data) {
GLenum format;
if (nrChannels == 1)
format = GL_RED;
else if (nrChannels == 3)
format = GL_RGB;
else if (nrChannels == 4)
format = GL_RGBA;
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
stbi_image_free(data);
}
else {
std::cerr << "Cubemap texture failed to load at path: " << faces[i] << std::endl;
stbi_image_free(data);
}
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
return textureID;
}
| 32.014388 | 122 | 0.586517 | [
"vector",
"model"
] |
7aac54004945854b1ceed8d4a4f1fefcddf6996b | 2,198 | cpp | C++ | src/backtest.cpp | nKastelan/Ed | ffa8e2800ba1f9e1001230710820742897acb7a9 | [
"MIT"
] | 2 | 2021-10-09T12:56:02.000Z | 2022-01-04T05:33:46.000Z | src/backtest.cpp | nKastelan/Ed | ffa8e2800ba1f9e1001230710820742897acb7a9 | [
"MIT"
] | null | null | null | src/backtest.cpp | nKastelan/Ed | ffa8e2800ba1f9e1001230710820742897acb7a9 | [
"MIT"
] | null | null | null | #include "backtest.hpp"
Backtest::Backtest(std::vector<std::string>* symbols, std::string* csvDirectory, double* initialCapital) : exchange(&eventQueue, &dataHandler) {
this->symbols = *symbols;
this->csvDirectory = *csvDirectory;
this->initialCapital = initialCapital;
this->continueBacktest = false;
this->dataHandler = SingleCSVDataHandler(&eventQueue, csvDirectory, symbols, &continueBacktest);
this->portfolio = SimplePortfolio(&dataHandler, symbols, initialCapital);
this->benchmarkPortfolio = SimplePortfolio(&dataHandler, symbols, initialCapital);
}
void Backtest::run(TradingStrategy* strategy, Benchmark* benchmark) {
continueBacktest = true;
bool first = true;
dataHandler.loadData();
dataHandler.updateBars();
std::cout << "Backtest started!" << std::endl;
while (continueBacktest) {
while (!eventQueue.empty()) {
auto event = eventQueue.front();
eventQueue.pop();
switch (event->type) {
case 0: {
strategy->calculateSignals();
if (first) {
benchmark->calculateSignals();
first = false;
}
portfolio.update();
benchmarkPortfolio.update();
break;
}
case 1: {
auto signal = dynamic_pointer_cast<SignalEvent>(event);
if (event->target == "ALGO") {
portfolio.onSignal(signal);
}
else if (event->target == "BENCH") {
benchmarkPortfolio.onSignal(signal);
}
break;
}
case 2: {
auto order = dynamic_pointer_cast<OrderEvent>(event);
exchange.executeOrder(order);
order->logOrder();
break;
}
case 3: {
auto fill = dynamic_pointer_cast<FillEvent>(event);
if (event->target == "ALGO") {
portfolio.onFill(fill);
portfolio.update();
}
else if (event->target == "BENCH") {
benchmarkPortfolio.onFill(fill);
benchmarkPortfolio.update();
}
break;
}
}
}
dataHandler.updateBars();
}
std::cout << "Backtest ended!\n" << std::endl;
std::cout << "PERFORMANCE METRICS (TRADING STRATEGY)\n--------------------------------------" << std::endl;
portfolio.getMetrics();
std::cout << "\n\nPERFORMANCE METRICS (BUY AND HOLD)\n----------------------------------" << std::endl;
benchmarkPortfolio.getMetrics();
} | 26.804878 | 144 | 0.643767 | [
"vector"
] |
7ab31f6d0b9379402bb5366b1e3d4771d4be1e99 | 738 | cpp | C++ | NOIP/oj.noi.cn/1101_submatrix_sum.cpp | webturing/CPlusPlus | 6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f | [
"AFL-2.0"
] | 14 | 2018-06-21T14:41:26.000Z | 2021-12-19T14:43:51.000Z | NOIP/oj.noi.cn/1101_submatrix_sum.cpp | webturing/CPlusPlus | 6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f | [
"AFL-2.0"
] | null | null | null | NOIP/oj.noi.cn/1101_submatrix_sum.cpp | webturing/CPlusPlus | 6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f | [
"AFL-2.0"
] | 2 | 2020-04-20T11:16:53.000Z | 2021-01-02T15:58:35.000Z | //
// Created by jal on 18-6-29.
//
#include <bits/stdc++.h>
using namespace std;
int main(){
ifstream cin("input.txt");
int n,m;
cin >> n >> m;
vector<vector<int>>v(n+1, vector<int>(m+1, 0));
for(int i = 1; i <= n; i ++ ){
for(int j = 1; j <= m; j++){
cin >> v[i][j];
}
}
vector<vector<int>>sum(n+1,vector<int>(m+1,0));
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
sum[i][j] = sum[i][j-1] + sum[i-1][j] + v[i][j] - sum[i-1][j-1];
}
}
int q;
cin >> q;
while(q--){
int sx,sy,ex,ey;
cin >> sx >> sy >> ex >> ey;
cout << sum[ex][ey] - sum[sx-1][ey] - sum[ex][sy-1] + sum[sx-1][sy-1] << endl;
}
} | 24.6 | 86 | 0.410569 | [
"vector"
] |
7abbb274faabf33c64307fdbdf64adc62c58aca1 | 3,889 | cc | C++ | bin/preinit-lazylm-get-statetable.cc | chenzhehuai/kaldi-decoders | b6f6e1e72f09a44efe5ee943d65ebf32c994aa47 | [
"MIT"
] | 17 | 2018-01-21T23:58:43.000Z | 2019-08-15T11:47:19.000Z | bin/preinit-lazylm-get-statetable.cc | chenzhehuai/kaldi-decoders | b6f6e1e72f09a44efe5ee943d65ebf32c994aa47 | [
"MIT"
] | null | null | null | bin/preinit-lazylm-get-statetable.cc | chenzhehuai/kaldi-decoders | b6f6e1e72f09a44efe5ee943d65ebf32c994aa47 | [
"MIT"
] | 5 | 2018-04-28T13:29:49.000Z | 2020-02-11T03:16:03.000Z | // bin/preinit-lazylm-get-statetable.cc
//
// Copyright 2018 Zhehuai Chen
//
// 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 "base/kaldi-common.h"
#include "util/common-utils.h"
#include "tree/context-dep.h"
#include "hmm/transition-model.h"
#include "fstext/fstext-lib.h"
#include "decoder/decoder-wrappers.h"
#include "decoder/decodable-matrix.h"
#include "base/timer.h"
#include <fst/script/info.h>
#include "lazylm.h"
int main(int argc, char *argv[]) {
try {
using namespace kaldi;
typedef kaldi::int32 int32;
using fst::SymbolTable;
using fst::VectorFst;
using fst::StdArc;
const char *usage =
"get state table for preinit algorithm based on acc\n";
ParseOptions po(usage);
Timer timer;
fst::LazyLMConfig lazylm_config;
fst::CacheOptions cache_config;
int gc_limit = 536870912; // 512MB
// design for getting statetable
lazylm_config.otf_mode=13;
lazylm_config.preinit_mode=2;
lazylm_config.preinit_para=-1;
lazylm_config.Register(&po);
po.Register("compose-gc-limit", &gc_limit,
"Number of bytes allowed in the composition cache before "
"garbage collection.");
po.Read(argc, argv);
cache_config.gc_limit = gc_limit;
KALDI_ASSERT(lazylm_config.statetable_out_filename != "");
if (po.NumArgs() != 2) {
po.PrintUsage();
exit(1);
}
std::string hcl_in_str = po.GetArg(1),
g_in_str = po.GetArg(2);
const bool is_table_hcl =
ClassifyRspecifier(hcl_in_str, NULL, NULL) != kNoRspecifier;
const bool is_table_g =
ClassifyRspecifier(g_in_str, NULL, NULL) != kNoRspecifier;
if (!is_table_hcl && !is_table_g) {
// It's important that we initialize decode_fst after loglikes_reader,
// as it can prevent crashes on systems installed without enough virtual
// memory.
// It has to do with what happens on UNIX systems if you call fork() on a
// large process: the page-table entries are duplicated, which requires a
// lot of virtual memory.
fst::Fst<StdArc> *hcl_fst = fst::ReadFstKaldiGeneric(hcl_in_str, true);
fst::Fst<StdArc> *g_fst = fst::ReadFstKaldiGeneric(g_in_str, true);
// On-demand composition of HCL and G
fst::LazyLMComposeFst<StdArc> lazylm(*hcl_fst, *g_fst, lazylm_config, cache_config);
lazylm.PreInitFST();
delete hcl_fst;
delete g_fst;
} else {
KALDI_ERR << "The decoding of tables/non-tables and match-type that you "
<< "supplied is not currently supported. Either implement "
<< "this, ask the maintainers to implement it, or call this "
<< "program differently.";
}
KALDI_LOG << "Time taken "<< timer.Elapsed();
} catch(const std::exception &e) {
std::cerr << e.what();
return -1;
}
}
| 35.678899 | 90 | 0.686552 | [
"model"
] |
7ac1204b11d6a7f1a93d70895514b4e607ad5e64 | 735 | cpp | C++ | C++/0939-Minimum-Area-Rectangle/soln-1.cpp | wyaadarsh/LeetCode-Solutions | 3719f5cb059eefd66b83eb8ae990652f4b7fd124 | [
"MIT"
] | 5 | 2020-07-24T17:48:59.000Z | 2020-12-21T05:56:00.000Z | C++/0939-Minimum-Area-Rectangle/soln-1.cpp | zhangyaqi1989/LeetCode-Solutions | 2655a1ffc8678ad1de6c24295071308a18c5dc6e | [
"MIT"
] | null | null | null | C++/0939-Minimum-Area-Rectangle/soln-1.cpp | zhangyaqi1989/LeetCode-Solutions | 2655a1ffc8678ad1de6c24295071308a18c5dc6e | [
"MIT"
] | 2 | 2020-07-24T17:49:01.000Z | 2020-08-31T19:57:35.000Z | class Solution {
public:
int minAreaRect(vector<vector<int>>& points) {
unordered_map<int, unordered_set<int>> x_to_ys;
for(vector<int> & point : points) x_to_ys[point[0]].insert(point[1]);
int min_area = INT_MAX;
for(vector<int> & p1 : points) {
for(vector<int> & p2 : points) {
int x1 = p1[0], y1 = p1[1], x2 = p2[0], y2 = p2[1];
if (x1 == x2 || y1 == y2) continue;
if (x_to_ys[x1].find(y2) != x_to_ys[x1].end() && x_to_ys[x2].find(y1) != x_to_ys[x2].end()) {
min_area = min(min_area, abs(x2 - x1) * abs(y2 - y1));
}
}
}
return min_area == INT_MAX ? 0 : min_area;
}
};
| 38.684211 | 109 | 0.488435 | [
"vector"
] |
7ac2fd5370f680c18ef5c1910e5db987ad451802 | 4,997 | cc | C++ | test/parse_html.cc | RobertWeber1/web_ui_helper | 88ebe6fd5b8bd5b23301400c0dfc4056a576358c | [
"MIT"
] | null | null | null | test/parse_html.cc | RobertWeber1/web_ui_helper | 88ebe6fd5b8bd5b23301400c0dfc4056a576358c | [
"MIT"
] | null | null | null | test/parse_html.cc | RobertWeber1/web_ui_helper | 88ebe6fd5b8bd5b23301400c0dfc4056a576358c | [
"MIT"
] | null | null | null | #include <catch2/catch.hpp>
#include <web_ui/compressor.h>
#include <iostream>
TEST_CASE("get file content")
{
REQUIRE(
web_ui::Compressor::get_file_content(TEST_DATA_PATH "index.html")
==
R"XML(<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8"/>
<title>Foo</title>
<link rel="stylesheet" type="text/css" href="style.css"/>
<link rel="shortcut icon" href="fav.ico"/>
<script src="javascript.js"></script>
</head>
<body onload="display_msg()">
<p> <img src="drawing.svg" alt="test image 1"/> </p>
<p> <img src="image.png" alt="test image 2"/> </p>
</body>
</html>
)XML");
}
TEST_CASE("get file content base64 encoded")
{
REQUIRE(
web_ui::Compressor::get_file_content_base64(TEST_DATA_PATH "fav.ico")
==
"AAABAAEAEBAQAAEABAAoAQAAFgAAACgAAAAQAAAAIAAAAAEABAAAAAAAAAAAAAAAAAAAAA"
"AAAAAAAAAAAADqDg4ADg7qAA7qfAD///8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAMzMzMzMzMzMxEREREREREzERERERERETMRERERERER"
"MxAAAAABEREzEAAAAAERETMwAAAAAzMzMzAAAAADMzMzMAAAAAMzMzMiIiIiIiIzMyIiIi"
"IiIjMzIiIiIiIiMzMiIiIiIiIzMyIiIiIiIjMzIiIiIiIiMzMzMzMzMzMzMAAAAAAAAAAA"
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
"AAAA");
}
TEST_CASE("remove white space chars from CSS")
{
REQUIRE(web_ui::Compressor::remove_ws("{}") == "{}");
REQUIRE(web_ui::Compressor::remove_ws(" { } ") == " { } ");
REQUIRE(web_ui::Compressor::remove_ws("{ }") == "{ }");
REQUIRE(web_ui::Compressor::remove_ws("{ \n\r\t }") == "{ }");
}
TEST_CASE("replace stylesheet-link-tag with style-tag")
{
REQUIRE(
web_ui::Compressor::embed_externals(
R"XML(<html><link rel="stylesheet" type="text/css" href="style.css"/></html>)XML",
TEST_DATA_PATH,
false)
== "<html><style> body { background-color: lightblue; } </style></html>");
}
TEST_CASE("replace faviocn ref with file base64 encoded content")
{
REQUIRE(
web_ui::Compressor::embed_externals(
R"XML(<html><link rel="shortcut icon" href="fav.ico"/></html>)XML",
TEST_DATA_PATH,
false)
== R"XML(<html><link rel="shortcut icon" href="data:image/ico;base64,)XML"
R"XML(AAABAAEAEBAQAAEABAAoAQAAFgAAACgAAAAQAAAAIAAAAAEABAAAAAAAAAAAAAAAAAAAAA)XML"
R"XML(AAAAAAAAAAAADqDg4ADg7qAA7qfAD///8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA)XML"
R"XML(AAAAAAAAAAAAAAAAAAAAAAAAAAAAMzMzMzMzMzMxEREREREREzERERERERETMRERERERER)XML"
R"XML(MxAAAAABEREzEAAAAAERETMwAAAAAzMzMzAAAAADMzMzMAAAAAMzMzMiIiIiIiIzMyIiIi)XML"
R"XML(IiIjMzIiIiIiIiMzMiIiIiIiIzMyIiIiIiIjMzIiIiIiIiMzMzMzMzMzMzMAAAAAAAAAAA)XML"
R"XML(AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA)XML"
R"XML(AAAA"/></html>)XML");
}
TEST_CASE("embed javascript")
{
REQUIRE(
web_ui::Compressor::embed_externals(
R"XML(<html><script src="javascript.js"></script></html>)XML",
TEST_DATA_PATH,
false)
== R"XML(<html><script> function display_msg() { console.log("Hello World!"); } </script></html>)XML");
}
TEST_CASE("embed svg")
{
REQUIRE(
web_ui::Compressor::embed_externals(
R"XML(<html><img src="drawing.svg" alt="test image 1"/></html>)XML",
TEST_DATA_PATH,
false)
== R"XML(<html><svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" width="188.97638" height="196.50986" viewBox="0 0 49.999999 51.993235" version="1.1" id="svg8" inkscape:version="0.92.5 (2060ec1f9f, 2020-04-08)" sodipodi:docname="drawing.svg"><defs id="defs2"/><sodipodi:namedview id="base" pagecolor="#ffffff" bordercolor="#666666" borderopacity="1.0" inkscape:pageopacity="0.0" inkscape:pageshadow="2" inkscape:zoom="1.979899" inkscape:cx="261.85006" inkscape:cy="86.265814" inkscape:document-units="mm" inkscape:current-layer="layer1" showgrid="false" units="px" inkscape:window-width="1916" inkscape:window-height="1056" inkscape:window-x="0" inkscape:window-y="20" inkscape:window-maximized="1" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0"/><metadata id="metadata5"><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage"/><dc:title/></cc:Work></rdf:RDF></metadata><g inkscape:label="Layer 1" inkscape:groupmode="layer" id="layer1" transform="translate(-0.30710585,-244.71155)"><g id="g59" transform="matrix(14.063359,0,0,14.063359,-4.0118313,-3875.9595)"><rect y="293.61002" x="1.0984933" height="2.0079985" width="1.7717634" id="rect12" style="fill:#00ff00;stroke-width:0.26458332"/><rect y="293.0076" x="2.0788691" height="1.8544457" width="1.7835751" id="rect14" style="fill:#800000;stroke-width:0.26458332"/><rect y="295.3345" x="0.30710566" height="1.3701665" width="2.775763" id="rect16" style="fill:#008080;stroke-width:0.26458332"/></g></g></svg></html>)XML");
}
| 50.474747 | 1,886 | 0.728037 | [
"transform"
] |
7ac54ddd370ddf9f0a1e1b17a2f5aac71db746d8 | 43,647 | cc | C++ | squid/squid3-3.3.8.spaceify/src/snmp_core.cc | spaceify/spaceify | 4296d6c93cad32bb735cefc9b8157570f18ffee4 | [
"MIT"
] | 4 | 2015-01-20T15:25:34.000Z | 2017-12-20T06:47:42.000Z | squid/squid3-3.3.8.spaceify/src/snmp_core.cc | spaceify/spaceify | 4296d6c93cad32bb735cefc9b8157570f18ffee4 | [
"MIT"
] | 4 | 2015-05-15T09:32:55.000Z | 2016-02-18T13:43:31.000Z | squid/squid3-3.3.8.spaceify/src/snmp_core.cc | spaceify/spaceify | 4296d6c93cad32bb735cefc9b8157570f18ffee4 | [
"MIT"
] | null | null | null | /*
* DEBUG: section 49 SNMP support
* AUTHOR: Glenn Chisholm
*
* SQUID Web Proxy Cache http://www.squid-cache.org/
* ----------------------------------------------------------
*
* Squid is the result of efforts by numerous individuals from
* the Internet community; see the CONTRIBUTORS file for full
* details. Many organizations have provided support for Squid's
* development; see the SPONSORS file for full details. Squid is
* Copyrighted (C) 2001 by the Regents of the University of
* California; see the COPYRIGHT file for full details. Squid
* incorporates software developed and/or copyrighted by other
* sources; see the CREDITS file for full details.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
*
*/
#include "squid.h"
#include "acl/FilledChecklist.h"
#include "base/CbcPointer.h"
#include "CachePeer.h"
#include "client_db.h"
#include "comm.h"
#include "comm/Connection.h"
#include "comm/Loops.h"
#include "comm/UdpOpenDialer.h"
#include "ip/Address.h"
#include "ip/tools.h"
#include "snmp_agent.h"
#include "snmp_core.h"
#include "snmp/Forwarder.h"
#include "SnmpRequest.h"
#include "SquidConfig.h"
#include "tools.h"
static void snmpPortOpened(const Comm::ConnectionPointer &conn, int errNo);
mib_tree_entry *mib_tree_head;
mib_tree_entry *mib_tree_last;
Comm::ConnectionPointer snmpIncomingConn;
Comm::ConnectionPointer snmpOutgoingConn;
static mib_tree_entry * snmpAddNodeStr(const char *base_str, int o, oid_ParseFn * parsefunction, instance_Fn * instancefunction, AggrType aggrType = atNone);
static mib_tree_entry *snmpAddNode(oid * name, int len, oid_ParseFn * parsefunction, instance_Fn * instancefunction, AggrType aggrType, int children,...);
static oid *snmpCreateOid(int length,...);
mib_tree_entry * snmpLookupNodeStr(mib_tree_entry *entry, const char *str);
int snmpCreateOidFromStr(const char *str, oid **name, int *nl);
SQUIDCEXTERN void (*snmplib_debug_hook) (int, char *);
static oid *static_Inst(oid * name, snint * len, mib_tree_entry * current, oid_ParseFn ** Fn);
static oid *time_Inst(oid * name, snint * len, mib_tree_entry * current, oid_ParseFn ** Fn);
static oid *peer_Inst(oid * name, snint * len, mib_tree_entry * current, oid_ParseFn ** Fn);
static oid *client_Inst(oid * name, snint * len, mib_tree_entry * current, oid_ParseFn ** Fn);
static void snmpDecodePacket(SnmpRequest * rq);
static void snmpConstructReponse(SnmpRequest * rq);
static oid_ParseFn *snmpTreeNext(oid * Current, snint CurrentLen, oid ** Next, snint * NextLen);
static oid_ParseFn *snmpTreeGet(oid * Current, snint CurrentLen);
static mib_tree_entry *snmpTreeEntry(oid entry, snint len, mib_tree_entry * current);
static mib_tree_entry *snmpTreeSiblingEntry(oid entry, snint len, mib_tree_entry * current);
extern "C" void snmpSnmplibDebug(int lvl, char *buf);
/*
* The functions used during startup:
* snmpInit
* snmpConnectionOpen
* snmpConnectionClose
*/
/*
* Turns the MIB into a Tree structure. Called during the startup process.
*/
void
snmpInit(void)
{
debugs(49, 5, "snmpInit: Building SNMP mib tree structure");
snmplib_debug_hook = snmpSnmplibDebug;
/*
* This following bit of evil is to get the final node in the "squid" mib
* without having a "search" function. A search function should be written
* to make this and the other code much less evil.
*/
mib_tree_head = snmpAddNode(snmpCreateOid(1, 1), 1, NULL, NULL, atNone, 0);
assert(mib_tree_head);
debugs(49, 5, "snmpInit: root is " << mib_tree_head);
snmpAddNodeStr("1", 3, NULL, NULL);
snmpAddNodeStr("1.3", 6, NULL, NULL);
snmpAddNodeStr("1.3.6", 1, NULL, NULL);
snmpAddNodeStr("1.3.6.1", 4, NULL, NULL);
snmpAddNodeStr("1.3.6.1.4", 1, NULL, NULL);
snmpAddNodeStr("1.3.6.1.4.1", 3495, NULL, NULL);
mib_tree_entry *m2 = snmpAddNodeStr("1.3.6.1.4.1.3495", 1, NULL, NULL);
mib_tree_entry *n = snmpLookupNodeStr(NULL, "1.3.6.1.4.1.3495.1");
assert(m2 == n);
/* SQ_SYS - 1.3.6.1.4.1.3495.1.1 */
snmpAddNodeStr("1.3.6.1.4.1.3495.1", 1, NULL, NULL);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.1", SYSVMSIZ, snmp_sysFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.1", SYSSTOR, snmp_sysFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.1", SYS_UPTIME, snmp_sysFn, static_Inst, atMax);
/* SQ_CONF - 1.3.6.1.4.1.3495.1.2 */
snmpAddNodeStr("1.3.6.1.4.1.3495.1", 2, NULL, NULL);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.2", CONF_ADMIN, snmp_confFn, static_Inst);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.2", CONF_VERSION, snmp_confFn, static_Inst);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.2", CONF_VERSION_ID, snmp_confFn, static_Inst);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.2", CONF_LOG_FAC, snmp_confFn, static_Inst);
/* SQ_CONF + CONF_STORAGE - 1.3.6.1.4.1.3495.1.5 */
snmpAddNodeStr("1.3.6.1.4.1.3495.1.2", CONF_STORAGE, NULL, NULL);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.2.5", CONF_ST_MMAXSZ, snmp_confFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.2.5", CONF_ST_SWMAXSZ, snmp_confFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.2.5", CONF_ST_SWHIWM, snmp_confFn, static_Inst, atMin);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.2.5", CONF_ST_SWLOWM, snmp_confFn, static_Inst, atMin);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.2", CONF_UNIQNAME, snmp_confFn, static_Inst);
/* SQ_PRF - 1.3.6.1.4.1.3495.1.3 */
snmpAddNodeStr("1.3.6.1.4.1.3495.1", 3, NULL, NULL); /* SQ_PRF */
/* PERF_SYS - 1.3.6.1.4.1.3495.1.3.1 */
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3", PERF_SYS, NULL, NULL);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.1", PERF_SYS_PF, snmp_prfSysFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.1", PERF_SYS_NUMR, snmp_prfSysFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.1", PERF_SYS_MEMUSAGE, snmp_prfSysFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.1", PERF_SYS_CPUTIME, snmp_prfSysFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.1", PERF_SYS_CPUUSAGE, snmp_prfSysFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.1", PERF_SYS_MAXRESSZ, snmp_prfSysFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.1", PERF_SYS_NUMOBJCNT, snmp_prfSysFn, static_Inst, atSum);
/*
Amos comments:
The meaning of LRU is "oldest timestamped object in cache, if LRU algorithm is
used"...
What this SMP support needs to do is aggregate via a special filter equivalent to
min() to retain the semantic oldest-object meaning. A special one is needed that
works as unsigned and ignores '0' values.
*/
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.1", PERF_SYS_CURLRUEXP, snmp_prfSysFn, static_Inst);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.1", PERF_SYS_CURUNLREQ, snmp_prfSysFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.1", PERF_SYS_CURUNUSED_FD, snmp_prfSysFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.1", PERF_SYS_CURRESERVED_FD, snmp_prfSysFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.1", PERF_SYS_CURUSED_FD, snmp_prfSysFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.1", PERF_SYS_CURMAX_FD, snmp_prfSysFn, static_Inst, atMax);
/* PERF_PROTO - 1.3.6.1.4.1.3495.1.3.2 */
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3", PERF_PROTO, NULL, NULL);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2", PERF_PROTOSTAT_AGGR, NULL, NULL);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.1", PERF_PROTOSTAT_AGGR_HTTP_REQ, snmp_prfProtoFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.1", PERF_PROTOSTAT_AGGR_HTTP_HITS, snmp_prfProtoFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.1", PERF_PROTOSTAT_AGGR_HTTP_ERRORS, snmp_prfProtoFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.1", PERF_PROTOSTAT_AGGR_HTTP_KBYTES_IN, snmp_prfProtoFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.1", PERF_PROTOSTAT_AGGR_HTTP_KBYTES_OUT, snmp_prfProtoFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.1", PERF_PROTOSTAT_AGGR_ICP_S, snmp_prfProtoFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.1", PERF_PROTOSTAT_AGGR_ICP_R, snmp_prfProtoFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.1", PERF_PROTOSTAT_AGGR_ICP_SKB, snmp_prfProtoFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.1", PERF_PROTOSTAT_AGGR_ICP_RKB, snmp_prfProtoFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.1", PERF_PROTOSTAT_AGGR_REQ, snmp_prfProtoFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.1", PERF_PROTOSTAT_AGGR_ERRORS, snmp_prfProtoFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.1", PERF_PROTOSTAT_AGGR_KBYTES_IN, snmp_prfProtoFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.1", PERF_PROTOSTAT_AGGR_KBYTES_OUT, snmp_prfProtoFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.1", PERF_PROTOSTAT_AGGR_CURSWAP, snmp_prfProtoFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.1", PERF_PROTOSTAT_AGGR_CLIENTS, snmp_prfProtoFn, static_Inst, atSum);
/* Note this is time-series rather than 'static' */
/* cacheMedianSvcTable */
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2", PERF_PROTOSTAT_MEDIAN, NULL, NULL);
/* cacheMedianSvcEntry */
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.2", 1, NULL, NULL);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.2.1", PERF_MEDIAN_TIME, snmp_prfProtoFn, time_Inst, atAverage);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.2.1", PERF_MEDIAN_HTTP_ALL, snmp_prfProtoFn, time_Inst, atAverage);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.2.1", PERF_MEDIAN_HTTP_MISS, snmp_prfProtoFn, time_Inst, atAverage);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.2.1", PERF_MEDIAN_HTTP_NM, snmp_prfProtoFn, time_Inst, atAverage);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.2.1", PERF_MEDIAN_HTTP_HIT, snmp_prfProtoFn, time_Inst, atAverage);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.2.1", PERF_MEDIAN_ICP_QUERY, snmp_prfProtoFn, time_Inst, atAverage);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.2.1", PERF_MEDIAN_ICP_REPLY, snmp_prfProtoFn, time_Inst, atAverage);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.2.1", PERF_MEDIAN_DNS, snmp_prfProtoFn, time_Inst, atAverage);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.2.1", PERF_MEDIAN_RHR, snmp_prfProtoFn, time_Inst, atAverage);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.2.1", PERF_MEDIAN_BHR, snmp_prfProtoFn, time_Inst, atAverage);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.3.2.2.1", PERF_MEDIAN_HTTP_NH, snmp_prfProtoFn, time_Inst, atAverage);
/* SQ_NET - 1.3.6.1.4.1.3495.1.4 */
snmpAddNodeStr("1.3.6.1.4.1.3495.1", 4, NULL, NULL);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.4", NET_IP_CACHE, NULL, NULL);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.4.1", IP_ENT, snmp_netIpFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.4.1", IP_REQ, snmp_netIpFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.4.1", IP_HITS, snmp_netIpFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.4.1", IP_PENDHIT, snmp_netIpFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.4.1", IP_NEGHIT, snmp_netIpFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.4.1", IP_MISS, snmp_netIpFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.4.1", IP_GHBN, snmp_netIpFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.4.1", IP_LOC, snmp_netIpFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.4", NET_FQDN_CACHE, NULL, NULL);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.4.2", FQDN_ENT, snmp_netFqdnFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.4.2", FQDN_REQ, snmp_netFqdnFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.4.2", FQDN_HITS, snmp_netFqdnFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.4.2", FQDN_PENDHIT, snmp_netFqdnFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.4.2", FQDN_NEGHIT, snmp_netFqdnFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.4.2", FQDN_MISS, snmp_netFqdnFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.4.2", FQDN_GHBN, snmp_netFqdnFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.4", NET_DNS_CACHE, NULL, NULL);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.4.3", DNS_REQ, snmp_netDnsFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.4.3", DNS_REP, snmp_netDnsFn, static_Inst, atSum);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.4.3", DNS_SERVERS, snmp_netDnsFn, static_Inst, atSum);
/* SQ_MESH - 1.3.6.1.4.1.3495.1.5 */
snmpAddNodeStr("1.3.6.1.4.1.3495.1", 5, NULL, NULL);
/* cachePeerTable - 1.3.6.1.4.1.3495.1.5.1 */
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5", MESH_PTBL, NULL, NULL);
/* CachePeerTableEntry (version 3) - 1.3.6.1.4.1.3495.1.5.1.3 */
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.1", 3, NULL, NULL);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.1.3", MESH_PTBL_INDEX, snmp_meshPtblFn, peer_Inst);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.1.3", MESH_PTBL_NAME, snmp_meshPtblFn, peer_Inst);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.1.3", MESH_PTBL_ADDR_TYPE, snmp_meshPtblFn, peer_Inst);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.1.3", MESH_PTBL_ADDR, snmp_meshPtblFn, peer_Inst);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.1.3", MESH_PTBL_HTTP, snmp_meshPtblFn, peer_Inst);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.1.3", MESH_PTBL_ICP, snmp_meshPtblFn, peer_Inst);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.1.3", MESH_PTBL_TYPE, snmp_meshPtblFn, peer_Inst);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.1.3", MESH_PTBL_STATE, snmp_meshPtblFn, peer_Inst);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.1.3", MESH_PTBL_SENT, snmp_meshPtblFn, peer_Inst);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.1.3", MESH_PTBL_PACKED, snmp_meshPtblFn, peer_Inst);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.1.3", MESH_PTBL_FETCHES, snmp_meshPtblFn, peer_Inst);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.1.3", MESH_PTBL_RTT, snmp_meshPtblFn, peer_Inst);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.1.3", MESH_PTBL_IGN, snmp_meshPtblFn, peer_Inst);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.1.3", MESH_PTBL_KEEPAL_S, snmp_meshPtblFn, peer_Inst);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.1.3", MESH_PTBL_KEEPAL_R, snmp_meshPtblFn, peer_Inst);
/* cacheClientTable - 1.3.6.1.4.1.3495.1.5.2 */
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5", MESH_CTBL, NULL, NULL);
/* BUG 2811: we NEED to create a reliable index for the client DB and make version 3 of the table. */
/* for now we have version 2 table with OID capable of mixed IPv4 / IPv6 clients and upgraded address text format. */
/* cacheClientEntry - 1.3.6.1.4.1.3495.1.5.2.2 */
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.2", 2, NULL, NULL);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.2.2", MESH_CTBL_ADDR_TYPE, snmp_meshCtblFn, client_Inst);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.2.2", MESH_CTBL_ADDR, snmp_meshCtblFn, client_Inst);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.2.2", MESH_CTBL_HTREQ, snmp_meshCtblFn, client_Inst);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.2.2", MESH_CTBL_HTBYTES, snmp_meshCtblFn, client_Inst);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.2.2", MESH_CTBL_HTHITS, snmp_meshCtblFn, client_Inst);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.2.2", MESH_CTBL_HTHITBYTES, snmp_meshCtblFn, client_Inst);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.2.2", MESH_CTBL_ICPREQ, snmp_meshCtblFn, client_Inst);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.2.2", MESH_CTBL_ICPBYTES, snmp_meshCtblFn, client_Inst);
snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.2.2", MESH_CTBL_ICPHITS, snmp_meshCtblFn, client_Inst);
mib_tree_last = snmpAddNodeStr("1.3.6.1.4.1.3495.1.5.2.2", MESH_CTBL_ICPHITBYTES, snmp_meshCtblFn, client_Inst);
debugs(49, 9, "snmpInit: Completed SNMP mib tree structure");
}
void
snmpOpenPorts(void)
{
debugs(49, 5, "snmpConnectionOpen: Called");
if (Config.Port.snmp <= 0)
return;
snmpIncomingConn = new Comm::Connection;
snmpIncomingConn->local = Config.Addrs.snmp_incoming;
snmpIncomingConn->local.SetPort(Config.Port.snmp);
if (!Ip::EnableIpv6 && !snmpIncomingConn->local.SetIPv4()) {
debugs(49, DBG_CRITICAL, "ERROR: IPv6 is disabled. " << snmpIncomingConn->local << " is not an IPv4 address.");
fatal("SNMP port cannot be opened.");
}
/* split-stack for now requires IPv4-only SNMP */
if (Ip::EnableIpv6&IPV6_SPECIAL_SPLITSTACK && snmpIncomingConn->local.IsAnyAddr()) {
snmpIncomingConn->local.SetIPv4();
}
AsyncCall::Pointer call = asyncCall(49, 2, "snmpIncomingConnectionOpened",
Comm::UdpOpenDialer(&snmpPortOpened));
Ipc::StartListening(SOCK_DGRAM, IPPROTO_UDP, snmpIncomingConn, Ipc::fdnInSnmpSocket, call);
if (!Config.Addrs.snmp_outgoing.IsNoAddr()) {
snmpOutgoingConn = new Comm::Connection;
snmpOutgoingConn->local = Config.Addrs.snmp_outgoing;
snmpOutgoingConn->local.SetPort(Config.Port.snmp);
if (!Ip::EnableIpv6 && !snmpOutgoingConn->local.SetIPv4()) {
debugs(49, DBG_CRITICAL, "ERROR: IPv6 is disabled. " << snmpOutgoingConn->local << " is not an IPv4 address.");
fatal("SNMP port cannot be opened.");
}
/* split-stack for now requires IPv4-only SNMP */
if (Ip::EnableIpv6&IPV6_SPECIAL_SPLITSTACK && snmpOutgoingConn->local.IsAnyAddr()) {
snmpOutgoingConn->local.SetIPv4();
}
AsyncCall::Pointer call = asyncCall(49, 2, "snmpOutgoingConnectionOpened",
Comm::UdpOpenDialer(&snmpPortOpened));
Ipc::StartListening(SOCK_DGRAM, IPPROTO_UDP, snmpOutgoingConn, Ipc::fdnOutSnmpSocket, call);
} else {
snmpOutgoingConn = snmpIncomingConn;
debugs(1, DBG_IMPORTANT, "Sending SNMP messages from " << snmpOutgoingConn->local);
}
}
static void
snmpPortOpened(const Comm::ConnectionPointer &conn, int errNo)
{
if (!Comm::IsConnOpen(conn))
fatalf("Cannot open SNMP %s Port",(conn->fd == snmpIncomingConn->fd?"receiving":"sending"));
Comm::SetSelect(conn->fd, COMM_SELECT_READ, snmpHandleUdp, NULL, 0);
if (conn->fd == snmpIncomingConn->fd)
debugs(1, DBG_IMPORTANT, "Accepting SNMP messages on " << snmpIncomingConn->local);
else if (conn->fd == snmpOutgoingConn->fd)
debugs(1, DBG_IMPORTANT, "Sending SNMP messages from " << snmpOutgoingConn->local);
else
fatalf("Lost SNMP port (%d) on FD %d", (int)conn->local.GetPort(), conn->fd);
}
void
snmpClosePorts(void)
{
if (Comm::IsConnOpen(snmpIncomingConn)) {
debugs(49, DBG_IMPORTANT, "Closing SNMP receiving port " << snmpIncomingConn->local);
snmpIncomingConn->close();
}
snmpIncomingConn = NULL;
if (Comm::IsConnOpen(snmpOutgoingConn) && snmpIncomingConn != snmpOutgoingConn) {
// Perform OUT port closure so as not to step on IN port when sharing a conn.
debugs(49, DBG_IMPORTANT, "Closing SNMP sending port " << snmpOutgoingConn->local);
snmpOutgoingConn->close();
}
snmpOutgoingConn = NULL;
}
/*
* Functions for handling the requests.
*/
/*
* Accept the UDP packet
*/
void
snmpHandleUdp(int sock, void *not_used)
{
LOCAL_ARRAY(char, buf, SNMP_REQUEST_SIZE);
Ip::Address from;
SnmpRequest *snmp_rq;
int len;
debugs(49, 5, "snmpHandleUdp: Called.");
Comm::SetSelect(sock, COMM_SELECT_READ, snmpHandleUdp, NULL, 0);
memset(buf, '\0', SNMP_REQUEST_SIZE);
len = comm_udp_recvfrom(sock,
buf,
SNMP_REQUEST_SIZE,
0,
from);
if (len > 0) {
buf[len] = '\0';
debugs(49, 3, "snmpHandleUdp: FD " << sock << ": received " << len << " bytes from " << from << ".");
snmp_rq = (SnmpRequest *)xcalloc(1, sizeof(SnmpRequest));
snmp_rq->buf = (u_char *) buf;
snmp_rq->len = len;
snmp_rq->sock = sock;
snmp_rq->outbuf = (unsigned char *)xmalloc(snmp_rq->outlen = SNMP_REQUEST_SIZE);
snmp_rq->from = from;
snmpDecodePacket(snmp_rq);
xfree(snmp_rq->outbuf);
xfree(snmp_rq);
} else {
debugs(49, DBG_IMPORTANT, "snmpHandleUdp: FD " << sock << " recvfrom: " << xstrerror());
}
}
/*
* Turn SNMP packet into a PDU, check available ACL's
*/
static void
snmpDecodePacket(SnmpRequest * rq)
{
struct snmp_pdu *PDU;
u_char *Community;
u_char *buf = rq->buf;
int len = rq->len;
allow_t allow = ACCESS_DENIED;
if (!Config.accessList.snmp) {
debugs(49, DBG_IMPORTANT, "WARNING: snmp_access not configured. agent query DENIED from : " << rq->from);
return;
}
debugs(49, 5, HERE << "Called.");
PDU = snmp_pdu_create(0);
/* Allways answer on SNMPv1 */
rq->session.Version = SNMP_VERSION_1;
Community = snmp_parse(&rq->session, PDU, buf, len);
/* Check if we have explicit permission to access SNMP data.
* default (set above) is to deny all */
if (Community) {
ACLFilledChecklist checklist(Config.accessList.snmp, NULL, NULL);
checklist.src_addr = rq->from;
checklist.snmp_community = (char *) Community;
allow = checklist.fastCheck();
if (allow == ACCESS_ALLOWED && (snmp_coexist_V2toV1(PDU))) {
rq->community = Community;
rq->PDU = PDU;
debugs(49, 5, "snmpAgentParse: reqid=[" << PDU->reqid << "]");
snmpConstructReponse(rq);
} else {
debugs(49, DBG_IMPORTANT, "WARNING: SNMP agent query DENIED from : " << rq->from);
}
xfree(Community);
} else {
debugs(49, DBG_IMPORTANT, "WARNING: Failed SNMP agent query from : " << rq->from);
snmp_free_pdu(PDU);
}
}
/*
* Packet OK, ACL Check OK, Create reponse.
*/
static void
snmpConstructReponse(SnmpRequest * rq)
{
struct snmp_pdu *RespPDU;
debugs(49, 5, "snmpConstructReponse: Called.");
if (UsingSmp() && IamWorkerProcess()) {
AsyncJob::Start(new Snmp::Forwarder(static_cast<Snmp::Pdu&>(*rq->PDU),
static_cast<Snmp::Session&>(rq->session), rq->sock, rq->from));
snmp_free_pdu(rq->PDU);
return;
}
RespPDU = snmpAgentResponse(rq->PDU);
snmp_free_pdu(rq->PDU);
if (RespPDU != NULL) {
snmp_build(&rq->session, RespPDU, rq->outbuf, &rq->outlen);
comm_udp_sendto(rq->sock, rq->from, rq->outbuf, rq->outlen);
snmp_free_pdu(RespPDU);
}
}
/*
* Decide how to respond to the request, construct a response and
* return the response to the requester.
*/
struct snmp_pdu *
snmpAgentResponse(struct snmp_pdu *PDU) {
struct snmp_pdu *Answer = NULL;
debugs(49, 5, "snmpAgentResponse: Called.");
if ((Answer = snmp_pdu_create(SNMP_PDU_RESPONSE))) {
Answer->reqid = PDU->reqid;
Answer->errindex = 0;
if (PDU->command == SNMP_PDU_GET || PDU->command == SNMP_PDU_GETNEXT) {
/* Indirect way */
int get_next = (PDU->command == SNMP_PDU_GETNEXT);
variable_list *VarPtr_;
variable_list **RespVars = &(Answer->variables);
oid_ParseFn *ParseFn;
int index = 0;
/* Loop through all variables */
for (VarPtr_ = PDU->variables; VarPtr_; VarPtr_ = VarPtr_->next_variable) {
variable_list *VarPtr = VarPtr_;
variable_list *VarNew = NULL;
oid *NextOidName = NULL;
snint NextOidNameLen = 0;
++index;
if (get_next)
ParseFn = snmpTreeNext(VarPtr->name, VarPtr->name_length, &NextOidName, &NextOidNameLen);
else
ParseFn = snmpTreeGet(VarPtr->name, VarPtr->name_length);
if (ParseFn == NULL) {
Answer->errstat = SNMP_ERR_NOSUCHNAME;
debugs(49, 5, "snmpAgentResponse: No such oid. ");
} else {
if (get_next) {
VarPtr = snmp_var_new(NextOidName, NextOidNameLen);
xfree(NextOidName);
}
int * errstatTmp = &(Answer->errstat);
VarNew = (*ParseFn) (VarPtr, (snint *) errstatTmp);
if (get_next)
snmp_var_free(VarPtr);
}
if ((Answer->errstat != SNMP_ERR_NOERROR) || (VarNew == NULL)) {
Answer->errindex = index;
debugs(49, 5, "snmpAgentResponse: error.");
if (VarNew)
snmp_var_free(VarNew);
while ((VarPtr = Answer->variables) != NULL) {
Answer->variables = VarPtr->next_variable;
snmp_var_free(VarPtr);
}
/* Steal the original PDU list of variables for the error response */
Answer->variables = PDU->variables;
PDU->variables = NULL;
return (Answer);
}
/* No error. Insert this var at the end, and move on to the next.
*/
*RespVars = VarNew;
RespVars = &(VarNew->next_variable);
}
}
}
return (Answer);
}
static oid_ParseFn *
snmpTreeGet(oid * Current, snint CurrentLen)
{
oid_ParseFn *Fn = NULL;
mib_tree_entry *mibTreeEntry = NULL;
int count = 0;
debugs(49, 5, "snmpTreeGet: Called");
MemBuf tmp;
debugs(49, 6, "snmpTreeGet: Current : " << snmpDebugOid(Current, CurrentLen, tmp) );
mibTreeEntry = mib_tree_head;
if (Current[count] == mibTreeEntry->name[count]) {
++count;
while ((mibTreeEntry) && (count < CurrentLen) && (!mibTreeEntry->parsefunction)) {
mibTreeEntry = snmpTreeEntry(Current[count], count, mibTreeEntry);
++count;
}
}
if (mibTreeEntry && mibTreeEntry->parsefunction)
Fn = mibTreeEntry->parsefunction;
debugs(49, 5, "snmpTreeGet: return");
return (Fn);
}
AggrType
snmpAggrType(oid* Current, snint CurrentLen)
{
debugs(49, 5, HERE);
mib_tree_entry* mibTreeEntry = mib_tree_head;
AggrType type = atNone;
int count = 0;
if (Current[count] == mibTreeEntry->name[count]) {
++count;
while (mibTreeEntry != NULL && count < CurrentLen) {
mibTreeEntry = snmpTreeEntry(Current[count], count, mibTreeEntry);
if (mibTreeEntry != NULL)
type = mibTreeEntry->aggrType;
++count;
}
}
return type;
}
static oid_ParseFn *
snmpTreeNext(oid * Current, snint CurrentLen, oid ** Next, snint * NextLen)
{
oid_ParseFn *Fn = NULL;
mib_tree_entry *mibTreeEntry = NULL, *nextoid = NULL;
int count = 0;
debugs(49, 5, "snmpTreeNext: Called");
MemBuf tmp;
debugs(49, 6, "snmpTreeNext: Current : " << snmpDebugOid(Current, CurrentLen, tmp));
mibTreeEntry = mib_tree_head;
if (Current[count] == mibTreeEntry->name[count]) {
++count;
while ((mibTreeEntry) && (count < CurrentLen) && (!mibTreeEntry->parsefunction)) {
mib_tree_entry *nextmibTreeEntry = snmpTreeEntry(Current[count], count, mibTreeEntry);
if (!nextmibTreeEntry)
break;
else
mibTreeEntry = nextmibTreeEntry;
++count;
}
debugs(49, 5, "snmpTreeNext: Recursed down to requested object");
} else {
return NULL;
}
if (mibTreeEntry == mib_tree_last)
return (Fn);
if ((mibTreeEntry) && (mibTreeEntry->parsefunction)) {
*NextLen = CurrentLen;
*Next = (*mibTreeEntry->instancefunction) (Current, NextLen, mibTreeEntry, &Fn);
if (*Next) {
MemBuf tmp;
debugs(49, 6, "snmpTreeNext: Next : " << snmpDebugOid(*Next, *NextLen, tmp));
return (Fn);
}
}
if ((mibTreeEntry) && (mibTreeEntry->parsefunction)) {
--count;
nextoid = snmpTreeSiblingEntry(Current[count], count, mibTreeEntry->parent);
if (nextoid) {
debugs(49, 5, "snmpTreeNext: Next OID found for sibling" << nextoid );
mibTreeEntry = nextoid;
++count;
} else {
debugs(49, 5, "snmpTreeNext: Attempting to recurse up for next object");
while (!nextoid) {
--count;
if (mibTreeEntry->parent->parent) {
nextoid = mibTreeEntry->parent;
mibTreeEntry = snmpTreeEntry(Current[count] + 1, count, nextoid->parent);
if (!mibTreeEntry) {
mibTreeEntry = nextoid;
nextoid = NULL;
}
} else {
nextoid = mibTreeEntry;
mibTreeEntry = NULL;
}
}
}
}
while ((mibTreeEntry) && (!mibTreeEntry->parsefunction)) {
mibTreeEntry = mibTreeEntry->leaves[0];
}
if (mibTreeEntry) {
*NextLen = mibTreeEntry->len;
*Next = (*mibTreeEntry->instancefunction) (mibTreeEntry->name, NextLen, mibTreeEntry, &Fn);
}
if (*Next) {
MemBuf tmp;
debugs(49, 6, "snmpTreeNext: Next : " << snmpDebugOid(*Next, *NextLen, tmp));
return (Fn);
} else
return NULL;
}
static oid *
static_Inst(oid * name, snint * len, mib_tree_entry * current, oid_ParseFn ** Fn)
{
oid *instance = NULL;
if (*len <= current->len) {
instance = (oid *)xmalloc(sizeof(name) * (*len + 1));
memcpy(instance, name, (sizeof(name) * *len));
instance[*len] = 0;
*len += 1;
}
*Fn = current->parsefunction;
return (instance);
}
static oid *
time_Inst(oid * name, snint * len, mib_tree_entry * current, oid_ParseFn ** Fn)
{
oid *instance = NULL;
int identifier = 0, loop = 0;
int index[TIME_INDEX_LEN] = {TIME_INDEX};
if (*len <= current->len) {
instance = (oid *)xmalloc(sizeof(name) * (*len + 1));
memcpy(instance, name, (sizeof(name) * *len));
instance[*len] = *index;
*len += 1;
} else {
identifier = name[*len - 1];
while ((loop < TIME_INDEX_LEN) && (identifier != index[loop]))
++loop;
if (loop < (TIME_INDEX_LEN - 1)) {
instance = (oid *)xmalloc(sizeof(name) * (*len));
memcpy(instance, name, (sizeof(name) * *len));
instance[*len - 1] = index[++loop];
}
}
*Fn = current->parsefunction;
return (instance);
}
static oid *
peer_Inst(oid * name, snint * len, mib_tree_entry * current, oid_ParseFn ** Fn)
{
oid *instance = NULL;
CachePeer *peers = Config.peers;
if (peers == NULL) {
debugs(49, 6, "snmp peer_Inst: No Peers.");
current = current->parent->parent->parent->leaves[1];
while ((current) && (!current->parsefunction))
current = current->leaves[0];
instance = client_Inst(current->name, len, current, Fn);
} else if (*len <= current->len) {
debugs(49, 6, "snmp peer_Inst: *len <= current->len ???");
instance = (oid *)xmalloc(sizeof(name) * ( *len + 1));
memcpy(instance, name, (sizeof(name) * *len));
instance[*len] = 1 ;
*len += 1;
} else {
int no = name[current->len] ;
int i;
// Note: This works because the Config.peers keeps its index according to its position.
for ( i=0 ; peers && (i < no) ; peers = peers->next , ++i ) ;
if (peers) {
debugs(49, 6, "snmp peer_Inst: Encode peer #" << i);
instance = (oid *)xmalloc(sizeof(name) * (current->len + 1 ));
memcpy(instance, name, (sizeof(name) * current->len ));
instance[current->len] = no + 1 ; // i.e. the next index on cache_peeer table.
} else {
debugs(49, 6, "snmp peer_Inst: We have " << i << " peers. Can't find #" << no);
return (instance);
}
}
*Fn = current->parsefunction;
return (instance);
}
static oid *
client_Inst(oid * name, snint * len, mib_tree_entry * current, oid_ParseFn ** Fn)
{
oid *instance = NULL;
Ip::Address laddr;
Ip::Address *aux;
int size = 0;
int newshift = 0;
if (*len <= current->len) {
aux = client_entry(NULL);
if (aux)
laddr = *aux;
else
laddr.SetAnyAddr();
if (laddr.IsIPv4())
size = sizeof(in_addr);
else
size = sizeof(in6_addr);
debugs(49, 6, HERE << "len" << *len << ", current-len" << current->len << ", addr=" << laddr << ", size=" << size);
instance = (oid *)xmalloc(sizeof(name) * (*len + size ));
memcpy(instance, name, (sizeof(name) * (*len)));
if ( !laddr.IsAnyAddr() ) {
addr2oid(laddr, &instance[ *len]); // the addr
*len += size ;
}
} else {
int shift = *len - current->len ; // i.e 4 or 16
oid2addr(&name[*len - shift], laddr,shift);
aux = client_entry(&laddr);
if (aux)
laddr = *aux;
else
laddr.SetAnyAddr();
if (!laddr.IsAnyAddr()) {
if (laddr.IsIPv4())
newshift = sizeof(in_addr);
else
newshift = sizeof(in6_addr);
debugs(49, 6, HERE << "len" << *len << ", current-len" << current->len << ", addr=" << laddr << ", newshift=" << newshift);
instance = (oid *)xmalloc(sizeof(name) * (current->len + newshift));
memcpy(instance, name, (sizeof(name) * (current->len)));
addr2oid(laddr, &instance[current->len]); // the addr.
*len = current->len + newshift ;
}
}
*Fn = current->parsefunction;
return (instance);
}
/*
* Utility functions
*/
/*
* Tree utility functions.
*/
/*
* Returns a sibling object for the requested child object or NULL
* if it does not exit
*/
static mib_tree_entry *
snmpTreeSiblingEntry(oid entry, snint len, mib_tree_entry * current)
{
mib_tree_entry *next = NULL;
int count = 0;
while ((!next) && (count < current->children)) {
if (current->leaves[count]->name[len] == entry) {
next = current->leaves[count];
}
++count;
}
/* Exactly the sibling on right */
if (count < current->children) {
next = current->leaves[count];
} else {
next = NULL;
}
return (next);
}
/*
* Returns the requested child object or NULL if it does not exist
*/
static mib_tree_entry *
snmpTreeEntry(oid entry, snint len, mib_tree_entry * current)
{
mib_tree_entry *next = NULL;
int count = 0;
while ((!next) && current && (count < current->children)) {
if (current->leaves[count]->name[len] == entry) {
next = current->leaves[count];
}
++count;
}
return (next);
}
void
snmpAddNodeChild(mib_tree_entry *entry, mib_tree_entry *child)
{
debugs(49, 5, "snmpAddNodeChild: assigning " << child << " to parent " << entry);
entry->leaves = (mib_tree_entry **)xrealloc(entry->leaves, sizeof(mib_tree_entry *) * (entry->children + 1));
entry->leaves[entry->children] = child;
entry->leaves[entry->children]->parent = entry;
++ entry->children;
}
mib_tree_entry *
snmpLookupNodeStr(mib_tree_entry *root, const char *str)
{
oid *name;
int namelen;
mib_tree_entry *e;
if (root)
e = root;
else
e = mib_tree_head;
if (! snmpCreateOidFromStr(str, &name, &namelen))
return NULL;
/* I wish there were some kind of sensible existing tree traversal
* routine to use. I'll worry about that later */
if (namelen <= 1) {
xfree(name);
return e; /* XXX it should only be this? */
}
int i, r = 1;
while (r < namelen) {
/* Find the child node which matches this */
for (i = 0; i < e->children && e->leaves[i]->name[r] != name[r]; ++i) ; // seek-loop
/* Are we pointing to that node? */
if (i >= e->children)
break;
assert(e->leaves[i]->name[r] == name[r]);
/* Skip to that node! */
e = e->leaves[i];
++r;
}
xfree(name);
return e;
}
int
snmpCreateOidFromStr(const char *str, oid **name, int *nl)
{
char const *delim = ".";
char *p;
*name = NULL;
*nl = 0;
char *s = xstrdup(str);
char *s_ = s;
/* Parse the OID string into oid bits */
while ( (p = strsep(&s_, delim)) != NULL) {
*name = (oid*)xrealloc(*name, sizeof(oid) * ((*nl) + 1));
(*name)[*nl] = atoi(p);
++(*nl);
}
xfree(s);
return 1;
}
/*
* Create an entry. Return a pointer to the newly created node, or NULL
* on failure.
*/
static mib_tree_entry *
snmpAddNodeStr(const char *base_str, int o, oid_ParseFn * parsefunction, instance_Fn * instancefunction, AggrType aggrType)
{
mib_tree_entry *m, *b;
oid *n;
int nl;
char s[1024];
/* Find base node */
b = snmpLookupNodeStr(mib_tree_head, base_str);
if (! b)
return NULL;
debugs(49, 5, "snmpAddNodeStr: " << base_str << ": -> " << b);
/* Create OID string for new entry */
snprintf(s, 1024, "%s.%d", base_str, o);
if (! snmpCreateOidFromStr(s, &n, &nl))
return NULL;
/* Create a node */
m = snmpAddNode(n, nl, parsefunction, instancefunction, aggrType, 0);
/* Link it into the existing tree */
snmpAddNodeChild(b, m);
/* Return the node */
return m;
}
/*
* Adds a node to the MIB tree structure and adds the appropriate children
*/
static mib_tree_entry *
snmpAddNode(oid * name, int len, oid_ParseFn * parsefunction, instance_Fn * instancefunction, AggrType aggrType, int children,...)
{
va_list args;
int loop;
mib_tree_entry *entry = NULL;
va_start(args, children);
MemBuf tmp;
debugs(49, 6, "snmpAddNode: Children : " << children << ", Oid : " << snmpDebugOid(name, len, tmp));
va_start(args, children);
entry = (mib_tree_entry *)xmalloc(sizeof(mib_tree_entry));
entry->name = name;
entry->len = len;
entry->parsefunction = parsefunction;
entry->instancefunction = instancefunction;
entry->children = children;
entry->leaves = NULL;
entry->aggrType = aggrType;
if (children > 0) {
entry->leaves = (mib_tree_entry **)xmalloc(sizeof(mib_tree_entry *) * children);
for (loop = 0; loop < children; ++loop) {
entry->leaves[loop] = va_arg(args, mib_tree_entry *);
entry->leaves[loop]->parent = entry;
}
}
va_end(args);
return (entry);
}
/* End of tree utility functions */
/*
* Returns the list of parameters in an oid
*/
static oid *
snmpCreateOid(int length,...)
{
va_list args;
oid *new_oid;
int loop;
va_start(args, length);
new_oid = (oid *)xmalloc(sizeof(oid) * length);
if (length > 0) {
for (loop = 0; loop < length; ++loop) {
new_oid[loop] = va_arg(args, int);
}
}
va_end(args);
return (new_oid);
}
/*
* Debug calls, prints out the OID for debugging purposes.
*/
const char *
snmpDebugOid(oid * Name, snint Len, MemBuf &outbuf)
{
char mbuf[16];
int x;
if (outbuf.isNull())
outbuf.init(16, MAX_IPSTRLEN);
for (x = 0; x < Len; ++x) {
size_t bytes = snprintf(mbuf, sizeof(mbuf), ".%u", (unsigned int) Name[x]);
outbuf.append(mbuf, bytes);
}
return outbuf.content();
}
void
snmpSnmplibDebug(int lvl, char *buf)
{
debugs(49, lvl, buf);
}
/*
IPv4 address: 10.10.0.9 ==>
oid == 10.10.0.9
IPv6 adress : 20:01:32:ef:a2:21:fb:32:00:00:00:00:00:00:00:00:OO:01 ==>
oid == 32.1.50.239.162.33.251.20.50.0.0.0.0.0.0.0.0.0.1
*/
void
addr2oid(Ip::Address &addr, oid * Dest)
{
u_int i ;
u_char *cp = NULL;
struct in_addr i4addr;
struct in6_addr i6addr;
oid code = addr.IsIPv6()? INETADDRESSTYPE_IPV6 : INETADDRESSTYPE_IPV4 ;
u_int size = (code == INETADDRESSTYPE_IPV4) ? sizeof(struct in_addr):sizeof(struct in6_addr);
// Dest[0] = code ;
if ( code == INETADDRESSTYPE_IPV4 ) {
addr.GetInAddr(i4addr);
cp = (u_char *) &(i4addr.s_addr);
} else {
addr.GetInAddr(i6addr);
cp = (u_char *) &i6addr;
}
for ( i=0 ; i < size ; ++i) {
// OID's are in network order
Dest[i] = *cp;
++cp;
}
MemBuf tmp;
debugs(49, 7, "addr2oid: Dest : " << snmpDebugOid(Dest, size, tmp));
}
/*
oid == 10.10.0.9 ==>
IPv4 address: 10.10.0.9
oid == 32.1.50.239.162.33.251.20.50.0.0.0.0.0.0.0.0.0.1 ==>
IPv6 adress : 20:01:32:ef:a2:21:fb:32:00:00:00:00:00:00:00:00:OO:01
*/
void
oid2addr(oid * id, Ip::Address &addr, u_int size)
{
struct in_addr i4addr;
struct in6_addr i6addr;
u_int i;
u_char *cp;
if ( size == sizeof(struct in_addr) )
cp = (u_char *) &(i4addr.s_addr);
else
cp = (u_char *) &(i6addr);
MemBuf tmp;
debugs(49, 7, "oid2addr: id : " << snmpDebugOid(id, size, tmp) );
for (i=0 ; i<size; ++i) {
cp[i] = id[i];
}
if ( size == sizeof(struct in_addr) )
addr = i4addr;
else
addr = i6addr;
}
/* SNMP checklists */
#include "acl/Strategy.h"
#include "acl/Strategised.h"
#include "acl/StringData.h"
class ACLSNMPCommunityStrategy : public ACLStrategy<char const *>
{
public:
virtual int match (ACLData<MatchType> * &, ACLFilledChecklist *);
static ACLSNMPCommunityStrategy *Instance();
/* Not implemented to prevent copies of the instance. */
/* Not private to prevent brain dead g++ warnings about
* private constructors with no friends */
ACLSNMPCommunityStrategy(ACLSNMPCommunityStrategy const &);
private:
static ACLSNMPCommunityStrategy Instance_;
ACLSNMPCommunityStrategy() {}
ACLSNMPCommunityStrategy&operator=(ACLSNMPCommunityStrategy const &);
};
class ACLSNMPCommunity
{
private:
static ACL::Prototype RegistryProtoype;
static ACLStrategised<char const *> RegistryEntry_;
};
ACL::Prototype ACLSNMPCommunity::RegistryProtoype(&ACLSNMPCommunity::RegistryEntry_, "snmp_community");
ACLStrategised<char const *> ACLSNMPCommunity::RegistryEntry_(new ACLStringData, ACLSNMPCommunityStrategy::Instance(), "snmp_community");
int
ACLSNMPCommunityStrategy::match (ACLData<MatchType> * &data, ACLFilledChecklist *checklist)
{
return data->match (checklist->snmp_community);
}
ACLSNMPCommunityStrategy *
ACLSNMPCommunityStrategy::Instance()
{
return &Instance_;
}
ACLSNMPCommunityStrategy ACLSNMPCommunityStrategy::Instance_;
| 36.342215 | 157 | 0.624258 | [
"object"
] |
7ac864a0e59eb5fb7f48451bd9263a2c2b1ff8fa | 7,823 | cpp | C++ | Project/check.cpp | jsmjsm/jlu_cpp_2019_design | b2b68da39616c366e621e5cfe640b9f13a8a979c | [
"MIT"
] | null | null | null | Project/check.cpp | jsmjsm/jlu_cpp_2019_design | b2b68da39616c366e621e5cfe640b9f13a8a979c | [
"MIT"
] | null | null | null | Project/check.cpp | jsmjsm/jlu_cpp_2019_design | b2b68da39616c366e621e5cfe640b9f13a8a979c | [
"MIT"
] | null | null | null | //
// Created by Levy Pan on 2019-09-24.
//
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <SQLiteCpp/SQLiteCpp.h>
#include <vector>
#include "listedit.h"
#include "dataPZY.h"
int checkid(std::string _app, int _id){
std::string app = "";
if (_app == "qq"){app = "QQinfo";};
if (_app == "wc"){app = "WCinfo";};
if (_app == "wb"){app = "WBinfo";};
int num = 0;
int ID = 0;
// Open a database file
SQLite::Database imdb("im.db",SQLite::OPEN_READWRITE | SQLite::OPEN_CREATE);
// Compile a SQL query, containing one parameter (index 1)
std::string operation = "SELECT * FROM "+ app +" WHERE ID = " + std::to_string(_id);
// std::cout << operation <<std::endl;
SQLite::Statement query(imdb, operation);
// Loop to execute the query step by step, to get rows of result
while (query.executeStep())
{
// Demonstrate how to get some typed column value
num = query.getColumn(0);
ID = query.getColumn(1);
}
if (num == 0){
//std::cout << "这个用户未注册" <<std::endl;
num = 0;
}
//std::cout << "num:"<<num <<std::endl;
return num;
} //返回num
std::string checkpassword(std::string _app,int _id){
std::string app = "";
if (_app == "qq"){app = "QQlogin";};
if (_app == "wc"){app = "WClogin";};
if (_app == "wb"){app = "WBlogin";};
bool flag = false;
const char*temp = nullptr;
// Open a database file
SQLite::Database imdb("im.db", SQLite::OPEN_READWRITE | SQLite::OPEN_CREATE);
//std::cout << "***database open ***"<< std::endl;
// Compile a SQL query, containing one parameter (index 1)
std::string operation = "SELECT password FROM "+ app +" WHERE id = " + std::to_string(_id);
//std::cout << "*** operation :"<< operation << std::endl;
SQLite::Statement query(imdb, operation);
// Loop to execute the query step by step, to get rows of result
while (query.executeStep())
{
std::string _password = query.getColumn(0);
temp = _password.data();
}
std::string password = temp;
// std::cout << password <<std::endl;
return password;
}
std::string checkfd(std::string table,std::string column, int _num){
// table 是表格名
const char*temp = nullptr;
SQLite::Database imdb("im.db",SQLite::OPEN_READWRITE | SQLite::OPEN_CREATE);
std::string operation = "SELECT " + column + " FROM " + table + " WHERE num = " + std::to_string(_num);
SQLite::Statement query(imdb, operation);
while (query.executeStep())
{
// Demonstrate how to get some typed column value
std::string _list = query.getColumn(0);
temp = _list.data();
}
std::string rawlist = temp;
return rawlist;
}
std::string checkusr(std::string table,std::string column, int _num){
int num = 0;
int ID = 0;
const char *cNAME = nullptr;
const char *cBIRTHDAY = nullptr;
const char *cLOCATION = nullptr;
SQLite::Database imdb("im.db",SQLite::OPEN_READWRITE | SQLite::OPEN_CREATE);
// 根据num来查
std::string operation = "SELECT " + column + " FROM " + table + " WHERE num = " + std::to_string(_num);
SQLite::Statement query(imdb, operation);
while (query.executeStep()) {
// Demonstrate how to get some typed column value
num = query.getColumn(0); //加载到成员
ID = query.getColumn(1); //加载到成员
std::string NAME = query.getColumn(2);
cNAME = NAME.data();
std::string BIRTHDAY = query.getColumn(3);
cBIRTHDAY = BIRTHDAY.data();
std::string LOCATION = query.getColumn(4);
cLOCATION = LOCATION.data();
}
std::string name = cNAME;
std::string birthday = cBIRTHDAY;
std::string location = cLOCATION;
std::string info ="|ID:" + std::to_string(ID) + " |用户名: " + name + " |生日:" + birthday + " "
" |所在地:" +location;
// std::cout << info << std::endl;
return info;
}
int checkid(std::string table, std::string column, std::string rule, int _id) {
// checkid 自由版,根据table 和column 返回对应的num
int num = 0;
int ID = 0;
int type = 0;
// Open a database file
SQLite::Database imdb("im.db",SQLite::OPEN_READWRITE | SQLite::OPEN_CREATE);
// Compile a SQL query, containing one parameter (index 1)
std::string operation = "SELECT " + column +" FROM " + table + " WHERE " + rule + " = " + std::to_string(_id);
// SELECT * FROM QQgp WHERE ID = _id;
SQLite::Statement query(imdb, operation);
// Loop to execute the query step by step, to get rows of result
while (query.executeStep())
{
// Demonstrate how to get some typed column value
num = query.getColumn(0);
ID = query.getColumn(1);
type = query.getColumn(2);
}
//std::cout << "ID:" << _id << " 查询到的num:" << num << std::endl;
return num;
}
std::string checkgp(std::string table, std::string column, std::string rule, int _num) {
int numgp = 0;
int IDgp = 0;
int type = 0;
int fathernum = 0;
const char *cNAMEgp = 0;
SQLite::Database imdb("im.db",SQLite::OPEN_READWRITE | SQLite::OPEN_CREATE);
//std::cout << "database open succesfully " << std::endl;
std::string operation = "SELECT " + column + " FROM " + table + " WHERE " + rule + " = " + std::to_string(_num);
// std::cout << "operation: " << operation << std::endl;
// SELECT * FROM QQgp WHERE NUM = _NUM;
SQLite::Statement query(imdb, operation);
while (query.executeStep()) {
numgp = query.getColumn(0);
IDgp = query.getColumn(1);
type = query.getColumn(2);
std::string tempNAMEgp = query.getColumn(3);
cNAMEgp = tempNAMEgp.data();
fathernum = query.getColumn(8);
}
std::string namegp = cNAMEgp;
std::string typeinfo = " ";
if (type == 1){
typeinfo ="申请加入";
}else if (type == 2) {
typeinfo ="推荐加入";
}else if (type == 3){
typeinfo ="讨论组(子群)";
}
// father id
std::string info;
if (type == 3){
int fatherid = checkint(table,"IDgp","numgp",fathernum);
info ="|群ID:" + std::to_string(IDgp) + " |群类型:" + typeinfo + " |群名: " + namegp +" |父群ID: " + std::to_string(fatherid) ;
} else{
info ="|群ID:" + std::to_string(IDgp) + " |群类型:" + typeinfo + " |群名: " + namegp ;
}
//std::cout << info << std::endl;
return info;
}
std::string checklist(std::string table, std::string column,std::string rule, int _num) {
// table 是表格名
const char*temp = nullptr;
SQLite::Database imdb("im.db",SQLite::OPEN_READWRITE | SQLite::OPEN_CREATE);
std::string operation = "SELECT " + column + " FROM " + table + " WHERE "+ rule +" = " + std::to_string(_num);
//std::cout << "operation:" << operation << std::endl;
SQLite::Statement query(imdb, operation);
while (query.executeStep())
{
// Demonstrate how to get some typed column value
std::string _list = query.getColumn(0);
temp = _list.data();
}
std::string rawlist = temp;
return rawlist;
}
int checkint(std::string table, std::string column,std::string rule, int _num) {
// table 是表格名
int number = -1;
SQLite::Database imdb("im.db",SQLite::OPEN_READWRITE | SQLite::OPEN_CREATE);
std::string operation = "SELECT " + column + " FROM " + table + " WHERE "+ rule +" = " + std::to_string(_num);
// std::cout << "operation:" << operation << std::endl;
SQLite::Statement query(imdb, operation);
while (query.executeStep())
{
// Demonstrate how to get some typed column value
number = query.getColumn(0);
}
return number;
}
| 29.858779 | 134 | 0.577656 | [
"vector"
] |
7ac911205fecf75775f1e4860b50d75f0caabe58 | 6,044 | cpp | C++ | rdPhysicS/rdPhysicS/src/rdps-CL/Application/ApplicationCL.cpp | rt-framework/rdPhysicalS | 0c4cd477169f2a573b1130f5d2867c04ce139368 | [
"MIT"
] | null | null | null | rdPhysicS/rdPhysicS/src/rdps-CL/Application/ApplicationCL.cpp | rt-framework/rdPhysicalS | 0c4cd477169f2a573b1130f5d2867c04ce139368 | [
"MIT"
] | null | null | null | rdPhysicS/rdPhysicS/src/rdps-CL/Application/ApplicationCL.cpp | rt-framework/rdPhysicalS | 0c4cd477169f2a573b1130f5d2867c04ce139368 | [
"MIT"
] | null | null | null | #include "ApplicationCL.h"
#include "PlatformComponent.h"
#include "DeviceComponent.h"
#include "ContextComponent.h"
#include "CommandQueueComponent.h"
#include "ProgramComponent.h"
#include "KernelComponent.h"
#include "MemObjectComponent.h"
#include "ItensWorkGroupComponent.h"
USING_RDPS
USING_CL
ApplicationCL::ApplicationCL() :
platform(nullptr),
device(nullptr),
context(nullptr),
queue(nullptr),
program(nullptr),
kernel(nullptr),
itens(nullptr)
{}
ApplicationCL::ApplicationCL(const PlatformComponent &_platform,
const DeviceComponent &_device ) :
platform(new PlatformComponent(_platform)),
device(new DeviceComponent(_device)),
context(nullptr),
queue(nullptr),
program(nullptr),
kernel(nullptr),
itens(nullptr)
{}
ApplicationCL &ApplicationCL::CreateContext()
{
context = new ContextComponent(*device);
return (*this);
}
ApplicationCL &ApplicationCL::CreateCommandQueue()
{
queue = new CommmandQueueComponent(*context, *device);
return (*this);
}
ApplicationCL::~ApplicationCL()
{
if(program)
delete program;
if(device)
delete device;
if(context)
delete context;
if(queue)
delete queue;
if(kernel)
delete kernel;
for (auto i : buffers)
i->Release();
buffers.clear();
}
PlatformComponent *ApplicationCL::GetPlatform() const
{
return platform;
}
DeviceComponent *ApplicationCL::GetDevice() const
{
return device;
}
ContextComponent *ApplicationCL::GetContext() const
{
return context;
}
CommmandQueueComponent *ApplicationCL::GetQueue() const
{
return queue;
}
ProgramComponent *ApplicationCL::GetProgram() const
{
return program;
}
KernelComponent *ApplicationCL::GetKernel() const
{
return kernel;
}
const std::vector<MemObjectComponent*> &ApplicationCL::GetBuffers() const
{
return buffers;
}
ItensWorkGroupComponent * ApplicationCL::GetItens() const
{
return itens;
}
ApplicationCL &ApplicationCL::CreateProgram(const std::string &source)
{
CreateContext();
CreateCommandQueue();
program = new ProgramComponent(*context, source);
program->BuildProgram(*device);
return (*this);
}
ApplicationCL &ApplicationCL::CreateKernel(const std::string &name)
{
kernel = new KernelComponent(*program, name);
return (*this);
}
int ApplicationCL::CreateBuffer(const int id, const ActionFile typeAction, const size_t bytes)
{
if (id <= ARRAY_WITHOUT_INDEX)
{
MemObjectComponent *mem = new MemObjectComponent(*context, typeAction, bytes);
buffers.push_back(mem);
return static_cast<int>(buffers.size() - 1);
}
int _id = GetBuffer(id);
if (_id == EMPTY_BUFFER || _id == BUSY_LOCATION)
{
Logger::Log((_id == EMPTY_BUFFER) ?
"ERROR: list of objects of memory empty.\n" :
"ERROR requested index invalidates busy location.\n");
}
*buffers[_id] = MemObjectComponent(*context, typeAction, bytes);
return id;
}
std::string ApplicationCL::GetInfo(const ComponentCL type) const
{
switch (type)
{
case PLATFORM_COMPONENT:
return platform->GetInfo(CL_PLATFORM_NAME);
break;
case DEVICE_COMPONENT:
return device->GetInfo(CL_DEVICE_NAME);
break;
case CONTEXT_COMPONENT:
break;
case COMMAND_QUEUE_COMPONENT:
break;
case PROGRAM_COMPONENT:
break;
case KERNEL_COMPONENT:
break;
case ALL_COMPONENTS:
break;
}
return std::string();
}
int ApplicationCL::GetBuffer()
{
buffers.push_back(new MemObjectComponent());
return static_cast<int>(buffers.size() - 1);
}
int ApplicationCL::GetBuffer(const int location)
{
if (buffers.size() == 0)
return EMPTY_BUFFER;
if ((*buffers[location])())
return BUSY_LOCATION;
return location;
}
ApplicationCL &ApplicationCL::SetPlatform(const PlatformComponent &_platform)
{
if (!platform)
{
platform = new PlatformComponent(_platform);
}
else
{
*platform = _platform;
}
return (*this);
}
ApplicationCL &ApplicationCL::SetDevice(const DeviceComponent &_device)
{
if (!device)
{
device = new DeviceComponent(_device);
}
else
{
*device = _device;
}
return (*this);
}
ApplicationCL &ApplicationCL::SetItensWorkGroup(const ItensWorkGroupComponent &_itens)
{
if (!itens)
{
itens = new ItensWorkGroupComponent(_itens);
}
else
{
*itens = _itens;
}
return (*this);
}
void rdps::Cl::ApplicationCL::DestroyBuffer(const int id)
{
if (buffers.size() > 0)
if ((*buffers[id])())
buffers[id]->Release();
}
void ApplicationCL::DestroyApp()
{
kernel->Release();
program->Release();
for (auto i : buffers)
{
i->Release();
delete i;
}
buffers.clear();
queue->Release();
context->Release();
}
ApplicationCL &ApplicationCL::ApplyArgument(const int id)
{
kernel->SetArgument(id, (*buffers[id])());
return (*this);
}
ApplicationCL &ApplicationCL::ApplyArguments()
{
int size = static_cast<int>(buffers.size());
for (int i = 0; i < size; i++)
kernel->SetArgument(i, (*buffers[i])());
return(*this);
}
ApplicationCL &ApplicationCL::ApplyArguments(const std::initializer_list<uint> index)
{
std::vector<uint> ids = index;
for (auto i : ids)
kernel->SetArgument(i, (*buffers[i])());
return (*this);
}
ApplicationCL &ApplicationCL::ApplyBuffer(const int id, const ActionFile typeAction, const size_t bytes, void *data)
{
if (typeAction == RETURN_DATA_WRITING)
{
//int _id = id;// GetBuffer(bf.GetId());
if (id == EMPTY_BUFFER || id == BUSY_LOCATION)
{
Logger::Log("ERROR requested index invalidates " +
(id == EMPTY_BUFFER) ? "empty array." : "busy location.");
}
queue->WriteBuffer((*buffers[id]), bytes, data);
}
else if (typeAction == RETURN_DATA_READING)
{
//int _id = id;//GetBuffer(bf.GetId());
if (id == EMPTY_BUFFER || id == BUSY_LOCATION)
{
Logger::Log("ERROR requested index invalidates " +
(id == EMPTY_BUFFER) ? "empty array." : "busy location.");
}
queue->ReadBuffer((*buffers[id]), bytes, data);
}
return (*this);
}
ApplicationCL &ApplicationCL::Process(const bool applyEverything)
{
if (applyEverything)
ApplyArguments();
queue->EnqueueNDRangeKernel(*kernel, *itens);
return (*this);
}
| 19.371795 | 116 | 0.702515 | [
"vector"
] |
7acae258ea045dfa61ac78bce57aa2a25dece84c | 1,235 | cpp | C++ | kruskal_mst.cpp | rj011/Hacktoberfest2021-4 | 0aa981d4ba5e71c86cc162d34fe57814050064c2 | [
"MIT"
] | 41 | 2021-10-03T16:03:52.000Z | 2021-11-14T18:15:33.000Z | kruskal_mst.cpp | rj011/Hacktoberfest2021-4 | 0aa981d4ba5e71c86cc162d34fe57814050064c2 | [
"MIT"
] | 175 | 2021-10-03T10:47:31.000Z | 2021-10-20T11:55:32.000Z | kruskal_mst.cpp | rj011/Hacktoberfest2021-4 | 0aa981d4ba5e71c86cc162d34fe57814050064c2 | [
"MIT"
] | 208 | 2021-10-03T11:24:04.000Z | 2021-10-31T17:27:59.000Z | //Kruskal's Algorithm to find Minimum Spanning Tree using DSU
#include "bits/stdc++.h"
using namespace std;
typedef pair<int, pair<int, int> >ii;
vector<int> root;
vector<int> size;
int find(int a){
if(root[a] == a) return a;
return root[a] = find(root[a]);
}
void join(int a, int b){
a = find(a);
b = find(b);
if(a != b){
if(size[a] < size[b]) root[b] = a;
else root[a] = b;
size[b] += size[a];
size[a] = size[b];
}
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
int nodes, edges, mst_weight = 0;
vector<ii> adj;
cin >> nodes >> edges;
root.resize(nodes);
size.resize(nodes);
adj.resize(nodes);
for(int i = 0; i < edges; i++){
int a, b, weight;
cin >> a >> b >> weight;
if(a == b) continue;
adj.push_back({weight, {a, b}});
}
sort(adj.begin(), adj.end());
for (int i = 0; i < nodes; i++){
root[i] = i;
size[i] = 1;
}
for(auto e: adj){
if(find(e.second.first) != find(e.second.second)){
mst_weight += e.first;
join(e.second.first, e.second.second);
}
}
cout << mst_weight << '\n';
return 0;
}
| 19.296875 | 61 | 0.496356 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.