text
stringlengths
8
6.88M
#pragma once #include <string> #include <vector> #include <algorithm> #include "BagOfWords.h" #include "parser.hpp" const int COLUMN_NUMBER_RATING = 1; const int COLUMN_NUMBER_TEXT = 2; const int CUTOFF_FOR_POSITIVE_SENTIMENT = 4; class Input { std::string fileLocation; std::vector<std::string> textReviews; std::vector<int> sentiments; std::vector<BagOfWords> reviews; void convertTextReviewsIntoBagOfWords(); public: Input(); void fetchDataFromFile(std::string fileLocation); std::vector<int>& getSentiments(); std::vector<BagOfWords>& getReviews(); };
/* Copyright 2021 University of Manchester Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http: // www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include <cstdint> #include "dma_interface.hpp" #include "gmock/gmock.h" using orkhestrafs::dbmstodspi::DMAInterface; using orkhestrafs::dbmstodspi::module_config_values:: DMACrossbarDirectionSelection; using orkhestrafs::dbmstodspi::query_acceleration_constants::kMaxIOStreamCount; class MockDMA : public DMAInterface { using crossbar_value_array = std::array<int, 4>; public: MOCK_METHOD(void, SetControllerParams, (bool is_input, int stream_id, int ddr_burst_size, int records_per_ddr_burst, int buffer_start, int buffer_end), (override)); MOCK_METHOD(volatile uint32_t, GetControllerParams, (bool is_input, int stream_id), (override)); MOCK_METHOD(void, SetControllerStreamAddress, (bool is_input, int stream_id, uintptr_t address), (override)); MOCK_METHOD(volatile uintptr_t, GetControllerStreamAddress, (bool is_input, int stream_id), (override)); MOCK_METHOD(void, SetControllerStreamSize, (bool is_input, int stream_id, int size), (override)); MOCK_METHOD(volatile int, GetControllerStreamSize, (bool is_input, int stream_id), (override)); MOCK_METHOD(void, StartController, (bool is_input, std::bitset<kMaxIOStreamCount> stream_active), (override)); MOCK_METHOD(bool, IsControllerFinished, (bool is_input), (override)); MOCK_METHOD(void, SetRecordSize, (int stream_id, int recordSize), (override)); MOCK_METHOD(void, SetRecordChunkIDs, (int stream_id, int interfaceCycle, int chunkID), (override)); MOCK_METHOD(void, SetCrossbarValues, (DMACrossbarDirectionSelection crossbar_selection, int stream_id, int clock_cycle, int offset, crossbar_value_array configuration_values), (override)); MOCK_METHOD(void, SetNumberOfInputStreamsWithMultipleChannels, (int number), (override)); MOCK_METHOD(void, SetRecordsPerBurstForMultiChannelStreams, (int stream_id, int records_per_burst), (override)); MOCK_METHOD(void, SetDDRBurstSizeForMultiChannelStreams, (int stream_id, int ddr_burst_size), (override)); MOCK_METHOD(void, SetNumberOfActiveChannelsForMultiChannelStreams, (int stream_id, int active_channels), (override)); MOCK_METHOD(void, SetAddressForMultiChannelStreams, (int stream_id, int channel_id, uintptr_t address), (override)); MOCK_METHOD(void, SetSizeForMultiChannelStreams, (int stream_id, int channel_id, int number_of_records), (override)); MOCK_METHOD(volatile uint64_t, GetRuntime, (), (override)); MOCK_METHOD(volatile uint64_t, GetValidReadCyclesCount, (), (override)); MOCK_METHOD(volatile uint64_t, GetValidWriteCyclesCount, (), (override)); MOCK_METHOD(volatile uint32_t, GetInputActiveDataCycles, (), (override)); MOCK_METHOD(volatile uint32_t, GetInputActiveDataLastCycles, (), (override)); MOCK_METHOD(volatile uint32_t, GetInputActiveControlCycles, (), (override)); MOCK_METHOD(volatile uint32_t, GetInputActiveControlLastCycles, (), (override)); MOCK_METHOD(volatile uint32_t, GetInputActiveEndOfStreamCycles, (), (override)); MOCK_METHOD(volatile uint32_t, GetOutputActiveDataLastCycles, (), (override)); MOCK_METHOD(volatile uint32_t, GetOutputActiveControlCycles, (), (override)); MOCK_METHOD(volatile uint32_t, GetOutputActiveDataCycles, (), (override)); MOCK_METHOD(volatile uint32_t, GetOutputActiveControlLastCycles, (), (override)); MOCK_METHOD(volatile uint32_t, GetOutputActiveEndOfStreamCycles, (), (override)); MOCK_METHOD(volatile uint32_t, GetInputActiveInstructionCycles, (), (override)); MOCK_METHOD(volatile uint32_t, GetOutputActiveInstructionCycles, (), (override)); MOCK_METHOD(void, GlobalReset, (), (override)); MOCK_METHOD(void, DecoupleFromPRRegion, (), (override)); };
#include <iostream> using namespace std; struct NodeType { char data; NodeType* prev; NodeType* next; }; int main() { NodeType* editor; NodeType* cursor; editor = new NodeType; // dummy node editor->data = '\0'; editor->prev = NULL; editor->next = NULL; cursor = editor; char buffer = '\0'; NodeType* node; while (1) { buffer = getchar(); if (buffer == '\n') { break; } node = new NodeType; node->data = buffer; node->prev = cursor; node->next = NULL; cursor->next = node; cursor = node; } int m = 0; cin >> m; char command = '\0'; while (m--) { cin >> command; switch (command) { case 'L': if (cursor->prev != NULL) { cursor = cursor->prev; } break; case 'D': if (cursor->next != NULL) { cursor = cursor->next; } break; case 'B': if (cursor->prev != NULL) { // not first node (dummy) if (cursor->next != NULL) { // not last node cursor->prev->next = cursor->next; cursor->next->prev = cursor->prev; node = cursor; cursor = cursor->prev; delete node; } else { // last node cursor->prev->next = cursor->next; node = cursor; cursor = cursor->prev; delete node; } } break; case 'P': cin >> buffer; node = new NodeType; if (cursor->next != NULL) { // not last node node->data = buffer; node->prev = cursor; node->next = cursor->next; cursor->next->prev = node; cursor->next = node; cursor = cursor->next; } else { // last node node->data = buffer; node->prev = cursor; node->next = cursor->next; cursor->next = node; cursor = cursor->next; } break; default: break; } } node = editor->next; while (node != NULL) { cout << node->data; node = node->next; } return 0; }
#pragma once namespace BeeeOn { class FileLoader; class ConfigurationExplorer { public: virtual ~ConfigurationExplorer(); virtual void explore(FileLoader &loader) = 0; }; }
// Copyright 2018 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd #include "packager/media/chunking/chunking_handler.h" #include <gmock/gmock.h> #include <gtest/gtest.h> #include "packager/media/base/media_handler_test_base.h" #include "packager/media/chunking/cue_alignment_handler.h" #include "packager/media/public/ad_cue_generator_params.h" #include "packager/status_macros.h" #include "packager/status_test_util.h" using ::testing::_; using ::testing::ElementsAre; using ::testing::IsEmpty; namespace shaka { namespace media { namespace { const size_t kOneInput = 1; const size_t kOneOutput = 1; const size_t kThreeInput = 3; const size_t kThreeOutput = 3; const bool kEncrypted = true; const bool kKeyFrame = true; const uint32_t kMsTimeScale = 1000; const char* kNoId = ""; const char* kNoSettings = ""; const char* kNoPayload = ""; const size_t kChild = 0; const size_t kParent = 0; } // namespace class CueAlignmentHandlerTest : public MediaHandlerTestBase { protected: Status DispatchStreamInfo(size_t stream, std::shared_ptr<const StreamInfo> info) { return Input(stream)->Dispatch( StreamData::FromStreamInfo(kChild, std::move(info))); } Status DispatchMediaSample(size_t stream, std::shared_ptr<const MediaSample> sample) { return Input(stream)->Dispatch( StreamData::FromMediaSample(kChild, std::move(sample))); } Status DispatchTextSample(size_t stream, std::shared_ptr<const TextSample> sample) { return Input(stream)->Dispatch( StreamData::FromTextSample(kChild, std::move(sample))); } Status FlushAll(std::initializer_list<size_t> inputs) { for (auto& input : inputs) { RETURN_IF_ERROR(Input(input)->FlushAllDownstreams()); } return Status::OK; } }; TEST_F(CueAlignmentHandlerTest, VideoInputWithNoCues) { const size_t kVideoStream = 0; const int64_t kSampleDuration = 1000; const int64_t kSample0Start = 0; const int64_t kSample1Start = kSample0Start + kSampleDuration; const int64_t kSample2Start = kSample1Start + kSampleDuration; AdCueGeneratorParams params; SyncPointQueue sync_points(params); std::shared_ptr<MediaHandler> handler = std::make_shared<CueAlignmentHandler>(&sync_points); ASSERT_OK(SetUpAndInitializeGraph(handler, kOneInput, kOneOutput)); { testing::InSequence s; EXPECT_CALL(*Output(kVideoStream), OnProcess(IsStreamInfo(kParent, kMsTimeScale, !kEncrypted, _))); EXPECT_CALL(*Output(kVideoStream), OnProcess(IsMediaSample(kParent, kSample0Start, kSampleDuration, !kEncrypted, _))); EXPECT_CALL(*Output(kVideoStream), OnProcess(IsMediaSample(kParent, kSample1Start, kSampleDuration, !kEncrypted, _))); EXPECT_CALL(*Output(kVideoStream), OnProcess(IsMediaSample(kParent, kSample2Start, kSampleDuration, !kEncrypted, _))); EXPECT_CALL(*Output(kVideoStream), OnFlush(kParent)); } auto stream_info = GetVideoStreamInfo(kMsTimeScale); auto sample_0 = GetMediaSample(kSample0Start, kSampleDuration, kKeyFrame); auto sample_1 = GetMediaSample(kSample1Start, kSampleDuration, !kKeyFrame); auto sample_2 = GetMediaSample(kSample2Start, kSampleDuration, kKeyFrame); DispatchStreamInfo(kVideoStream, std::move(stream_info)); DispatchMediaSample(kVideoStream, std::move(sample_0)); DispatchMediaSample(kVideoStream, std::move(sample_1)); DispatchMediaSample(kVideoStream, std::move(sample_2)); ASSERT_OK(FlushAll({kVideoStream})); } TEST_F(CueAlignmentHandlerTest, AudioInputWithNoCues) { const size_t kAudioStream = 0; const int64_t kSampleDuration = 1000; const int64_t kSample0Start = 0; const int64_t kSample1Start = kSample0Start + kSampleDuration; const int64_t kSample2Start = kSample1Start + kSampleDuration; AdCueGeneratorParams params; SyncPointQueue sync_points(params); std::shared_ptr<MediaHandler> handler = std::make_shared<CueAlignmentHandler>(&sync_points); ASSERT_OK(SetUpAndInitializeGraph(handler, kOneInput, kOneOutput)); { testing::InSequence s; EXPECT_CALL(*Output(kAudioStream), OnProcess(IsStreamInfo(kParent, kMsTimeScale, !kEncrypted, _))); EXPECT_CALL(*Output(kAudioStream), OnProcess(IsMediaSample(kParent, kSample0Start, kSampleDuration, !kEncrypted, _))); EXPECT_CALL(*Output(kAudioStream), OnProcess(IsMediaSample(kParent, kSample1Start, kSampleDuration, !kEncrypted, _))); EXPECT_CALL(*Output(kAudioStream), OnProcess(IsMediaSample(kParent, kSample2Start, kSampleDuration, !kEncrypted, _))); EXPECT_CALL(*Output(kAudioStream), OnFlush(kParent)); } auto stream_info = GetAudioStreamInfo(kMsTimeScale); auto sample_0 = GetMediaSample(kSample0Start, kSampleDuration, kKeyFrame); auto sample_1 = GetMediaSample(kSample1Start, kSampleDuration, kKeyFrame); auto sample_2 = GetMediaSample(kSample2Start, kSampleDuration, kKeyFrame); ASSERT_OK(DispatchStreamInfo(kAudioStream, std::move(stream_info))); ASSERT_OK(DispatchMediaSample(kAudioStream, std::move(sample_0))); ASSERT_OK(DispatchMediaSample(kAudioStream, std::move(sample_1))); ASSERT_OK(DispatchMediaSample(kAudioStream, std::move(sample_2))); ASSERT_OK(FlushAll({kAudioStream})); } TEST_F(CueAlignmentHandlerTest, TextInputWithNoCues) { const size_t kTextStream = 0; const int64_t kSampleDuration = 1000; const int64_t kSample0Start = 0; const int64_t kSample0End = kSample0Start + kSampleDuration; const int64_t kSample1Start = kSample0End; const int64_t kSample1End = kSample1Start + kSampleDuration; const int64_t kSample2Start = kSample1End; const int64_t kSample2End = kSample2Start + kSampleDuration; AdCueGeneratorParams params; SyncPointQueue sync_points(params); std::shared_ptr<MediaHandler> handler = std::make_shared<CueAlignmentHandler>(&sync_points); ASSERT_OK(SetUpAndInitializeGraph(handler, kOneInput, kOneOutput)); { testing::InSequence s; EXPECT_CALL(*Output(kTextStream), OnProcess(IsStreamInfo(kParent, kMsTimeScale, !kEncrypted, _))); EXPECT_CALL(*Output(kTextStream), OnProcess(IsTextSample(_, kNoId, kSample0Start, kSample0End, kNoSettings, kNoPayload))); EXPECT_CALL(*Output(kTextStream), OnProcess(IsTextSample(_, kNoId, kSample1Start, kSample1End, kNoSettings, kNoPayload))); EXPECT_CALL(*Output(kTextStream), OnProcess(IsTextSample(_, kNoId, kSample2Start, kSample2End, kNoSettings, kNoPayload))); EXPECT_CALL(*Output(kTextStream), OnFlush(kParent)); } auto stream_info = GetTextStreamInfo(kMsTimeScale); auto sample_0 = GetTextSample(kNoId, kSample0Start, kSample0End, kNoPayload); auto sample_1 = GetTextSample(kNoId, kSample1Start, kSample1End, kNoPayload); auto sample_2 = GetTextSample(kNoId, kSample2Start, kSample2End, kNoPayload); ASSERT_OK(DispatchStreamInfo(kTextStream, std::move(stream_info))); ASSERT_OK(DispatchTextSample(kTextStream, std::move(sample_0))); ASSERT_OK(DispatchTextSample(kTextStream, std::move(sample_1))); ASSERT_OK(DispatchTextSample(kTextStream, std::move(sample_2))); ASSERT_OK(FlushAll({kTextStream})); } TEST_F(CueAlignmentHandlerTest, TextAudioVideoInputWithNoCues) { const size_t kTextStream = 0; const size_t kAudioStream = 1; const size_t kVideoStream = 2; const int64_t kSampleDuration = 1000; const int64_t kSample0Start = 0; const int64_t kSample0End = kSample0Start + kSampleDuration; const int64_t kSample1Start = kSample0Start + kSampleDuration; const int64_t kSample1End = kSample1Start + kSampleDuration; const int64_t kSample2Start = kSample1Start + kSampleDuration; const int64_t kSample2End = kSample2Start + kSampleDuration; AdCueGeneratorParams params; SyncPointQueue sync_points(params); std::shared_ptr<MediaHandler> handler = std::make_shared<CueAlignmentHandler>(&sync_points); ASSERT_OK(SetUpAndInitializeGraph(handler, kThreeInput, kThreeOutput)); { testing::InSequence s; EXPECT_CALL(*Output(kTextStream), OnProcess(IsStreamInfo(kParent, kMsTimeScale, !kEncrypted, _))); EXPECT_CALL(*Output(kTextStream), OnProcess(IsTextSample(_, kNoId, kSample0Start, kSample0End, kNoSettings, kNoPayload))); EXPECT_CALL(*Output(kTextStream), OnProcess(IsTextSample(_, kNoId, kSample1Start, kSample1End, kNoSettings, kNoPayload))); EXPECT_CALL(*Output(kTextStream), OnProcess(IsTextSample(_, kNoId, kSample2Start, kSample2End, kNoSettings, kNoPayload))); EXPECT_CALL(*Output(kTextStream), OnFlush(kParent)); } { testing::InSequence s; EXPECT_CALL(*Output(kAudioStream), OnProcess(IsStreamInfo(kParent, kMsTimeScale, !kEncrypted, _))); EXPECT_CALL(*Output(kAudioStream), OnProcess(IsMediaSample(kParent, kSample0Start, kSampleDuration, !kEncrypted, _))); EXPECT_CALL(*Output(kAudioStream), OnProcess(IsMediaSample(kParent, kSample1Start, kSampleDuration, !kEncrypted, _))); EXPECT_CALL(*Output(kAudioStream), OnProcess(IsMediaSample(kParent, kSample2Start, kSampleDuration, !kEncrypted, _))); EXPECT_CALL(*Output(kAudioStream), OnFlush(kParent)); } { testing::InSequence s; EXPECT_CALL(*Output(kVideoStream), OnProcess(IsStreamInfo(kParent, kMsTimeScale, !kEncrypted, _))); EXPECT_CALL(*Output(kVideoStream), OnProcess(IsMediaSample(kParent, kSample0Start, kSampleDuration, !kEncrypted, _))); EXPECT_CALL(*Output(kVideoStream), OnProcess(IsMediaSample(kParent, kSample1Start, kSampleDuration, !kEncrypted, _))); EXPECT_CALL(*Output(kVideoStream), OnProcess(IsMediaSample(kParent, kSample2Start, kSampleDuration, !kEncrypted, _))); EXPECT_CALL(*Output(kVideoStream), OnFlush(kParent)); } // Text samples auto text_stream_info = GetTextStreamInfo(kMsTimeScale); auto text_sample_0 = GetTextSample(kNoId, kSample0Start, kSample0End, kNoPayload); auto text_sample_1 = GetTextSample(kNoId, kSample1Start, kSample1End, kNoPayload); auto text_sample_2 = GetTextSample(kNoId, kSample2Start, kSample2End, kNoPayload); // Audio samples auto audio_stream_info = GetAudioStreamInfo(kMsTimeScale); auto audio_sample_0 = GetMediaSample(kSample0Start, kSampleDuration, kKeyFrame); auto audio_sample_1 = GetMediaSample(kSample1Start, kSampleDuration, kKeyFrame); auto audio_sample_2 = GetMediaSample(kSample2Start, kSampleDuration, kKeyFrame); // Video samples auto video_stream_info = GetVideoStreamInfo(kMsTimeScale); auto video_sample_0 = GetMediaSample(kSample0Start, kSampleDuration, kKeyFrame); auto video_sample_1 = GetMediaSample(kSample1Start, kSampleDuration, !kKeyFrame); auto video_sample_2 = GetMediaSample(kSample2Start, kSampleDuration, kKeyFrame); // Dispatch Stream Info ASSERT_OK(DispatchStreamInfo(kTextStream, std::move(text_stream_info))); ASSERT_OK(DispatchStreamInfo(kAudioStream, std::move(audio_stream_info))); ASSERT_OK(DispatchStreamInfo(kVideoStream, std::move(video_stream_info))); // Dispatch Sample 0 ASSERT_OK(DispatchTextSample(kTextStream, std::move(text_sample_0))); ASSERT_OK(DispatchMediaSample(kAudioStream, std::move(audio_sample_0))); ASSERT_OK(DispatchMediaSample(kVideoStream, std::move(video_sample_0))); // Dispatch Sample 1 ASSERT_OK(DispatchTextSample(kTextStream, std::move(text_sample_1))); ASSERT_OK(DispatchMediaSample(kAudioStream, std::move(audio_sample_1))); ASSERT_OK(DispatchMediaSample(kVideoStream, std::move(video_sample_1))); // Dispatch Sample 2 ASSERT_OK(DispatchTextSample(kTextStream, std::move(text_sample_2))); ASSERT_OK(DispatchMediaSample(kAudioStream, std::move(audio_sample_2))); ASSERT_OK(DispatchMediaSample(kVideoStream, std::move(video_sample_2))); ASSERT_OK(FlushAll({kTextStream, kAudioStream, kVideoStream})); } TEST_F(CueAlignmentHandlerTest, VideoInputWithCues) { const size_t kVideoStream = 0; const int64_t kSampleDuration = 1000; const int64_t kSample0Start = 0; const int64_t kSample1Start = kSample0Start + kSampleDuration; const int64_t kSample2Start = kSample1Start + kSampleDuration; const double kSample2StartInSeconds = static_cast<double>(kSample2Start) / kMsTimeScale; // Put the cue between two key frames. Cuepoint cue; cue.start_time_in_seconds = static_cast<double>(kSample1Start) / kMsTimeScale; AdCueGeneratorParams params; params.cue_points.push_back(cue); SyncPointQueue sync_points(params); std::shared_ptr<MediaHandler> handler = std::make_shared<CueAlignmentHandler>(&sync_points); ASSERT_OK(SetUpAndInitializeGraph(handler, kOneInput, kOneOutput)); { testing::InSequence s; EXPECT_CALL(*Output(kVideoStream), OnProcess(IsStreamInfo(kParent, kMsTimeScale, !kEncrypted, _))); EXPECT_CALL(*Output(kVideoStream), OnProcess(IsMediaSample(kParent, kSample0Start, kSampleDuration, !kEncrypted, _))); EXPECT_CALL(*Output(kVideoStream), OnProcess(IsMediaSample(kParent, kSample1Start, kSampleDuration, !kEncrypted, _))); EXPECT_CALL(*Output(kVideoStream), OnProcess(IsCueEvent(kParent, kSample2StartInSeconds))); EXPECT_CALL(*Output(kVideoStream), OnProcess(IsMediaSample(kParent, kSample2Start, kSampleDuration, !kEncrypted, _))); EXPECT_CALL(*Output(kVideoStream), OnFlush(kParent)); } auto stream_info = GetVideoStreamInfo(kMsTimeScale); auto sample_0 = GetMediaSample(kSample0Start, kSampleDuration, kKeyFrame); auto sample_1 = GetMediaSample(kSample1Start, kSampleDuration, !kKeyFrame); auto sample_2 = GetMediaSample(kSample2Start, kSampleDuration, kKeyFrame); ASSERT_OK(DispatchStreamInfo(kVideoStream, std::move(stream_info))); ASSERT_OK(DispatchMediaSample(kVideoStream, std::move(sample_0))); ASSERT_OK(DispatchMediaSample(kVideoStream, std::move(sample_1))); ASSERT_OK(DispatchMediaSample(kVideoStream, std::move(sample_2))); ASSERT_OK(FlushAll({kVideoStream})); } TEST_F(CueAlignmentHandlerTest, AudioInputWithCues) { const size_t kAudioStream = 0; const int64_t kSampleDuration = 1000; const int64_t kSample0Start = 0; const int64_t kSample1Start = kSample0Start + kSampleDuration; const int64_t kSample2Start = kSample1Start + kSampleDuration; const double kSample1StartInSeconds = static_cast<double>(kSample1Start) / kMsTimeScale; Cuepoint cue; cue.start_time_in_seconds = static_cast<double>(kSample1Start) / kMsTimeScale; AdCueGeneratorParams params; params.cue_points.push_back(cue); SyncPointQueue sync_points(params); std::shared_ptr<MediaHandler> handler = std::make_shared<CueAlignmentHandler>(&sync_points); ASSERT_OK(SetUpAndInitializeGraph(handler, kOneInput, kOneOutput)); { testing::InSequence s; EXPECT_CALL(*Output(kAudioStream), OnProcess(IsStreamInfo(kParent, kMsTimeScale, !kEncrypted, _))); EXPECT_CALL(*Output(kAudioStream), OnProcess(IsMediaSample(kParent, kSample0Start, kSampleDuration, !kEncrypted, _))); EXPECT_CALL(*Output(kAudioStream), OnProcess(IsCueEvent(kParent, kSample1StartInSeconds))); EXPECT_CALL(*Output(kAudioStream), OnProcess(IsMediaSample(kParent, kSample1Start, kSampleDuration, !kEncrypted, _))); EXPECT_CALL(*Output(kAudioStream), OnProcess(IsMediaSample(kParent, kSample2Start, kSampleDuration, !kEncrypted, _))); EXPECT_CALL(*Output(kAudioStream), OnFlush(kParent)); } auto stream_info = GetAudioStreamInfo(kMsTimeScale); auto sample_0 = GetMediaSample(kSample0Start, kSampleDuration, kKeyFrame); auto sample_1 = GetMediaSample(kSample1Start, kSampleDuration, kKeyFrame); auto sample_2 = GetMediaSample(kSample2Start, kSampleDuration, kKeyFrame); ASSERT_OK(DispatchStreamInfo(kAudioStream, std::move(stream_info))); ASSERT_OK(DispatchMediaSample(kAudioStream, std::move(sample_0))); ASSERT_OK(DispatchMediaSample(kAudioStream, std::move(sample_1))); ASSERT_OK(DispatchMediaSample(kAudioStream, std::move(sample_2))); ASSERT_OK(FlushAll({kAudioStream})); } TEST_F(CueAlignmentHandlerTest, TextInputWithCues) { const size_t kTextStream = 0; const int64_t kSampleDuration = 1000; const int64_t kSample0Start = 0; const int64_t kSample0End = kSample0Start + kSampleDuration; const int64_t kSample1Start = kSample0End; const int64_t kSample1End = kSample1Start + kSampleDuration; const int64_t kSample2Start = kSample1End; const int64_t kSample2End = kSample2Start + kSampleDuration; const double kSample1StartInSeconds = static_cast<double>(kSample1Start) / kMsTimeScale; Cuepoint cue; cue.start_time_in_seconds = static_cast<double>(kSample1Start) / kMsTimeScale; AdCueGeneratorParams params; params.cue_points.push_back(cue); SyncPointQueue sync_points(params); std::shared_ptr<MediaHandler> handler = std::make_shared<CueAlignmentHandler>(&sync_points); ASSERT_OK(SetUpAndInitializeGraph(handler, kOneInput, kOneOutput)); { testing::InSequence s; EXPECT_CALL(*Output(kTextStream), OnProcess(IsStreamInfo(kParent, kMsTimeScale, !kEncrypted, _))); EXPECT_CALL(*Output(kTextStream), OnProcess(IsTextSample(_, kNoId, kSample0Start, kSample0End, kNoSettings, kNoPayload))); EXPECT_CALL(*Output(kTextStream), OnProcess(IsCueEvent(kParent, kSample1StartInSeconds))); EXPECT_CALL(*Output(kTextStream), OnProcess(IsTextSample(_, kNoId, kSample1Start, kSample1End, kNoSettings, kNoPayload))); EXPECT_CALL(*Output(kTextStream), OnProcess(IsTextSample(_, kNoId, kSample2Start, kSample2End, kNoSettings, kNoPayload))); EXPECT_CALL(*Output(kTextStream), OnFlush(kParent)); } auto stream_info = GetTextStreamInfo(kMsTimeScale); auto sample_0 = GetTextSample(kNoId, kSample0Start, kSample0End, kNoPayload); auto sample_1 = GetTextSample(kNoId, kSample1Start, kSample1End, kNoPayload); auto sample_2 = GetTextSample(kNoId, kSample2Start, kSample2End, kNoPayload); ASSERT_OK(DispatchStreamInfo(kTextStream, std::move(stream_info))); ASSERT_OK(DispatchTextSample(kTextStream, std::move(sample_0))); ASSERT_OK(DispatchTextSample(kTextStream, std::move(sample_1))); ASSERT_OK(DispatchTextSample(kTextStream, std::move(sample_2))); ASSERT_OK(FlushAll({kTextStream})); } TEST_F(CueAlignmentHandlerTest, TextInputWithCueAfterLastStart) { const size_t kTextStream = 0; const int64_t kSampleDuration = 1000; const int64_t kSample0Start = 0; const int64_t kSample0End = kSample0Start + kSampleDuration; const int64_t kSample1Start = kSample0End; const int64_t kSample1End = kSample1Start + kSampleDuration; const int64_t kSample2Start = kSample1End; const int64_t kSample2End = kSample2Start + kSampleDuration; const double kCueTimeInSeconds = static_cast<double>(kSample2Start + kSample2End) / kMsTimeScale; // Put the cue between the start and end of the last sample. Cuepoint cue; cue.start_time_in_seconds = kCueTimeInSeconds; AdCueGeneratorParams params; params.cue_points.push_back(cue); SyncPointQueue sync_points(params); std::shared_ptr<MediaHandler> handler = std::make_shared<CueAlignmentHandler>(&sync_points); ASSERT_OK(SetUpAndInitializeGraph(handler, kOneInput, kOneOutput)); { testing::InSequence s; EXPECT_CALL(*Output(kTextStream), OnProcess(IsStreamInfo(kParent, kMsTimeScale, !kEncrypted, _))); EXPECT_CALL(*Output(kTextStream), OnProcess(IsTextSample(_, kNoId, kSample0Start, kSample0End, kNoSettings, kNoPayload))); EXPECT_CALL(*Output(kTextStream), OnProcess(IsTextSample(_, kNoId, kSample1Start, kSample1End, kNoSettings, kNoPayload))); EXPECT_CALL(*Output(kTextStream), OnProcess(IsTextSample(_, kNoId, kSample2Start, kSample2End, kNoSettings, kNoPayload))); EXPECT_CALL(*Output(kTextStream), OnProcess(IsCueEvent(kParent, kCueTimeInSeconds))); EXPECT_CALL(*Output(kTextStream), OnFlush(kParent)); } auto stream_info = GetTextStreamInfo(kMsTimeScale); auto sample_0 = GetTextSample(kNoId, kSample0Start, kSample0End, kNoPayload); auto sample_1 = GetTextSample(kNoId, kSample1Start, kSample1End, kNoPayload); auto sample_2 = GetTextSample(kNoId, kSample2Start, kSample2End, kNoPayload); ASSERT_OK(DispatchStreamInfo(kTextStream, std::move(stream_info))); ASSERT_OK(DispatchTextSample(kTextStream, std::move(sample_0))); ASSERT_OK(DispatchTextSample(kTextStream, std::move(sample_1))); ASSERT_OK(DispatchTextSample(kTextStream, std::move(sample_2))); ASSERT_OK(FlushAll({kTextStream})); } TEST_F(CueAlignmentHandlerTest, TextAudioVideoInputWithCues) { const size_t kTextStream = 0; const size_t kAudioStream = 1; const size_t kVideoStream = 2; const int64_t kSampleDuration = 1000; const int64_t kSample0Start = 0; const int64_t kSample0End = kSample0Start + kSampleDuration; const int64_t kSample1Start = kSample0End; const int64_t kSample1End = kSample1Start + kSampleDuration; const int64_t kSample2Start = kSample1End; const int64_t kSample2End = kSample2Start + kSampleDuration; const double kSample2StartInSeconds = static_cast<double>(kSample2Start) / kMsTimeScale; // Put the cue between two key frames. Cuepoint cue; cue.start_time_in_seconds = static_cast<double>(kSample1Start) / kMsTimeScale; AdCueGeneratorParams params; params.cue_points.push_back(cue); SyncPointQueue sync_points(params); std::shared_ptr<MediaHandler> handler = std::make_shared<CueAlignmentHandler>(&sync_points); ASSERT_OK(SetUpAndInitializeGraph(handler, kThreeInput, kThreeOutput)); { testing::InSequence s; EXPECT_CALL(*Output(kTextStream), OnProcess(IsStreamInfo(kParent, kMsTimeScale, !kEncrypted, _))); EXPECT_CALL(*Output(kTextStream), OnProcess(IsTextSample(_, kNoId, kSample0Start, kSample0End, kNoSettings, kNoPayload))); EXPECT_CALL(*Output(kTextStream), OnProcess(IsTextSample(_, kNoId, kSample1Start, kSample1End, kNoSettings, kNoPayload))); EXPECT_CALL(*Output(kTextStream), OnProcess(IsCueEvent(kParent, kSample2StartInSeconds))); EXPECT_CALL(*Output(kTextStream), OnProcess(IsTextSample(_, kNoId, kSample2Start, kSample2End, kNoSettings, kNoPayload))); EXPECT_CALL(*Output(kTextStream), OnFlush(kParent)); } { testing::InSequence s; EXPECT_CALL(*Output(kAudioStream), OnProcess(IsStreamInfo(kParent, kMsTimeScale, !kEncrypted, _))); EXPECT_CALL(*Output(kAudioStream), OnProcess(IsMediaSample(kParent, kSample0Start, kSampleDuration, !kEncrypted, _))); EXPECT_CALL(*Output(kAudioStream), OnProcess(IsMediaSample(kParent, kSample1Start, kSampleDuration, !kEncrypted, _))); EXPECT_CALL(*Output(kAudioStream), OnProcess(IsCueEvent(kParent, kSample2StartInSeconds))); EXPECT_CALL(*Output(kAudioStream), OnProcess(IsMediaSample(kParent, kSample2Start, kSampleDuration, !kEncrypted, _))); EXPECT_CALL(*Output(kAudioStream), OnFlush(kParent)); } { testing::InSequence s; EXPECT_CALL(*Output(kVideoStream), OnProcess(IsStreamInfo(kParent, kMsTimeScale, !kEncrypted, _))); EXPECT_CALL(*Output(kVideoStream), OnProcess(IsMediaSample(kParent, kSample0Start, kSampleDuration, !kEncrypted, _))); EXPECT_CALL(*Output(kVideoStream), OnProcess(IsMediaSample(kParent, kSample1Start, kSampleDuration, !kEncrypted, _))); EXPECT_CALL(*Output(kVideoStream), OnProcess(IsCueEvent(kParent, kSample2StartInSeconds))); EXPECT_CALL(*Output(kVideoStream), OnProcess(IsMediaSample(kParent, kSample2Start, kSampleDuration, !kEncrypted, _))); EXPECT_CALL(*Output(kVideoStream), OnFlush(kParent)); } // Text samples auto text_stream_info = GetTextStreamInfo(kMsTimeScale); auto text_sample_0 = GetTextSample(kNoId, kSample0Start, kSample0End, kNoPayload); auto text_sample_1 = GetTextSample(kNoId, kSample1Start, kSample1End, kNoPayload); auto text_sample_2 = GetTextSample(kNoId, kSample2Start, kSample2End, kNoPayload); // Audio samples auto audio_stream_info = GetAudioStreamInfo(kMsTimeScale); auto audio_sample_0 = GetMediaSample(kSample0Start, kSampleDuration, kKeyFrame); auto audio_sample_1 = GetMediaSample(kSample1Start, kSampleDuration, kKeyFrame); auto audio_sample_2 = GetMediaSample(kSample2Start, kSampleDuration, kKeyFrame); // Video samples auto video_stream_info = GetVideoStreamInfo(kMsTimeScale); auto video_sample_0 = GetMediaSample(kSample0Start, kSampleDuration, kKeyFrame); auto video_sample_1 = GetMediaSample(kSample1Start, kSampleDuration, !kKeyFrame); auto video_sample_2 = GetMediaSample(kSample2Start, kSampleDuration, kKeyFrame); // Dispatch Stream Info ASSERT_OK(DispatchStreamInfo(kTextStream, std::move(text_stream_info))); ASSERT_OK(DispatchStreamInfo(kAudioStream, std::move(audio_stream_info))); ASSERT_OK(DispatchStreamInfo(kVideoStream, std::move(video_stream_info))); // Dispatch Sample 0 ASSERT_OK(DispatchTextSample(kTextStream, std::move(text_sample_0))); ASSERT_OK(DispatchMediaSample(kAudioStream, std::move(audio_sample_0))); ASSERT_OK(DispatchMediaSample(kVideoStream, std::move(video_sample_0))); // Dispatch Sample 1 ASSERT_OK(DispatchTextSample(kTextStream, std::move(text_sample_1))); ASSERT_OK(DispatchMediaSample(kAudioStream, std::move(audio_sample_1))); ASSERT_OK(DispatchMediaSample(kVideoStream, std::move(video_sample_1))); // Dispatch Sample 2 ASSERT_OK(DispatchTextSample(kTextStream, std::move(text_sample_2))); ASSERT_OK(DispatchMediaSample(kAudioStream, std::move(audio_sample_2))); ASSERT_OK(DispatchMediaSample(kVideoStream, std::move(video_sample_2))); ASSERT_OK(FlushAll({kTextStream, kAudioStream, kVideoStream})); } // TODO(kqyang): Add more tests, in particular, multi-thread tests. } // namespace media } // namespace shaka
#pragma once #include <gpu/material.h> class Transparent : public Material { public: __device__ Transparent(float ref_index) : refractive_index(ref_index) {}; __device__ ~Transparent() = default; __device__ bool Transparent::scatter(const Ray& r, HitDesc& d, glm::vec3& attenuation, Ray& scattered, curandState* local_rand_state) override { return false; } public: float refractive_index; };
// energy.h #ifndef ENERGY_H #define ENERGY_H #include <memory> #include <unordered_map> #include <utility> #include <vector> #include "BlobCrystallinOligomer/config.h" #include "BlobCrystallinOligomer/ifile.h" #include "BlobCrystallinOligomer/hash.h" #include "BlobCrystallinOligomer/monomer.h" #include "BlobCrystallinOligomer/param.h" #include "BlobCrystallinOligomer/particle.h" #include "BlobCrystallinOligomer/potential.h" #include "BlobCrystallinOligomer/shared_types.h" namespace energy { using config::Config; using config::monomerArrayT; using ifile::InteractionData; using ifile::PotentialData; using monomer::Monomer; using param::InputParams; using particle::Particle; using potential::PairPotential; using shared_types::CoorSet; using shared_types::distT; using shared_types::eneT; using std::pair; using std::reference_wrapper; using std::unique_ptr; using std::unordered_map; using std::vector; /** System energy * * Contains all potentials present in system and maps from pairs of * particles to their interaction potential type. Responsible for * instantiating the potentials. */ class Energy { public: Energy(Config& conf, InputParams& params); Energy(Config& conf, vector<PotentialData>, vector<InteractionData>); /** Calculate total system energy */ eneT calc_total_energy(); /** Calculate pair energy between two monomers */ eneT calc_monomer_pair_energy( Monomer& monomer1, CoorSet coorset1, Monomer& monomer2, CoorSet coorset2); /** Check if monomers within range to have non-zero pair potential */ bool monomers_interacting( Monomer& monomer1, CoorSet coorset1, Monomer& monomer2, CoorSet coorset2); /** Create list of monomers interacting with given monomer */ monomerArrayT get_interacting_monomers(Monomer& monomer1, CoorSet coorset1); /** Calculate energy difference between current and trial */ eneT calc_monomer_diff(Monomer& monomer); /** Check if particles within range to have non-zero pair potential */ bool particles_interacting( Particle& particle1, int conformer1, CoorSet coorset1, Particle& particle2, int conformer2, CoorSet coorset2); /** Calculate pair energy between two particles.*/ eneT calc_particle_pair_energy( Particle& particle1, int conformer1, CoorSet coorset1, Particle& particle2, int conformer2, CoorSet coorset2); private: Config& m_config; vector<unique_ptr<PairPotential>> m_potentials; unordered_map<pair<int, int>, reference_wrapper<PairPotential>> m_same_pair_to_pot; unordered_map<pair<int, int>, reference_wrapper<PairPotential>> m_different_pair_to_pot; distT m_max_cutoff; void create_potentials(vector<PotentialData> potentials, vector<InteractionData> same_conformers_interactions, vector<InteractionData> different_conformers_interactions); bool monomers_in_range( Monomer& monomer1, CoorSet coorset1, Monomer& monomer2, CoorSet coorset2); }; } #endif // ENERGY_H
#include "pch.h" #include "AISystem.h" #include "Core\EntityAssembler.h" #include "Core\AssembledBehaviorReg.h" #include "Core\Entity.h" #include "Component\Transform.h" #include <io.h> #include "Core\InputManager.h" #include "Renderer\DebugRenderer.h" #include "Component\Motor.h" #include "Core\TimeManager.h" namespace Hourglass { static bool s_bDrawDebugAIDestination = false; void AISystem::Init() { ComponentPoolInit( SID(Separation), m_Separations, &m_SeparationPool, s_kMaxSeparations ); ComponentPoolInit( SID(BehaviorTree), m_BehaviorTrees, &m_BehaviorTreePool, s_kMaxBehaviorTrees ); ComponentPoolInit( SID(WaypointAgent), m_WaypointAgents, &m_WaypointAgentPool, s_kMaxWaypointAgents ); BehaviorPoolInit( SID(Sequence), m_Sequences, &m_SequencePool, s_kMaxBehaviorTrees ); BehaviorPoolInit( SID(Selector), m_Selectors, &m_SelectorPool, s_kMaxSelectors ); BehaviorPoolInit( SID(RepeatUntilFail), m_Rufs, &m_RufPool, s_kMaxRufs ); BehaviorPoolInit( SID(Inverter), m_Inverters, &m_InverterPool, s_kMaxInverters ); BehaviorPoolInit( SID(Parallel), m_Parallels, &m_ParallelPool, s_kMaxParallels ); } void AISystem::Start() { m_WaypointSearch.Init( &m_WaypointGraph ); m_InverterPool.Start(); m_ParallelPool.Start(); m_RufPool.Start(); m_SelectorPool.Start(); m_SequencePool.Start(); } void AISystem::LoadBehaviors() { LoadBehaviorsFromXML(); } void AISystem::Update() { m_WaypointGraph.DrawDebugEdges(); float dt = hg::g_Time.Delta(); for (unsigned int i = 0; i < s_kMaxWaypointAgents; ++i) { if (m_WaypointAgents[i].IsAlive() && m_WaypointAgents[i].IsEnabled() && !m_WaypointAgents[i].IsDormant()) { m_WaypointAgents[i].Update(); if (m_WaypointAgents[i].DoesNeedPath()) { if (m_WaypointAgents[i].DoesNeedCurrentWaypoint()) { const Vector3& currentPos = m_WaypointAgents[i].GetEntity()->GetTransform()->GetWorldPosition(); unsigned int toCurrentWaypoint = m_WaypointGraph.FindNearestVertex( currentPos ); m_WaypointAgents[i].SetCurrentWaypoint( toCurrentWaypoint ); } else if (m_WaypointAgents[i].DoesNeedNextWaypoint()) { Vector3 destination = m_WaypointAgents[i].GetDestination(); unsigned int toDestination = m_WaypointGraph.FindNearestVertex( destination ); m_WaypointSearch.Configure( m_WaypointAgents[i].GetCurrentWaypoint(), toDestination ); m_WaypointSearch.FindPath(); //m_WaypointSearch.FindPath(); unsigned int solutionWaypoint = m_WaypointSearch.GetSolutionWaypoint(); m_WaypointAgents[i].SetNextWaypoint( solutionWaypoint ); m_WaypointAgents[i].SetWaypointPosition( m_WaypointGraph[solutionWaypoint].m_Waypoint ); } } //m_WaypointSearch.DrawDebug(); if (s_bDrawDebugAIDestination && DEBUG_RENDER) { if (m_WaypointAgents[i].GetCurrentWaypoint() < 3000) { Vector4 debugColor = { 0.0f, 0.0f, 1.0f, 1.0f }; Aabb debugAabb; debugAabb.pMin = m_WaypointGraph[m_WaypointAgents[i].GetCurrentWaypoint()].m_Waypoint - Vector3(0.5f, 0.5f, 0.5f); debugAabb.pMax = m_WaypointGraph[m_WaypointAgents[i].GetCurrentWaypoint()].m_Waypoint + Vector3(0.5f, 0.5f, 0.5f); DebugRenderer::DrawAabb(debugAabb, debugColor); } if (m_WaypointAgents[i].GetNextWaypoint() < 3000) { Vector4 debugColor = { 0.0f, 0.5f, 1.0f, 1.0f }; Aabb debugAabb; debugAabb.pMin = m_WaypointGraph[m_WaypointAgents[i].GetNextWaypoint()].m_Waypoint - Vector3(0.5f, 0.5f, 0.5f); debugAabb.pMax = m_WaypointGraph[m_WaypointAgents[i].GetNextWaypoint()].m_Waypoint + Vector3(0.5f, 0.5f, 0.5f); DebugRenderer::DrawAabb(debugAabb, debugColor); } } } } for (unsigned int i = 0; i < s_kMaxBehaviorTrees; ++i) { if (m_BehaviorTrees[i].IsAlive() && m_BehaviorTrees[i].IsEnabled()) { m_BehaviorTrees[i].Update(); } } for (unsigned int i = 0; i < s_kMaxSeparations; ++i) { Separation& separation = m_Separations[i]; if (separation.IsAlive() && separation.IsEnabled()) { Motor& motor = *separation.GetEntity()->GetComponent<Motor>(); float speed = motor.GetMaxSpeed(); Vector3 acc = CalcSeparationAcc( &separation ); Vector3 pos = separation.GetEntity()->GetTransform()->GetWorldPosition(); //DebugRenderer::DrawLine( pos, pos + acc, Vector4( 0.0f, 0.0f, 1.0f, 1.0f ) ); acc += separation.GetDesiredMove(); acc *= speed * dt; Vector3 velocity = motor.GetDesiredMove() * motor.GetSpeed() + acc * 10; float magnitude = velocity.Length(); motor.SetSpeed( min( speed, magnitude ) ); velocity.Normalize(); //DebugRenderer::DrawLine( pos, pos + velocity, Vector4( 1.0f, 0.0f, 0.0f, 1.0f ) ); motor.SetDesiredMove( velocity ); } } } void AISystem::LoadBehaviorsFromXML() { char folder[FILENAME_MAX] = "Assets\\XML\\Behavior\\"; char filter[FILENAME_MAX]; strcpy_s( filter, folder ); strcat_s( filter, "*.xml" ); WIN32_FIND_DATAA fileData; HANDLE searchHandle = FindFirstFileA( filter, &fileData ); if (searchHandle != INVALID_HANDLE_VALUE) { do { // Piece together the full path from folder + file name char fullpath[FILENAME_MAX]; strcpy_s( fullpath, folder ); strcat_s( fullpath, fileData.cFileName ); // Load a single document from the behaviors folder LoadBehaviorTreeXML( fullpath ); } while (FindNextFileA( searchHandle, &fileData )); FindClose( searchHandle ); } } void AISystem::LoadBehaviorTreeXML( const char* path ) { tinyxml2::XMLDocument doc; tinyxml2::XMLError errorResult = doc.LoadFile( path ); assert( errorResult == tinyxml2::XML_SUCCESS ); // Get the behavior tree tinyxml2::XMLElement * xmlTree = doc.FirstChildElement(); assert( strcmp(xmlTree->Value(), "BehaviorTree") == 0 ); const char* behaviorTreeName = xmlTree->Attribute( "name" ); // Get the behavior tree root tinyxml2::XMLElement* xmlRoot = xmlTree->FirstChildElement(); // There can only be one root, no siblings allowed for this one assert( xmlRoot->NextSibling() == NULL ); IBehavior* root = RecursiveLoadBehaviorXML( xmlRoot ); hg::AssembledBehaviorReg reg( WSID(behaviorTreeName), root ); } IBehavior* AISystem::RecursiveLoadBehaviorXML( tinyxml2::XMLElement* behaviorXML ) { IBehavior* behavior = BehaviorFactory::GetBehaviorToAssemble( WSID( behaviorXML->Value() ) ); tinyxml2::XMLElement* behaviorChildXML = behaviorXML->FirstChildElement(); for (; behaviorChildXML; behaviorChildXML = behaviorChildXML->NextSiblingElement()) { behavior->AddBehavior( RecursiveLoadBehaviorXML( behaviorChildXML ) ); } behavior->LoadFromXML( behaviorXML ); return behavior; } Vector3 AISystem::CalcSeparationAcc( Separation* curr ) { Vector3 sum = Vector3::Zero; Entity* currEntity = curr->GetEntity(); const Vector3& currPos = currEntity->GetTransform()->GetWorldPosition(); for (unsigned int i = 0; i < s_kMaxSeparations; ++i) { Separation* other = &m_Separations[i]; if (other == curr || !other->IsAlive() || !other->IsEnabled()) continue; Entity* otherEntity = other->GetEntity(); const Vector3& otherPos = otherEntity->GetTransform()->GetWorldPosition(); Vector3 toVector = currPos - otherPos; toVector.y = 0.0f; float dist = toVector.Length(); float otherSafeRadius = other->GetSafeRadius(); float safeDist = curr->GetSafeRadius() + other->GetSafeRadius(); if (dist < safeDist) { toVector.Normalize(); toVector *= (safeDist - dist) / safeDist; sum += toVector; } } if (sum.Length() > 1.0f) sum.Normalize(); sum *= curr->GetSeparationStrength(); return sum; } void AISystem::LoadWaypoints( tinyxml2::XMLElement* waypointsXML ) { // Process all waypoints tinyxml2::XMLElement* xmlWaypoint = waypointsXML->FirstChildElement(); while (xmlWaypoint != nullptr) { tinyxml2::XMLElement* xmlPosition = xmlWaypoint->FirstChildElement( "Position" ); Vector3 position; xmlPosition->QueryFloatAttribute( "x", &position.x ); xmlPosition->QueryFloatAttribute( "y", &position.y ); xmlPosition->QueryFloatAttribute( "z", &position.z ); unsigned int vertIndex = m_WaypointGraph.AddVertex( position ); WaypointGraph::WVertex& newVertex = m_WaypointGraph[vertIndex]; tinyxml2::XMLElement* xmlEdges = xmlWaypoint->FirstChildElement( "Edges" ); tinyxml2::XMLElement* xmlEdge = xmlEdges->FirstChildElement( "Edge" ); while (xmlEdge != nullptr) { WaypointGraph::Edge edge; xmlEdge->QueryUnsignedAttribute( "vertex", &edge.m_ToVertex ); xmlEdge->QueryFloatAttribute( "distance", &edge.m_Distance ); newVertex.AddEdge( edge ); xmlEdge = xmlEdge->NextSiblingElement(); } xmlWaypoint = xmlWaypoint->NextSiblingElement(); } } }
#include <bits/stdc++.h> #define REP(i, a, n) for(ll i = ((ll) a); i < ((ll) n); i++) #define MOD 1000000007LL using namespace std; typedef long long ll; class ModuloCombination { private: vector<ll> fact, inv_fact; static ll modulo_power(ll a, ll n) { if(n == 0) return 1; if(n % 2 == 0) return modulo_power((a * a) % MOD, n / 2); return (a * modulo_power(a, n - 1)) % MOD; } public: ModuloCombination(ll N): fact(N + 1), inv_fact(N + 1) { fact[0] = 1; REP(i, 1, N + 1) fact[i] = (i * fact[i - 1]) % MOD; REP(i, 0, N + 1) inv_fact[i] = modulo_power(fact[i], MOD - 2); } ll operator()(ll n, ll r) { return fact[n] * inv_fact[r] % MOD * inv_fact[n - r] % MOD; } }; int main(void) { ModuloCombination comb(200000); assert(comb(200000, 100000) == 879467333LL); }
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*- * * Copyright (C) 1995-2011 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * Allowed #if-ery: none. * Sort order: alphabetic */ #ifndef POSIX_SYS_NONIX_CHOICE_H #define POSIX_SYS_NONIX_CHOICE_H __FILE__ #define SYSTEM_BLOCK_CON_FILE NO #define SYSTEM_COLORREF NO /* COLORREF type */ #define SYSTEM_DRIVES NO #define SYSTEM_DTOA NO /* dtoa() */ #define SYSTEM_ETOA NO /* etoa() */ #define SYSTEM_GETPHYSMEM NO /* OpSystemInfo::GetPhysicalMemorySizeMB */ #define SYSTEM_GUID NO #define SYSTEM_ITOA NO /* itoa() */ #define SYSTEM_LTOA NO /* ltoa() */ #define SYSTEM_MAKELONG NO /* MAKELONG(,) macro */ #define SYSTEM_MULTIPLE_DRIVES NO #define SYSTEM_NETWORK_BACKSLASH_PATH NO #define SYSTEM_OWN_OP_STATUS_VALUES NO #define SYSTEM_POINT NO /* POINT struct */ #define SYSTEM_RECT NO /* RECT struct */ #define SYSTEM_RGB NO /* RGB macro */ #define SYSTEM_SIZE NO /* SIZE struct */ #define SYSTEM_STRCASE NO /* strlwr, strupr */ #define SYSTEM_STRREV NO /* at least, not on Linux */ #define SYSTEM_UNI_ITOA NO /* itow */ #define SYSTEM_UNI_LTOA NO /* ltow */ #define SYSTEM_UNI_MEMCHR NO #define SYSTEM_UNI_SNPRINTF POSIX_SYS_USE_UNI #define SYSTEM_UNI_SPRINTF POSIX_SYS_USE_UNI #define SYSTEM_UNI_SSCANF POSIX_SYS_USE_UNI #define SYSTEM_UNI_STRCAT POSIX_SYS_USE_UNI #define SYSTEM_UNI_STRCHR POSIX_SYS_USE_UNI #define SYSTEM_UNI_STRCMP POSIX_SYS_USE_UNI #define SYSTEM_UNI_STRCPY POSIX_SYS_USE_UNI #define SYSTEM_UNI_STRCSPN POSIX_SYS_USE_UNI #define SYSTEM_UNI_STRDUP POSIX_SYS_USE_UNI #define SYSTEM_UNI_STRICMP POSIX_SYS_USE_UNI #define SYSTEM_UNI_STRISTR POSIX_SYS_USE_UNI #define SYSTEM_UNI_STRLCAT POSIX_SYS_USE_UNI #define SYSTEM_UNI_STRLCPY POSIX_SYS_USE_UNI #define SYSTEM_UNI_STRLEN POSIX_SYS_USE_UNI #define SYSTEM_UNI_STRNCAT POSIX_SYS_USE_UNI #define SYSTEM_UNI_STRNCMP POSIX_SYS_USE_UNI #define SYSTEM_UNI_STRNCPY POSIX_SYS_USE_UNI #define SYSTEM_UNI_STRNICMP POSIX_SYS_USE_UNI #define SYSTEM_UNI_STRPBRK POSIX_SYS_USE_UNI #define SYSTEM_UNI_STRRCHR POSIX_SYS_USE_UNI #define SYSTEM_UNI_STRREV POSIX_SYS_USE_UNI #define SYSTEM_UNI_STRSPN POSIX_SYS_USE_UNI #define SYSTEM_UNI_STRSTR POSIX_SYS_USE_UNI #define SYSTEM_UNI_STRTOK POSIX_SYS_USE_UNI #define SYSTEM_UNI_VSNPRINTF POSIX_SYS_USE_UNI #define SYSTEM_UNI_VSPRINTF POSIX_SYS_USE_UNI #define SYSTEM_YIELD NO #endif /* POSIX_SYS_NONIX_CHOICE_H */
// Created on: 1997-03-26 // Created by: Christian CAILLET // Copyright (c) 1997-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _StepBasic_ApprovalDateTime_HeaderFile #define _StepBasic_ApprovalDateTime_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <StepBasic_DateTimeSelect.hxx> #include <Standard_Transient.hxx> class StepBasic_Approval; class StepBasic_ApprovalDateTime; DEFINE_STANDARD_HANDLE(StepBasic_ApprovalDateTime, Standard_Transient) //! Added from StepBasic Rev2 to Rev4 class StepBasic_ApprovalDateTime : public Standard_Transient { public: Standard_EXPORT StepBasic_ApprovalDateTime(); Standard_EXPORT void Init (const StepBasic_DateTimeSelect& aDateTime, const Handle(StepBasic_Approval)& aDatedApproval); Standard_EXPORT void SetDateTime (const StepBasic_DateTimeSelect& aDateTime); Standard_EXPORT StepBasic_DateTimeSelect DateTime() const; Standard_EXPORT void SetDatedApproval (const Handle(StepBasic_Approval)& aDatedApproval); Standard_EXPORT Handle(StepBasic_Approval) DatedApproval() const; DEFINE_STANDARD_RTTIEXT(StepBasic_ApprovalDateTime,Standard_Transient) protected: private: StepBasic_DateTimeSelect theDateTime; Handle(StepBasic_Approval) theDatedApproval; }; #endif // _StepBasic_ApprovalDateTime_HeaderFile
// Copyright: 2017 Bing-Hui WANG // // Author: Bing-Hui WANG // // Date: 2017-10-3 // // Description: This code has build a class (FHandle) for parsing math expression from string. // It just like "function handle" in MATLAB. User can creat a FHandle variable from string, and // calculate the value of your function expression by using "double FHandle::eval(const double&)" // // Example 1: // FHandle f = "exp(-x) * sin(x) + cos(5*x)^2 * sqrt(1+x^2)"; // Get f from string. // cout << f.eval(1) << endl; // Calculate the value of f at point 0. // // Example 2: // FHandle f; // cin >> f; // Get f from terminal. // cout << f.eval(0) << endl; // Calculate the value of f at point 0. // // See usage details in "./README.md" // See more examples in "./examples/" #ifndef FHandle_H #define FHandle_H #include <stack> #include <cmath> #include <math.h> #include <sstream> #include <vector> #include <cfloat> #include <time.h> #include <algorithm> #include <fstream> #include <unistd.h> #include <iostream> using namespace std; #define PI 3.1415926536 #define WRONG nan("1") // Define class "Element". It represent the element of a expression. // Used to store element in an expression. // For example, in expression "5*exp(x)": 5,*,exp,(,x,) is 6 expression elements. class Element { friend ostream& operator <<(ostream&o, const Element& X); public: int type; // Used to identify an Element is operator, number or "x". // * type = 0 means this element is operator // * type = 1 means this element is number or variable // * type = -1 means this element is wrong. int identify; // Used to number the operators // For example, identify = 1 means this element is "+" // identify = 8 means this element is "sin" // For other situation, you can see in file "./Note/Element.txt" double data; // If element is a numer, data used to store the value of this number. // If not, let data = 0. public: Element(); Element(int t, int i, double d); Element(const Element& X); Element& operator =(const Element& X); bool operator ==(const Element& X); bool operator !=(const Element& X); }; // Define the class "FHandle". See the details in head of this file or in file "./README.md" class FHandle { friend ostream& operator <<(ostream& o, const FHandle& f); friend istream& operator >>(istream& i, FHandle& f); public: int variable_system = 0; // 0 means no variable // 1 means variable can only use "x, y, z" // 2 means variable can only use "x1, x2, x3, ..." int n_variables = 0; vector<Element> Postfix; // Used to store the ordered Elements of postfix expression string f_str; // Used to store the string of initial(infix) expression private: double plot_xstart; double plot_xend; double surf_xstart; double surf_xend; double surf_ystart; double surf_yend; private: Element getElement(const string& str, int& i); void check(); // Function: vector<Element> infix2postfix(string); // // Description: Convert infix expression string into postfix expression's Element array. // // Input Parameter: const string& str: The infix expression string. // // Output Parameter: Nothing // // Return: The Element array of postfix expression in type vector<Element>. void set_postfix_from_infix_string(string str); public: FHandle(); FHandle(const FHandle& g); FHandle(const string& str); FHandle(const char* c_str); FHandle(const double& k); FHandle(const int& k); //------------------------------------------------------------------------------- // Function: FHandle& FHandle::operator =(const FHandle&); // // Description: Reload of FHandle's operator "=". // Make it possible to clone a FHandle to another by using "=". // // Input Parameter: const FHandle& f: FHandle on the right of "=" // // Output Parameter: Nothing. // // Return: the reference of FHandle on the right of "=". FHandle& operator =(const FHandle& f); //------------------------------------------------------------------------------- // Function: FHandle& FHandle::operator =(const string&); // // Description: Reload of FHandle's operator "=". // Make it possible to convert from string to FHandle by using "=". // // Input Parameter: const string& str: string on the right of "=". // // Output Parameter: Nothing. // // Return: the reference of FHandle after "=". FHandle& operator =(const string& str); //------------------------------------------------------------------------------- // Function: FHandle& FHandle::operator =(const char*); // // Description: Reload of FHandle's operator "=". // Make it possible to convert from C style string to FHandle by using "=". // // Input Parameter: const char* c_str: C style string on the right of "=". // // Output Parameter: Nothing. // // Return: the reference of FHandle after "=". FHandle& operator =(const char* c_str); FHandle& input(const string& str_promt); //------------------------------------------------------------------------------- // Function: void FHandle::clear(); // // Description: Clear FHandle's memory. // // Input Parameter: Nothing // // Output Parameter: Nothing // // Return: void. void clear(); //------------------------------------------------------------------------------- // Function: bool FHandle::empty()const; // // Description: To judge a FHandle is empty or not. // // Input Parameter: Nothing // // Output Parameter: Nothing // // Return: "true" when FHandle is empty. bool empty()const; //------------------------------------------------------------------------------- // Function: double FHandle::eval(const double& x=0.)const; // // Description: To calculate the expression's value at point x of a FHandle variable. // // Input Parameter: const double& x: The observing point of expression. // // Output Parameter: Nothing // // Return: The value of expression at point x of FHandle in type "double". template<typename ... DataTypes> double operator()(DataTypes... varargin)const; FHandle fix_variable(const vector<int>& indexs, const vector<double>& values); FHandle fix_variable(int index, double value); friend FHandle operator +(const FHandle& f1, const FHandle& f2); friend FHandle operator +(const FHandle& f1, const double& k); friend FHandle operator +(const double& k, const FHandle& f2); friend FHandle operator -(const FHandle& f1, const FHandle& f2); friend FHandle operator -(const FHandle& f1, const double& k); friend FHandle operator -(const double& k, const FHandle& f2); friend FHandle operator *(const FHandle& f1, const FHandle& f2); friend FHandle operator *(const FHandle& f1, const double& k); friend FHandle operator *(const double& k, const FHandle& f2); friend FHandle operator /(const FHandle& f1, const FHandle& f2); friend FHandle operator /(const FHandle& f1, const double& k); friend FHandle operator /(const double& k, const FHandle& f2); friend FHandle operator ^(const FHandle& f1, const FHandle& f2); friend FHandle operator ^(const FHandle& f1, const double& k); friend FHandle operator ^(const double& k, const FHandle& f2); //------------------------------------------------------------------------------- // Function: double FHandle::max(const double& a, const double& b)const; // // Description: To find the maximum value of FHandle in interval [a, b]. // // Input Parameter: const double& a: The lower limit of interval. // const double& b: The upper limit of interval. // // Output Parameter: Nothing // // Return: The maximum value of FHandle in interval [a, b] in type "double". double max(const double& a, const double& b)const; //------------------------------------------------------------------------------- // Function: double FHandle::min(const double& a, const double& b)const; // // Description: To find the minimum value of FHandle in interval [a, b]. // // Input Parameter: const double& a: The lower limit of interval. // const double& b: The upper limit of interval. // // Output Parameter: Nothing // // Return: The minimum value of FHandle in interval [a, b] in type "double". double min(const double& a, const double& b)const; }; bool isNumber(const char& ch); // To judge if a double number is a interge. bool isInt(const double& x); // Get the sign of a double number. int sgn(const double& x); // Convert string to a double number. double string2double(const string& str); double getNumberData(const string& str, int i); vector<double> varargin2vector(); template<typename DataType, typename ... DataTypes> vector<double> varargin2vector(DataType xn); template<typename Datatype, typename ... DataTypes> vector<double> varargin2vector(Datatype first, DataTypes ... rest); //////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// template<typename DataType, typename ... DataTypes> vector<double> varargin2vector(DataType xn) { return vector<double>(1, (double)xn); } template<typename Datatype, typename ... DataTypes> vector<double> varargin2vector(Datatype first, DataTypes ... rest) { vector<double> variables(1, (double)first), variables_rest; variables_rest = varargin2vector(rest...); variables.insert(variables.end(), variables_rest.begin(), variables_rest.end()); return variables; } template<typename DataType> string cout2str(const DataType& value) { stringstream ss; string str; ss << value; ss >> str; return str; } // Function: double FHandle::eval(const double& x=0.)const; // // Description: To calculate the expression's value at point x of a FHandle variable. // // Calls: bool isInt(const double&); // // Declared in "./FHandle.h" // // Defined in current file. // // Input Parameter: const double& x: The observing point of expression. // // Output Parameter: Nothing // // Return: The value of expression at point x of FHandle in type "double". template<typename ... DataTypes> double FHandle::operator ()(DataTypes ... varargin)const { vector<double> variables = varargin2vector(varargin...); if( empty() ) { return WRONG; } stack<double> Object; Element ele_temp; double X, Y; for(vector<Element>::const_iterator it = Postfix.begin(); it != Postfix.end(); it++) { ele_temp = *it; switch(ele_temp.type) { case 1://ele_temp is number or "PI" or variables { switch(ele_temp.identify) { case 0: { Object.push(ele_temp.data); break; } default: { if(ele_temp.identify > (int)variables.size()) { Object.push(0); } else { Object.push(variables[ele_temp.identify-1]); } break; } } break; } case 0://ele_temp is operator { int ide = ele_temp.identify; if( ide >= 1 && ide <= 5 ) { if(Object.empty()) { cout << endl << "The format of the input math expresion is wrong!" << endl << endl; return WRONG; } else { Y = Object.top(); Object.pop(); } if(Object.empty()) { cout << endl << "The format of the input math expresion is wrong!" << endl << endl; return WRONG; } else { X = Object.top(); Object.pop(); } switch(ide) { case 1:/*+*/ Object.push(X + Y); break; case 2:/*-*/ Object.push(X - Y); break; case 3:/***/ Object.push(X * Y); break; case 4:/*/*/ { if(Y == 0) { cout << endl << "Error in X / Y, Y is 0 now!" << endl; return WRONG; } Object.push(X / Y); break; } case 5:/*^*/ { if(X == 0 && Y < 0) { cout << endl << "Error in X^Y, X is 0 and Y is negtive now!" << endl; return WRONG; } Object.push( pow(X, Y) ); break; } } } else { if(Object.empty()) { cout << endl << "The format of the input math expresion is wrong!" << endl << endl; return WRONG; } else { X = Object.top(); Object.pop(); } switch(ide) { case 8://sin { Object.push( sin(X) ); break; } case 9://cos { Object.push( cos(X) ); break; } case 10://tan { if( isInt( (X-PI/2)/PI ) ) { cout << endl << "Error in tan(x), x is (PI/2 + k*PI) now!" << endl << endl; return WRONG; } Object.push( tan(X) ); break; } case 11://csc { if(sin(X) == 0) { cout << endl << "Error in csc(x), sin(x) is 0 now!" << endl << endl; return WRONG; } Object.push( 1/sin(X) ); break; } case 12://sec { if(cos(X) == 0) { cout << endl << "Error in sec(x), cos(x) is 0 now!" << endl << endl; return WRONG; } Object.push( 1/cos(X) ); break; } case 13://cot { if(tan(X) == 0) { cout << endl << "Error in cot(x), tan(x) is 0 now!" << endl << endl; return WRONG; } Object.push( 1/tan(X) ); break; } case 14://asin { if(X < -1 || X > 1) { cout << endl << "Error in asin(x), x is out of [-1, 1] now!" << endl << endl; return WRONG; } Object.push( asin(X) ); break; } case 15://acos { if(X < -1 || X > 1) { cout << endl << "Error in acos(x), x is out of [-1, 1] now!" << endl << endl; return WRONG; } Object.push( acos(X) ); break; } case 16://atan { Object.push( atan(X) ); break; } case 17://acsc { if(X > -1 && X < 1) { cout << endl << "Error in acsc(x), x is in [-1, 1] now!" << endl << endl; return WRONG; } Object.push( asin(1/X) ); break; } case 18://asec { if(X > -1 && X < 1) { cout << endl << "Error in asec(x), x is in [-1, 1] now!" << endl << endl; return WRONG; } Object.push( acos(1/X) ); break; } case 19://acot { if(X < 0) { Object.push( PI + atan(1/X) ); } else if(X > 0) { Object.push( atan(1/X) ); } else { Object.push( PI/2 ); } break; } case 20://sinh { Object.push( sinh(X) ); break; } case 21://cosh { Object.push( cosh(X) ); break; } case 22://tanh { Object.push( tanh(X) ); break; } case 23://csch { if(X == 0) { cout << endl << "Error in csch(x), x is 0 now!" << endl << endl; return WRONG; } Object.push( 1/sinh(X) ); break; } case 24://sech { Object.push( 1/cosh(X) ); break; } case 25://coth { if(X == 0) { cout << endl << "Error in coth(x), x is 0 now!" << endl << endl; return WRONG; } Object.push(1/tanh(X)); break; } case 26://asinh { Object.push( asinh(X) ); break; } case 27://acosh { if(X < 1) { cout << endl << "Error in acosh(x), x < 1 now!" << endl << endl; return WRONG; } Object.push( acosh(X) ); break; } case 28://atanh { if(X <= -1 || X >= 1) { cout << endl << "Error in atanh(x), x is out of ]-1, 1[ now!" << endl << endl; return WRONG; } Object.push( atanh(X) ); break; } case 29://acsch { if(X == 0) { cout << endl << "Error in acsch(x), x is 0 now!" << endl << endl; return WRONG; } Object.push( log( (1 + sgn(X) * sqrt(1 + X*X)) / X ) ); break; } case 30://asech { if(X <= 0 || X > 1) { cout << endl << "Error in asech(x), x is out of ]0, 1] now!" << endl << endl; return WRONG; } Object.push( log( (1 + sqrt(1 - X*X)) / X ) ); break; } case 31://acoth { if(X >= -1 || X <= 1) { cout << endl << "Error in acoth(x), x is in [-1, 1], now!" << endl << endl; return WRONG; } Object.push( 0.5 * log( (X+1)/(X-1) ) ); break; } case 32://exp { Object.push( exp(X) ); break; } case 33://log { if(X <= 0) { cout << endl << "Error in log(x), x <= 0 now!" << endl << endl; return WRONG; } Object.push( log(X) ); break; } case 34://lg { if(X <= 0) { cout << endl << "Error in lg(x), x <= 0 now!" << endl << endl; return WRONG; } Object.push( log10(X) ); break; } case 35://ln { if(X <= 0) { cout << endl << "Error in ln(x), x <= 0 now!" << endl << endl; return WRONG; } Object.push( log(X) ); break; } case 36://sqrt { if(X < 0) { cout << endl << "Error in sqrt(x), x < 0 now!" << endl << endl; return WRONG; } Object.push( sqrt(X) ); break; } case 37://abs { Object.push( fabs(X) ); break; } } } break; } } } if(Object.size()!=1) { cout << endl << "The format of the input math expresion is wrong!" << endl << endl; return WRONG; } else { if( abs( Object.top() ) <= 1E-6 ) { return 0; } else { return Object.top(); } } } #endif
#ifndef BVHVIEW_H #define BVHVIEW_H #include "BVH.h" #include "viewwidget.h" class BVHView : public ViewWidget { Q_OBJECT public: explicit BVHView(Manager *, QWidget *parent = 0); signals: public slots: protected: /// Initialise the GL scene void initializeGL(); /// Paint the GL scene void paintGL(); /// Resize the GL scene void resizeGL(int width, int height); private: BVH *m_bvh; double m_t; }; #endif // BVHVIEW_H
#pragma once #include "modes.h" #include "events/event.hpp" #include <chrono> namespace lab { enum class PlayMode { NotStarted, Playing, Paused }; class Timeline : public MinorMode { PlayMode _playMode = PlayMode::NotStarted; double _current_time = 100.0; void play(); void pause(); void rewind(); void update(std::chrono::steady_clock::time_point&); public: Timeline(); virtual ~Timeline(); virtual const char * name() const override { return "timeline"; } virtual void ui(lab::EditState& edit_state, lab::CursorManager& cursorManager, lab::FontManager& fontManager, float width, float height) override; }; extern event<void()> evt_timeline_play; extern event<void()> evt_timeline_pause; extern event<void()> evt_timeline_rewind; } // lab
/* Author: Mincheul Kang */ #ifndef OMPL_GEOMETRIC_PLANNERS_PRM_HARMONIOUS_LAZY_PRM_STAR_MULTI_ #define OMPL_GEOMETRIC_PLANNERS_PRM_HARMONIOUS_LAZY_PRM_STAR_MULTI_ #include <ompl/geometric/planners/PlannerIncludes.h> #include <ompl/datastructures/NearestNeighbors.h> #include <boost/graph/graph_traits.hpp> #include <boost/graph/adjacency_list.hpp> #include <boost/functional/hash.hpp> #include <boost/function.hpp> #include <boost/tuple/tuple.hpp> #include <utility> #include <vector> #include <map> #include <queue> #include <harmonious_sampling/HarmoniousSampler.h> namespace ompl { namespace base { // Forward declare for use in implementation OMPL_CLASS_FORWARD(OptimizationObjective); } namespace geometric { /** @anchor gHarmoniousLazyPRMstarMulti @par Short description HarmoniousLazyPRMstarMulti is a planner that uses lazy collision checking with dynamc shortest path tree. @par External documentation */ /** \brief Lazy Probabilistic RoadMap planner */ class HarmoniousLazyPRMstarMulti : public base::Planner { public: struct vertex_state_t { typedef boost::vertex_property_tag kind; }; struct vertex_flags_t { typedef boost::vertex_property_tag kind; }; struct vertex_radius_t { typedef boost::vertex_property_tag kind; }; struct vertex_witness_t { typedef boost::vertex_property_tag kind; }; struct vertex_cost_t { typedef boost::vertex_property_tag kind; }; struct vertex_children_t { typedef boost::vertex_property_tag kind; }; struct vertex_neighbors_t { typedef boost::vertex_property_tag kind; }; struct edge_flags_t { typedef boost::edge_property_tag kind; }; /** @brief The type for a vertex in the roadmap. */ typedef boost::adjacency_list_traits<boost::vecS, boost::listS, boost::undirectedS>::vertex_descriptor Vertex; /** @brief The underlying roadmap graph. @par Any BGL graph representation could be used here. Because we expect the roadmap to be sparse (m<n^2), an adjacency_list is more appropriate than an adjacency_matrix. We use listS for the vertex list because vertex descriptors are invalidated by remove operations if using vecS. @par Obviously, a ompl::base::State* vertex property is required. The incremental connected components algorithm requires vertex_predecessor_t and vertex_rank_t properties. If boost::vecS is not used for vertex storage, then there must also be a boost:vertex_index_t property manually added. @par Edges should be undirected and have a weight property. */ typedef std::pair<Vertex, double> type_neighbor; typedef boost::adjacency_list < boost::vecS, boost::listS, boost::undirectedS, // Vertex properties. boost::property < vertex_state_t, base::State *, boost::property < boost::vertex_index_t, unsigned long int, boost::property < vertex_flags_t, unsigned int, boost::property < vertex_radius_t, double, boost::property < vertex_witness_t, base::State *, boost::property < vertex_cost_t, double, boost::property < vertex_children_t, std::vector<Vertex> *, boost::property < vertex_neighbors_t, std::vector<type_neighbor>, boost::property < boost::vertex_color_t, unsigned int, boost::property < boost::vertex_predecessor_t, Vertex, boost::property < boost::vertex_rank_t, unsigned long int > > > > > > > > > > >, // Edge properties. boost::property < boost::edge_weight_t, base::Cost, boost::property < edge_flags_t, unsigned int > > > Graph; /** @brief The type for an edge in the roadmap. */ typedef boost::graph_traits<Graph>::edge_descriptor Edge; /** @brief A nearest neighbors data structure for roadmap vertices. */ typedef boost::shared_ptr< NearestNeighbors<Vertex> > RoadmapNeighbors; /** @brief A function returning the milestones that should be * attempted to connect to. */ typedef boost::function<const std::vector<Vertex>&(const Vertex)> ConnectionStrategy; /** \brief Constructor */ HarmoniousLazyPRMstarMulti(const base::SpaceInformationPtr &si, base::HarmoniousSampler &hs, const std::vector<bool> &isContinuous, bool starStrategy = false); virtual ~HarmoniousLazyPRMstarMulti(); /** \brief Set the maximum length of a motion to be added to the roadmap. */ void setRange(double distance); /** \brief Get the range the planner is using */ double getRange() const { return maxDistance_; } /** \brief Set a different nearest neighbors datastructure */ template<template<typename T> class NN> void setNearestNeighbors() { nn_.reset(new NN<Vertex>()); nnB_.reset(new NN<Vertex>()); nnM_.reset(new NN<Vertex>()); if (!userSetConnectionStrategy_) { connectionStrategy_.clear(); } if (isSetup()) { setup(); } } template <typename Container> struct container_hash { std::size_t operator()(Container const& c) const { return boost::hash_range(c.begin(), c.end()); } }; virtual void setProblemDefinition(const base::ProblemDefinitionPtr &pdef); /** \brief Set the connection strategy function that specifies the milestones that connection attempts will be make to for a given milestone. \par The behavior and performance of PRM can be changed drastically by varying the number and properties if the milestones that are connected to each other. \param pdef A function that takes a milestone as an argument and returns a collection of other milestones to which a connection attempt must be made. The default connection strategy is to connect a milestone's 10 closest neighbors. */ void setConnectionStrategy(const ConnectionStrategy &connectionStrategy) { connectionStrategy_ = connectionStrategy; userSetConnectionStrategy_ = true; } /** \brief Convenience function that sets the connection strategy to the default one with k nearest neighbors. */ void setMaxNearestNeighbors(unsigned int k); /** \brief Return the number of milestones currently in the graph */ unsigned long int milestoneCount() const { return boost::num_vertices(g_); } /** \brief Return the number of edges currently in the graph */ unsigned long int edgeCount() const { return boost::num_edges(g_); } virtual void getPlannerData(base::PlannerData &data) const; virtual void setup(); virtual void clear(); /** \brief Clear the query previously loaded from the ProblemDefinition. Subsequent calls to solve() will reuse the previously computed roadmap, but will clear the set of input states constructed by the previous call to solve(). This enables multi-query functionality for HarmoniousLazyPRMstarMulti. */ void clearQuery(); virtual base::PlannerStatus solve(const base::PlannerTerminationCondition &ptc); void Decrease(const Vertex &v); void Increase(const Vertex vs); void cancelAdoption(const Vertex &v); protected: /** \brief Flag indicating validity of an edge of a vertex */ static const unsigned int VALIDITY_UNKNOWN = 0; /** \brief Flag indicating validity of an edge of a vertex */ static const unsigned int VALIDITY_TRUE = 1; /////////////////////////////////////// // Planner progress property functions std::string getIterationCount() const { return boost::lexical_cast<std::string>(iterations_); } std::string getBestCost() const { return boost::lexical_cast<std::string>(bestCost_); } std::string getMilestoneCountString() const { return boost::lexical_cast<std::string>(milestoneCount()); } std::string getEdgeCountString() const { return boost::lexical_cast<std::string>(edgeCount()); } /** \brief Free all the memory allocated by the planner */ void freeMemory(); /** \brief Construct a milestone for a given state (\e state), store it in the nearest neighbors data structure and then connect it to the roadmap in accordance to the connection strategy. */ Vertex addMilestone(base::State *state, bool isM, bool isChecked = true); /** \brief Given two milestones from the same connected component, construct a path connecting them and set it as the solution */ ompl::base::PathPtr constructSolution(const Vertex &start, const Vertex &goal); /** \brief Compute distance between two milestones (this is simply distance between the states of the milestones) */ double distanceFunction(const base::State *a, const base::State *b) const; double distanceFunctionHarmonious(const Vertex a, const Vertex b) const; double distanceFunctionBase(const base::State *a, const base::State *b) const; double distanceFunctionJoints(const base::State *a, const base::State *b) const; bool checkMotion(base::State *s1, base::State *s2) const; unsigned int validSegmentCount_compare(const double dist, const double longestValidSegment) const; void interpolate(const base::State *from, const base::State *to, const double t, base::State *state) const; boost::tuple<double, double, double> toEulerAngle(double w, double x, double y, double z) const; boost::tuple<double, double, double, double> toQuaternion(double pitch, double roll, double yaw) const; /** \brief Given two vertices, returns a heuristic on the cost of the path connecting them. This method wraps OptimizationObjective::motionCostHeuristic */ base::Cost costHeuristic(Vertex u, Vertex v) const; // <Dancing compoenents // Let's dance! std::vector<base::State*>* optimizeMotion(const Vertex &v1, const Vertex &v2); // > /** \brief Flag indicating whether the default connection strategy is the Star strategy */ bool starStrategy_; /** \brief Function that returns the milestones to attempt connections with */ ConnectionStrategy connectionStrategy_; /** \brief Flag indicating whether the employed connection strategy was set by the user (or defaults are assumed) */ bool userSetConnectionStrategy_; /** \brief The maximum length of a motion to be added to a tree */ double maxDistance_; /** \brief Sampler user for generating random in the state space */ base::StateSamplerPtr sampler_; /** \brief Nearest neighbors data structure */ RoadmapNeighbors nn_; RoadmapNeighbors nnB_; RoadmapNeighbors nnM_; /** \brief Connectivity graph */ Graph g_; /** \brief Array of start milestones */ std::vector<Vertex> startM_; /** \brief Array of goal milestones */ std::vector<Vertex> goalM_; /** \brief Access to the internal base::state at each Vertex */ boost::property_map<Graph, boost::vertex_index_t>::type indexProperty_; /** \brief Access to the internal base::state at each Vertex */ boost::property_map<Graph, vertex_state_t>::type stateProperty_; /** \brief Access to the approximate collision-free radius at each Vertex */ boost::property_map<Graph, vertex_radius_t>::type radiusProperty_; /** \brief Access to the approximate closest obstacle space at each Vertex */ boost::property_map<Graph, vertex_witness_t>::type witnessProperty_; /** \brief Access to the cost from start configuration at each Vertex */ boost::property_map<Graph, vertex_cost_t>::type costProperty_; /** \brief Access to the children of each Vertex */ boost::property_map<Graph, vertex_children_t>::type childrenProperty_; /** \brief Access to the neighbors within a ball of radius r_rrg* of each Vertex */ boost::property_map<Graph, vertex_neighbors_t>::type neighborProperty_; /** \brief Access to the predecessor of each Vertex */ boost::property_map<Graph, boost::vertex_predecessor_t>::type predecessorProperty_; /** \brief Access to the color of each Vertex used in Increase() */ boost::property_map<Graph, boost::vertex_color_t>::type colorProperty_; /** \brief Access to the weights of each Edge */ boost::property_map<Graph, boost::edge_weight_t>::type weightProperty_; /** \brief Access the validity state of a vertex */ boost::property_map<Graph, vertex_flags_t>::type vertexValidityProperty_; /** \brief Access the validity state of an edge */ boost::property_map<Graph, edge_flags_t>::type edgeValidityProperty_; /** \brief Objective cost function for PRM graph edges */ base::OptimizationObjectivePtr opt_; base::Cost bestCost_; unsigned long int iterations_; /** \brief The number of 'Increase' invoked to avoid color initialization. */ unsigned long int increaseIterations_; double k_rrgConstant_; /** \brief A set of parameters configuratable externally. */ // Toggler bool BisectionCC_; void setBisectionCC(bool v) { BisectionCC_ = v; } // Parameter double rewireFactor_; void setRewireFactor(double v) { rewireFactor_ = v; } base::HarmoniousSampler &hs_; const std::vector<bool> &isContinuous_; }; } } #endif
// Created on: 1998-04-08 // Created by: Philippe MANGIN // Copyright (c) 1998-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _BRepOffsetAPI_MakePipeShell_HeaderFile #define _BRepOffsetAPI_MakePipeShell_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <BRepPrimAPI_MakeSweep.hxx> #include <BRepFill_PipeShell.hxx> #include <BRepFill_TypeOfContact.hxx> #include <BRepBuilderAPI_PipeError.hxx> #include <Standard_Integer.hxx> #include <BRepBuilderAPI_TransitionMode.hxx> #include <TopTools_ListOfShape.hxx> class TopoDS_Wire; class gp_Ax2; class gp_Dir; class TopoDS_Shape; class TopoDS_Vertex; class Law_Function; //! This class provides for a framework to construct a shell //! or a solid along a spine consisting in a wire. //! To produce a solid, the initial wire must be closed. //! Two approaches are used: //! - definition by section //! - by a section and a scaling law //! - by addition of successive intermediary sections //! - definition by sweep mode. //! - pseudo-Frenet //! - constant //! - binormal constant //! - normal defined by a surface support //! - normal defined by a guiding contour. //! The two global approaches can also be combined. //! You can also close the surface later in order to form a solid. //! Warning: some limitations exist //! -- Mode with auxiliary spine is incompatible with hometetic laws //! -- Mode with auxiliary spine and keep contact produce only CO surface. class BRepOffsetAPI_MakePipeShell : public BRepPrimAPI_MakeSweep { public: DEFINE_STANDARD_ALLOC //! Constructs the shell-generating framework defined by the wire Spine. //! Sets an sweep's mode //! If no mode are set, the mode use in MakePipe is used Standard_EXPORT BRepOffsetAPI_MakePipeShell(const TopoDS_Wire& Spine); //! Sets a Frenet or a CorrectedFrenet trihedron //! to perform the sweeping //! If IsFrenet is false, a corrected Frenet trihedron is used. Standard_EXPORT void SetMode (const Standard_Boolean IsFrenet = Standard_False); //! Sets a Discrete trihedron //! to perform the sweeping Standard_EXPORT void SetDiscreteMode(); //! Sets a fixed trihedron to perform the sweeping //! all sections will be parallel. Standard_EXPORT void SetMode (const gp_Ax2& Axe); //! Sets a fixed BiNormal direction to perform the -- //! sweeping. Angular relations between the //! section(s) and <BiNormal> will be constant Standard_EXPORT void SetMode (const gp_Dir& BiNormal); //! Sets support to the spine to define the BiNormal of //! the trihedron, like the normal to the surfaces. //! Warning: To be effective, Each edge of the <spine> must //! have a representation on one face of<SpineSupport> Standard_EXPORT Standard_Boolean SetMode (const TopoDS_Shape& SpineSupport); //! Sets an auxiliary spine to define the Normal //! For each Point of the Spine P, an Point Q is evalued //! on <AuxiliarySpine> //! If <CurvilinearEquivalence> //! Q split <AuxiliarySpine> with the same length ratio //! than P split <Spline>. //! Else the plan define by P and the tangent to the <Spine> //! intersect <AuxiliarySpine> in Q. //! If <KeepContact> equals BRepFill_NoContact: The Normal is defined //! by the vector PQ. //! If <KeepContact> equals BRepFill_Contact: The Normal is defined to //! achieve that the sweeped section is in contact to the //! auxiliarySpine. The width of section is constant all along the path. //! In other words, the auxiliary spine lies on the swept surface, //! but not necessarily is a boundary of this surface. However, //! the auxiliary spine has to be close enough to the main spine //! to provide intersection with any section all along the path. //! If <KeepContact> equals BRepFill_ContactOnBorder: The auxiliary spine //! becomes a boundary of the swept surface and the width of section varies //! along the path. //! Give section to sweep. //! Possibilities are : //! - Give one or sevral section //! - Give one profile and an homotetic law. //! - Automatic compute of correspondence between spine, and section //! on the sweeped shape //! - correspondence between spine, and section on the sweeped shape //! defined by a vertex of the spine Standard_EXPORT void SetMode (const TopoDS_Wire& AuxiliarySpine, const Standard_Boolean CurvilinearEquivalence, const BRepFill_TypeOfContact KeepContact = BRepFill_NoContact); //! Adds the section Profile to this framework. First and last //! sections may be punctual, so the shape Profile may be //! both wire and vertex. Correspondent point on spine is //! computed automatically. //! If WithContact is true, the section is translated to be in //! contact with the spine. //! If WithCorrection is true, the section is rotated to be //! orthogonal to the spine?s tangent in the correspondent //! point. This option has no sense if the section is punctual //! (Profile is of type TopoDS_Vertex). Standard_EXPORT void Add (const TopoDS_Shape& Profile, const Standard_Boolean WithContact = Standard_False, const Standard_Boolean WithCorrection = Standard_False); //! Adds the section Profile to this framework. //! Correspondent point on the spine is given by Location. //! Warning: //! To be effective, it is not recommended to combine methods Add and SetLaw. Standard_EXPORT void Add (const TopoDS_Shape& Profile, const TopoDS_Vertex& Location, const Standard_Boolean WithContact = Standard_False, const Standard_Boolean WithCorrection = Standard_False); //! Sets the evolution law defined by the wire Profile with //! its position (Location, WithContact, WithCorrection //! are the same options as in methods Add) and a //! homotetic law defined by the function L. //! Warning: //! To be effective, it is not recommended to combine methods Add and SetLaw. Standard_EXPORT void SetLaw (const TopoDS_Shape& Profile, const Handle(Law_Function)& L, const Standard_Boolean WithContact = Standard_False, const Standard_Boolean WithCorrection = Standard_False); //! Sets the evolution law defined by the wire Profile with //! its position (Location, WithContact, WithCorrection //! are the same options as in methods Add) and a //! homotetic law defined by the function L. //! Warning: //! To be effective, it is not recommended to combine methods Add and SetLaw. Standard_EXPORT void SetLaw (const TopoDS_Shape& Profile, const Handle(Law_Function)& L, const TopoDS_Vertex& Location, const Standard_Boolean WithContact = Standard_False, const Standard_Boolean WithCorrection = Standard_False); //! Removes the section Profile from this framework. Standard_EXPORT void Delete (const TopoDS_Shape& Profile); //! Returns true if this tool object is ready to build the //! shape, i.e. has a definition for the wire section Profile. Standard_EXPORT Standard_Boolean IsReady() const; //! Get a status, when Simulate or Build failed. It can be //! BRepBuilderAPI_PipeDone, //! BRepBuilderAPI_PipeNotDone, //! BRepBuilderAPI_PlaneNotIntersectGuide, //! BRepBuilderAPI_ImpossibleContact. Standard_EXPORT BRepBuilderAPI_PipeError GetStatus() const; //! Sets the following tolerance values //! - 3D tolerance Tol3d //! - boundary tolerance BoundTol //! - angular tolerance TolAngular. Standard_EXPORT void SetTolerance (const Standard_Real Tol3d = 1.0e-4, const Standard_Real BoundTol = 1.0e-4, const Standard_Real TolAngular = 1.0e-2); //! Define the maximum V degree of resulting surface Standard_EXPORT void SetMaxDegree (const Standard_Integer NewMaxDegree); //! Define the maximum number of spans in V-direction //! on resulting surface Standard_EXPORT void SetMaxSegments (const Standard_Integer NewMaxSegments); //! Set the flag that indicates attempt to approximate //! a C1-continuous surface if a swept surface proved //! to be C0. Standard_EXPORT void SetForceApproxC1 (const Standard_Boolean ForceApproxC1); //! Sets the transition mode to manage discontinuities on //! the swept shape caused by fractures on the spine. The //! transition mode can be BRepBuilderAPI_Transformed //! (default value), BRepBuilderAPI_RightCorner, //! BRepBuilderAPI_RoundCorner: //! - RepBuilderAPI_Transformed: //! discontinuities are treated by //! modification of the sweeping mode. The //! pipe is "transformed" at the fractures of //! the spine. This mode assumes building a //! self-intersected shell. //! - BRepBuilderAPI_RightCorner: //! discontinuities are treated like right //! corner. Two pieces of the pipe //! corresponding to two adjacent //! segments of the spine are extended //! and intersected at a fracture of the spine. //! - BRepBuilderAPI_RoundCorner: //! discontinuities are treated like round //! corner. The corner is treated as rotation //! of the profile around an axis which //! passes through the point of the spine's //! fracture. This axis is based on cross //! product of directions tangent to the //! adjacent segments of the spine at their common point. //! Warnings //! The mode BRepBuilderAPI_RightCorner provides a //! valid result if intersection of two pieces of the pipe //! (corresponding to two adjacent segments of the spine) //! in the neighborhood of the spine?s fracture is //! connected and planar. This condition can be violated if //! the spine is non-linear in some neighborhood of the //! fracture or if the profile was set with a scaling law. //! The last mode, BRepBuilderAPI_RoundCorner, will //! assuredly provide a good result only if a profile was set //! with option WithCorrection = True, i.e. it is strictly //! orthogonal to the spine. Standard_EXPORT void SetTransitionMode (const BRepBuilderAPI_TransitionMode Mode = BRepBuilderAPI_Transformed); //! Simulates the resulting shape by calculating its //! cross-sections. The spine is divided by this //! cross-sections into (NumberOfSection - 1) equal //! parts, the number of cross-sections is //! NumberOfSection. The cross-sections are wires and //! they are returned in the list Result. //! This gives a rapid preview of the resulting shape, //! which will be obtained using the settings you have provided. //! Raises NotDone if <me> it is not Ready Standard_EXPORT void Simulate (const Standard_Integer NumberOfSection, TopTools_ListOfShape& Result); //! Builds the resulting shape (redefined from MakeShape). Standard_EXPORT virtual void Build(const Message_ProgressRange& theRange = Message_ProgressRange()) Standard_OVERRIDE; //! Transforms the sweeping Shell in Solid. //! If a propfile is not closed returns False Standard_EXPORT Standard_Boolean MakeSolid(); //! Returns the TopoDS Shape of the bottom of the sweep. Standard_EXPORT virtual TopoDS_Shape FirstShape() Standard_OVERRIDE; //! Returns the TopoDS Shape of the top of the sweep. Standard_EXPORT virtual TopoDS_Shape LastShape() Standard_OVERRIDE; //! Returns a list of new shapes generated from the shape //! S by the shell-generating algorithm. //! This function is redefined from BRepOffsetAPI_MakeShape::Generated. //! S can be an edge or a vertex of a given Profile (see methods Add). Standard_EXPORT virtual const TopTools_ListOfShape& Generated (const TopoDS_Shape& S) Standard_OVERRIDE; Standard_EXPORT Standard_Real ErrorOnSurface() const; //! Returns the list of original profiles void Profiles(TopTools_ListOfShape& theProfiles) { myPipe->Profiles(theProfiles); } //! Returns the spine const TopoDS_Wire& Spine() { return myPipe->Spine(); } protected: private: Handle(BRepFill_PipeShell) myPipe; }; #endif // _BRepOffsetAPI_MakePipeShell_HeaderFile
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style: "stroustrup" -*- * * Copyright (C) 1995-2010 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ /** * Wrapper to invoke the parser from the command line */ #include "core/pch.h" #include <string.h> #include <stdio.h> #include <wchar.h> #include "modules/logdoc/logdoc.h" #include "modules/logdoc/html5parser.h" #include "modules/logdoc/html5namemapper.h" #include "modules/logdoc/src/html5/h5node.h" #include "modules/logdoc/src/html5/html5entities.h" #include "modules/util/opstring.h" #include "modules/util/adt/bytebuffer.h" #include "modules/util/simset.h" #include "modules/debug/debug.h" Opera* g_opera = NULL; HTML5NameMapper* g_html5_name_mapper = NULL; #define INPUT_BUFFER_SIZE 4048 static int tokenize_only = FALSE; static Markup::Type context_elm_type = Markup::HTE_DOC_ROOT; static char* context_elm_name = NULL; extern OP_STATUS read_stdin(ByteBuffer &bbuf); #include <signal.h> extern "C" void Debug_OpAssert(const char* expression, const char* file, int line) { dbg_printf("ASSERT FAILED: OP_ASSERT(%s) %s:%d\n", expression, file, line); #if defined(UNIX) raise(SIGABRT); #else assert(0); #endif } static void DumpNode(const uni_char *spaces, H5Node *node) { switch (node->GetType()) { case H5Node::TEXT: dbg_printf("|%S\"%S\"\n", spaces, static_cast<H5Text*>(node)->Content()); break; case H5Node::DOCTYPE: { H5Doctype *doctype = static_cast<H5Doctype*>(node); dbg_printf("|%S<!DOCTYPE %S", spaces, doctype->GetName()); if (doctype->GetSystemIdentifier() || doctype->GetPublicIdentifier()) { if (doctype->GetPublicIdentifier()) dbg_printf(" \"%S\"", doctype->GetPublicIdentifier()); else dbg_printf(" \"\""); if (doctype->GetSystemIdentifier()) dbg_printf(" \"%S\"", doctype->GetSystemIdentifier()); else dbg_printf(" \"\""); } dbg_printf(">\n"); } break; case H5Node::COMMENT: dbg_printf("|%S<!-- %S -->\n", spaces, static_cast<H5Comment*>(node)->GetData()); break; case H5Node::ELEMENT: { H5Element *elm = static_cast<H5Element*>(node); const uni_char *prefix = UNI_L(""); if (elm->GetNs() == Markup::MATH) prefix = UNI_L("math "); else if (elm->GetNs() == Markup::SVG) prefix = UNI_L("svg "); dbg_printf("|%S<%S%S>\n", spaces, prefix, elm->GetName()); elm->SortAttributes(); for (unsigned i = 0; i < elm->GetAttributeCount(); i++) { HTML5AttrCopy *attr = elm->GetAttributeByIndex(i); const uni_char *attr_prefix = UNI_L(""); if (attr->GetNs() == Markup::XLINK) attr_prefix = UNI_L("xlink "); else if (attr->GetNs() == Markup::XML) attr_prefix = UNI_L("xml "); else if (attr->GetNs() == Markup::XMLNS) attr_prefix = UNI_L("xmlns "); dbg_printf("|%S %S%S=\"%S\"\n", spaces, attr_prefix, attr->GetName(), attr->GetValue()); } } break; } } void write_parser_results(HTML5Parser* parser, H5Node* root, const uni_char* buffer) { dbg_printf("#errors\n"); unsigned num_errors = parser->GetNumberOfErrors(); for (unsigned i = 0; i < num_errors; i++) { unsigned line; unsigned pos; HTML5Parser::ErrorCode code = parser->GetError(i, line, pos); dbg_printf("%u,%u: %s\n", line, pos, HTML5Parser::GetErrorString(code)); } if (context_elm_type == Markup::HTE_DOC_ROOT) dbg_printf("#document\n"); else dbg_printf("#document-fragment\n%s\n", context_elm_name); uni_char *spaces = OP_NEWA(uni_char, 256); H5Node *iter = root->FirstChild(); while (iter) { uni_char *current_space = spaces; H5Node *parent = iter->Parent(); while (parent && current_space < spaces + 254) { *current_space++ = L' '; *current_space++ = L' '; parent = parent->Parent(); } *current_space = 0; DumpNode(spaces, iter); iter = iter->Next(); } OP_DELETEA(spaces); } void parse_command_line(int argc, char **argv) { char tokenizer_flag[] = "-t"; for (; argc; argc--, argv++) { if (op_strncmp("-c=", *argv, 3) == 0) { context_elm_name = op_strchr(*argv, '=') + 1; OpString elm_string; elm_string.Set(context_elm_name); context_elm_type = g_html5_name_mapper->GetTypeFromName(elm_string.CStr(), FALSE, Markup::HTML); } else if (op_strcmp(tokenizer_flag, *argv) == 0) tokenize_only = TRUE; } } int main(int argc, char **argv) { ByteBuffer bbuffer; char memory[sizeof(Opera)]; /* ARRAY OK 2011-09-08 danielsp */ op_memset(memory, 0, sizeof(Opera)); g_opera = (Opera*)&memory; g_opera->InitL(); g_html5_name_mapper = OP_NEW(HTML5NameMapper, ()); g_html5_name_mapper->InitL(); HTML5EntityStates::InitL(); parse_command_line(argc, argv); LogicalDocument *logdoc = OP_NEW(LogicalDocument, ()); if (!logdoc) return 1; if (tokenize_only) logdoc->SetTokenizeOnly(); if (OpStatus::IsSuccess(read_stdin(bbuffer))) { uni_char *buffer = reinterpret_cast<uni_char*>(bbuffer.Copy(FALSE)); int buffer_length = (bbuffer.Length() / sizeof(uni_char)) - 1; int remaining_length = buffer_length; int chunk_size = context_elm_type == Markup::HTE_DOC_ROOT ? 1024 : buffer_length; // Parsing the buffer may replace its content, so write what we received before // parsing it if (!tokenize_only) { if (buffer) { uni_char *buffer_copy = OP_NEWA(uni_char, buffer_length + 1); op_memcpy(buffer_copy, buffer, (buffer_length + 1) * sizeof(uni_char)); // Replace NULs with 0xDFFF which are handled the same later, as tempbuffer doesn't handle NULs for (uni_char* c = buffer_copy; c < buffer_copy + buffer_length; c++) if (*c == 0) *c = 0xDFFF; dbg_printf("#data\n%S\n", buffer_copy); } else dbg_printf("#data\n\n"); } OP_PARSING_STATUS pstatus = OpStatus::OK; do { if (pstatus == ParsingStatus::EXECUTE_SCRIPT) { #if 0 static int i = 0; // dummy document.write content: const uni_char* script_buffer = i++ <= 1 ? UNI_L("<script>a</script>1<script>b</script>") : UNI_L("<blink>OMG!!1"); // const uni_char* script_buffer = i++ <= 1 ? UNI_L("<script>a</script>1") : UNI_L("<blink>OMG!!1</blink>2"); pstatus = logdoc->AddParsingData(script_buffer, uni_strlen(script_buffer)); if (pstatus == OpStatus::OK) #endif pstatus = logdoc->ContinueParsing(); } else pstatus = logdoc->Parse(context_elm_type, buffer + (buffer_length - remaining_length), MIN(remaining_length, chunk_size), remaining_length <= chunk_size); if (pstatus == ParsingStatus::NEED_MORE_DATA) remaining_length -= chunk_size; } while (remaining_length > 0 && (pstatus == ParsingStatus::NEED_MORE_DATA || pstatus == ParsingStatus::EXECUTE_SCRIPT)); if (!tokenize_only) write_parser_results(logdoc->GetParser(), logdoc->GetRoot(), buffer); } OP_DELETE(logdoc); HTML5EntityStates::Destroy(); OP_DELETE(g_html5_name_mapper); g_opera->Destroy(); return 0; }
#ifndef SDB_HPP #define SDB_HPP void sdb(); #endif
// https://oj.leetcode.com/problems/minimum-window-substring/ class Solution { public: string minWindow(string S, string T) { int ssize = S.size(), tsize = T.size(); if (ssize < tsize || ssize == 0) { return ""; } int wbegin = 0; int win_len = INT_MAX; int win_begin = -1; int expect[256], actual[256]; int nr_covered = 0; memset(expect, 0, 256 * sizeof(int)); memset(actual, 0, 256 * sizeof(int)); for (int i = 0; i < tsize; i++) { expect[T[i]]++; } for (int wend = 0; wend < ssize; wend++) { if (expect[S[wend]] > 0) { actual[S[wend]]++; if (actual[S[wend]] <= expect[S[wend]]) { nr_covered++; } } if (nr_covered == tsize) { // move behind pointer forward while (expect[S[wbegin]] == 0 || expect[S[wbegin]] < actual[S[wbegin]]) { actual[S[wbegin]]--; wbegin++; } if (win_len > wend - wbegin + 1) { win_len = wend - wbegin + 1; win_begin = wbegin; } } } return (win_len == INT_MAX) ? "" : S.substr(win_begin, win_len); } };
/* ID: stevenh6 TASK: comehome LANG: C++ */ #include <fstream> #include <string> #include <climits> #include <iostream> #include <map> #include <algorithm> using namespace std; ofstream fout("comehome.out"); ifstream fin("comehome.in"); int main() { int grid[60][60]; int shortpath = INT_MAX / 4; map<int, char> itc; map<char, int> cti; int p; fin >> p; for (int i = 0; i < 52; i++) { char letter; if (i < 26) { letter = char(i + 'a'); } else { letter = char(i - 26 + 'A'); } cti[letter] = i; itc[i] = letter; } for (int i = 0; i < 52; i++) { for (int j = 0; j < 52; j++) { grid[i][j] = INT_MAX / 4; } } for (int i = 0; i < p; ++i) { char a, b; int distance; fin >> a >> b >> distance; if (grid[cti[a]][cti[b]] > distance) { grid[cti[a]][cti[b]] = distance; grid[cti[b]][cti[a]] = distance; } } for (int i = 0; i < 52; ++i) { grid[i][i] = 0; } for (int i = 0; i < 52; i++) { for (int j = 0; j < 52; j++) { for (int k = 0; k < 52; k++) { grid[j][k] = min(grid[j][k], grid[j][i] + grid[k][i]); } } } int cletter = INT_MAX / 4; for (int i = 26; i < 51; i++) { if (grid[i][51] < shortpath) { cletter = i; shortpath = grid[i][51]; } } fout << itc[cletter] << " " << shortpath << endl; return 0; }
#include "FusionEKF.h" #include <iostream> #include "Eigen/Dense" #include "tools.h" //#include "cmath"
/* * ===================================================================================== * * Filename: dup_elements.cpp * * Description: Remove duplicates from linked list using hash table * * Version: 1.0 * Created: 11/06/2013 11:28:48 * Revision: none * Compiler: g++ * * Author: Ankit Goyal * Organization: * * ===================================================================================== */ #include<iostream> #include<unordered_map> #include "string" using namespace std; typedef std::unordered_map< int, bool > hashmap; struct list{ int data; struct list *next; public: list(){ next = NULL; } }; void findDup(struct list *head); int main(void){ struct list head, node1, node2, node3, node4, node5, *temp; head.data = 1; node1.data = 3; node2.data = 2; node3.data = 5; node4.data = 3; node5.data = 1; head.next = &node1; node1.next = &node2; node2.next = &node3; node3.next = &node4; node4.next = &node5; node5.next = NULL; std::cout << "found dups" << std::endl; findDup(&head); temp = &head; while(temp){ std::cout << temp -> data << std::endl; temp = temp -> next; } return 0; } void findDup(struct list *head) { hashmap elements; struct list *temp; temp = head; std::cout << "enering" << std::endl; while(temp){ std::cout << "ran" << std::endl; if(elements.find(temp->data) == elements.end()){ elements[temp-> data] = true ; head = temp; temp = temp -> next; }else{ std::cout << "removing duplicate " << temp->data << std::endl; head->next = temp -> next; temp = head -> next; } } }
// // Created by Yujing Shen on 29/05/2017. // #include "../../include/nodes/VarNode.h" namespace sjtu{ VarNode::VarNode(Session *sess, const Shape &shape): SessionNode(sess, shape) { } VarNode::~VarNode() { } Node VarNode::forward() { return this; } Node VarNode::backward() { return this; } Node VarNode::optimize() { if(_opt != NULL) _opt->run(this); return this; } }
// #include "TcpServer.h" // #include "EventLoop.h" // void onConnection(TcpConnPtr conn) { // } int main() { return 0; }
#pragma once #include <iberbar\Gui\Widgets\Button.h> namespace iberbar { namespace Gui { class __iberbarGuiApi__ CCheckBox : public CButton { public: enum class UCheckState { CheckedFalse, CheckedTrue, CheckedIndeterminate, }; public: CCheckBox( void ); protected: CCheckBox( const CCheckBox& checkbox ); public: virtual CCheckBox* Clone() const override; virtual const char* GetWidgetType() override { return "CheckBox"; } virtual UHandleMessageResult HandleMouse( const UMouseEventData* EventData ) override; virtual UHandleMessageResult HandleKeyboard( const UKeyboardEventData* EventData ) override; virtual void Update( float nElapsedTime ) override; public: void SetRenderElementFalse( const char* strElementId ); void SetRenderElementTrue( const char* strElementId ); void SetRenderElementIndeterminate( const char* strElementId ); void SetChecked( UCheckState nState ) { SetCheckedInternal( nState, false ); } UCheckState GetChecked() const { return m_nCheckState; } protected: virtual void SetCheckedInternal( UCheckState nState, bool bInternal ); protected: UCheckState m_nCheckState; CRenderElement* m_pRenderElementCheckFalse; CRenderElement* m_pRenderElementCheckTrue; CRenderElement* m_pRenderElementCheckIndeterminate; }; IBERBAR_UNKNOWN_PTR_DECLARE( CCheckBox ); } }
#include "Wall.h" #include "cocostudio/CocoStudio.h" #include "GameManager.h" using namespace cocos2d; Wall* Wall::create() { Wall* myNode = new Wall(); if (myNode->init()) { myNode->autorelease(); return myNode; } else { CC_SAFE_DELETE(myNode); return nullptr; } return myNode; } bool Wall::init() { if (!Node::init()) { return false; } //Load this object in from cocos studio. auto rootNode = CSLoader::createNode("res/Wall.csb"); addChild(rootNode); auto winSize = Director::getInstance()->getVisibleSize(); this->setPosition(Vec2(0.0f, winSize.height*0.8)); this->scheduleUpdate(); wall = (Sprite*)rootNode->getChildByName("Wall"); startXPosition = 1190.0f; startYPosition = wall->getPositionY(); wall->setPosition(startXPosition, startYPosition); currentSpeed = 514.8f; return true; } Wall::Wall() { } Wall::~Wall() { } void Wall::update(float deltaTime) { if (GameManager::sharedGameManager()->isGameLive) { //Get the window size. auto winSize = Director::getInstance()->getVisibleSize(); //Move the pipes to the left. Vec2 currentWallPos = wall->getPosition(); wall->setPosition(currentWallPos.x - currentSpeed*deltaTime, currentWallPos.y); //Did the x position (incorporating the sprite width) go off screen. if (currentWallPos.x < -wall->getBoundingBox().size.width*0.5f) { //Set the new positionings. wall->setPosition(startXPosition, startYPosition); } } } bool Wall::hasCollidedWithAWall(Rect collisionBoxToCheck) { Rect modifiedWall; modifiedWall.size = wall->getBoundingBox().size; modifiedWall.origin = convertToWorldSpaceAR(wall->getBoundingBox().origin); if (modifiedWall.intersectsRect(collisionBoxToCheck)) { return true; } return false; } void Wall::reset() { wall->setPosition(startXPosition, startYPosition); }
#include <iostream> /* Exercise 2.40 - write your own version of the Sales_data class (struct)*/ struct Sales_data { std::string bookId; unsigned unitsSold; double revenue; }; int main() { /* let's see if this works */ Sales_data book; Sales_data book2; book.bookId = "some id"; book.unitsSold = 0; book.revenue = 0; book.unitsSold++; book.revenue += 12.99; std::cout << "Book id " << book.bookId << " " << "units sold " << book.unitsSold << " " << "revenue " << book.revenue << std::endl; book2.bookId = "another book"; book2.unitsSold = 0; book2.revenue = 0; book2.unitsSold++; book2.revenue += 14.99; std::cout << "Book id " << book2.bookId << " " << "units sold " << book2.unitsSold << " " << "revenue " << book2.revenue << std::endl; }
/* * @lc app=leetcode.cn id=27 lang=cpp * * [27] 移除元素 */ // @lc code=start #include<iostream> #include<vector> #include<algorithm> using namespace std; class Solution { public: int removeElement(vector<int>& nums, int val) { int left=0; int right=nums.size()-1; while(left<=right) { if(nums[left]==val){ if(nums[right]!=val){ swap(nums[left],nums[right--]); }else{ right--; continue; } } left++; } return right+1; } }; // @lc code=end
// Created on: 2003-05-06 // Created by: Galina KULIKOVA // Copyright (c) 2003-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Interface_MapAsciiStringHasher_HeaderFile #define _Interface_MapAsciiStringHasher_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <Standard_Boolean.hxx> class TCollection_AsciiString; class Interface_MapAsciiStringHasher { public: DEFINE_STANDARD_ALLOC //! Computes a hash code for the given ASCII string, in the range [1, theUpperBound] //! @param theAsciiString the ASCII string which hash code is to be computed //! @param theUpperBound the upper bound of the range a computing hash code must be within //! @return a computed hash code, in the range [1, theUpperBound] Standard_EXPORT static Standard_Integer HashCode (const TCollection_AsciiString& theAsciiString, Standard_Integer theUpperBound); Standard_EXPORT static Standard_Boolean IsEqual (const TCollection_AsciiString& K1, const TCollection_AsciiString& K2); protected: private: }; #endif // _Interface_MapAsciiStringHasher_HeaderFile
#ifndef FREQAN_HPP #define FREQAN_HPP #include <string> #include "cipher.hpp" static const int C = 26; static const float english[C] = { .0781, .0128, .0293, .0411, .1305, .0288, .0139, .0565, .0677, .0023, .0042, .036, .0262, .0728, .0821, .0215, .0014, .0664, .0646, .0902, .0277, .01, .0149, .003, .0151, .0009 }; class FrequencyAnalyzer { public: void readBuffer(const std::string&); float indexOfCoincidence() const; float englishCorrelation() const; void showStats() const; void showCounts() const; void cipherReport(const Cipher&); private: int n; // no of alphabetic chars in text_buffer std::string text_buffer; int count[C]; float frequency[C]; void compute_frequencies(); float index_of_coincidence() const; float english_correlation() const; }; #endif
/********************************************************************** *Project : EngineTask * *Author : Jorge Cásedas * *Starting date : 24/06/2020 * *Ending date : 03/07/2020 * *Purpose : Creating a 3D engine that can be used later on for developing a playable demo, with the engine as static library * **********************************************************************/ #include "InputTask.hpp" #include <Keyboard.hpp> #include <MessageBus.hpp> #include <Message.hpp> #include <SDL.h> namespace engine { InputTask::InputTask(MessageBus* bus) { messageBus = bus; } void InputTask::Update() { const Uint8* state = SDL_GetKeyboardState(NULL); if (state[SDL_SCANCODE_A]) { messageBus->AddMessage(new Message("a")); } if (state[SDL_SCANCODE_D]) { messageBus->AddMessage(new Message("d")); } if (state[SDL_SCANCODE_W]) { messageBus->AddMessage(new Message("w")); } if (state[SDL_SCANCODE_S]) { messageBus->AddMessage(new Message("s")); } /* SDL_Event sdlEvent; if (SDL_PollEvent(&sdlEvent) > 0) { if (sdlEvent.type == SDL_EventType::) { if (keyboard->translate_sdl_key_code(sdlEvent.key.keysym.sym) == Keyboard::Key_Code::KEY_A) messageBus->AddMessage(new Message("a")); if (keyboard->translate_sdl_key_code(sdlEvent.key.keysym.sym) == Keyboard::Key_Code::KEY_D) messageBus->AddMessage(new Message("d")); } }*/ } }
// KC NOIRE - RACHEL J. MORRIS, 2012 - WWW.MOOSADER.COM - GNU GPL V3 #include "State/StateManager.h" #include "IOUtils/GameIO.h" #include <stdio.h> #include <stdlib.h> #include "IOUtils/Utils.h" int GIO::m_TypeSpeedMs = 0; std::ofstream GIO::m_OutStream; std::ofstream GIO::m_DebugStream; int main() { GIO::Init(); StateManager mgrStates; mgrStates.MainLoop(); GIO::Close(); // Annoy the user! if ( Utils::OperatingSystem() == "linux" ) { ::system( "x-www-browser reminder.html" ); } else if ( Utils::OperatingSystem() == "windows" ) { ::system( "reminder.html" ); } else if ( Utils::OperatingSystem() == "osx" ) { // ?? } return 0; };
#include "messagebox.h" MessageBox::MessageBox(QString message) { //label_dialog = new QLabel(message, this); // label_dialog->setGeometry(20, 20, 20, 20); setText(message); exec(); } MessageBox::~MessageBox() { }
#include <algorithm> #include <cassert> #include <functional> #include <numeric> #include <unordered_map> #include <utility> #include <vector> #include "block_system.h" #include "dbg.h" #include "dump.h" #include "orbits.h" #include "perm.h" #include "perm_group.h" #include "perm_set.h" namespace cgtl { bool BlockSystem::trivial() const { return size() == 1u || (*this)[0].size() == 1u; } BlockSystem::Block const& BlockSystem::operator[](unsigned i) const { return _blocks[i]; } BlockSystem::const_iterator BlockSystem::begin() const { return _blocks.begin(); } BlockSystem::const_iterator BlockSystem::end() const { return _blocks.end(); } unsigned BlockSystem::block_index(unsigned x) const { return _block_indices[x - 1u]; } PermSet BlockSystem::block_permuter(PermSet const &generators_) const { PermSet generators(generators_); std::vector<unsigned> perm(size()); for (auto i = 0u; i < generators.size(); ++i) { auto gen(generators[i]); for (unsigned j = 0u; j < size(); ++j) perm[j] = block_index(gen[(*this)[j][0]]) + 1u; generators[i] = Perm(perm); } return generators; } PermSet BlockSystem::block_stabilizers(PermSet const &generators, Block const &block) { // initialize block stabilizer generating set as generators of subgroup // stabilizing a block element (we arbitrarily choose the first one) PermGroup pg(generators.degree(), generators); pg.bsgs().base_change({block[0]}); auto stabilizer_generators(pg.bsgs().stabilizers(0)); auto stabilizer_orbit(Orbit::generate(block[0], stabilizer_generators)); // extend block stabilizer generating set std::unordered_set<unsigned> block_elements(block.begin(), block.end()); for (unsigned beta : pg.bsgs().orbit(0)) { if (block_elements.find(beta) == block_elements.end()) continue; if (stabilizer_orbit.contains(beta)) continue; Perm transv(pg.bsgs().transversal(0, beta)); stabilizer_generators.insert(transv); stabilizer_orbit.update(stabilizer_generators, transv); } return stabilizer_generators; } BlockSystem BlockSystem::minimal(PermSet const &generators, std::vector<unsigned> const &initial_block) { assert(initial_block.size() >= 2u); std::vector<unsigned> classpath(generators.degree()); std::vector<unsigned> cardinalities(generators.degree()); std::vector<unsigned> queue; DBG(DEBUG) << "=== Finding minimal block system for:"; DBG(DEBUG) << generators; DBG(DEBUG) << "Initial block: " << initial_block; for (auto i = 0u; i < generators.degree(); ++i) { classpath[i] = i; cardinalities[i] = 1u; } for (auto i = 0u; i < initial_block.size() - 1u; ++i) { unsigned tmp = initial_block[i + 1u]; classpath[tmp] = initial_block[0]; queue.push_back(tmp); } cardinalities[initial_block[0]] = static_cast<unsigned>(initial_block.size()); DBG(TRACE) << "Initial classpath: " << classpath; DBG(TRACE) << "Initial cardinalities: " << cardinalities; DBG(TRACE) << "Initial queue: " << queue; unsigned i = 0u; unsigned l = initial_block.size() - 2u; while (i <= l) { unsigned gamma = queue[i++]; DBG(TRACE) << "== Gamma: " << gamma; for (Perm const &gen : generators) { DBG(TRACE) << "= Gen: " << gen; unsigned c1 = gen[gamma + 1u] - 1u; unsigned c2 = gen[minimal_find_rep(gamma, classpath) + 1u] - 1u; DBG(TRACE) << "Considering classes " << c1 << " and " << c2; if (minimal_merge_classes(c1, c2, classpath, cardinalities, queue)) ++l; } } for (auto i = 0u; i < generators.degree(); ++i) minimal_find_rep(i, classpath); minimal_compress_classpath(classpath); DBG(TRACE) << "Final classpath is: " << classpath; BlockSystem res(classpath); DBG(TRACE) << "==> Resulting minimal block system: " << res; return res; } std::vector<BlockSystem> BlockSystem::non_trivial(PermGroup const &pg, bool assume_transitivity) { assert((!assume_transitivity || pg.is_transitive()) && "transitivity assumption correct"); DBG(DEBUG) << "=== Finding all non-trivial block systems for:"; DBG(DEBUG) << pg; bool transitive; if (assume_transitivity) { transitive = true; DBG(DEBUG) << "Assuming transitivity"; } else { transitive = pg.is_transitive(); DBG(DEBUG) << "Group " << (transitive ? "is" : "is not") << " transitive"; } return transitive ? non_trivial_transitive(pg) : non_trivial_non_transitive(pg); } BlockSystem::BlockSystem(BlockIndices const &block_indices) : _degree(block_indices.size()), _block_indices(block_indices) { for (auto i = 1u; i <= degree(); ++i) { unsigned j = block_index(i); if (j + 1u > size()) { for (auto k = j + 1u - size(); k > 0u; --k) _blocks.emplace_back(); } _blocks[j].push_back(i); } assert_blocks(); assert_block_indices(); } void BlockSystem::assert_blocks() const { #ifndef NDEBUG assert(size() > 0u && "number of blocks is positive"); for (auto const &block : *this) { for (unsigned x : block) assert(x > 0u && "blocks have valid elements"); } for (auto const &block : *this) assert(std::is_sorted(block.begin(), block.end()) && "blocks are sorted"); for (auto i = 1u; i < size(); ++i) assert((*this)[i].size() == (*this)[0].size() && "blocks have same size"); std::unordered_set<unsigned> block_union; for (auto const &block : *this) block_union.insert(block.begin(), block.end()); assert(block_union.size() == degree() && "blocks partition domain"); #endif } void BlockSystem::assert_block_indices() const { assert(_block_indices.size() == degree()); for (unsigned x = 1u; x < degree(); ++x) { unsigned i = block_index(x); assert(i < size()); auto block((*this)[i]); assert(std::find(block.begin(), block.end(), x) != block.end()); } } bool BlockSystem::is_block(PermSet const &generators, Block const &block) { auto maps_to_other_block = [&](Perm const &perm, unsigned x) { return std::find(block.begin(), block.end(), perm[x]) == block.end(); }; for (Perm const &gen : generators) { bool should_map_to_other_block = maps_to_other_block(gen, block[0]); for (auto i = 1u; i < block.size(); ++i) { if (maps_to_other_block(gen, block[i]) != should_map_to_other_block) return false; } } return true; } BlockSystem BlockSystem::from_block(PermSet const &generators, Block const &block) { assert(is_block(generators, block)); std::vector<Block> blocks{block}; std::vector<int> block_indices(generators.degree(), -1); for (unsigned x : block) block_indices[x - 1u] = 0; unsigned current_block_idx = 0u; unsigned processed = block.size(); while (current_block_idx < blocks.size()) { auto current_block(blocks[current_block_idx]); for (Perm const &gen : generators) { if (block_indices[gen[current_block[0]] - 1u] != -1) continue; blocks.push_back(current_block.permuted(gen)); for (unsigned x : current_block) block_indices[gen[x] - 1u] = blocks.size(); if ((processed += block.size()) == generators.degree()) return BlockSystem(blocks.begin(), blocks.end()); } ++current_block_idx; } throw std::logic_error("unreachable"); } unsigned BlockSystem::minimal_find_rep(unsigned k, std::vector<unsigned> &classpath) { // find class unsigned res = k; unsigned next = classpath[res]; while (next != res) { res = next; next = classpath[res]; } // compress path unsigned current = k; next = classpath[k]; while (next != current) { classpath[current] = res; current = next; next = classpath[current]; } return res; } bool BlockSystem::minimal_merge_classes(unsigned k1, unsigned k2, std::vector<unsigned> &classpath, std::vector<unsigned> &cardinalities, std::vector<unsigned> &queue) { unsigned r1 = minimal_find_rep(k1, classpath); unsigned r2 = minimal_find_rep(k2, classpath); DBG(TRACE) << "Representatives are: " << k1 << " => " << r1 << ", " << k2 << " => " << r2; if (r1 == r2) return false; if (cardinalities[r1] < cardinalities[r2]) std::swap(r1, r2); DBG(TRACE) << "=> Merging classes:"; classpath[r2] = r1; DBG(TRACE) << "Updated classpath: " << classpath; cardinalities[r1] += cardinalities[r2]; DBG(TRACE) << "Updated cardinalities: " << cardinalities; queue.push_back(r2); DBG(TRACE) << "Updated queue: " << queue; return true; } void BlockSystem::minimal_compress_classpath(std::vector<unsigned> &classpath) { std::unordered_map<unsigned, unsigned> compression; unsigned i = 0u; for (unsigned j : classpath) { if (compression.find(j) == compression.end()) compression[j] = i++; } for (unsigned &j : classpath) j = compression[j]; } std::vector<BlockSystem> BlockSystem::non_trivial_transitive( PermGroup const &pg) { // first base element unsigned first_base_elem = pg.bsgs().base_point(0); DBG(TRACE) << "First base element is: " << first_base_elem; // generators of stabilizer subgroup for first base element PermSet stab = pg.bsgs().stabilizers(1); if (stab.empty()) { DBG(TRACE) << "No generators stabilizing first base element"; return {}; } DBG(TRACE) << "Generators stabilizing first base element:"; DBG(TRACE) << stab; // resulting vector of blocksystems std::vector<BlockSystem> res; // iterate over orbit partition of stabilizer subgroup for (auto const &orbit : OrbitPartition(stab.degree(), stab)) { if (orbit[0] == first_base_elem) continue; // find minimal blocksystem corresponding to orbit auto bs(BlockSystem::minimal(pg.generators(), {first_base_elem, orbit[0]})); if (!bs.trivial()) { DBG(TRACE) << "Found blocksystem: " << bs; res.push_back(bs); } } DBG(TRACE) << "==> Resulting non-trivial block systems:"; DBG(TRACE) << res; return res; } std::vector<BlockSystem> BlockSystem::non_trivial_non_transitive( PermGroup const &pg) { OrbitPartition orbits(pg.degree(), pg.generators()); DBG(TRACE) << "Group has " << orbits.num_partitions() << " distinct orbits:"; #ifndef NDEBUG for (auto const &orbit : orbits) DBG(TRACE) << orbit; #endif std::vector<std::vector<BlockSystem>> partial_blocksystems(orbits.num_partitions()); std::vector<unsigned> domain_offsets(orbits.num_partitions()); for (auto i = 0u; i < orbits.num_partitions(); ++i) { // calculate all non trivial block systems for orbit restricted group PermSet restricted_gens; auto orbit_extremes = std::minmax_element(orbits[i].begin(), orbits[i].end()); unsigned orbit_low = *std::get<0>(orbit_extremes); unsigned orbit_high = *std::get<1>(orbit_extremes); domain_offsets[i] = orbit_low - 1u; for (Perm const &gen : pg.generators()) { Perm perm(gen.restricted(orbits[i].begin(), orbits[i].end())); if (!perm.id()) restricted_gens.insert(perm.normalized(orbit_low, orbit_high)); } DBG(TRACE) << "Group generators restricted to " << orbits[i] << ":"; DBG(TRACE) << restricted_gens; PermGroup pg_restricted(orbit_high - orbit_low + 1u, restricted_gens); partial_blocksystems[i] = non_trivial(pg_restricted, true); // append trivial blocksystem {{x} | x in orbit} std::vector<unsigned> trivial_classes(orbits[i].size()); std::iota(trivial_classes.begin(), trivial_classes.end(), 0u); BlockSystem bs(trivial_classes); partial_blocksystems[i].push_back(bs); } DBG(TRACE) << "=> Relevant block systems for all group restrictions:"; #ifndef NDEBUG for (auto const &bs : partial_blocksystems) DBG(TRACE) << bs; #endif auto blocksystem_representatives( non_trivial_find_representatives(pg.generators(), partial_blocksystems, domain_offsets)); auto blocksystems( non_trivial_from_representatives(pg.generators(), blocksystem_representatives)); DBG(TRACE) << "==> Resulting block systems:"; #ifndef NDEBUG for (BlockSystem const &bs : blocksystems) DBG(TRACE) << bs; #endif return blocksystems; } std::vector<BlockSystem::Block> BlockSystem::non_trivial_find_representatives( PermSet const &generators, std::vector<std::vector<BlockSystem>> const &partial_blocksystems, std::vector<unsigned> const &domain_offsets) { DBG(TRACE) << "== Finding block system representatives"; std::vector<Block> res; std::function<void(std::vector<BlockSystem const *> const &, unsigned, bool)> recurse = [&](std::vector<BlockSystem const *> const &current_blocksystems, unsigned i, bool one_trivial) { if (i == partial_blocksystems.size()) { DBG(TRACE) << "= Considering block system combination:"; #ifndef NDEBUG for (auto j = 0u; j < current_blocksystems.size(); ++j) { DBG(TRACE) << *current_blocksystems[j] << " (shifted by " << domain_offsets[j] << ")"; } #endif Block current_block_unshifted((*current_blocksystems[0])[0]); Block current_block(current_block_unshifted.shifted(domain_offsets[0])); for (auto j = 1u; j < current_blocksystems.size(); ++j) { bool next_block = false; for (auto const &block : *current_blocksystems[j]) { Block shifted_block(block.shifted(domain_offsets[j])); Block extended_block(current_block.unified(shifted_block)); if (is_block(generators, extended_block)) { current_block = extended_block; next_block = true; break; } } if (!next_block) return; } res.push_back(current_block); DBG(TRACE) << "=> Found representative block: " << current_block; return; } for (BlockSystem const &blocksystem : partial_blocksystems[i]) { if (blocksystem.trivial()) { if (one_trivial) return; one_trivial = true; } auto extended_blocksystems(current_blocksystems); extended_blocksystems.push_back(&blocksystem); recurse(extended_blocksystems, i + 1, one_trivial); } }; recurse({}, 0u, false); return res; } std::vector<BlockSystem> BlockSystem::non_trivial_from_representatives( PermSet const &generators, std::vector<Block> const &representatives) { DBG(TRACE) << "== Finding block systems from representatives"; std::vector<BlockSystem> res; for (auto const &repr : representatives) res.push_back(from_block(generators, repr)); return res; } std::ostream &operator<<(std::ostream &os, BlockSystem const &bs) { os << DUMP(bs._blocks, "{}", "{}"); return os; } } // namespace cgtl
#include "Heal.h" Heal::Heal(int cost, int points): Spell(cost, points) {} Heal::~Heal() {} void Heal::action(Unit* target) { target->increaseHP(this->points); }
#include "FadeIn.h" #include "Utils.h" #include "Time.h" #ifdef USING_OGL #define BUFFER_OFFSET(i) ((char *)NULL + (i)) #else #include <d3dcompiler.h> extern Microsoft::WRL::ComPtr<ID3D11Device> D3D11Device; extern Microsoft::WRL::ComPtr<ID3D11DeviceContext> D3D11DeviceContext; #endif void CFadeIn::Create( float fDuration ) { m_fAlpha = 0.0f; m_fSpeed = 1.0f / fDuration; CQVertex LeftTop{ 0,0,0,1, 0, 0 }; CQVertex RightTop{ 1,0,0,1, 1, 0 }; CQVertex LeftBottom{ 0,1,0,1, 0, 1 }; CQVertex RightBottom{ 1,1,0,1 , 1, 1 }; mesh.vertices.push_back( LeftTop ); mesh.vertices.push_back( RightTop ); mesh.vertices.push_back( RightBottom ); mesh.vertices.push_back( LeftBottom ); mesh.indices.push_back( 0 ); mesh.indices.push_back( 2 ); mesh.indices.push_back( 3 ); mesh.indices.push_back( 0 ); mesh.indices.push_back( 1 ); mesh.indices.push_back( 2 ); #ifdef USING_OGL char *vsS = "#version 130\n\ attribute highp vec4 Vertex;\ void main()\ {\ highp vec4 pos;\ pos.xy = Vertex.xy * 2.0;\ pos.xy -= 1.0;\ pos.y *= -1.0;\ pos.zw = vec2(0.f, 1.0);\ gl_Position = pos;\ }"; char *vfS = "#version 130\n\ uniform highp float Alpha;\ void main() \ {\ gl_FragColor = vec4(0.0,0.0,0.0, Alpha);\ }"; GLuint vshader_id = createShader( GL_VERTEX_SHADER, vsS ); GLuint fshader_id = createShader( GL_FRAGMENT_SHADER, vfS ); mesh.shaderID = glCreateProgram(); glAttachShader( mesh.shaderID, vshader_id ); glAttachShader( mesh.shaderID, fshader_id ); glLinkProgram( mesh.shaderID ); glUseProgram( mesh.shaderID ); mesh.vertexAttribLoc = glGetAttribLocation( mesh.shaderID, "Vertex" ); alphaAttribLoc = glGetUniformLocation( mesh.shaderID, "Alpha" ); glGenBuffers( 1, &mesh.vertexBufferID ); glBindBuffer( GL_ARRAY_BUFFER, mesh.vertexBufferID ); glBufferData( GL_ARRAY_BUFFER, mesh.vertices.size() * sizeof( CQVertex ), &mesh.vertices[0].x, GL_STATIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glGenBuffers( 1, &mesh.indexBufferID ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, mesh.indexBufferID ); glBufferData( GL_ELEMENT_ARRAY_BUFFER, mesh.indices.size() * sizeof( unsigned short ), &mesh.indices[0], GL_STATIC_DRAW ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 ); #else char *vsSource = "cbuffer ConstantBuffer\ { \ float4x4 Transf; \ float4 Alpha; \ } \ struct VS_INPUT{ float4 position : POSITION; \ float2 uvcoords : TEXCOORD; }; \ struct VS_OUTPUT{ float4 hposition : SV_POSITION;\ float2 huvcoords : TEXCOORD; };\ VS_OUTPUT VS(VS_INPUT input)\ {\ VS_OUTPUT output;\ float4 pos;\ pos.xy = input.position.xy * 2.0;\ pos.xy -= 1.0;\ pos.y *= -1.0;\ pos.zw = float2(0.0f, 1.0);\ output.hposition = pos;\ output.huvcoords = input.uvcoords;\ return output;\ }"; char *fsSorce = "cbuffer ConstantBuffer\ { \ float4x4 Transf; \ float4 Alpha; \ } \ struct VS_OUTPUT{ float4 hposition : SV_POSITION;\ float2 huvcoords : TEXCOORD; };\ float4 FS( VS_OUTPUT input) : SV_TARGET\ {\ return float4(0.0,0.0,0.0, Alpha.x);\ }"; std::string vsS = vsSource; std::string vfS = fsSorce; HRESULT hr; { mesh.VS_blob = nullptr; Microsoft::WRL::ComPtr<ID3DBlob> errorBlob = nullptr; hr = D3DCompile( vsS.c_str(), vsS.size(), 0, 0, 0, "VS", "vs_5_0", 0, 0, &mesh.VS_blob, &errorBlob ); if ( hr != S_OK ) { if ( errorBlob ) { printf( "errorBlob shader[%s]", (char*)errorBlob->GetBufferPointer() ); return; } if ( mesh.VS_blob ) { return; } } hr = D3D11Device->CreateVertexShader( mesh.VS_blob->GetBufferPointer(), mesh.VS_blob->GetBufferSize(), 0, &mesh.pVS ); if ( hr != S_OK ) { printf( "Error Creating Vertex Shader\n" ); return; } } { mesh.FS_blob = nullptr; Microsoft::WRL::ComPtr<ID3DBlob> errorBlob = nullptr; hr = D3DCompile( vfS.c_str(), vfS.size(), 0, 0, 0, "FS", "ps_5_0", 0, 0, &mesh.FS_blob, &errorBlob ); if ( hr != S_OK ) { if ( errorBlob ) { printf( "errorBlob shader[%s]", (char*)errorBlob->GetBufferPointer() ); return; } if ( mesh.FS_blob ) { return; } } hr = D3D11Device->CreatePixelShader( mesh.FS_blob->GetBufferPointer(), mesh.FS_blob->GetBufferSize(), 0, &mesh.pFS ); if ( hr != S_OK ) { printf( "Error Creating Pixel Shader\n" ); return; } } int offset = 0; D3D11_INPUT_ELEMENT_DESC elementDesc; elementDesc.SemanticName = "POSITION"; elementDesc.SemanticIndex = 0; elementDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; elementDesc.InputSlot = 0; elementDesc.AlignedByteOffset = offset; elementDesc.InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; elementDesc.InstanceDataStepRate = 0; offset += 16; mesh.VertexDecl.push_back( elementDesc ); elementDesc.SemanticName = "TEXCOORD"; elementDesc.SemanticIndex = 0; elementDesc.Format = DXGI_FORMAT_R32G32_FLOAT; elementDesc.InputSlot = 0; elementDesc.AlignedByteOffset = offset; elementDesc.InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; elementDesc.InstanceDataStepRate = 0; offset += 8; mesh.VertexDecl.push_back( elementDesc ); hr = D3D11Device->CreateInputLayout( &mesh.VertexDecl[0], mesh.VertexDecl.size(), mesh.VS_blob->GetBufferPointer(), mesh.VS_blob->GetBufferSize(), &mesh.Layout ); if ( hr != S_OK ) { printf( "Error Creating Input Layout\n" ); return; } D3D11DeviceContext->IASetInputLayout( mesh.Layout.Get() ); D3D11_BUFFER_DESC bdesc = { 0 }; bdesc.Usage = D3D11_USAGE_DEFAULT; bdesc.ByteWidth = sizeof( MeshD3DX::CBuffer ); bdesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; hr = D3D11Device->CreateBuffer( &bdesc, 0, mesh.pd3dConstantBuffer.GetAddressOf() ); if ( hr != S_OK ) { printf( "Error Creating Buffer Layout\n" ); return; } bdesc = { 0 }; bdesc.ByteWidth = mesh.vertices.size() * sizeof( CQVertex ); bdesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; D3D11_SUBRESOURCE_DATA subData = { &mesh.vertices[0], 0, 0 }; hr = D3D11Device->CreateBuffer( &bdesc, &subData, &mesh.VB ); if ( hr != S_OK ) { printf( "Error Creating Vertex Buffer\n" ); return; } bdesc = { 0 }; bdesc.ByteWidth = mesh.indices.size() * sizeof( unsigned short ); bdesc.BindFlags = D3D11_BIND_INDEX_BUFFER; subData = { &mesh.indices[0], 0, 0 }; hr = D3D11Device->CreateBuffer( &bdesc, &subData, &mesh.IB ); if ( hr != S_OK ) { printf( "Error Creating Index Buffer\n" ); return; } #endif } bool CFadeIn::Update() { m_fAlpha += m_fSpeed * Time::GetDt(); if ( m_fAlpha >= 1.0f ) return false; return true; } void CFadeIn::Draw( SRenderAttributes & renderAttribs ) { #ifdef USING_OGL glUseProgram( mesh.shaderID ); glUniform1f( alphaAttribLoc, m_fAlpha ); glBindBuffer( GL_ARRAY_BUFFER, mesh.vertexBufferID ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, mesh.indexBufferID ); glEnableVertexAttribArray( mesh.vertexAttribLoc ); glVertexAttribPointer( mesh.vertexAttribLoc, 4, GL_FLOAT, GL_FALSE, sizeof( CQVertex ), BUFFER_OFFSET( 0 ) ); glDrawElements( GL_TRIANGLES, mesh.indices.size(), GL_UNSIGNED_SHORT, 0 ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 ); glDisableVertexAttribArray( mesh.vertexAttribLoc ); glUseProgram( 0 ); #else UINT stride; UINT offset = 0; mesh.CnstBuffer.Transf = Mat4D::CMatrix4D(); mesh.CnstBuffer.Res.x = m_fAlpha; stride = sizeof( CQVertex ); D3D11DeviceContext->VSSetShader( mesh.pVS.Get(), 0, 0 ); D3D11DeviceContext->PSSetShader( mesh.pFS.Get(), 0, 0 ); D3D11DeviceContext->IASetInputLayout( mesh.Layout.Get() ); D3D11DeviceContext->IASetVertexBuffers( 0, 1, mesh.VB.GetAddressOf(), &stride, &offset ); D3D11DeviceContext->UpdateSubresource( mesh.pd3dConstantBuffer.Get(), 0, 0, &mesh.CnstBuffer, 0, 0 ); D3D11DeviceContext->VSSetConstantBuffers( 0, 1, mesh.pd3dConstantBuffer.GetAddressOf() ); D3D11DeviceContext->PSSetConstantBuffers( 0, 1, mesh.pd3dConstantBuffer.GetAddressOf() ); D3D11DeviceContext->IASetIndexBuffer( mesh.IB.Get(), DXGI_FORMAT_R16_UINT, 0 ); /**********************************Danger Zone*************************************/ D3D11DeviceContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST ); D3D11DeviceContext->DrawIndexed( mesh.indices.size(), 0, 0 ); /**********************************Danger Zone*************************************/ #endif } void CFadeIn::Destroy() { }
#include <bits/stdc++.h> using namespace std; #define MOD 1000000007 #define rep(i, n) for(int i = 0; i < (int)(n); i++) #define rep1(i, n) for(int i = 1; i <= (int)(n); i++) #define showmap(is, js, x) {rep(i, is){rep(j, js){cout << x[i][j] << " ";}cout << endl;}} #define show(x) {for(auto i: x){cout << i << " ";} cout<<endl;} #define showm(m) {for(auto i: m){cout << m.x << " ";} cout<<endl;} typedef long long ll; typedef pair<int, int> P; typedef pair<ll, ll> llP; ll gcd(int x, int y){ return y?gcd(y, x%y):x;} ll lcm(ll x, ll y){ return (x*y)/gcd(x,y);} const int N_MAX = 200050; int main() { int n, q; cin >> n >> q; vector<multiset<int>> rand(N_MAX); multiset<int> score; vector<P> enji(n+1); rep(i, n){ int a, b; cin >> a >> b; enji[i+1].first = a; enji[i+1].second = b; rand[b].insert(a); } rep(i, N_MAX){ if (rand[i].size() == 0) continue; auto itr = rand[i].end(); itr--; //cout << *itr << endl; score.insert(*itr); } rep(i, q){ int c, d; cin >> c >> d; //異動する園児の情報 int rate = enji[c].first; int en = enji[c].second; int from_before = *(--(rand[en].end())); int to_before = -1; if (rand[d].size() != 0) to_before = *(--(rand[d].end())); rand[en].erase(rand[en].find(rate)); rand[d].insert(rate); int from_after = -1; if (rand[en].size() != 0) from_after = *(--(rand[en].end())); int to_after = *(--(rand[d].end())); enji[c].second = d; score.erase(score.find(from_before)); if(from_after != -1) score.insert(from_after); if(to_before != -1) score.erase(score.find(to_before)); score.insert(to_after); auto itr = score.begin(); cout << *itr << endl; } }
#pragma once #include <windows.h> #include <gl/glu.h> #include "math.h" #include "includelist.h" // DEFINE THIS IF YOU WANT TO OPTIMIZE TO SQUARE TEXTURES #define __TEXGEN_SQUARE_TEXTURES__ // DEFINE THIS IF YOU WANT BILINEAR FILTERED TEXTURES #define __TEXGEN_BILINEAR__ #pragma pack(1) #ifdef INCLUDE_TEX_Envmap #define TEXGEN_Envmap 0 struct ENVMAPTEMPLATE { unsigned char Size; }; #endif #ifdef INCLUDE_TEX_Plasma #define TEXGEN_Plasma 1 struct PLASMATEMPLATE { unsigned char XSines; unsigned char YSines; }; #endif #ifdef INCLUDE_TEX_Map #define TEXGEN_Map 2 struct MAPTEMPLATE { unsigned char XDataLayer; unsigned char XDataChannel; unsigned char XAmount; unsigned char YDataLayer; unsigned char YDataChannel; unsigned char YAmount; }; #endif #ifdef INCLUDE_TEX_Blur #define TEXGEN_Blur 3 struct BLURTEMPLATE { unsigned char Iterations; unsigned char SampleWidth; }; #endif #ifdef INCLUDE_TEX_DirBlur #define TEXGEN_DirBlur 4 struct DIRBLURTEMPLATE { unsigned char DataLayer; unsigned char DataChannel; unsigned char Depth; }; #endif #ifdef INCLUDE_TEX_Text #define TEXGEN_Text 5 struct TEXTTEMPLATE { unsigned char Size; unsigned char X; unsigned char Y; unsigned char Bold; unsigned char Italic; unsigned char Font; unsigned char Spacing; char * Text; }; #endif #ifdef INCLUDE_TEX_SubPlasma #define TEXGEN_SubPlasma 6 struct SUBPLASMATEMPLATE { unsigned char Size; unsigned char RandSeed; }; #endif #ifdef INCLUDE_TEX_FractalPlasma #define TEXGEN_FractalPlasma 7 struct FRACTALPLASMATEMPLATE { unsigned char Min; unsigned char Max; unsigned char Blend; unsigned char RandSeed; }; #endif #ifdef INCLUDE_TEX_Colorize #define TEXGEN_Colorize 8 struct COLORIZETEMPLATE { unsigned int StartColor; unsigned int EndColor; unsigned char DataChannel; }; #endif #ifdef INCLUDE_TEX_Shade #define TEXGEN_Shade 9 struct SHADETEMPLATE { unsigned char DataLayer; unsigned char DataChannel; }; #endif #ifdef INCLUDE_TEX_Brightness #define TEXGEN_Brightness 10 struct BRIGHTNESSTEMPLATE { unsigned char Amount; }; #endif #ifdef INCLUDE_TEX_Copy #define TEXGEN_Copy 11 struct COPYTEMPLATE { unsigned char DataLayer; }; #endif #ifdef INCLUDE_TEX_Cells #define TEXGEN_Cells 12 struct CELLSTEMPLATE { unsigned char Points; unsigned char Power; unsigned char RandSeed; }; #endif #ifdef INCLUDE_TEX_Twirl #define TEXGEN_Twirl 13 struct TWIRLTEMPLATE { unsigned char Amount; }; #endif #ifdef INCLUDE_TEX_SineDist #define TEXGEN_SineDist 14 struct SINEDISTTEMPLATE { unsigned char XSines; unsigned char YSines; unsigned char XAmp; unsigned char YAmp; }; #endif #ifdef INCLUDE_TEX_Mix #define TEXGEN_Mix 15 struct MIXTEMPLATE { unsigned char DataLayer; unsigned char Amount; }; #endif #ifdef INCLUDE_TEX_MixMap #define TEXGEN_MixMap 16 struct MIXMAPTEMPLATE { unsigned char DataLayer; unsigned char MixLayer; unsigned char MixChannel; }; #endif #ifdef INCLUDE_TEX_Scale #define TEXGEN_Scale 17 struct SCALETEMPLATE { unsigned char DataChannel; unsigned char Min; unsigned char Max; }; #endif #ifdef INCLUDE_TEX_SineColor #define TEXGEN_SineColor 18 struct SINECOLORTEMPLATE { unsigned char DataChannel; unsigned char NumSines; }; #endif #ifdef INCLUDE_TEX_Max #define TEXGEN_Max 19 struct MAXTEMPLATE { unsigned char DataLayer; }; #endif #ifdef INCLUDE_TEX_HSV #define TEXGEN_HSV 20 struct HSVTEMPLATE { unsigned char Hue; unsigned char Saturation; }; #endif #ifdef INCLUDE_TEX_Emboss #define TEXGEN_Emboss 21 #endif #ifdef INCLUDE_TEX_Invert #define TEXGEN_Invert 22 #endif #ifdef INCLUDE_TEX_Glass #define TEXGEN_Glass 23 struct GLASSTEMPLATE { unsigned char DataLayer; unsigned char DataChannel; unsigned char Amount; }; #endif #ifdef INCLUDE_TEX_Pixelize #define TEXGEN_Pixelize 24 struct PIXELIZETEMPLATE { unsigned char XSquares; unsigned char YSquares; }; #endif #ifdef INCLUDE_TEX_Offset #define TEXGEN_Offset 25 struct OFFSETTEMPLATE { unsigned char X; unsigned char Y; }; #endif #ifdef INCLUDE_TEX_Crystalize #define TEXGEN_Crystalize 26 struct CRYSTALIZETEMPLATE { unsigned char Points; unsigned char RandSeed; }; #endif #ifdef INCLUDE_TEX_Rectangle #define TEXGEN_Rectangle 27 struct RECTANGLETEMPLATE { unsigned char StartX; unsigned char StartY; unsigned char SizeX; unsigned char SizeY; }; #endif #ifdef INCLUDE_TEX_Circle #define TEXGEN_Circle 28 struct CIRCLETEMPLATE { unsigned char InnerRadius; unsigned char OuterRadius; unsigned char X; unsigned char Y; }; #endif #ifdef INCLUDE_TEX_Contrast #define TEXGEN_Contrast 29 struct CONTRASTTEMPLATE { unsigned char Amount; }; #endif #ifdef INCLUDE_TEX_MakeMaterial #define TEXGEN_MakeMaterial 30 struct MAKEMATERIALTEMPLATE { unsigned char MaterialSlot; char * Name; }; #endif #ifdef INCLUDE_TEX_Gradient #define TEXGEN_Gradient 31 struct GRADIENTTEMPLATE { unsigned int _00; unsigned int _10; unsigned int _01; unsigned int _11; }; #endif #ifdef INCLUDE_TEX_Rotozoom #define TEXGEN_Rotozoom 32 struct ROTOZOOMTEMPLATE { unsigned char CX; unsigned char CY; unsigned char ZoomX; unsigned char ZoomY; unsigned char ZoomIn; unsigned char Rotation; }; #endif #ifdef INCLUDE_TEX_ChamferRectangle #define TEXGEN_ChamferRectangle 33 struct CHAMFERRECTANGLETEMPLATE { unsigned char StartX; unsigned char StartY; unsigned char SizeX; unsigned char SizeY; unsigned char Chamfer; }; #endif #ifdef INCLUDE_TEX_Dots #define TEXGEN_Dots 34 struct DOTSTEMPLATE { unsigned short Count; unsigned char Min,Max; bool Rounded; unsigned char SizeMin,SizeMax; unsigned char RandSeed; }; #endif #ifdef INCLUDE_TEX_Jpeg #define TEXGEN_Jpeg 35 struct JPEGTEMPLATE { int JPEGDataSize; unsigned char *JPEGData; }; #endif #ifdef INCLUDE_TEX_FractalPlasmaOld #define TEXGEN_FractalPlasmaOld 36 struct FRACTALPLASMAOLDTEMPLATE { unsigned char RandSeed; }; #endif ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// union RGBA { unsigned char c[4]; struct { unsigned char r,g,b,a; }; unsigned int dw; }; struct LAYER { GLuint TextureHandle; RGBA *Data; }; struct MATERIAL { LAYER ImageData; int TextureID; int SlotNumber; int Size; MATERIAL *Next; }; struct COMMAND { char Filter; char Operator; char OperatorMask[4]; char Layer; char DataSize; void *data; }; class TEXTURE { public: int Id; int XRes,YRes; char *Name; LAYER Layers[8]; int CommandNumber; COMMAND *Commands; TEXTURE(int Resolution) { for (int x=0; x<8; x++) Layers[x].Data=new RGBA[Resolution*Resolution]; CommandNumber=0; Commands=new COMMAND[255]; XRes=Resolution; YRes=Resolution; } TEXTURE *Next; #ifdef INCLUDE_TEX_Envmap void Envmap(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_Plasma void Plasma(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_SubPlasma void SubPlasma(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_Text void Text(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_Map void Map(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_Blur void Blur(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_DirBlur void DirBlur(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_FractalPlasma void FractalPlasma(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_Colorize void Colorize(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_Emboss void Emboss(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_Shade void Shade(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_Brightness void Brightness(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_Copy void Copy(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_Cells void Cells(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_Twirl void Twirl(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_SineDist void SineDist(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_Mix void Mix(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_MixMap void MixMap(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_Invert void Invert(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_Scale void Scale(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_SineColor void SineColor(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_Max void Max(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_HSV void HSV(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_Glass void Glass(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_Pixelize void Pixelize(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_Offset void Offset(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_Crystalize void Crystalize(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_Rectangle void Rectangle(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_Circle void Circle(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_Contrast void Contrast(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_MakeMaterial void MakeMaterial(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_Gradient void Gradient(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_Rotozoom void Rotozoom(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_ChamferRectangle void ChamferRectangle(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_Dots void Dots(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_Jpeg void Jpeg(RGBA*, COMMAND*); #endif #ifdef INCLUDE_TEX_FractalPlasmaOld void FractalPlasmaOld(RGBA*, COMMAND*); #endif void PerformCommand(RGBA* Layer, COMMAND* Parameters); void PerformFilter(RGBA*, RGBA*, COMMAND*); #ifdef __TEXGEN_BILINEAR__ unsigned int Bilinear(RGBA*,unsigned int, unsigned int); #endif }; extern TEXTURE *TextureList; #pragma pack() extern char CellsBufferImage[2048][2048]; void TexGenPrecalc(); void memcpy_dw(void * to, void * from, int count); //SetTextAlign
#include <algorithm> #include <iostream> #include <iterator> #include <map> #include <string> using kv_map = std::map<std::string, std::string>; template <typename InputIterator, typename Container, typename InputValueType = typename std::iterator_traits<InputIterator>::value_type> void parse_key_value_message(InputIterator f, InputIterator l, Container & o, const InputValueType field_separator, const InputValueType kv_separator) { using key_type = typename Container::key_type; using value_type = typename Container::mapped_type; for (auto p = std::find(f, l, kv_separator); p != l; p = std::find(f, l, kv_separator)) { auto q = std::find(p, l, field_separator); o.emplace(key_type(f, p), value_type(std::next(p), q)); f = std::next(q); } } template <typename InputIterator, typename Container> void parse_amps_message(InputIterator f, InputIterator l, Container & o) { parse_key_value_message(f, l, o, '\x01', '='); } int main() { // const std::string msg("key1=value1;key_2=1234;key3=;keyN=valueN;"); const std::string msg("key1=value1\u0001key_2=1234\u0001key3=\u0001keyN=valueN\u0001"); kv_map result; // parse_key_value_message(msg.begin(), msg.end(), result, ';', '='); parse_amps_message(msg.begin(), msg.end(), result); for (auto && p : result) std::cout << p.first << " ==> " << p.second << std::endl; return 0; }
#include "muduo/base/ThreadPool.h" #include "muduo/base/Exception.h" #include "muduo/base/Thread.h" using std::placeholders::_1; namespace muduo { void ThreadPool::start(int numThreads) { #ifndef NDEBUG fprintf(stderr, "Start thread pool with %d threads\n", numThreads); #endif assert(threads_.empty()); running_ = true; threads_.reserve(numThreads); for (int i = 0; i != numThreads; ++i) { char id[32]{}; snprintf(id, sizeof id, "%d", i); threads_.push_back(std::make_unique<Thread>(std::bind(&ThreadPool::runInThread, this), name_+id)); threads_.back()->start(); } if (numThreads == 0 && initCallback_) initCallback_(); } void ThreadPool::stop() { running_ = false; notEmpty_.notifyAll(); std::for_each(threads_.begin(), threads_.end(), std::bind(&Thread::join, _1)); threads_.clear(); } void ThreadPool::run(Task t) { if (threads_.empty()) { #ifndef NDEBUG fprintf(stderr, "threads_ is empty, run task directly\n"); #endif t(); } else { MutexLockGuard lock(mutex_); while (isFull()) notFull_.wait(); assert(!isFull()); #ifndef NDEBUG fprintf(stderr, "put a task to queue_\n"); #endif queue_.push_back(std::move(t)); notEmpty_.notify(); } } bool ThreadPool::isFull() const { mutex_.assertLocked(); return maxQueueSize_ > 0 && queue_.size() >= maxQueueSize_; } size_t ThreadPool::queueSize() const { MutexLockGuard lock(mutex_); return queue_.size(); } ThreadPool::Task ThreadPool::take() { MutexLockGuard lock(mutex_); while (queue_.empty() && running_) { #ifndef NDEBUG fprintf(stderr, "wait for not empty\n"); #endif notEmpty_.wait(); } Task t; if (!queue_.empty()) { t = queue_.front(); queue_.pop_front(); if (maxQueueSize_ > 0) notFull_.notify(); } return t; } void ThreadPool::runInThread() { #ifndef NDEBUG fprintf(stderr, "tid=%d, name=%s in threadpool\n", muduo::CurrentThread::tid(), muduo::CurrentThread::name()); #endif try { if (initCallback_) initCallback_(); while (running_) { Task t(take()); if (t) { t(); } } } catch (Exception &e) { printf("caught Exception\n"); abort(); } catch (std::exception &e) { printf("caught std::exception\n"); abort(); } catch (...) { throw; } } }
#ifndef __DCLSMOVEEDITOR_H #define __DCLSMOVEEDITOR_H #include "MClsMove.h" #include "MGroup.h" #include "TPresenter.h" #include "TViewCtrlPanel.h" #include "PathPatternEditor.h" namespace wh{ namespace view{ //----------------------------------------------------------------------------- /// Редактор для свойства действия class DClsMoveEditor : public wxDialog , public T_View { public: DClsMoveEditor(wxWindow* parent = nullptr, wxWindowID id = wxID_ANY, const wxString& title = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize(400, 300),//wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER, const wxString& name = wxDialogNameStr); void SetModel(std::shared_ptr<IModel>& model)override; void UpdateModel()const override; int ShowModal() override; private: void GetData(rec::ClsSlotAccess& rec) const; void SetData(const rec::ClsSlotAccess& rec); void OnChangeModel(const IModel* model, const MClsMove::T_Data* data); // графические компоненты свеху вниз PathPatternEditor* mMovEditor; PathPatternEditor* mSrcPathEditor; PathPatternEditor* mDstPathEditor; wxPropertyGrid* mPropGrid; wxButton* m_btnOK; wxButton* m_btnCancel; wxStdDialogButtonSizer* m_sdbSizer; // модели std::shared_ptr<MClsMove> mModel;// Модель разрешений перемещений /// Модель перемещаемого шаблона std::shared_ptr<temppath::model::Array> mMovPattern; /// Модель для массива шаблона-пути-источника std::shared_ptr<temppath::model::Array> mSrcPatternPath; /// Модель для массива шаблона-пути-приёмника std::shared_ptr<temppath::model::Array> mDstPatternPath; // сигналы sig::scoped_connection mChangeConnection; // TODO: заменить на диалоги групп и действий std::shared_ptr<MGroupArray> mGroupArray; }; //----------------------------------------------------------------------------- }//namespace view{ }//namespace wh{ #endif // __****_H
#include <iostream> #include <pqxx/pqxx> int main() { try { pqxx::connection conn("postgresql://<user>:<pass>@<host>:<port>/<db>"); std::cout << "Connected as " << conn.username() << "@" << conn.hostname() << ":" << conn.port() << "/" << conn.dbname() << std::endl; // Start a transaction. In libpqxx, you always work in one. pqxx::work txn(conn); std::tuple <int, std::string, std::string> row; pqxx::stream_from stream( txn, "SELECT id, aconcept, atag " " FROM tags" " WHERE atag NOT LIKE '%e%'" ); txn.commit(); while(stream >> row) { int theId = std::get<0>(row); std::string theConcept = std::get<1>(row); std::string theTag = std::get<2>(row); std::cout << "|" << theId << "| " << theConcept << " | " << theTag << " |" << std::endl; } stream.complete(); } catch (std::exception const &e) { std::cerr << e.what() << std::endl; return 1; } return 0; }
#include <ax12.h> //AX-12 libraries allow the ArbotiX to communicate with DYNAMIXEL servos, AX and MX #include <BioloidController.h> //The Bioloid controller library is used for servo interpolation #include <avr/pgmspace.h> //PROGMEM library allows the ArboitX to store poses in Flash memory, so that SRAM is not used #define SERVO_COUNT 6 //the number of servos that will be attached - change this for your specific robot #define POSE_COUNT 5 #define DEFAULT_BIOLID_DELAY 5000 //the time in ms it will take to move from one pose to the next #define DEFAULT_POSE_DELAY 1000 //the time to hold a pose before moving to the next pose BioloidController bioloid = BioloidController(1000000); //initialize the bioloid controller to 1000000 baud void setup() { delay(100); //delay to wait for DYNAMIXEL initialization } void loop() { playPoseOnce(pose1, DEFAULT_BIOLID_DELAY ); delay(DEFAULT_POSE_DELAY) } int playPoseOnce( const unsigned int * pose, int bioloidDelay) { bioloid.poseSize = SERVO_COUNT; // define the poseSize for the bioloid controller for(int j = 0; j<POSE_COUNT;j++) { bioloid.loadPose(poseTemp1); // load the pose from FLASH, into the nextPose buffer bioloid.readPose(); // read in current servo positions to the curPose buffer bioloid.interpolateSetup(bioloidDelay); // setup for interpolation from current->next over 1 second while(bioloid.interpolating > 0) { // do this while we have not reached our new pose bioloid.interpolateStep(); // move servos, if necessary. delay(3); } } }
/* filename: moruleset.h author: Sherri Harms last modified: 8/8/01 description: Class moruleset interface file for parallel MINEPI REAR rules Values of this type are vectors of rules, where a morule is a composite of an antecedent episode, and a consequent episode, with a confidence; ****************************************************************************** Known bugs: The constraints are all disjuctive singular events. step 5 from alg 5 generate candidatges has not been implemented input validation is not done ******************************************************************************* Local Data Structures: Local variables: ***************************************************************************** moruleset operations include: input, output, constructors, relational operators, accessor functions and operations to adds rules, etc *******************************************************************************/ #ifndef moRULESET_H #define moRULESET_H #include "event.h" #include "morule.h" #include <vector> #include <algorithm> #include <iostream> using namespace std; typedef vector<event> event_set; typedef vector<morule> p_rule_set; class moruleset { public: void cleanup(); void clear(); //cleare the current moruleset void insertrule(const morule& in_rule); //add a morule into the moruleset morule get_first_rule() const; //return the first morule bool empty() const; //true if rear empty bool contain(const morule& in_rule) const; //returns true if the moruleset already contains this morule string outputXML(char type) const; //Purpose: To add all of the rules generated by the algorithm to an // XML string for output //Author: Matt Culver //Last Modified: 6 July 2003 //type - The type of episode that the algorthm was looking for void output(ostream& outs, bool rar=false) const; // Dan Li, oct29, add one more parameter to output void output(ostream& outs, char type, bool rar=false) const; friend bool operator ==(const moruleset& r1, const moruleset& r2) //Returns true if i1 and i2 represent the same moruleset; //otherwise, returns false. { return (r1.rs==r2.rs); } friend bool operator !=(const moruleset& r1, const moruleset& r2) //Returns true if i1 != i2 ; otherwise, returns false. { return !(r1.rs==r2.rs); } moruleset( ); //Constructor. int AccessCount() const; /* friend istream& operator >>(istream& ins, moruleset& the_object) //Overloads the >> operator for input values of type moruleset. //Precondition: If ins is a file input stream, then ins has //already been connected to a file. //Overloads the >> operator for input values of type moruleset. //Precondition: If ins is a file input stream, then ins has //already been connected to a file. { morule i; ins>>i; //NOT IMPLEMENTED while (!ins.eof()) { the_object.rs.push_back(i); ins>>i; } return ins; } friend ostream& operator << (ostream& outs, const moruleset& the_object) //Overloads the << operator for output values of type moruleset. //Precondition: If outs is a file output stream, then outs as //already been connected to a file. //Overloads the << operator for output values of type moruleset. //Precondition: If outs is a file output stream, then outs as //already been connected to a file. { ostream_iterator<morule> output(outs, " "); copy(the_object.rs.begin(), the_object.rs.end(), output); return outs; } */ private: p_rule_set rs; int count; }; #endif //ruleset_H
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2011 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #include "core/pch.h" #include "adjunct/desktop_pi/DesktopOpView.h" #include "modules/pi/OpView.h" #ifdef VEGA_OPPAINTER_SUPPORT # include "modules/libgogi/pi_impl/mde_opview.h" #endif // VEGA_OPPAINTER_SUPPORT OP_STATUS OpView::Create(OpView **new_opview, OpWindow *parentwindow) { OP_ASSERT(new_opview); #ifdef VEGA_OPPAINTER_SUPPORT if (parentwindow && parentwindow->GetStyle() == OpWindow::STYLE_BITMAP_WINDOW) { MDE_OpView* opview = OP_NEW(MDE_OpView, ()); RETURN_OOM_IF_NULL(opview); OP_STATUS status = opview->Init(parentwindow); if (OpStatus::IsError(status)) { OP_DELETE(opview); *new_opview = NULL; return status; } else { *new_opview = opview; return OpStatus::OK; } } #endif // VEGA_OPPAINTER_SUPPORT return DesktopOpView::Create(new_opview, parentwindow); } OP_STATUS OpView::Create(OpView **new_opview, OpView *parentview) { OP_ASSERT(new_opview); #ifdef VEGA_OPPAINTER_SUPPORT OpWindow *root_window = parentview ? parentview->GetRootWindow() : NULL; if (root_window && root_window->GetStyle() == OpWindow::STYLE_BITMAP_WINDOW) { MDE_OpView *opview = OP_NEW(MDE_OpView, ()); RETURN_OOM_IF_NULL(opview); OP_STATUS status = opview->Init(parentview); if (OpStatus::IsError(status)) { OP_DELETE(opview); *new_opview = NULL; return status; } else { *new_opview = opview; return OpStatus::OK; } } #endif // VEGA_OPPAINTER_SUPPORT return DesktopOpView::Create(new_opview, parentview); }
class Solution { public: int maxProfit(vector<int>& prices) { if(prices.empty()) return 0; int sell = 0; int buy = INT_MAX; for(int i=0; i<prices.size(); ++i){ buy = min(buy,prices[i]); sell = max(sell,prices[i]-buy); } return sell; } };
#pragma once namespace Petunia { enum ConnectionRole { Auto, Server, Client }; }
#include <eosiolib/eosio.hpp> using namespace eosio; class[[eosio::contract]] externcont : public eosio::contract{ public: using contract::contract; externcont(name receiver, name code, datastream<const char*> ds) : contract(receiver, code, ds) {}; [[eosio::action]] void eostransfer(name from, name to, uint64_t id ) { require_auth(from); externcont_index externcont_table(_code, _code.value); auto iterator = externcont_table.find(from.value); if (iterator == externcont_table.end()) { externcont_table.emplace(from, [&](auto& row) { row.id = id; row.from = from; row.to= to; }); } else { std::string changes; externcont_table.modify(iterator, from, [&](auto& row) { row.id = id; row.from= from; row.to= to; }); } eosio_assert(false, "wow error in externcont contract!"); } private: struct[[eosio::table]] tran{ uint64_t id; name from; name to; uint64_t primary_key() const { return id; } }; typedef eosio::multi_index<"trans"_n, tran> externcont_index; }; EOSIO_DISPATCH(externcont, (eostransfer))
#ifndef DOUBLE_H #define DOUBLE_H class Double { public: double value; Double(); Double(double val); Double(const Double &other); Double& operator+= (const Double &val); Double& operator* (Double &t); }; inline Double::Double() : value(0.0) {} inline Double::Double(double val) { value = val; } inline Double::Double (const Double &other) { value = other.value; } inline Double& Double::operator+= (const Double &val) { value += val.value; return *this; } inline Double& Double::operator* (Double &t) { value *= t.value; return *this; } #endif
#include<iostream> #include<cstdlib> using namespace std; void shuffle(int *arr,int s,int e) { srand(time(NULL)); int i,j; for(i=e;i>0;i--) { j=rand()%(i+1); swap(arr[i],arr[j]); } } int partition(int *arr,int s,int e) { int i=s-1; int p=e; int j=s; for(j=s;j<e;j++) { if(arr[j]<arr[p]) { i++; swap(arr[i],arr[j]); } } swap(arr[i+1],arr[p]); return i+1; } void quicksort(int *arr,int s,int e) { if(s>=e) return; int p=partition(arr,s,e); quicksort(arr,s,p-1); quicksort(arr,p+1,e); } int main() { int n; cin>>n; int arr[n]; for(int i=0;i<n;i++) cin>>arr[i]; shuffle(arr,0,n-1); quicksort(arr,0,n-1); for(int i=0;i<n;i++) cout<<arr[i]<<" "; return 0; }
////////////////////////////////////////////////////////////////////////////// // // Copyright (c) Triad National Security, LLC. This file is part of the // Tusas code (LA-CC-17-001) and is subject to the revised BSD license terms // in the LICENSE file found in the top-level directory of this distribution. // ////////////////////////////////////////////////////////////////////////////// #ifndef ERROR_ESTIMATOR_H #define ERROR_ESTIMATOR_H #include "Mesh.h" //teuchos support #include <Teuchos_RCP.hpp> // Epetra support #include "Epetra_Vector.h" #include "Epetra_Map.h" #include "Epetra_Import.h" #include <Teuchos_TimeMonitor.hpp> #include <Tpetra_Vector.hpp> //needed for create_onetoone hack below #include "Epetra_Comm.h" #include "Epetra_Directory.h" //#define ERROR_ESTIMATOR_OMP //template<class Scalar> /// Gradient recovery / error estimation. /** Compute a Zienkiewicz-Zhu gradient recovery and H^1 error estimator. Supports only bilinear quad and tri elements in serial at this time.*/ class error_estimator { public: /// Constructor. /** Input total number of PDEs in the system numeqs, and the index index of the variable to create error estimator for. */ error_estimator(const Teuchos::RCP<const Epetra_Comm>& comm, ///< MPI communicator Mesh *mesh, ///< mesh object const int numeqs, ///< the total number of pdes const int index ///< the index of the variable ); /// Destructor. ~error_estimator(); /// Estimate the gradient at each node. void estimate_gradient(const Teuchos::RCP<Epetra_Vector>& ///< solution vector (input) ); /// Estimate the gradient at each node. void estimate_gradient(const Teuchos::RCP<Tpetra::Vector<> >& ///< solution vector (input) ); /// Estimate the error on each element. void estimate_error(const Teuchos::RCP<Epetra_Vector>& ///< solution vector (input) ); /// Estimate the error on each element. void estimate_error(const Teuchos::RCP<Tpetra::Vector<> >& ///< solution vector (input) ); /// A helper function to test the Lapack implementation. void test_lapack(); /// Output the nodal gradient and the elemental error contribution to the exodus file. void update_mesh_data(); /// Estimate the global H^1 error. double estimate_global_error(); /// Estimated nodal derivative wrt to x. Teuchos::RCP<Epetra_Vector> gradx_; /// Estimated nodal derivative wrt to y. Teuchos::RCP<Epetra_Vector> grady_; /// Estimated nodal derivative wrt to y. Teuchos::RCP<Epetra_Vector> gradz_; private: ///Mesh object Mesh *mesh_; /// Total number of PDEs. int numeqs_; /// Variable index. int index_; /// MPI comm object. const Teuchos::RCP<const Epetra_Comm> comm_; /// Node map object. Teuchos::RCP<const Epetra_Map> node_map_; /// Node overlap map object. Teuchos::RCP<const Epetra_Map> overlap_map_; /// Element map object. Teuchos::RCP<const Epetra_Map> elem_map_; /// Error contribution on each element. Teuchos::RCP<Epetra_Vector> elem_error_; /// Import object. Teuchos::RCP<const Epetra_Import> importer_; /// Global H^1 error estimate. double global_error_; /// Timing object. Teuchos::RCP<Teuchos::Time> ts_time_grad; /// Timing object. Teuchos::RCP<Teuchos::Time> ts_time_error; /// Estimate the gradient at each node. void estimate_gradient(const double * uvec ///< solution vector (input) ); /// Estimate the error on each element. void estimate_error(const double * uvec ///< solution vector (input) ); //we need this in some public utility class... const Mesh::mesh_lint_t epetra_map_gid(Teuchos::RCP<const Epetra_Map> map, const int lid) { #ifdef MESH_64 const Mesh::mesh_lint_t gid = map->GID64(lid); #else const Mesh::mesh_lint_t gid = map->GID(lid); #endif return gid; }; //we need these in some static public utility class... Epetra_Map Create_OneToOne_Map64(const Epetra_Map& usermap, bool high_rank_proc_owns_shared=false) { //if usermap is already 1-to-1 then we'll just return a copy of it. if (usermap.IsOneToOne()) { Epetra_Map newmap(usermap); return(newmap); } int myPID = usermap.Comm().MyPID(); Epetra_Directory* directory = usermap.Comm().CreateDirectory(usermap); int numMyElems = usermap.NumMyElements(); const long long* myElems = usermap.MyGlobalElements64(); int* owner_procs = new int[numMyElems]; directory->GetDirectoryEntries(usermap, numMyElems, myElems, owner_procs, 0, 0, high_rank_proc_owns_shared); //we'll fill a list of map-elements which belong on this processor long long* myOwnedElems = new long long[numMyElems]; int numMyOwnedElems = 0; for(int i=0; i<numMyElems; ++i) { long long GID = myElems[i]; int owner = owner_procs[i]; if (myPID == owner) { myOwnedElems[numMyOwnedElems++] = GID; } } Epetra_Map one_to_one_map((long long)-1, numMyOwnedElems, myOwnedElems, usermap.IndexBase(), usermap.Comm()); // CJ TODO FIXME long long delete [] myOwnedElems; delete [] owner_procs; delete directory; return(one_to_one_map); }; }; #endif
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QPushButton> #include <QPoint> #include <mycanvas.h> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: void change_button_color(QPushButton *butt, QColor color); void add_new_point(const QPoint& point, const ModeAdd& mode); void close_region(); void change_horizontal_point(QPoint& point); void update_cutter(const QPoint& point); explicit MainWindow(QWidget *parent = nullptr); ~MainWindow(); private slots: void on_button_add_point_clicked(); void on_button_clear_1_clicked(); void on_button_clear_2_clicked(); void on_button_choose_line_color_clicked(); void on_button_choose_cutter_color_clicked(); void on_button_choose_cut_color_clicked(); void on_button_cut_region_clicked(); void on_button_clear_cutter_clicked(); void on_button_clear_lines_clicked(); private: Ui::MainWindow *ui; MyCanvas *view_scene; bool mouse_is_active; protected: void mousePressEvent(QMouseEvent *event); void keyPressEvent(QKeyEvent *event); void keyReleaseEvent(QKeyEvent *event); }; #endif // MAINWINDOW_H
#pragma once #include "uninitialized.hpp" template<typename T, std::size_t N> class uninitialized_array { public: typedef T value_type; typedef T& reference; typedef const T& const_reference; typedef T* pointer; typedef const T* const_pointer; typedef pointer iterator; typedef const_pointer const_iterator; typedef std::size_t size_type; __forceinline__ __device__ iterator begin() { return data(); } __forceinline__ __device__ const_iterator begin() const { return data(); } __forceinline__ __device__ iterator end() { return begin() + size(); } __forceinline__ __device__ const_iterator end() const { return begin() + size(); } __forceinline__ __device__ const_iterator cbegin() const { return begin(); } __forceinline__ __device__ const_iterator cend() const { return end(); } __forceinline__ __device__ size_type size() const { return N; } __forceinline__ __device__ bool empty() const { return false; } __forceinline__ __device__ T* data() { return impl.get(); } __forceinline__ __device__ const T* data() const { return impl.get(); } // element access __forceinline__ __device__ reference operator[](size_type n) { return data()[n]; } __forceinline__ __device__ const_reference operator[](size_type n) const { return data()[n]; } __forceinline__ __device__ reference front() { return *data(); } __forceinline__ __device__ const_reference front() const { return *data(); } __forceinline__ __device__ reference back() { return data()[size() - size_type(1)]; } __forceinline__ __device__ const_reference back() const { return data()[size() - size_type(1)]; } private: uninitialized<T[N]> impl; };
#include <iostream> #include <cmath> bool checkPrime(int num) { for( int i = 2; i <= sqrt(num); i++) { if(num%i == 0) { return false; } } return true; } int main() { int number; std::cout << "Please, enter a number: "; std::cin >> number; for( int i = 1; i <= number; i++) { if(number%i == 0 && checkPrime(i)) { std::cout << i << std::endl; } } return 0; }
#include <stdint.h> #include <string.h> void blocked_reorder_naive( float* src, float* dst, uint32_t* src_block_starts, uint32_t* dst_block_starts, uint32_t* block_sizes, uint32_t num_blocks) { for (uint32_t block_idx = 0; block_idx < num_blocks; ++block_idx) { for (uint32_t elem_idx = 0; elem_idx < block_sizes[block_idx]; ++elem_idx) { uint32_t src_start = src_block_starts[block_idx]; uint32_t dst_start = dst_block_starts[block_idx]; float f = src[src_start + elem_idx]; dst[dst_start + elem_idx] = f; } } } void blocked_reorder_memcpy( float* src, float* dst, uint32_t* src_block_starts, uint32_t* dst_block_starts, uint32_t* block_sizes, uint32_t num_blocks) { for (uint32_t block_idx = 0; block_idx < num_blocks; ++block_idx) { memcpy( &dst[dst_block_starts[block_idx]], &src[src_block_starts[block_idx]], block_sizes[block_idx] * sizeof(float)); } }
// windowdriver_p.cc // 2/1/2013 jichi #include "config.h" #include "window/windowdriver_p.h" #include "window/windowhash.h" #include "window/windowmanager.h" #include "winiter/winiter.h" #include "winiter/winitertl.h" #include <commctrl.h> #include <QtCore/QHash> #include <QtCore/QTextCodec> #include <QtCore/QTimer> #include <unordered_map> //#include <boost/bind.hpp> //#define DEBUG "windowdriver_p" //#include "sakurakit/skdebug.h" enum { TEXT_BUFFER_SIZE = 256 }; // - Construction - static WindowDriverPrivate *instance_; WindowDriverPrivate *WindowDriverPrivate::instance() { return instance_; } WindowDriverPrivate::WindowDriverPrivate(QObject *parent) : Base(parent) , enabled(false) , textVisible(false) , translationEnabled(false) { manager = new WindowManager(this); refreshTimer = new QTimer(this); refreshTimer->setSingleShot(false); // keep refreshing refreshTimer->setInterval(RefreshInterval); connect(refreshTimer, SIGNAL(timeout()), SLOT(refresh())); connect(this, SIGNAL(updateContextMenuRequested(void*,void*)), SLOT(onUpdateContextMenuRequested(void*,void*)), Qt::QueuedConnection); ::instance_ = this; refreshTimer->start(); } WindowDriverPrivate::~WindowDriverPrivate() { ::instance_ = nullptr; } // - Text - QString WindowDriverPrivate::transformText(const QString &text, qint64 hash) const { QString ret; if (translationEnabled) { ret = manager->findTranslationWithHash(hash); //if (repl.isEmpty()) { // if (enabled) // manager->requestTranslation(text, hash); if (textVisible && !ret.isEmpty() && ret != text) ret.append(" / ") .append(text); //ret = QString("%1 / %2").arg(ret, text); } if (ret.isEmpty()) ret = text; return ret; } // - Processes and threads - void WindowDriverPrivate::updateThreadWindows(DWORD threadId) { WinIter::iterThreadChildWindows(threadId, [](HWND hWnd) { ::instance_->updateAbstractWindow(hWnd); }); //WinIter::iterThreadChildWindows(threadId, // boost::bind(&Self::updateAbstractWindow, ::instance_, _1)); } void WindowDriverPrivate::updateProcessWindows(DWORD processId) { WinIter::iterProcessThreadIds(processId, updateThreadWindows); } // - Windows - void WindowDriverPrivate::updateAbstractWindow(HWND hWnd) { wchar_t buf[TEXT_BUFFER_SIZE]; // https://msdn.microsoft.com/en-us/library/windows/desktop/ee671196%28v=vs.85%29.aspx if (::RealGetWindowClassW(hWnd, buf, TEXT_BUFFER_SIZE)) { if (!::wcscmp(buf, L"SysTabControl32")) { // Tab, TabItem updateTabControl(hWnd, buf, TEXT_BUFFER_SIZE); return; } if (!::wcscmp(buf, L"SysListView32")) { // DataGrid, List updateListView(hWnd, buf, TEXT_BUFFER_SIZE); return; } //DOUT(QString::fromUtf16(buf)); // Only translate selected controls //if (::wcscmp(buf, L"ComboBox") && // ::wcscmp(buf, L"ComboBoxEx32") && // ::wcscmp(buf, L"Edit") && // ::wcscmp(buf, L"ListBox") && // ::wcscmp(buf, L"SysLink") && // ::wcscmp(buf, L"SysTreeView32")) // return; } if (updateStandardWindow(hWnd, buf, TEXT_BUFFER_SIZE)) repaintWindow(hWnd); if (HMENU hMenu = ::GetMenu(hWnd)) if (updateMenu(hMenu, hWnd, buf, TEXT_BUFFER_SIZE)) repaintMenuBar(hWnd); } void WindowDriverPrivate::updateContextMenu(HMENU hMenu, HWND hWnd) { wchar_t buf[TEXT_BUFFER_SIZE]; updateMenu(hMenu, hWnd, buf, TEXT_BUFFER_SIZE); } void WindowDriverPrivate::repaintMenuBar(HWND hWnd) { ::DrawMenuBar(hWnd); } void WindowDriverPrivate::repaintWindow(HWND hWnd) { enum { MaximumRepaintCount = 5 }; static std::unordered_map<HWND, int> windows_; // 7/26/2015: Avoid repainting outer-most window // http://sakuradite.com/topic/981 // http://sakuradite.com/topic/994 auto p = windows_.find(hWnd); if (p == windows_.end()) windows_[hWnd] = 1; else { if (!::GetParent(hWnd)) // paint only once for root window return; if (p->second > MaximumRepaintCount) return; p->second++; } ::InvalidateRect(hWnd, nullptr, TRUE); } bool WindowDriverPrivate::updateStandardWindow(HWND hWnd, LPWSTR buffer, int bufferSize) { enum { TextRole = Window::WindowTextRole }; qint64 h = 0; int sz = ::GetWindowTextW(hWnd, buffer, bufferSize); if (sz) { #ifdef VNRAGENT_ENABLE_NTLEA // NTLEA could mess up the length of the string orz sz = ::wcslen(buffer); #endif // VNRAGENT_ENABLE_NTLEA h = Window::hashWCharArray(buffer, sz); } QString repl; long anchor = Window::hashWindow((WId)hWnd); const auto &e = manager->findEntryWithAnchor(anchor); if (!e.isEmpty()) repl = transformText(e.text, e.hash); else if (enabled && h && sz) { QByteArray data((const char *)buffer, sz * 2); repl = manager->decodeText(data); manager->addEntry(data, repl, h, anchor, TextRole); } // DefWindowProcW is used instead of SetWindowTextW // https://groups.google.com/forum/?fromgroups#!topic/microsoft.public.platformsdk.mslayerforunicode/nWi3dlZeS60 if (!repl.isEmpty() && h != Window::hashString(repl)) { if (repl.size() >= bufferSize) //::SetWindowTextW(hWnd, repl.utf16()); ::DefWindowProcW(hWnd, WM_SETTEXT, 0, (LPARAM)repl.utf16()); else { // faster memcpy(buffer, repl.utf16(), repl.size()); buffer[repl.size()] = 0; //repl.toWCharArray(buffer); //::SetWindowTextW(hWnd, buffer); ::DefWindowProcW(hWnd, WM_SETTEXT, 0, (LPARAM)buffer); } return true; } return false; } bool WindowDriverPrivate::updateMenu(HMENU hMenu, HWND hWnd, LPWSTR buffer, int bufferSize) { enum { TextRole = Window::MenuTextRole }; if (!hMenu) return false; int count = ::GetMenuItemCount(hMenu); if (count <= 0) return false; bool ret = false; MENUITEMINFOW info = {}; info.cbSize = sizeof(info); for (int i = 0; i < count; i++) { info.fMask = MIIM_SUBMENU | MIIM_TYPE | MIIM_ID; info.cch = bufferSize; info.dwTypeData = buffer; if (::GetMenuItemInfoW(hMenu, i, TRUE, &info)) { // fByPosition: TRUE if (int sz = info.cch) { #ifdef VNRAGENT_ENABLE_NTLEA // NTLEA could mess up the length of the string orz sz = ::wcslen(buffer); #endif // VNRAGENT_ENABLE_NTLEA qint64 h = Window::hashWCharArray(buffer, sz); QString repl; long anchor = Window::hashWindowItem((WId)hWnd, Window::MenuTextRole, (info.wID<<2) + (i<<4)); const auto &e = manager->findEntryWithAnchor(anchor); if (!e.isEmpty()) repl = transformText(e.text, e.hash); else if (enabled && h && sz) { QByteArray data((const char *)buffer, sz * 2); QString t = QString::fromUtf16(buffer, sz); //repl = manager->decodeText(data); // disable transcoding menu text repl = QString::fromUtf16(buffer, sz); manager->addEntry(data, repl, h, anchor, TextRole); } if (!repl.isEmpty() && h != Window::hashString(repl)) { int sz = qMin(repl.size(), bufferSize); info.fMask = MIIM_STRING; info.dwTypeData = buffer; info.cch = sz; memcpy(info.dwTypeData, repl.utf16(), sz); info.dwTypeData[sz] = 0; //repl.toWCharArray(info.dwTypeData); ::SetMenuItemInfoW(hMenu, i, TRUE, &info); ret = true; } } if (info.hSubMenu) ret = updateMenu(info.hSubMenu, hWnd, buffer, bufferSize) || ret; } } return ret; } bool WindowDriverPrivate::updateTabControl(HWND hWnd, LPWSTR buffer, int bufferSize) { enum { TextRole = Window::TabTextRole }; bool ret = false; LRESULT count = ::SendMessageW(hWnd, TCM_GETITEMCOUNT, 0, 0); TCITEMW item = {}; for (int i = 0; i < count; i++) { item.mask = TCIF_TEXT; item.pszText = buffer; item.cchTextMax = bufferSize; if (!::SendMessageW(hWnd, TCM_GETITEM, i, (LPARAM)&item)) break; int sz = ::wcslen(item.pszText); if (!sz) continue; qint64 h = Window::hashWCharArray(buffer, sz); QString repl; long anchor = Window::hashWindowItem((WId)hWnd, TextRole, i); const auto &e = manager->findEntryWithAnchor(anchor); if (!e.isEmpty()) repl = transformText(e.text, e.hash); else if (enabled && h && sz) { QByteArray data((const char *)buffer, sz * 2); repl = manager->decodeText(data); manager->addEntry(data, repl, h, anchor, TextRole); } if (!repl.isEmpty() && h != Window::hashString(repl)) { ret = true; if (repl.size() < bufferSize) { //repl.toWCharArray(buffer); memcpy(buffer, repl.utf16(), repl.size()); buffer[repl.size()] = 0; item.pszText = buffer; item.mask = TCIF_TEXT; ::SendMessageW(hWnd, TCM_SETITEM, i, (LPARAM)&item); } else { wchar_t *w = new wchar_t[repl.size() +1]; //repl.toWCharArray(w); memcpy(w, repl.utf16(), repl.size()); w[repl.size()] = 0; item.pszText = w; item.mask = TCIF_TEXT; ::SendMessageW(hWnd, TCM_SETITEM, i, (LPARAM)&item); delete[] w; } } } return ret; } bool WindowDriverPrivate::updateListView(HWND hWnd, LPWSTR buffer, int bufferSize) { enum { TextRole = Window::ListTextRole }; enum { MAX_COLUMN = 100 }; bool ret = false; for (int i = 0; i < MAX_COLUMN; i++) { LVCOLUMNW column = {}; column.mask = LVCF_TEXT; column.pszText = buffer; column.cchTextMax = bufferSize; if (!ListView_GetColumn(hWnd, i, &column)) break; int sz = ::wcslen(buffer); if (!sz) continue; qint64 h = Window::hashWCharArray(buffer, sz); QString repl; long anchor = Window::hashWindowItem((WId)hWnd, TextRole, i); const auto &e = manager->findEntryWithAnchor(anchor); if (!e.isEmpty()) repl = transformText(e.text, e.hash); else if (enabled && h && sz) { QByteArray data((const char *)buffer, sz * 2); repl = manager->decodeText(data); manager->addEntry(data, repl, h, anchor, TextRole); } if (!repl.isEmpty() && h != Window::hashString(repl)) { ret = true; if (repl.size() < bufferSize) { //repl.toWCharArray(buffer); memcpy(buffer, repl.utf16(), repl.size()); buffer[repl.size()] = 0; column.mask = TCIF_TEXT; column.pszText = buffer; ListView_SetColumn(hWnd, i, &column); } else { wchar_t *w = new wchar_t[repl.size() +1]; //repl.toWCharArray(w); memcpy(buffer, repl.utf16(), repl.size()); w[repl.size()] = 0; column.mask = TCIF_TEXT; column.pszText = w; ListView_SetColumn(hWnd, i, &column); delete[] w; } } } return ret; } // EOF /* // - Helpers - void WindowDriverPrivate::updateWindows() { QHash<HWND, uint> w; foreach (const auto &e, manager->entries()) w[e.window] |= e.role; enum { BUFFER_SIZE = 256 }; wchar_t buf[BUFFER_SIZE]; for (auto it = w.begin(); it != w.end(); ++it) { HWND h = it.key(); if (::IsWindow(h)) { uint roles = it.value(); if (roles & Window::WindowTextRole) updateWindow(h, buf, BUFFER_SIZE); if (roles & Window::MenuTextRole) if (HMENU hMenu = ::GetMenu(h)) { updateMenu(hMenu, h, buf, BUFFER_SIZE); ::DrawMenuBar(h); } } inline bool NotSupportedWindow(HWND hWnd) { enum { bufsz = 64 }; char buf[bufsz]; return !::RealGetWindowClassA(hWnd, buf, bufsz) || ::strcmp(buf, "ComboBox") && ::strcmp(buf, "ComboBoxEx32") && ::strcmp(buf, "Edit") && ::strcmp(buf, "ListBox") && ::strcmp(buf, "SysLink") && ::strcmp(buf, "SysTreeView32"); } */
#include<bits/stdc++.h> using namespace std; #define maxn 100005 int n,m; int square[3][maxn]; int pre[3][maxn]; int ans[maxn]; int k,l,r; int main() { memset(ans,1000000,sizeof(ans)); scanf("%d%d",&n,&m); for(int i=1; i<=n; i++) { for(int j=1; j<=m; j++) { scanf("%d",&square[i%2][j]); if(i==1) { pre[i%2][j]=1; } else if(i>1) { if(square[i%2][j]>=square[(i-1)%2][j]) { pre[i%2][j]=pre[(i-1)%2][j]; } else { pre[i%2][j]=i; } } if(j>1){ ans[i]=min(ans[i],pre[i%2][j]); printf("pre=%d %d ",pre[i%2][j],ans[i]); } } printf("%d ",ans[i]); } scanf("%d",&k); for(int i=0;i<k;i++){ scanf("%d%d",&l,&r); if(ans[r]<=l) printf("Yes"); else printf("No"); printf("\n"); } return 0; } /* #include <iostream> #include <cstdio> #include <vector> #include <algorithm> using namespace std; vector<int> x; int s[100010]; int c[100010]; int main() { int n,m; scanf("%d%d",&n,&m); int i,j; int temp; int Min; fill(c,c+100002,1); for(i=1;i<=n;i++) { Min=1000000010; for(j=1;j<=m;j++) { scanf("%d",&temp); if(temp>=s[j]) { } else { c[j]=i; } if(Min>c[j]) Min=c[j]; s[j]=temp; } x.push_back(Min); // cout<<Min<<endl; } int y; scanf("%d",&y); int f,g; for(i=0;i<y;i++) { scanf("%d%d",&f,&g); if(x[g-1]<=f) { printf("Yes\n"); } else { printf("No\n"); } } return 0; } */
#include <iostream> // We are going to create a videogame log class class Log { public: enum Level { levelError, levelWarning, levelInfo }; private: Level m_LogLevelM = levelInfo; public: void setLevel(Level level) { m_LogLevelM = level; } void warn(const char* message) { if (m_LogLevelM >= levelWarning) { std::cout << "[WARNING]: " << message << std::endl; } } void info(const char* message) { if (m_LogLevelM >= levelInfo) { std::cout << "[INFO]: " << message << std::endl; } } void error(const char* message) { if (m_LogLevelM >= levelError) { std::cout << "[ERROR]: " << message << std::endl; } } }; int main() { Log log; log.setLevel(Log::levelError); log.warn("Hello"); log.info("Hello"); log.error("Hello"); std::cin.get(); }
/* * UserRepositoryImpl.cc * * Created on: Nov 11, 2017 * Author: cis505 */ #include "UserRepositoryImpl.h" using namespace std; //Status UserRepositoryImpl::GetUser(ServerContext* context, const GetUserRequest* request, UserDTO* user) { // // cerr << "Received a request for user" << endl; // // TODO: This is where we would retrieve the user data from the key-store (BigTable) // // using the data from in the request to find the user // user->set_username("user1"); // user->set_password("password1"); // user->set_nickname("nickname1"); // // cerr << "Returning the following user:" << endl; // cerr << user->SerializeAsString() << endl; // // return Status::OK; //} Status UserRepositoryImpl::GetUser(ServerContext* context, const GetUserRequest* request, UserDTO* user) { cerr << "Received a request for user" << endl; // TODO: This is where we would retrieve the user data from the key-store (BigTable) // using the data from in the request to find the user // --- Below is Modified by Yuding Nov 21 --------- string usrPassword = bigTablePtr->get(request->username(),"password"); // cerr<<"BE usrPassword is "<< usrPassword<<endl; // string usrNickname = bigTablePtr->get(request->username(),"nickname"); if(usrPassword == ""){ // the user don't exist user->set_username("notfound"); } else { user->set_username(request->username()); user->set_password(usrPassword); // user->set_nickname(usrNickname); } cerr<< "BE | GetUser(): Password is " << user->password() << " user name is "<<user->username()<<endl; cerr << "Returning the following user:" << endl; cerr << user->SerializeAsString() << endl; return Status::OK; } Status UserRepositoryImpl::CreateUser(ServerContext* context, const UserDTO* request, CreateUserResponse* response) { // TODO: Add the user to the key-value store // Nov 21, modified by Yuding cerr<<"Username = " << request->username() << " password = \"" << request->password()<<"\""<< endl; bigTablePtr->put(request->username(), "password","password", request->password().size(), request->password().c_str()); // bigTablePtr->print(); response->set_success(true); response->set_message("Successfully added user " + request->username()); string usrPassword = bigTablePtr->get(request->username(),"password"); cerr<<"BE | CreateUser(): usrPassword is \""<< usrPassword<<"\""<< endl; bigTablePtr->print(); return Status::OK; }
/* Cheat that uses a driver for reading / writing virtual memory, instead of using Win32API Functions. Written By Zer0Mem0ry, https://www.youtube.com/watch?v=sJdBtPosWQs */ #include <Windows.h> #include <vector> #include <string> /* IOCTL Codes needed for our driver */ // Request to read virtual user memory (memory of a program) from kernel space #define IO_READ_REQUEST CTL_CODE(FILE_DEVICE_UNKNOWN, 0x0700 /* Our Custom Code */, METHOD_BUFFERED, FILE_SPECIAL_ACCESS) // Request to write virtual user memory (memory of a program) from kernel space #define IO_WRITE_REQUEST CTL_CODE(FILE_DEVICE_UNKNOWN, 0x0701 /* Our Custom Code */, METHOD_BUFFERED, FILE_SPECIAL_ACCESS) // Request to check if is valid address #define IO_IS_VALID_ADDRESS CTL_CODE(FILE_DEVICE_UNKNOWN, 0x0702 /* Our Custom Code */, METHOD_BUFFERED, FILE_SPECIAL_ACCESS) // Request to retrieve the process id of csgo process, from kernel space #define IO_SET_PROCESS_NAME_REQUEST CTL_CODE(FILE_DEVICE_UNKNOWN, 0x0703 /* Our Custom Code */, METHOD_BUFFERED, FILE_SPECIAL_ACCESS) // Request to retrieve the module base/size of process, from kernel space #define IO_GET_MODULE_REQUEST CTL_CODE(FILE_DEVICE_UNKNOWN, 0x0704 /* Our Custom Code */, METHOD_BUFFERED, FILE_SPECIAL_ACCESS) // Request to retrieve the module base/size of process, from kernel space #define IO_VIRTUAL_QUERY_REQUEST CTL_CODE(FILE_DEVICE_UNKNOWN, 0x0705 /* Our Custom Code */, METHOD_BUFFERED, FILE_SPECIAL_ACCESS) // Request virtual memory protection on address/size from kernel space #define IO_PROTECT_VIRTUAL_MEMORY_REQUEST CTL_CODE(FILE_DEVICE_UNKNOWN, 0x0706 /* Our Custom Code */, METHOD_BUFFERED, FILE_SPECIAL_ACCESS) // Request to retrieve the base address of client.dll in csgo.exe from kernel space #define IO_GET_BASE_ADDRESS CTL_CODE(FILE_DEVICE_UNKNOWN, 0x0707 /* Our Custom Code */, METHOD_BUFFERED, FILE_SPECIAL_ACCESS) // Offset to force jump action #define FORCE_JUMP 0x04F5FD5C // offset to local player #define LOCAL_PLAYER 0x00AA66D4 #define FFLAGS 0x00000100 // structure definitions typedef struct _MODULE_INFO { UINT64 Base; ULONG Size; WCHAR Name[1024]; } MODULE_INFO, *PMODULE_INFO; typedef struct _KERNEL_READ_REQUEST { UINT64 Address; // Source SIZE_T Size; PVOID Response; // Target } KERNEL_READ_REQUEST, * PKERNEL_READ_REQUEST; typedef struct _KERNEL_WRITE_REQUEST { UINT64 Address; // Target PVOID Value; // Source SIZE_T Size; BOOLEAN BytePatching; } KERNEL_WRITE_REQUEST, *PKERNEL_WRITE_REQUEST; typedef struct _KERNEL_MODULE_REQUEST { MODULE_INFO buffer; WCHAR moduleName[1024]; } KERNEL_MODULE_REQUEST, * PKERNEL_MODULE_REQUEST; typedef struct _MEMORY_REQUEST { ULONG ProcessId; KERNEL_READ_REQUEST read; KERNEL_WRITE_REQUEST write; KERNEL_MODULE_REQUEST module; } MEMORY_REQUEST; typedef struct _VIRTUAL_QUERY_REQUEST { ULONG ProcessId; UINT64 Address; // Target MEMORY_BASIC_INFORMATION info; } VIRTUAL_QUERY_REQUEST, *PVIRTUAL_QUERY_REQUEST; typedef struct _PROTECT_VIRTUAL_MEMORY_REQUEST { ULONG ProcessId; UINT64 Address; // Target DWORD size; ULONG NewAccessProtection; ULONG OldAccessProtection; } PROTECT_VIRTUAL_MEMORY_REQUEST, *PPROTECT_VIRTUAL_MEMORY_REQUEST; typedef struct _GET_PROCESS_ID_REQUEST { ULONG ProcessId; wchar_t processName[256]; } GET_PROCESS_ID_REQUEST, *PGET_PROCESS_ID_REQUEST; // interface for our driver class KeInterface { public: HANDLE hDriver; // Handle to driver // Initializer KeInterface::KeInterface(LPCSTR RegistryPath) { hDriver = CreateFileA(RegistryPath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0); } template <typename type> type ReadVirtualMemory(ULONG ProcessId, ULONG ReadAddress, SIZE_T Size, PVOID OutputBuffer = NULL) { if (hDriver == INVALID_HANDLE_VALUE) return (type)NULL; DWORD dwBytes; MEMORY_REQUEST memoryRequest = { 0 }; type ReturnValue = NULL; memoryRequest.ProcessId = ProcessId; memoryRequest.read.Address = ReadAddress; memoryRequest.read.Size = Size; if (OutputBuffer) memoryRequest.read.Response = OutputBuffer; else memoryRequest.read.Response = static_cast<void*>(&ReturnValue); // send code to our driver with the arguments if (DeviceIoControl(hDriver, IO_READ_REQUEST, &memoryRequest, sizeof(memoryRequest), &memoryRequest, sizeof(memoryRequest), &dwBytes, NULL)) return (type)(OutputBuffer ? 0 : ReturnValue); else return (type)NULL; } template <typename type> std::basic_string<type> ReadString(ULONG ProcessId, ULONG ReadAddress, SIZE_T Size = 256) { if (hDriver == INVALID_HANDLE_VALUE) return (type)NULL; DWORD dwBytes; MEMORY_REQUEST memoryRequest = { 0 }; std::basic_string<type> buffer(Size, type()); memoryRequest.ProcessId = ProcessId; memoryRequest.read.Address = ReadAddress; memoryRequest.read.Size = buffer.size(); memoryRequest.read.Response = static_cast<void*>(&buffer[0]); // send code to our driver with the arguments if (DeviceIoControl(hDriver, IO_READ_REQUEST, &memoryRequest, sizeof(memoryRequest), &memoryRequest, sizeof(memoryRequest), &dwBytes, NULL)) return std::basic_string<type>(buffer.data()); else return std::basic_string<type>(); } bool WriteVirtualMemory(ULONG ProcessId, ULONG WriteAddress, ULONG WriteValue, SIZE_T WriteSize) { if (hDriver == INVALID_HANDLE_VALUE) return false; DWORD dwBytes; MEMORY_REQUEST memoryRequest = { 0 }; memoryRequest.ProcessId = ProcessId; memoryRequest.write.Address = WriteAddress; memoryRequest.write.Value = (PVOID)WriteValue; memoryRequest.write.Size = WriteSize; if (DeviceIoControl(hDriver, IO_WRITE_REQUEST, &memoryRequest, sizeof(memoryRequest), 0, 0, &dwBytes, NULL)) return true; else return false; } BOOLEAN IsValidAddress(ULONG ProcessId, ULONG ReadAddress) { if (hDriver == INVALID_HANDLE_VALUE) return 0; DWORD dwBytes; BOOLEAN isValid = FALSE; //TODO: Only reason this works is because it recasts ProcessId to BOOLEAN lol could be risky if struct changes. - HighGamer VIRTUAL_QUERY_REQUEST moduleList; moduleList.ProcessId = ProcessId; moduleList.Address = ReadAddress; if (DeviceIoControl(hDriver, IO_IS_VALID_ADDRESS, (LPVOID)&moduleList, sizeof(VIRTUAL_QUERY_REQUEST), &isValid, sizeof(BOOLEAN), &dwBytes, NULL)) return isValid; else return FALSE; } DWORD GetModulesInformation(MEMORY_REQUEST* moduleList) { if (hDriver == INVALID_HANDLE_VALUE) return 0; DWORD dwBytes; if (DeviceIoControl(hDriver, IO_GET_MODULE_REQUEST, moduleList, sizeof(MEMORY_REQUEST), moduleList, sizeof(MEMORY_REQUEST), &dwBytes, NULL)) return 1; else return 0; } DWORD VirtualQueryInfo(VIRTUAL_QUERY_REQUEST* moduleList) { if (hDriver == INVALID_HANDLE_VALUE) return 0; DWORD dwBytes; if (DeviceIoControl(hDriver, IO_VIRTUAL_QUERY_REQUEST, moduleList, sizeof(VIRTUAL_QUERY_REQUEST), moduleList, sizeof(VIRTUAL_QUERY_REQUEST), &dwBytes, NULL)) return 1; else return 0; } DWORD ProtectVirtualMemory(PROTECT_VIRTUAL_MEMORY_REQUEST* virtualMemoryRequest) { if (hDriver == INVALID_HANDLE_VALUE) return 0; DWORD dwBytes = 0; if (DeviceIoControl(hDriver, IO_PROTECT_VIRTUAL_MEMORY_REQUEST, virtualMemoryRequest, sizeof(PROTECT_VIRTUAL_MEMORY_REQUEST), virtualMemoryRequest, sizeof(PROTECT_VIRTUAL_MEMORY_REQUEST), &dwBytes, NULL)) return 1; else return 0; } DWORD GetTargetProcessId(wchar_t* processName) { if (hDriver == INVALID_HANDLE_VALUE) return false; DWORD dwBytes; GET_PROCESS_ID_REQUEST processIdRequest; processIdRequest.ProcessId = 0; wcscpy(processIdRequest.processName, processName); if (DeviceIoControl(hDriver, IO_SET_PROCESS_NAME_REQUEST, &processIdRequest, sizeof(GET_PROCESS_ID_REQUEST), &processIdRequest, sizeof(GET_PROCESS_ID_REQUEST), &dwBytes, NULL)) return processIdRequest.ProcessId; else return 0; } DWORD GetClientBaseAddressModule() { if (hDriver == INVALID_HANDLE_VALUE) return false; ULONG Address; DWORD dwBytes; if (DeviceIoControl(hDriver, IO_GET_BASE_ADDRESS, &Address, sizeof(Address), &Address, sizeof(Address), &dwBytes, NULL)) return Address; else return false; } };
#include "GnSystemPCH.h" #include "GnMemoryObject.h" #if !defined(NI_DISABLE_EXCEPTIONS) #include <exception> // for std::bad_alloc #include <new> #endif #ifdef GN_MEMORY_DEBUGGER void* GnMemoryObject::operator new(gsize stSize) #if defined(NI_DISABLE_EXCEPTIONS) throw() #endif { #if defined(NI_DISABLE_EXCEPTIONS) return NULL; #else throw std::bad_alloc(); #endif } void* GnMemoryObject::operator new[](gsize stSize) #if defined(NI_DISABLE_EXCEPTIONS) throw() #endif { #if defined(NI_DISABLE_EXCEPTIONS) return NULL; #else throw std::bad_alloc(); #endif } void* GnMemoryObject::operator new(gsize stSizeInBytes, const char* pcSourceFile, int iSourceLine, const char* pcFunction) { if (stSizeInBytes == 0) stSizeInBytes = 1; void* p = GnMemoryManager::Instance()->Allocate(stSizeInBytes, GN_MEM_ALIGNMENT, GN_OPER_NEW, true, pcSourceFile, iSourceLine, pcFunction); #if !defined(NI_DISABLE_EXCEPTIONS) if (p == 0) throw std::bad_alloc(); #endif return p; } void* GnMemoryObject::operator new[](gsize stSizeInBytes, const char* pcSourceFile, int iSourceLine, const char* pcFunction) { if (stSizeInBytes == 0) stSizeInBytes = 1; void* p = GnMemoryManager::Instance()->Allocate(stSizeInBytes, GN_MEM_ALIGNMENT, GN_OPER_NEW_ARRAY, false, pcSourceFile, iSourceLine, pcFunction); #if !defined(NI_DISABLE_EXCEPTIONS) if (p == 0) throw std::bad_alloc(); #endif return p; } #else // #ifdef GN_MEMORY_DEBUGGER void* GnMemoryObject::operator new(gsize stSizeInBytes) { if (stSizeInBytes == 0) stSizeInBytes = 1; void* p = GnMemoryManager::Instance()->Allocate(stSizeInBytes, GN_MEM_ALIGNMENT, GN_OPER_NEW, true); #if !defined(NI_DISABLE_EXCEPTIONS) if (p == 0) throw std::bad_alloc(); #endif return p; } void* GnMemoryObject::operator new[](gsize stSizeInBytes) { if (stSizeInBytes == 0) stSizeInBytes = 1; void* p = GnMemoryManager::Instance()->Allocate(stSizeInBytes, GN_MEM_ALIGNMENT, GN_OPER_NEW_ARRAY, false); #if !defined(NI_DISABLE_EXCEPTIONS) if (p == 0) throw std::bad_alloc(); #endif return p; } #endif // #ifdef GN_MEMORY_DEBUGGER void GnMemoryObject::operator delete(void* pvMem, gsize stElementSize) { if (pvMem) { GnMemoryManager::Instance()->Deallocate(pvMem, GN_OPER_DELETE, stElementSize); } } void GnMemoryObject::operator delete[](void* pvMem, gsize stElementSize) { if (pvMem) { GnMemoryManager::Instance()->Deallocate(pvMem, GN_OPER_DELETE_ARRAY); } }
#include<iostream> #include<map> #include<iterator> #include<string> using namespace std; int main() { //Map object creation //2d map map<int, map<int, int>> m; //to access map value use iterator //To access the outer iterator map<int, map<int, int>> ::iterator outer_itr=m.begin(); //To access the outer iterator map<int, int> ::iterator inner_itr; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { m[i][j] = i + j; } } //earth and sun for (outer_itr = m.begin(); outer_itr != m.end(); outer_itr++) { cout << outer_itr->first << " : "; for (inner_itr = outer_itr->second.begin(); inner_itr != outer_itr->second.end(); inner_itr++) { cout << inner_itr->first <<" "<< inner_itr->second<<" | "; } cout << endl; } return 0; }
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * 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 Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <string> #include <fstream> #include <iostream> #include <octomap/octomap.h> #include <cstdlib> #include <cstring> using namespace std; using namespace octomap; int main(int argc, char **argv) { //bool rotate = false; // Fix orientation of webots-exported files bool show_help = false; string outputFilename(""); string inputFilename(""); // double minX = 0.0; // double minY = 0.0; // double minZ = 0.0; // double maxX = 0.0; // double maxY = 0.0; // double maxZ = 0.0; // bool applyBBX = false; // bool applyOffset = false; octomap::point3d offset(0.0, 0.0, 0.0); double scale = 1.0; double res = -1.0; if(argc == 1) show_help = true; for(int i = 1; i < argc && !show_help; i++) { if(strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-help") == 0 || strcmp(argv[i], "--usage") == 0 || strcmp(argv[i], "-usage") == 0 || strcmp(argv[i], "-h") == 0 ) show_help = true; } if(show_help) { cout << "Usage: "<<argv[0]<<" [OPTIONS] <filename.bt>" << endl; cout << "\tOPTIONS:" << endl; cout << "\t -o <file> Output filename (default: first input filename + .bt)" << endl; // cout << "\t --mark-free Mark not occupied cells as 'free' (default: unknown)" << endl; // cout << "\t --rotate Rotate left by 90 deg. to fix the coordinate system when exported from Webots" << endl; cout << "\t --offset <x> <y> <z>: add an offset to the octree coordinates (translation)\n"; // cout << "\t --bb <minx> <miny> <minz> <maxx> <maxy> <maxz>: force bounding box for OcTree" << endl; cout << "\t --res <resolution>: set ressolution of OcTree to new value\n"; cout << "\t --scale <scale>: scale octree resolution by a value\n"; exit(0); } for(int i = 1; i < argc; i++) { // Parse command line arguments if(strcmp(argv[i], "--rotate") == 0) { OCTOMAP_WARNING_STR(argv[i] << " not yet implemented!\n"); //rotate = true; continue; } else if(strcmp(argv[i], "-o") == 0 && i < argc - 1) { i++; outputFilename = argv[i]; continue; } else if (strcmp(argv[i], "--bb") == 0 && i < argc - 7) { OCTOMAP_WARNING_STR(argv[i] << " not yet implemented!\n"); i++; //minX = atof(argv[i]); i++; //minY = atof(argv[i]); i++; //minZ = atof(argv[i]); i++; //maxX = atof(argv[i]); i++; //maxY = atof(argv[i]); i++; //maxZ = atof(argv[i]); //applyBBX = true; continue; } else if (strcmp(argv[i], "--res") == 0 && i < argc - 1) { i++; res = atof(argv[i]); continue; } else if (strcmp(argv[i], "--scale") == 0 && i < argc - 1) { i++; scale = atof(argv[i]); continue; } else if (strcmp(argv[i], "--offset") == 0 && i < argc - 4) { OCTOMAP_WARNING_STR(argv[i] << " not yet implemented!\n"); i++; offset(0) = (float) atof(argv[i]); i++; offset(1) = (float) atof(argv[i]); i++; offset(2) = (float) atof(argv[i]); //applyOffset = true; continue; } else if (i == argc-1){ inputFilename = string(argv[i]); } } if (outputFilename == ""){ outputFilename = inputFilename + ".edit.bt"; } OcTree* tree = new OcTree(0.1); if (!tree->readBinary(inputFilename)){ OCTOMAP_ERROR("Could not open file, exiting.\n"); exit(1); } // apply scale / resolution setting: if (scale != 1.0){ res = tree->getResolution() * scale; } if (res > 0.0){ std::cout << "Setting new tree resolution: " << res << std::endl; tree->setResolution(res); } // TODO: implement rest (move, bounding box, rotation...) // size = width * height * depth; // double res = double(scale)/double(depth); // // if(!tree) { // cout << "Generate labeled octree with leaf size " << res << endl << endl; // tree = new OcTree(res); // } // // if (applyBBX){ // cout << "Bounding box for Octree: [" << minX << ","<< minY << "," << minZ << " - " // << maxX << ","<< maxY << "," << maxZ << "]\n"; // // } // if (applyOffset){ // std::cout << "Offset on final map: "<< offset << std::endl; // // } // // // if(rotate) { // endpoint.rotate_IP(M_PI_2, 0.0, 0.0); // } // if (applyOffset) // endpoint += offset; // // if (!applyBBX || (endpoint(0) <= maxX && endpoint(0) >= minX // && endpoint(1) <= maxY && endpoint(1) >= minY // && endpoint(2) <= maxZ && endpoint(2) >= minZ)){ // // // mark cell in octree as free or occupied // if(mark_free || value == 1) { // tree->updateNode(endpoint, value == 1); // } // } else{ // nr_voxels_out ++; // } // } // // // prune octree // cout << "Prune octree" << endl << endl; // tree->prune(); // write octree to file cout << "Writing octree to " << outputFilename << endl; if (!tree->writeBinary(outputFilename)){ OCTOMAP_ERROR("Error writing tree to %s\n", outputFilename.c_str()); exit(1); } cout << "done" << endl << endl; delete tree; return 0; }
class PartWheel { weight = 10; }; class PartFueltank { weight = 10; }; class PartGlass { weight = 5; }; class PartEngine { weight = 15; }; class PartVRotor { weight = 15; }; class PartFueltankBroken { weight = 10; }; class PartWheelBroken { weight = 10; }; class PartEngineBroken { weight = 15; }; class PartVRotorBroken { weight = 15; }; class PartGlassBroken { weight = 5; }; // PartGeneric can be found under Items\Metal.hpp
#include "outputwindow.h" #include <QHBoxLayout> #include <QTextEdit> #include <QToolBar> #include <QToolButton> #include <QDebug> OutputWindow::OutputWindow(QWidget *parent) :QWidget(parent) { m_editor = new QTextEdit; m_editor->setReadOnly(true); m_toolBar = new QToolBar; QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->addWidget(m_toolBar); mainLayout->addWidget(m_editor); mainLayout->setSpacing(0); mainLayout->setContentsMargins(0, 0, 0, 0); mainLayout->setMargin(0); setup(); setLayout(mainLayout); } void OutputWindow::showMessages(QByteArray message) { m_editor->append(message); } void OutputWindow::debug() { // TO do qDebug() << "Show debug messages"; } void OutputWindow::info() { qDebug() << "Show info messages"; } void OutputWindow::setup() { QToolButton *clearButton = new QToolButton(); clearButton->setText("&Clear"); QToolButton *debugButton = new QToolButton(); debugButton->setText("&Debug"); connect(clearButton, SIGNAL(clicked(bool)), m_editor, SLOT(clear())); connect(debugButton, SIGNAL(clicked(bool)), this, SLOT(debug())); m_toolBar->addWidget(clearButton); m_toolBar->addWidget(debugButton); }
#include<iostream> using namespace std; typedef struct node { int value; struct node *next; }qu; qu *front=NULL,*rear=NULL; void store(int data); void retrieve(); int main() { int data,prompt=1; while(prompt!=0) { cout<<"Enter <1>To store data\n"<<endl; cout<<"Enter <2>To retrieve data\n"<<endl; cout<<"Enter <0>To exit\n"<<endl; cout<<"Enter your choice: "<<endl; cin>>prompt; switch(prompt) { case 1: cout<<"\nEnter data to store"<<endl; cin>>data; store(data); break; case 2: retrieve(); break; case 0: break; } } return 0; } void store(int data) { qu *temp=NULL; temp=new qu; if(temp==NULL) { cout<<"!!! Queu overflow !!!\n\n"<<endl; return; } temp->value=data; temp->next=NULL; if(front==NULL) { front=temp; rear=temp; } else { rear->next=temp; rear=temp; } } void retrieve() { qu *temp; if(front==NULL) { cout<<"!!! Queu underflow !!!\n\n"<<endl; return; } temp=front; cout<<"Value retrieved is "<<front->value<<"\n\n"; if(front==rear) { front=NULL; rear=NULL; } else { front=front->next; } delete temp; }
// // Created by kamlesh on 30/10/15. // #ifndef PIGEON_HTTP_SERVER_H #define PIGEON_HTTP_SERVER_H namespace pigeon { class http_server { private: void init_parser(); void init_server(); public: void start(); }; } #endif //PIGEON_HTTP_SERVER_H
// // Created by 송지원 on 2020/06/29. // #include <iostream> #include <queue> #include <utility> using namespace std; #define X first #define Y second int M, N; int box[1005][1005]; int vis[1005][1005]; int dx[4] = {1, 0, -1, 0}; int dy[4] = {0, 1, 0, -1}; int cnt_input[3] = {0}; //-1, 0, 1 int change_cnt = 0; int DAY = 0; void print_box() { cout << "===================\n"; for (int i=0; i<N; i++) { for (int j=0; j<M; j++) { cout << box[i][j] << " "; } cout << "\n"; } } int main() { ios::sync_with_stdio(0); cin.tie(0); queue<pair<int, int>> Q; cin >> M >> N; for (int i=0; i<N; i++){ for (int j=0; j<M; j++) { cin >> box[i][j]; cnt_input[box[i][j]+1]++; if (box[i][j] == 1) { Q.push({i, j}); vis[i][j] = 1; } } } if (cnt_input[1] == 0) { cout << "0"; return 0; } while (!Q.empty()) { cout << DAY; print_box(); DAY++; // cout << Q.size() << ">>>\n"; queue<pair<int,int>> temp_Q; int size = Q.size(); for (int x=0; x<size; x++) { auto cur = Q.front(); Q.pop(); cout << "\ncur:[" << cur.X << "," << cur.Y <<"]"; for (int dir=0; dir<4; dir++) { int nx = cur.X + dx[dir]; int ny = cur.Y + dy[dir]; if (nx<0 || nx >= N || ny<0 || ny>=M ) continue; if (vis[nx][ny] || box[nx][ny] != 0) continue; cout << "\tnx:" <<nx << ", ny:" << ny; temp_Q.push({nx, ny}); vis[nx][ny] = 1; change_cnt++; box[nx][ny] = 1; } } while (!temp_Q.empty()) { Q.push(temp_Q.front()); temp_Q.pop(); } } if (change_cnt == cnt_input[1]) cout << --DAY; else cout << "-1"; }
#include<graphics.h> #include<iostream.h> #include<conio.h> #include<math.h> void main() { int gd=DETECT,gm; int x1,y1,x2,y2,m,x,y; initgraph(&gd,&gm,"C:\\TC\\BGI"); x=0; cout<<"Enter left cordinate:"; cin>>x1>>y1; cout<<"Enter right cordinate:"; cin>>x2>>y2; m=abs((y2-y2)/(x2-x1)); cout<<"Slope"<<m; y=y1; for(x=x1;x<=x2;x++) { putpixel(x,abs(y),RED); y=y+m; } getch(); closegraph(); restorecrtmode(); }
/* * File: main.cpp * Author: Daniel Canales * * Created on June 30, 2014, 5:37 PM */ #include <cstdlib> #include <iostream> using namespace std; /* * */ int main(int argc, char** argv) { float home; // value of home cout << "What is the value of your home? " << endl; cin >> home; float insur = home*.8; cout << "The minimun amount of insurance you should purchase is " << insur << endl; return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2008 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #ifndef _MATCHURL_TESTMAN_H_ #define _MATCHURL_TESTMAN_H_ #if defined(SELFTEST) #include "modules/network_selftest/urldoctestman.h" class MatchWithURL_Tester : public URL_DocSelfTest_Item { protected: class MatchURLLoader : public URL_DocumentLoader { private: MatchWithURL_Tester *parent; public: MatchURLLoader(MatchWithURL_Tester *prnt):parent(prnt){} virtual void OnAllDocumentsFinished(); }; MatchURLLoader loader; URL match_url; URL_InUse match_url_use; public: MatchWithURL_Tester():loader(this){}; MatchWithURL_Tester(URL &a_url, URL &ref, URL &mtch_url,BOOL unique=TRUE) : URL_DocSelfTest_Item(a_url, ref, unique), loader(this),match_url(mtch_url),match_url_use(mtch_url) {}; virtual ~MatchWithURL_Tester(){} OP_STATUS Construct(){return url.IsValid() && match_url.IsValid() ? OpStatus::OK : OpStatus::ERR;} OP_STATUS Construct(URL &a_url, URL &ref, URL &match_base, URL &mtch_url, BOOL unique=TRUE); OP_STATUS Construct(const OpStringC8 &source_url, URL &ref, URL &match_base, const OpStringC8 &mtch_url, BOOL unique=TRUE); OP_STATUS Construct(const OpStringC &source_url, URL &ref, URL &match_base, const OpStringC &mtch_url, BOOL unique=TRUE); virtual BOOL Verify_function(URL_DocSelfTest_Event event, Str::LocaleString status_code=Str::NOT_A_STRING); virtual void MatchURLs_Loaded(); }; #endif #endif // _MATCHURL_TESTMAN_H_
#include "GnSystemPCH.h" #include "GnStandardAllocator.h" #define IS_POWER_OF_TWO(x) (((x)&(x-1)) == 0) void* GnStandardAllocator::Allocate(gsize& stSizeInBytes, gsize& stAlignment, GnMemoryEventType eEventType, bool bProvideAccurateSizeOnDeallocate) { GnAssert(IS_POWER_OF_TWO(stAlignment)); return GnExternalAlignedMalloc(stSizeInBytes, stAlignment); } void* GnStandardAllocator::Reallocate(void* pvMemory, gsize& stSizeInBytes, gsize& stAlignment, GnMemoryEventType eEventType, bool bProvideAccurateSizeOnDeallocate, gsize stSizeCurrent) { GnAssert(IS_POWER_OF_TWO(stAlignment)); // The deallocation case should have been caught by us before in // the allocation functions. GnAssert(stSizeInBytes != 0); return GnExternalAlignedRealloc(pvMemory, stSizeInBytes, stAlignment); } void GnStandardAllocator::Deallocate(void* pvMemory, GnMemoryEventType eEventType, gsize stSizeInBytes) { if (pvMemory == NULL) return; GnExternalAlignedFree(pvMemory); } void GnStandardAllocator::Initialize() { } void GnStandardAllocator::Shutdown() { }
// Created on: 1997-02-11 // Created by: Alexander BRIVIN and Dmitry TARASOV // Copyright (c) 1997-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Vrml_MaterialBinding_HeaderFile #define _Vrml_MaterialBinding_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <Vrml_MaterialBindingAndNormalBinding.hxx> #include <Standard_OStream.hxx> //! defines a MaterialBinding node of VRML specifying properties of geometry //! and its appearance. //! Material nodes may contain more than one material. This node specifies how the current //! materials are bound to shapes that follow in the scene graph. Each shape node may //! interpret bindings differently. For example, a Sphere node is always drawn using the first //! material in the material node, no matter what the current MaterialBinding, while a Cube //! node may use six different materials to draw each of its six faces, depending on the //! MaterialBinding. class Vrml_MaterialBinding { public: DEFINE_STANDARD_ALLOC Standard_EXPORT Vrml_MaterialBinding(const Vrml_MaterialBindingAndNormalBinding aValue); Standard_EXPORT Vrml_MaterialBinding(); Standard_EXPORT void SetValue (const Vrml_MaterialBindingAndNormalBinding aValue); Standard_EXPORT Vrml_MaterialBindingAndNormalBinding Value() const; Standard_EXPORT Standard_OStream& Print (Standard_OStream& anOStream) const; protected: private: Vrml_MaterialBindingAndNormalBinding myValue; }; #endif // _Vrml_MaterialBinding_HeaderFile
#include<bits/stdc++.h> using namespace std; const int siz=50005; int tr[siz<<2]; void pushup(int rt){ tr[rt]=tr[rt<<1]+tr[rt<<1|1]; } void build(int l,int r,int rt){ int mid; if(l==r){ scanf("%d",&tr[rt]); return; } mid=(l+r)>>1; build(l,mid,rt<<1); build(mid+1,r,rt<<1|1); pushup(rt); } void change(int p,int q,int l,int r,int rt){ int mid; if(l==r){ tr[rt]+=q; return; } mid=(l+r)>>1; if(p<=mid) change(p,q,l,mid,rt<<1); else change(p,q,mid+1,r,rt<<1|1); pushup(rt); } int query(int L,int R,int l,int r,int rt){ int ans,mid; if(L<=l&&r<=R) return tr[rt]; ans=0,mid=(l+r)>>1; if(L<=mid) ans+=query(L,R,l,mid,rt<<1); if(R>mid) ans+=query(L,R,mid+1,r,rt<<1|1); return ans; }
#pragma once #include "gameNode.h" class Phoenix : public gameNode { private: float _x, _y; image* img; RECT _rc; bool isFire; float speed; int _count; int _index; public: Phoenix() {} ~Phoenix() {} HRESULT init(); void release(); void update(); void render(); void fire(float x , float y); void bulletMove(); void anim(); void bulletOut(); RECT getPhoenixRect() { return _rc; } };
#pragma once #include "AvatarLogic.h" #include "Core.h" class IALogic : public AvatarLogic { public: IALogic(); virtual ~IALogic(); public: virtual void computeNextAction(const float elapsedTime, AvatarEntity* ,AvatarLogicInfo ); private: int m_commonThresholds[4][4]; float m_timeout; ActionManager::actions m_last_actions; bool m_approach; };
#include "ros/ros.h" #include "std_msgs/String.h" #include "beginner_tutorials/Num.h" #include "custom_messages/driveMessage.h" #include "std_msgs/Float32.h" #include "std_msgs/Int16.h" #include "beginner_tutorials/driveCmd.h" #include "math.h" class PID_Event_Trig { ros::NodeHandle n; ros::Publisher pub_teleop; ros::Subscriber vp_subscribe; //subscriber for vanishing point beginner_tutorials::driveCmd tele_cmd; // public: //Parameters for PID float sampling_rate; //sampling rate in hz, make it match the estimator/ // error signal gen rate float ub; // upper and lower bounds on control signal float lb; // same for throttle and steering as of now // PID gains float Kp_vel; float Kd_vel; float Ki_vel; float Kp_steer; float Kd_steer; float Ki_steer; //sampling rate for PID using Euler float h; // For vanishing point error signal float temp_steer_float; int temp_steer_int; // variables for PID for velocity and steering float u_km1_vel; // u(k-1) float u_k_vel; // u(k) float e_km1_vel; // e(k-1) float e_km2_vel; // e(k-2) float e_k_vel; // e(k) float u_km1_steer; // u(k-1) float u_k_steer; // u(k) float e_km1_steer; // e(k-1) float e_km2_steer; // e(k-2) float e_k_steer; // e(k) float ff_vel; //feed forward term for vel float ff_steer; //ff term for steer float SaturateSignal(float signal, const float lb, const float ub); // function to act as saturator // void vp_listen(const std_msgs::Int16::ConstPtr& msg); //everything happens on callback to this public: PID_Event_Trig(void) { // create publisher pub_teleop = n.advertise<beginner_tutorials::driveCmd>("teleop_commands",1000); // subscribe to vanishing point vp_subscribe = n.subscribe("vanishing_point_topic",1000,&PID_Event_Trig::vp_listen,this); tele_cmd.steering = 0; tele_cmd.throttle = 0; pub_teleop.publish(tele_cmd); ROS_INFO("Initialised motors with 0 throttle and steering"); // init PID params sampling_rate = 22; //in Hz h = 1/sampling_rate; ub = 5; lb = -5; temp_steer_float = 0; temp_steer_int = 0; Kp_vel = 0; Kd_vel = 0; Ki_vel = 0; Kp_steer = 5; Kd_steer = 0; Ki_steer = 0.1; //init vars u_km1_vel = 0; u_k_vel = 0; e_km1_vel = 0; e_km2_vel = 0; e_k_vel = 0; ff_vel = 0; u_km1_steer = 0; u_k_steer = 0; e_km1_steer = 0; e_km2_steer = 0; e_k_steer = 0; ff_steer = 0; } void vp_listen(const std_msgs::Float32::ConstPtr& msg) { ROS_INFO("I Heard vp"); temp_steer_float = msg->data; //temp_steer_float = 1.0*temp_steer_int; // this goes to e_k_steer PID_Event_Trig::PID_Event_steer(); PID_Event_Trig::PID_Event_vel(); PID_Event_Trig::PublishCommand(); } /* void PID_Event_steer(); void PID_Event_vel(); void PublishCommand();*/ void PID_Event_vel() { // PID for velocity // feed forward term if any for vel ff_vel = 0.5; //error signal for velocity //progress time first, information is old e_km2_vel = e_km1_vel; e_km1_vel = e_k_vel; e_k_vel = 0; //compute e_k u_km1_vel = u_k_vel; u_k_vel = u_km1_vel + (1/h)*(Kp_vel*h + Kd_vel + Ki_vel*h*h)*e_k_vel + (1/h)*(-Kp_vel*h-2*Kd_vel)*e_km1_vel + (1/h)*Kd_vel*e_km2_vel; } void PID_Event_steer() { // PID for steering // feed forward term if any for steer ff_steer = 0; //error signal for steering //progress time first, information is old e_km2_steer = e_km1_steer; e_km1_steer = e_k_steer; e_k_steer = temp_steer_float; //compute e_k u_km1_steer = u_k_steer; u_k_steer = u_km1_steer + (1/h)*(Kp_steer*h + Kd_steer + Ki_steer*h*h)*e_k_steer + (1/h)*(-Kp_steer*h-2*Kd_steer)*e_km1_steer + (1/h)*Kd_steer*e_km2_steer; } void PublishCommand() { //check between -5 and +5 publish tele_cmd.steering = u_k_steer + ff_steer; tele_cmd.throttle = u_k_vel + ff_vel; tele_cmd.steering = SaturateSignal(tele_cmd.steering,ub,lb); // saturator tele_cmd.throttle = SaturateSignal(tele_cmd.throttle,ub,lb); ROS_INFO("Steering: %f; Throttle %f", tele_cmd.steering, tele_cmd.throttle); pub_teleop.publish(tele_cmd); } }; float PID_Event_Trig::SaturateSignal(float signal, const float ub, const float lb) { if(signal<=ub && signal>=lb) signal=signal; else if(signal>ub) signal = ub; else if(signal<lb) signal = lb; return signal; } int main(int argc, char **argv) { ros::init(argc,argv,"PID_Euler_EventTrig"); PID_Event_Trig pid; // ROS_INFO("B_S"); ros::spin(); // ROS_INFO("A_S"); return 0; }
#pragma once #include "ofMain.h" class sphere : public ofBaseApp{ public: sphere(); //constructor ~sphere(); //deconstructor void setup(int posX, int posY, int posZ, int size); void update(); void draw(); ofSpherePrimitive sphereShell; int sphereRadius, sphereRes, spherePulse, counter, alpha, timeOfDay; float rotation; ofColor colorChange; ofVec3f point; };
#include "MyWnd.h" MY_IMPLEMENT_DYNCREATE(CMyWnd, CMyCmdTarget) CMyWnd::CMyWnd() { MyOutPutDebugString(_T("CMyWnd::CMyWnd()")); } CMyWnd::~CMyWnd() { MyOutPutDebugString(_T("CMyWnd::~CMyWnd()")); }
#include<iostream> using namespace std; int main() { int a,b; cout<<"Enter two numbers:"; cin>>a>>b; cout<<a<<"=="<<b<<"="<<(a==b); cout<<"\n"; cout<<a<<"!="<<b<<"="<<(a!=b); return 0; }
#include "AuthorizationManager.h" boost::property_tree::ptree AuthorizationManager::loginUser(boost::property_tree::ptree &params) { auto login = params.get<std::string>("body.login"); if (dbConnector.userIsRegistered(login)) { std::cout << "TUT"; dbConnector.authorizeUser(login); dbConnector.getUserInfo(params); params.add("status", "true"); params.add("error", ""); params.add("body.ip", "192.168.0.70"); params.add("body.port", "5556"); } else { params.add("status", "false"); params.add("error", "Not registered"); } return params; } boost::property_tree::ptree AuthorizationManager::logoutUser(boost::property_tree::ptree &params) { auto login = params.get<std::string>("body.login"); if (dbConnector.userIsAuthorized(login)) { dbConnector.logoutUser(login); params.add("status", "true"); params.add("error", ""); } else { params.add("error", "User not login"); params.add("status", "false"); } return params; }
// Copyright (c) 2019, tlblanc <tlblanc1490 at gmail dot com> #ifndef OS_EVENTLOOP_H_ #define OS_EVENTLOOP_H_ #include "aio.hpp" #include "channel.hpp" #include "status.hpp" #include <chrono> class EventLoopException final { public: EventLoopException(const char *msg, int err): m_msg(msg), m_err(err){ } inline const char *msg() const noexcept { return m_msg; } inline int err() const noexcept { return m_err; } private: const char *m_msg; const int m_err; }; class EventLoop final { public: enum class MonitorMode { level, edge }; struct Properties final { struct Builder final { Builder &timeout(std::chrono::milliseconds timeout) { m_timeout = timeout; return *this; } Builder &inactivity(std::chrono::milliseconds inactivity) { m_inactivity = inactivity; return *this; } Builder &max_fd(int max_fd) { m_max_fd = max_fd; return *this; } Builder &event_queue_size(size_t event_queue_size) { m_event_queue_size = event_queue_size; return *this; } Properties build() { return Properties(m_timeout, m_inactivity, m_max_fd, m_event_queue_size); } std::chrono::milliseconds m_timeout; std::chrono::milliseconds m_inactivity; int m_max_fd = 1024; size_t m_event_queue_size = 512; }; Properties(const std::chrono::milliseconds &timeout, const std::chrono::milliseconds &inactivity, const int max_fd, const size_t event_queue_size): m_timeout(timeout), m_inactivity(inactivity), m_max_fd(max_fd), m_event_queue_size(event_queue_size) { } inline std::chrono::milliseconds timeout() const noexcept { return m_timeout; } inline std::chrono::milliseconds inactivity() const noexcept { return m_inactivity; } inline int max_fd() const noexcept { return m_max_fd; } inline int event_queue_size() const noexcept { return m_event_queue_size; } const std::chrono::milliseconds m_timeout; const std::chrono::milliseconds m_inactivity; const int m_max_fd; const size_t m_event_queue_size; }; EventLoop(); explicit EventLoop(const Properties &properties); ~EventLoop(); EventLoop(const EventLoop &loop) = delete; EventLoop(EventLoop &&loop): m_timeout(loop.m_timeout), m_inactivity(loop.m_inactivity), m_max_fd(loop.m_max_fd), m_event_queue_size(loop.m_event_queue_size) { m_fd = loop.m_fd; loop.m_fd = -1; } EventLoop& operator=(const EventLoop &loop) = delete; EventLoop& operator=(EventLoop &&loop) = delete; /// monitor monitors the channel for read and write events /// with the specified MonitorMode Status monitor(Channel *channel, MonitorMode mode) noexcept; /// rmonitor monitors the channel for read events /// with the specified MonitorMode Status rmonitor(Channel *channel, MonitorMode mode) noexcept; /// wmonitor monitors the channel for write events /// with the specified MonitorMode Status wmonitor(Channel *channel, MonitorMode mode) noexcept; /// unmonitor the event loop stops /// monitoring any events for that channel Status unmonitor(Channel *channel) noexcept; /// runmonitor the event loop stops /// monitoring read events for that channel Status runmonitor(Channel *channel) noexcept; /// wunmonitor the event loop stops /// monitoring read events for that channel Status wunmonitor(Channel *channel) noexcept; /// run the event loop and starts processing /// events for the monitored channels Status run() noexcept; private: int m_fd; const std::chrono::milliseconds m_timeout; const std::chrono::milliseconds m_inactivity; const int m_max_fd; const size_t m_event_queue_size; }; #endif // OS_EVENTLOOP_H_
// Created on: 1995-04-24 // Created by: Modelistation // Copyright (c) 1995-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _ChFiDS_ChamfSpine_HeaderFile #define _ChFiDS_ChamfSpine_HeaderFile #include <Standard.hxx> #include <Standard_Real.hxx> #include <ChFiDS_ChamfMethod.hxx> #include <ChFiDS_Spine.hxx> class ChFiDS_ChamfSpine; DEFINE_STANDARD_HANDLE(ChFiDS_ChamfSpine, ChFiDS_Spine) //! Provides data specific to chamfers //! distances on each of faces. class ChFiDS_ChamfSpine : public ChFiDS_Spine { public: Standard_EXPORT ChFiDS_ChamfSpine(); Standard_EXPORT ChFiDS_ChamfSpine(const Standard_Real Tol); Standard_EXPORT void SetDist (const Standard_Real Dis); Standard_EXPORT void GetDist (Standard_Real& Dis) const; Standard_EXPORT void SetDists (const Standard_Real Dis1, const Standard_Real Dis2); Standard_EXPORT void Dists (Standard_Real& Dis1, Standard_Real& Dis2) const; Standard_EXPORT void GetDistAngle (Standard_Real& Dis, Standard_Real& Angle) const; Standard_EXPORT void SetDistAngle (const Standard_Real Dis, const Standard_Real Angle); Standard_EXPORT void SetMode (const ChFiDS_ChamfMode theMode); //! Return the method of chamfers used Standard_EXPORT ChFiDS_ChamfMethod IsChamfer() const; //! Return the mode of chamfers used //Standard_EXPORT ChFiDS_ChamfMode Mode() const; DEFINE_STANDARD_RTTIEXT(ChFiDS_ChamfSpine,ChFiDS_Spine) protected: private: Standard_Real d1; Standard_Real d2; //Standard_Boolean dison1; Standard_Real angle; ChFiDS_ChamfMethod mChamf; }; #endif // _ChFiDS_ChamfSpine_HeaderFile
#include<iostream> #include<algorithm> using namespace std; int countPair(int x[],int n1,int y[],int n2){ stable_sort(y,y+n2); int freq[5]={0}; for(int i=0;i<n2;i++){ if(y[i]<5){ freq[y[i]]++; } } int ans=0; for(int i=0;i<n1;i++){ if(x[i]==0){ continue; } if(x[i]==1){ ans+=freq[0]; continue; } auto idx=upper_bound(y,y+n2,x[i]); ans+=(y+n2-idx)+freq[0]+freq[1]; if(x[i]==2){ ans-=(freq[3]+freq[4]); } if(x[i]==3){ ans+=freq[2]; } } return ans; } int main(int argc, char const *argv[]) { int x[]={2,3,4,5}; int y[]={1,2,3}; int n1=4; int n2=3; int a=countPair(x,n1,y,n2); cout<<x[14]; return 0; }
#include <unistd.h> #include <errno.h> #include <sys/shm.h> #include <thread> #include <vector> #include <iostream> #include <algorithm> #include <memory.h> #include <clock.h> #include <tools.h> #include <sysv_shm.h> int main() { std::vector<char> b(202,0); std::generate(b.begin(),b.end(),[](){return rand()&0xFF;}); std::cout<<format_bin(&b.front(),b.size())<<std::endl; return 0; sysv_shm t; t.open("TEST",1); if(t.num_attach()>1) { printf("nattach=%d\n",t.num_attach()); return 0; } while(true) { printf("nattach=%d\n",t.num_attach()); sleep(1); } return 0; }
/***************************************************************************************************************** * File Name : PrimeNumberChecker.h * File Location : C:\Users\AVINASH\Desktop\CC++\Programming\src\tutorials\topcoder\number theory\PrimeNumberChecker.h * Created on : Jan 23, 2014 :: 7:33:59 PM * Author : AVINASH * Testing Status : TODO * URL : TODO *****************************************************************************************************************/ /************************************************ Namespaces ****************************************************/ using namespace std; using namespace __gnu_cxx; /************************************************ User Includes *************************************************/ #include <string> #include <vector> #include <cstdlib> #include <cstdio> #include <cmath> #include <algorithm> #include <ctime> #include <list> #include <map> #include <set> #include <bitset> #include <functional> #include <utility> #include <iostream> #include <fstream> #include <sstream> #include <string.h> #include <hash_map> #include <stack> #include <queue> #include <limits.h> #include <programming/ds/tree.h> #include <programming/ds/linkedlist.h> #include <programming/utils/treeutils.h> #include <programming/utils/llutils.h> /************************************************ User defined constants *******************************************/ #define null NULL /************************************************* Main code ******************************************************/ #ifndef PRIMENUMBERCHECKER_H_ #define PRIMENUMBERCHECKER_H_ bool checkIfNumberIsPrimeNaive(unsigned int userInput){ if(userInput == 1 || userInput == 0){ return false; } unsigned int sumOfDivisors = 0; for(unsigned int counter = 1;counter <= userInput;counter++){ if(userInput%counter == 0){ sumOfDivisors++; } } return sumOfDivisors == 2?true:false; } bool checkIfNumberIsPrime(unsigned int userInput){ if(userInput == 1 || userInput == 0){ return false; } if(userInput == 2){ return true; } unsigned int squareRootOfUserInput = sqrt(userInput); bool isPrimeNumber = true; for(unsigned int counter = 2;counter <= squareRoot;counter++){ if(userInput % counter == 0){ isPrimeNumber = false; break; } } return isPrimeNumber; } #endif /* PRIMENUMBERCHECKER_H_ */ /************************************************* End code *******************************************************/
#pragma once #include <exception> #include <memory> #include <type_traits> #include <boost/iterator/counting_iterator.hpp> #define MAYBE_UNUSED(var) (void)var struct throw_reaction { void operator () () { throw std::invalid_argument ("convert null pointer to not_null");} }; template<typename T, typename NULL_REACTION = throw_reaction> class not_null { public: template<typename U> not_null (U data) : not_null_data_ (data) { static_assert (std::is_pointer<T>::value, "not_null could only accept pointers"); if (not_null_data_ == nullptr) NULL_REACTION()(); } operator T () { return not_null_data_; } template<typename OTHER> not_null operator = (OTHER that) noexcept { not_null_data_ = that; } not_null operator = (const not_null& that) noexcept { not_null_data_ = that.not_null_data_; if (not_null_data_ == nullptr) { NULL_REACTION () (); } } T operator -> () { return not_null_data_; } template<typename OTHER> not_null (const not_null<OTHER>& that) noexcept { not_null_data_ = that.get (); } T get () const noexcept {return not_null_data_; } ~not_null () = default; private: T not_null_data_; }; template<typename DATA, typename BINOP> struct value_guard { value_guard (DATA ref) :ref_ (ref) { if (!(BINOP () (ref_))) { throw std::logic_error ("cannot construct value_guard"); } } private: DATA ref_; }; namespace std { template< class T > constexpr bool is_function_v = is_function<T>::value; template< class Base, class Derived > constexpr bool is_base_of_v = is_base_of<Base, Derived>::value; template< class T > constexpr bool is_member_pointer_v = is_member_pointer<T>::value; } namespace detail { template <class T> struct is_reference_wrapper : std::false_type {}; template <class U> struct is_reference_wrapper<std::reference_wrapper<U>> : std::true_type {}; template <class T> constexpr bool is_reference_wrapper_v = is_reference_wrapper<T>::value; template <class Base, class T, class Derived, class... Args> auto INVOKE(T Base::*pmf, Derived&& ref, Args&&... args) noexcept(noexcept((std::forward<Derived>(ref).*pmf)(std::forward<Args>(args)...))) -> std::enable_if_t<std::is_function_v<T> && std::is_base_of_v<Base, std::decay_t<Derived>>, decltype((std::forward<Derived>(ref).*pmf)(std::forward<Args>(args)...))> { return (std::forward<Derived>(ref).*pmf)(std::forward<Args>(args)...); } template <class Base, class T, class RefWrap, class... Args> auto INVOKE(T Base::*pmf, RefWrap&& ref, Args&&... args) noexcept(noexcept((ref.get().*pmf)(std::forward<Args>(args)...))) -> std::enable_if_t<std::is_function_v<T> && is_reference_wrapper_v<std::decay_t<RefWrap>>, decltype((ref.get().*pmf)(std::forward<Args>(args)...))> { return (ref.get().*pmf)(std::forward<Args>(args)...); } template <class Base, class T, class Pointer, class... Args> auto INVOKE(T Base::*pmf, Pointer&& ptr, Args&&... args) noexcept(noexcept(((*std::forward<Pointer>(ptr)).*pmf)(std::forward<Args>(args)...))) -> std::enable_if_t<std::is_function_v<T> && !is_reference_wrapper_v<std::decay_t<Pointer>> && !std::is_base_of_v<Base, std::decay_t<Pointer>>, decltype(((*std::forward<Pointer>(ptr)).*pmf)(std::forward<Args>(args)...))> { return ((*std::forward<Pointer>(ptr)).*pmf)(std::forward<Args>(args)...); } template <class Base, class T, class Derived> auto INVOKE(T Base::*pmd, Derived&& ref) noexcept(noexcept(std::forward<Derived>(ref).*pmd)) -> std::enable_if_t<!std::is_function_v<T> && std::is_base_of_v<Base, std::decay_t<Derived>>, decltype(std::forward<Derived>(ref).*pmd)> { return std::forward<Derived>(ref).*pmd; } template <class Base, class T, class RefWrap> auto INVOKE(T Base::*pmd, RefWrap&& ref) noexcept(noexcept(ref.get().*pmd)) -> std::enable_if_t<!std::is_function_v<T> && is_reference_wrapper_v<std::decay_t<RefWrap>>, decltype(ref.get().*pmd)> { return ref.get().*pmd; } template <class Base, class T, class Pointer> auto INVOKE(T Base::*pmd, Pointer&& ptr) noexcept(noexcept((*std::forward<Pointer>(ptr)).*pmd)) -> std::enable_if_t<!std::is_function_v<T> && !is_reference_wrapper_v<std::decay_t<Pointer>> && !std::is_base_of_v<Base, std::decay_t<Pointer>>, decltype((*std::forward<Pointer>(ptr)).*pmd)> { return (*std::forward<Pointer>(ptr)).*pmd; } template <class F, class... Args> auto INVOKE(F&& f, Args&&... args) noexcept(noexcept(std::forward<F>(f)(std::forward<Args>(args)...))) -> std::enable_if_t<!std::is_member_pointer_v<std::decay_t<F>>, decltype(std::forward<F>(f)(std::forward<Args>(args)...))> { return std::forward<F>(f)(std::forward<Args>(args)...); } } // namespace detail template< class F, class... ArgTypes > auto invoke(F&& f, ArgTypes&&... args) // exception specification for QoI noexcept(noexcept(detail::INVOKE(std::forward<F>(f), std::forward<ArgTypes>(args)...))) -> decltype(detail::INVOKE(std::forward<F>(f), std::forward<ArgTypes>(args)...)) { return detail::INVOKE(std::forward<F>(f), std::forward<ArgTypes>(args)...); } template<typename T> auto weak (T&& t) { std::weak_ptr<typename std::decay_t<T>::element_type> wp = t; return wp; } struct i_range { boost::counting_iterator<int> start; boost::counting_iterator<int> stop; auto begin () { return start; } auto end () { return stop; } }; inline auto step (int start, int stop) { return i_range {start, stop}; } inline auto step (int stop) { return step (0, stop); } #define S1(x) #x #define S2(x) S1(x) #define LOCATION " file: " __FILE__ " line: " S2(__LINE__) #define except(x) \ throw std::logic_error (x LOCATION)
#include <jni.h> #include <string> #include "x264.h" #include "librtmp/rtmp.h" #include "VideoChannel.h" #include "AudioChannel.h" #include "macro.h" #include "safe_queue.h" int isStart = 0;// 为了防止用户重复点击开始直播,导致重新初始化 VideoChannel *pVideoChannel; AudioChannel *pAudioChannel; pthread_t pid; uint32_t start_time;// 记录开始时间 int readyPushing = 0;// 是否准备好推流 // FIXME 提示 initialization of 'packets' with static storage duration may throw an exception that cannot be caught SafeQueue<RTMPPacket *> packets;// RTMP协议数据包队列,包含音频、视频 /** * 封装为RTMP数据后的回调,将数据添加到队列 * @param packet 按照RTMP协议封装的数据包 */ void callback(RTMPPacket *packet) { if (packet != nullptr) { // 设置时间戳 packet->m_nTimeStamp = RTMP_GetTime() - start_time; // 加入队列 packets.put(packet); LOG_D("等待上传 packet 大小: %d", packets.size()); } } void releasePackets(RTMPPacket *packet) { if (packet != nullptr) { RTMPPacket_Free(packet); delete packet; packet = nullptr; } } /** * 释放音频、视频资源 */ void releaseMediaChannel() { if (pVideoChannel != nullptr) { DELETE(pVideoChannel); } if (pAudioChannel != nullptr) { DELETE(pAudioChannel); } } /** * 被线程调用的指针函数,不断从队列中读取RTMP数据,向服务器推流 * @param args url * @return */ void *start(void *args) { char *url = static_cast<char *>(args); RTMP *pRTMP = RTMP_Alloc();// 申请内存 if (!pRTMP) { LOG_E("alloc rtmp 失败"); return nullptr; } RTMP_Init(pRTMP);// 初始化 int ret = RTMP_SetupURL(pRTMP, url);// 设置地址 if (!ret) { LOG_E("设置地址失败: %s", url); return nullptr; } pRTMP->Link.timeout = 5;// 超时时间 RTMP_EnableWrite(pRTMP);// 开启输出模式 ret = RTMP_Connect(pRTMP, nullptr);// 连接服务器 if (!ret) { LOG_E("连接服务器: %s", url); return nullptr; } ret = RTMP_ConnectStream(pRTMP, 0);// 连接流 if (!ret) { LOG_E("连接流: %s", url); return nullptr; } start_time = RTMP_GetTime(); packets.setWork(1);// 队列开始工作 callback(pAudioChannel->getAudioTag());// 将音频第一帧添加到队列 RTMPPacket *packet = nullptr; readyPushing = 1;// 准备推流状态 while (readyPushing) { packets.get(packet);// 队列取数据 if (!readyPushing) { break; } if (packet == nullptr) { continue; } packet->m_nInfoField2 = pRTMP->m_stream_id;// 设置流类型 ret = RTMP_SendPacket(pRTMP, packet, 1); releasePackets(packet);// packet 释放 LOG_D("上传后 packet 大小:%d", packets.size()); } isStart = 0; packets.setWork(0);// 队列停止工作 packets.clear();// 清空队列 RTMP_Close(pRTMP); RTMP_Free(pRTMP); delete (url); releaseMediaChannel(); return nullptr; } extern "C" JNIEXPORT void JNICALL Java_com_ff_push_LivePusher_native_1init(JNIEnv *env, jobject instance) { pVideoChannel = new VideoChannel; // 设置回调,当视频数据封装为RTMP数据后的回调 pVideoChannel->setVideoCallback(callback); pAudioChannel = new AudioChannel; // 设置回调,当音频数据封装为RTMP数据后的回调 pAudioChannel->setAudioCallback(callback); } extern "C" JNIEXPORT void JNICALL Java_com_ff_push_LivePusher_native_1start(JNIEnv *env, jobject instance, jstring path_) { if (isStart) { return; } isStart = 1; const char *path = env->GetStringUTFChars(path_, nullptr); // 因为开启线程,path_在方法结束后会销毁,这里新建一个变量 char *url = new char[strlen(path) + 1]; strcpy(url, path); // 参数1:线程id,pthread_t型指针 // 参数2:线程的属性,nullptr默认属性 // 参数3:线程创建之后执行的函数,函数指针,可以写&start,由于函数名就是函数指针,所以可以省略& // 参数4:start函数接受的参数,void型指针 pthread_create(&pid, nullptr, start, url); env->ReleaseStringUTFChars(path_, path); } extern "C" JNIEXPORT void JNICALL Java_com_ff_push_LivePusher_native_1setVideoInfo(JNIEnv *env, jobject instance, jint width, jint height, jint fps, jint bitrate) { if (!pVideoChannel) { return; } pVideoChannel->setVideoInfo(width, height, fps, bitrate); } extern "C" JNIEXPORT void JNICALL Java_com_ff_push_LivePusher_native_1pushVideo(JNIEnv *env, jobject instance, jbyteArray data_) { if (pVideoChannel == nullptr || !readyPushing) { return; } jbyte *data = env->GetByteArrayElements(data_, nullptr); // 这里data是I420编码 pVideoChannel->encodeData(data); env->ReleaseByteArrayElements(data_, data, 0); } extern "C" JNIEXPORT void JNICALL Java_com_ff_push_LivePusher_native_1setAudioInfo(JNIEnv *env, jobject instance, jint samplesInHZ, jint channels) { if (pAudioChannel != nullptr) { pAudioChannel->setAudioInfo(samplesInHZ, channels); } } extern "C" JNIEXPORT void JNICALL Java_com_ff_push_LivePusher_native_1pushAudio(JNIEnv *env, jobject instance, jbyteArray data_) { if (pAudioChannel == nullptr || !readyPushing) { return; } jbyte *data = env->GetByteArrayElements(data_, nullptr); pAudioChannel->encodeData(data); env->ReleaseByteArrayElements(data_, data, 0); } extern "C" JNIEXPORT jint JNICALL Java_com_ff_push_LivePusher_getInputSamples(JNIEnv *env, jobject instance) { if (pAudioChannel == nullptr) { return -1; } return pAudioChannel->getInputSamples(); } extern "C" JNIEXPORT void JNICALL Java_com_ff_push_LivePusher_native_1release(JNIEnv *env, jobject instance) { if (readyPushing) { readyPushing = 0; } else { releaseMediaChannel(); } }
// Created on: 2009-01-20 // Created by: Alexander A. BORODIN // Copyright (c) 2009-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Font_NListOfSystemFont_HeaderFile #define _Font_NListOfSystemFont_HeaderFile #include <NCollection_List.hxx> #include <Font_SystemFont.hxx> typedef NCollection_List<Handle(Font_SystemFont)> Font_NListOfSystemFont; inline Standard_Boolean IsEqual (const Handle(Font_SystemFont)& theFirstFont, const Handle(Font_SystemFont)& theSecondFont) { return theFirstFont->IsEqual (theSecondFont); } #endif
#include "BaseKeyTapListener.hpp" using namespace Leap; Gesture::Type BaseKeyTapListener::getGestureType() { return Gesture::TYPE_KEY_TAP; } void BaseKeyTapListener::onGestureDetected(const Gesture& gesture) { onKeyTap(KeyTapGesture(gesture)); }
#include <Dot++/lexer/Token.hpp> namespace dot_pp { namespace lexer { Token::Token() : type_(TokenType::string) { } Token::Token(const std::string& value, const TokenType type) : value_(value) , type_(type) { } bool Token::empty() const { if(type_ == TokenType::string_literal) { return false; } for(const auto c : value_) { if((c != '\n') && (c != '\r') && (c != '\t') && (c != ' ')) { return false; } } return true; } void Token::clear() { value_.clear(); type_ = TokenType::string; } }}
#include <PA9.h> #include "Blob.h" #include "Cell.h" #include "C3DSpriteData.h" #include "Team.h" #include "DSspecs.h" #include "STDfunctions.h" #include "all_gfx.h" #include "Scroll.h" #include "Sound.h" C3DSpriteData g_blobGfx[3] = { C3DSpriteData((void*)NULL, (void*)NULL, 32, 32, TEX_256COL), //fake neutral C3DSpriteData((void*)Blob_Red_Texture, (void*)Blob_Pal, 32, 32, TEX_256COL), C3DSpriteData((void*)Blob_Blue_Texture, (void*)Blob_Pal, 32, 32, TEX_256COL)}; void Blob::UpdateVelocity(){ u16 angle = PA_GetAngle(unfix(m_x), unfix(m_y), unfix(m_target->X()), unfix(m_target->Y())); m_vx = unfix(PA_Cos(angle)*m_velocity); m_vy = unfix(-PA_Sin(angle)*m_velocity); } Blob::Blob() :m_x((DS_WIDTH+64)<<8), m_y(0), m_team(TEAM_NONE), m_strength(0), m_radius(0), m_velocity(0), m_vx(0), m_vy(0), m_state(INACTIVE), m_target(NULL), m_id(MAX_3DSPRITES){ } Blob::Blob(s32 x, s32 y, TEAM team, u32 strength, u32 velocity, Cell * const target) :m_x(x), m_y(y), m_team(team), m_strength(strength), m_radius(0), m_velocity(velocity), m_vx(0), m_vy(0), m_state(INACTIVE), m_target(target), m_id(MAX_3DSPRITES){ } Blob::~Blob(){ } /* void Blob::Create(s32 x, s32 y, TEAM team, u32 strength, u32 velocity, Cell * const target){ m_x = x; m_y = y; m_team = team; m_strength = strength; m_radius = 0; m_velocity = velocity; m_vx = 0; m_vy = 0; m_state = INACTIVE; m_target = target; m_id = MAX_3DSPRITES; } void Blob::Destroy(){ } */ void Blob::Load(){ m_id = Create3DSprite(&g_blobGfx[Team2Id(m_team)], unfix(m_x), unfix(m_y)); } void Blob::Unload(){ Destroy3DSprite(m_id); m_id = MAX_3DSPRITES; } void Blob::Set(s32 x, s32 y, TEAM team, u32 strength, u32 velocity, Cell * const target){ SetXY(x, y); SetTeam(team); SetStrength(strength); SetVelocity(velocity); SetState(CREATION); SetTarget(target); } void Blob::Reset(){ PA_3DSetSpriteXY(m_id, DS_WIDTH+64, 0); SetTeam(TEAM_NONE); SetState(INACTIVE); } void Blob::SetXY(s32 x, s32 y){ m_x = x; m_y = y; PA_3DSetSpriteXY(m_id, unfix(m_x)-scrollx, unfix(m_y)-scrolly); } void Blob::SetTeam(TEAM team){ m_team = team; if(team!=TEAM_NONE){ g_blobGfx[Team2Id(m_team)].ChangeSpriteGraphics(m_id); } } void Blob::SetStrength(u32 strength){ m_strength = strength; m_radius = 2 + ((16*m_strength)>>7); PA_3DSetSpriteWidthHeight(m_id, (m_radius<<1), (m_radius<<1)); } void Blob::SetVelocity(u32 velocity){ m_velocity = velocity; UpdateVelocity(); } void Blob::SetTarget(Cell * const target){ m_target = target; } void Blob::SetState(BLOB_STATE state){ m_state = state; } s32 Blob::X()const{return m_x;} s32 Blob::Y()const{return m_y;} TEAM Blob::Team()const{return m_team;} u32 Blob::Strength()const{return m_strength;} u16 Blob::Radius()const{return m_radius;} s32 Blob::Velocity()const{return m_velocity;} s16 Blob::XVelocity()const{return m_vx;} s16 Blob::YVelocity()const{return m_vy;} BLOB_STATE Blob::State()const{return m_state;} u16 Blob::SpriteId()const{return m_id;} void Blob::Update(){ switch(m_state){ case INACTIVE: // //if(Stylus.Held) m_state = TRAVEL; break; case CREATION: m_state = TRAVEL; //break; case TRAVEL: if((u64)PA_Distance(unfix(m_x), unfix(m_y), unfix(m_target->X()), unfix(m_target->Y())) <= (u64)(m_radius+m_target->Radius())*(m_radius+m_target->Radius())){ m_state = DESTINATION; } else{ m_x += m_vx; m_y += m_vy; //scroll PA_3DSetSpriteXY(m_id, unfix(m_x)-scrollx, unfix(m_y)-scrolly); UpdateVelocity(); } break; case COLLISION: //jeej break; case DESTINATION: //Do stuff to target :D mmEffectCancelAll(); mmEffectRelease(mmEffect(SFX_BLUB)); m_target->TakeDamage(Team(), m_strength); Reset(); break; default: //ErrorMsg(DS_TOP,"blob class: unhandled state"); break; } }
// // Created by Brady Bodily on 4/22/17. // #ifndef ITAK_KEYVALUE_HPP #define ITAK_KEYVALUE_HPP #include "UserIP.hpp" #include <vector> #include <string> class KeyValue { public: std::string Key; KeyValue(); std::string GetKey(); std::vector<UserIP> GetValue(); std::vector<UserIP> Value; void SetKey(std::string key); void SetValue(std::vector<UserIP> value); void AddValue(UserIP ValueToAdd); KeyValue(std::string key, std::vector<UserIP> value); void AddToValue(UserIP valueToAdd); }; #endif //ITAK_KEYVALUE_HPP
// Copyright (c) 2021 ETH Zurich // Copyright (c) 2020 John Biddiscombe // Copyright (c) 2016 Thomas Heller // Copyright (c) 2016 Hartmut Kaiser // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // This file provides functionality similar to CUDA's built-in // cudaStreamAddCallback, with the difference that an event is recorded and an // pika scheduler polls for the completion of the event. When the event is ready, // a callback is called. #pragma once #include <pika/config.hpp> #include <pika/async_cuda/cuda_stream.hpp> #include <pika/functional/unique_function.hpp> #include <pika/threading_base/thread_pool_base.hpp> #include <whip.hpp> #include <string> namespace pika::cuda::experimental::detail { using event_callback_function_type = pika::util::detail::unique_function<void(whip::error_t)>; PIKA_EXPORT void add_event_callback(event_callback_function_type&& f, whip::stream_t stream, pika::execution::thread_priority = pika::execution::thread_priority::default_); PIKA_EXPORT void add_event_callback( event_callback_function_type&& f, cuda_stream const& stream); PIKA_EXPORT void register_polling(pika::threads::detail::thread_pool_base& pool); PIKA_EXPORT void unregister_polling(pika::threads::detail::thread_pool_base& pool); } // namespace pika::cuda::experimental::detail
// Project #12 Driver header file // CS-1410-X01-deBry-Fall 2015 // Miles Meacham // 10/11/2015 // ------------------------ #include <iostream> #include "MyVector.h" using namespace std; const int TEST_VALUE1 = 21; const int TEST_VALUE2 = 31; const int TEST_VALUE3 = 41; const int MAX = 12;
#include <iostream> using std::cin; using std::cout; const int SIZE = 5; // input size. int main(void) { int numero; int quant = 0; for(int i=0; i < SIZE; i++){ cin >> numero; if(numero < 0){ quant = quant + 1; } } cout << quant; return 0; }
/* * touch_dispatcher.h * * * */ #ifndef TOUCH_DISPATCHER_H #define TOUCH_DISPATCHER_H #include "mbed.h" #include <vector> #include "uLCD_4DLibrary.h" #include "singleton.h" #include "ulcd_rect.h" /* * public types * */ typedef enum { not_touched, touch_began, touch_moved, touch_ended } touch_event_t; /* * public class * */ class ulcd_component; class touch_dispatcher_delegate { public : virtual ~touch_dispatcher_delegate(){} virtual void did_touch_screen(ulcd_origin_t touch_point, touch_event_t touch_state){} }; class touch_dispatcher : public singleton<touch_dispatcher> { friend class singleton<touch_dispatcher>; private : vector<ulcd_component*> m_listening_components; uLCD_4DLibrary* m_lcd; touch_dispatcher(); ~touch_dispatcher(); public : void touch_periodic_task(); void add_register_component(ulcd_component* component); void clear_components(); void set_lcd(uLCD_4DLibrary* p_lcd); }; #endif
#include <CVMLParse.h> #include <cstring> bool CVML:: parse(const std::string &filename) { try { reset(); pc_ = 0; if (! parseFile(filename)) return false; } catch (CVMLError error) { std::cerr << error.msg << std::endl; return false; } return true; } bool CVML:: parseFile(const std::string &filename) { fileName_ = filename; line_num_ = 0; if (! CFile::exists(fileName_)) { std::cerr << "File \'" << fileName_ << "\' does not exist" << std::endl; return false; } file_ = new CFile(fileName_); bool eof; for (;;) { if (! parseNextLine(&eof)) { delete file_; return false; } if (eof) break; } delete file_; return true; } bool CVML:: parseNextLine(bool *eof) { *eof = false; if (! file_->readLine(line_)) { *eof = true; return true; } while (! line_.empty() && line_[line_.size() - 1] == '\\') { line_ = line_.substr(0, line_.size() - 1); std::string line1; if (! file_->readLine(line1)) break; line_ += line1; } ++line_num_; if (! parseLine()) { syntaxError(); return false; } return true; } bool CVML:: parseLine() { std::string identifier; parse_ = new CStrParse(line_); //----- parse_->skipSpace(); //----- // Process pre-processor line if (parse_->isChar('#')) { if (! parsePreProLine()) return false; return true; } //----- // Skip Comment if (parse_->isChar(';')) return true; //----- // Read optional label CVMLLabel *label = NULL; int dim = 0; if (parseLabel(identifier, &dim)) { label = addLabel(identifier); if (label == NULL) return false; } parse_->skipSpace(); //----- // If end of line then add label with zero value // (don't increment pc so next line will have same address) // TODO: handle disconnected labels if (parse_->eof() || parse_->isChar(';')) { if (label != NULL) parseLabels_.push_back(label); return true; } if (label != NULL) parseLabels_.push_back(label); //----- // Check for label followed by value if (! parseLabels_.empty() || parse_->isChar(':')) { if (parse_->isChar(':')) { parse_->skipChar(); parse_->skipSpace(); } CVMLData *data = NULL; if (parse_->isChar('.')) { int value; bool is_char; if (! parseValue(&value, &is_char)) return false; if (dim > 0) { if (is_char) data = new CVMLData(this, pc_, char(value), dim); else data = new CVMLData(this, pc_, ushort(value), dim); } else { if (is_char) data = new CVMLData(this, pc_, char(value)); else data = new CVMLData(this, pc_, ushort(value)); } } else if (parse_->isChar('\"')) { std::string str; if (! parseString(str)) return false; if (dim > 0) return false; CVMLStringId id = lookupStringId(str); data = new CVMLData(this, pc_, id); } if (data != NULL) { CVMLLine *line = NULL; auto numParseLabels = parseLabels_.size(); for (uint i = 0; i < numParseLabels; ++i) { CVMLLabel *label1 = parseLabels_[i]; line = new CVMLLine(label1, data); addLine(line); } parseLabels_.clear(); parse_->skipSpace(); if (! parse_->eof() && ! parse_->isChar(';')) return false; pc_ += line->getAddressLen(); return true; } } //----- if (dim > 0) return false; //----- // Read instruction if (parse_->isAlpha()) { if (! parseInstruction(identifier)) return false; CVMLOpCode *opCode = lookupOpCode(identifier); if (opCode == NULL) return false; parse_->skipSpace(); //----- // Read instruction arguments CVMLArgument **arguments = new CVMLArgument * [opCode->num_args]; for (uint i = 0; i < opCode->num_args; i++) { arguments[i] = new CVMLArgument(this); if (i > 0) { if (! parse_->isChar(',')) return false; parse_->skipChar(); parse_->skipSpace(); } if (! parseArgument(*arguments[i])) return false; parse_->skipSpace(); } //----- CVMLOp *op = new CVMLOp(*this, opCode, pc_, line_num_); for (uint i = 0; i < opCode->num_args; i++) op->setArgument(i, *arguments[i]); CVMLLine *line = NULL; if (! parseLabels_.empty()) { auto numParseLabels = parseLabels_.size(); for (uint i = 0; i < numParseLabels; ++i) { CVMLLabel *label1 = parseLabels_[i]; line = new CVMLLine(label1, op); addLine(line); } parseLabels_.clear(); } else { line = new CVMLLine(NULL, op); addLine(line); } pc_ += line->getAddressLen(); for (uint i = 0; i < opCode->num_args; i++) delete arguments[i]; delete [] arguments; } //----- parse_->skipSpace(); //----- if (! parse_->eof() && ! parse_->isChar(';')) return false; return true; } bool CVML:: parsePreProLine() { parse_->skipChar(); parse_->skipSpace(); std::string cmd; if (! parse_->readIdentifier(cmd)) return true; if (CStrUtil::casecmp(cmd, "include") == 0) { parse_->skipSpace(); std::string filename; if (! parse_->readString(filename)) return false; filename = filename.substr(1, filename.size() - 2); std::string save_filename = fileName_; int save_line_num = line_num_; bool flag = parseFile(filename); fileName_ = save_filename; line_num_ = save_line_num; return flag; } else { std::cerr << "Invalid command " << cmd << std::endl; return false; } return true; } bool CVML:: parseLabel(std::string &label, int *dim) { *dim = 0; parse_->skipSpace(); int pos = parse_->getPos(); if (! parse_->isIdentifier()) goto fail; if (! parse_->readIdentifier(label)) goto fail; parse_->skipSpace(); if (parse_->isChar('@')) { parse_->skipChar(); parse_->skipSpace(); if (parse_->isDigit()) { int i; if (! parse_->readInteger(&i)) goto fail; if (i < 0) goto fail; pc_ = i; parse_->skipSpace(); } } else if (parse_->isChar('[')) { parse_->skipChar(); parse_->skipSpace(); if (! parse_->readInteger(dim)) goto fail; if (*dim <= 0) goto fail; parse_->skipSpace(); if (! parse_->isChar(']')) goto fail; parse_->skipChar(); parse_->skipSpace(); } if (! parse_->isChar(':')) goto fail; parse_->skipChar(); return true; fail: parse_->setPos(pos); return false; } bool CVML:: parseArgument(CVMLArgument &argument) { int pos = parse_->getPos(); if (parse_->isChar('.')) { int value; bool is_char; if (parseValue(&value, &is_char)) { if (is_char) argument.setArgumentChar(char(value)); else argument.setArgumentInteger(ushort(value)); } else { parse_->skipChar(); if (parse_->isIdentifier()) { std::string identifier; if (! parse_->readIdentifier(identifier)) goto fail; argument.setArgumentVariableValue(identifier); } else goto fail; } } else { bool decrement = false; if (parse_->isChar('-')) { parse_->skipChar(); decrement = true; } std::string identifier; int reg_num, offset; if (parse_->isDigit()) { if (! parse_->readInteger(&offset)) goto fail; if (decrement) { offset = -offset; decrement = false; } argument.setArgumentInteger(ushort(offset)); } else { if (! parse_->readIdentifier(identifier)) goto fail; if (isRegister(identifier, &reg_num)) argument.setArgumentRegisterAddr(ushort(reg_num)); else argument.setArgumentVariableAddr(identifier); } if (parse_->isChar('[')) { CVMLArgument argument1(this); parse_->skipChar(); if (! parseArgument(argument1)) goto fail; if (! parse_->isChar(']')) goto fail; parse_->skipChar(); if (argument.getType() == CVML_ARGUMENT_VARIABLE_ADDR) argument.setType(CVML_ARGUMENT_VARIABLE_VALUE); if (argument.getType() != CVML_ARGUMENT_VARIABLE_VALUE && argument.getType() != CVML_ARGUMENT_INTEGER) goto fail; if (argument1.getType() != CVML_ARGUMENT_REGISTER_ADDR) goto fail; if (argument.getType() == CVML_ARGUMENT_VARIABLE_VALUE) argument.setArgumentRegisterVarOffset(ushort(argument1.getArgRegNum()), argument.getName()); else { short offset1 = unsignedToSigned(ushort(argument.getInteger())); argument.setArgumentRegisterOffset(ushort(argument1.getArgRegNum()), offset1); } if (parse_->isChar('^')) { parse_->skipChar(); if (argument.getType() == CVML_ARGUMENT_REGISTER_OFFSET) argument.setType(CVML_ARGUMENT_REGISTER_OFFSET_DEFERRED); else argument.setType(CVML_ARGUMENT_REGISTER_VAR_OFFSET_DEFERRED); } } else if (parse_->isChar('^')) { bool deferred = false; bool increment = false; parse_->skipChar(); if (parse_->isChar('^')) { deferred = true; parse_->skipChar(); } if (parse_->isChar('+')) { increment = true; parse_->skipChar(); } if (decrement && increment) goto fail; if (argument.getType() != CVML_ARGUMENT_REGISTER_ADDR) goto fail; argument.setType(CVML_ARGUMENT_REGISTER_VALUE); if (decrement) { if (deferred) argument.setType(CVML_ARGUMENT_REGISTER_VALUE_DEFERRED_DECR); else argument.setType(CVML_ARGUMENT_REGISTER_VALUE_DECR); } else if (increment) { if (deferred) argument.setType(CVML_ARGUMENT_REGISTER_VALUE_DEFERRED_INCR); else argument.setType(CVML_ARGUMENT_REGISTER_VALUE_INCR); } } else { if (decrement) goto fail; } } return true; fail: parse_->setPos(pos); return false; } bool CVML:: parseValue(int *value, bool *is_char) { int pos = parse_->getPos(); if (! parse_->isChar('.')) goto fail; parse_->skipChar(); if (parse_->isChar('\'')) { char c; parse_->skipChar(); std::string str; while (! parse_->eof()) { if (parse_->isChar('\\')) { if (! parse_->readChar(&c)) break; str += c; if (! parse_->eof()) { if (! parse_->readChar(&c)) break; str += c; } } else if (parse_->isChar('\'')) break; else { if (! parse_->readChar(&c)) goto fail; str += c; } } if (parse_->eof()) goto fail; parse_->skipChar(); if (! stringToChar(str, &c)) goto fail; *value = c; *is_char = true; } else if (parse_->isChar('-')) { int i; parse_->skipChar(); if (parse_->isDigit()) { if (! parse_->readInteger(&i)) goto fail; i = -i; *value = i; *is_char = false; } else goto fail; } else if (parse_->isChar('0')) { int i; if (! parse_->readBaseInteger(8, &i)) goto fail; *value = i; *is_char = false; } else if (parse_->isDigit()) { int i; if (! parse_->readInteger(&i)) goto fail; *value = i; *is_char = false; } else goto fail; return true; fail: parse_->setPos(pos); return false; } bool CVML:: parseString(std::string &str) { char c; int pos = parse_->getPos(); bool found = false; if (! parse_->isChar('\"')) goto fail; parse_->skipChar(); while (! parse_->eof()) { if (! parse_->readChar(&c)) goto fail; if (c == '\\') { if (! parse_->readChar(&c)) goto fail; if (c == 'b') str += '\b'; else if (c == 'n') str += '\n'; else if (c == 't') str += '\t'; else if (c == '0') str += '\0'; else if (c == '\'') str += '\''; else if (c == '\"') str += '\"'; else { std::cerr << "Invalid escape code" << std::endl; goto fail; } } else { if (c == '\"') { found = true; break; } str += c; } } if (! found) goto fail; return true; fail: parse_->setPos(pos); return false; } bool CVML:: parseInstruction(std::string &identifier) { int pos = parse_->getPos(); if (! parse_->isAlpha()) goto fail; char c; if (! parse_->readChar(&c)) goto fail; identifier = ""; identifier += c; while (! parse_->eof() && ! parse_->isSpace()) { if (! parse_->readChar(&c)) goto fail; identifier += c; } return true; fail: parse_->setPos(pos); return false; } //------------------------ bool CVML:: parseBin(const std::string &ifilename, const std::string &ofilename) { CFile file(ofilename); std::vector<ushort> codes; uint num_codes, size; reset(); if (! writeHeader(&file)) { std::cerr << "Invalid VML file" << std::endl; goto fail; } if (! writeStringTable(&file)) { std::cerr << "Bad String Table" << std::endl; goto fail; } if (! writeDebug(&file)) { std::cerr << "Bad Debug Section" << std::endl; goto fail; } if (! writeData(&file)) { std::cerr << "Bad Data Section" << std::endl; goto fail; } pc_ = 0; if (! parseBinFile(ifilename, codes)) goto fail; num_codes = uint(codes.size()); size = num_codes*sizeof(ushort); file.write(reinterpret_cast<uchar *>(&size), sizeof(size)); for (uint i = 0; i < num_codes; ++i) { ushort code = codes[i]; file.write(reinterpret_cast<uchar *>(&code), sizeof(code)); } file.close(); return true; fail: file.close(); return false; } bool CVML:: parseBinFile(const std::string &filename, std::vector<ushort> &codes) { fileName_ = filename; if (! CFile::exists(fileName_)) { std::cerr << "File \'" << fileName_ << "\' does not exist" << std::endl; return false; } file_ = new CFile(fileName_); while (file_->readLine(line_)) { ++line_num_; if (! parseBinLine(codes)) { syntaxError(); delete file_; return false; } } delete file_; return true; } bool CVML:: parseBinLine(std::vector<ushort> &codes) { parse_ = new CStrParse(line_); parse_->skipSpace(); std::string address, code; char c; while (parse_->isDigit()) { if (! parse_->readChar(&c)) goto fail; address += c; } parse_->skipSpace(); if (! parse_->isChar(':')) goto fail; if (! parse_->skipChar()) goto fail; parse_->skipSpace(); while (parse_->isDigit()) { if (! parse_->readChar(&c)) goto fail; code += c; } parse_->skipSpace(); if (! parse_->eof()) goto fail; int address_val, code_val; if (! CStrUtil::toBaseInteger(address, 8, &address_val)) goto fail; if (! CStrUtil::toBaseInteger(code , 8, &code_val )) goto fail; while (pc_ < ushort(address_val)) { codes.push_back(0); pc_ += 2; } codes.push_back(ushort(code_val)); pc_ += 2; return true; fail: return false; }
/* * 题目:1442. 形成两个异或相等数组的三元组数目 * 链接:https://leetcode-cn.com/problems/count-triplets-that-can-form-two-arrays-of-equal-xor/ * 知识点:前缀和 */ class Solution { public: // 三层循环 int countTriplets(vector<int>& arr) { int n = arr.size(); vector<int> s(n + 1); for (int i = 0; i < n; i++) { s[i + 1] = s[i] ^ arr[i]; } int ans = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { for (int k = j; k < n; k++) { if (s[i] == s[k + 1]) { ans++; } } } } return ans; } // 双层循环 // 当s[i] == s[k + 1], (i, k]范围内的数字都可以作为j int countTriplets(vector<int>& arr) { int n = arr.size(); vector<int> s(n + 1); for (int i = 0; i < n; i++) { s[i + 1] = s[i] ^ arr[i]; } int ans = 0; for (int i = 0; i < n; i++) { for (int k = i + 1; k < n; k++) { if (s[i] == s[k + 1]) { ans += k - i; } } } return ans; } // 单层循环,哈希表优化 // 优化依据:(k - i1) + (k - i2) + ... + (k - im) = k * m - (i1 + i2 + ... + im) int countTriplets(vector<int>& arr) { int n = arr.size(); vector<int> s(n + 1); for (int i = 0; i < n; i++) { s[i + 1] = s[i] ^ arr[i]; } int ans = 0; unordered_map<int, int> cnt, total; for (int i = 0; i < n; i++) { if (cnt.count(s[i + 1])) { ans += i * cnt[s[i + 1]] - total[s[i + 1]]; } cnt[s[i]]++; total[s[i]] += i; } return ans; } // 空间优化,将求前缀和过程和求解过程结合 int countTriplets(vector<int>& arr) { int n = arr.size(); unordered_map<int, int> cnt, total; int ans = 0, s = 0; for (int i = 0; i < n; i++) { if (cnt.count(s ^ arr[i])) { ans += i * cnt[s ^ arr[i]] - total[s ^ arr[i]]; } cnt[s]++; total[s] += i; s ^= arr[i]; } return ans; } };
#include "Shader.h" #include "Exception.h" #include "Core.h" #include <fstream> #include <iostream> #include <sstream> void Shader::Load(std::string _path) { rendShader = core->GetContext()->createShader(); std::ifstream file(_path.c_str()); std::string shaderSrc; if (!file.is_open()) { throw Exception("Cannot Open File"); } while (!file.eof()) { std::string line; std::getline(file, line); shaderSrc += line + "\n"; } file.close(); rendShader->parse(shaderSrc); } Shader::~Shader() { rendShader->~Shader(); }