text
stringlengths 8
6.88M
|
|---|
#include "PlayerCharacter.h"
#include "AnimInstance/PlayerCharacterAnimInst/PlayerCharacterAnimInst.h"
#include "Component/ZoomableSpringArm/ZoomableSpringArmComponent.h"
#include "Component/CharacterMovementHelper/CharacterMovementHelperComponent.h"
#include "Component/PlayerInteract/PlayerInteractComponent.h"
APlayerCharacter::APlayerCharacter()
{
static ConstructorHelpers::FObjectFinder<USkeletalMesh> SK_TEST_MESH(
TEXT("SkeletalMesh'/Game/Resources/PlayerCharacter/GKnight/Meshes/SK_GothicKnight_VF.SK_GothicKnight_VF'"));
if (SK_TEST_MESH.Succeeded()) GetMesh()->SetSkeletalMesh(SK_TEST_MESH.Object);
static ConstructorHelpers::FClassFinder<UPlayerCharacterAnimInst> BP_PLAYER_CHARACTER_ANIM_INST(
TEXT("AnimBlueprint'/Game/Blueprints/AnimInstance/BP_PlayerCharacter.BP_PlayerCharacter_C'"));
if (BP_PLAYER_CHARACTER_ANIM_INST.Succeeded()) BP_PlayerCharacterAnimInst = BP_PLAYER_CHARACTER_ANIM_INST.Class;
// ์ปดํฌ๋ํธ ์ถ๊ฐ
CharacterMovementHelper = CreateDefaultSubobject<UCharacterMovementHelperComponent>(TEXT("MOVEMENT_HELPER"));
SpringArm = CreateDefaultSubobject<UZoomableSpringArmComponent>(TEXT("SPRING_ARM"));
Camera = CreateDefaultSubobject<UCameraComponent>(TEXT("CAMERA"));
Camera->SetConstraintAspectRatio(true);
PlayerInteract = CreateDefaultSubobject<UPlayerInteractComponent>(TEXT("PLAYER_INTERACT"));
// Spring Arm Component ๋ฅผ ๋ฃจํธ ์ปดํฌ๋ํธ์ ์ถ๊ฐํฉ๋๋ค.
SpringArm->SetupAttachment(GetRootComponent());
// Camera Component ๋ฅผ SpringArm ์ปดํฌ๋ํธ์ ์ถ๊ฐํฉ๋๋ค.
Camera->SetupAttachment(SpringArm);
// ์ปจํธ๋กค๋ฌ์ ํ์ ๊ฐ์ SpringArm Component ํ์ ๊ฐ์ผ๋ก ์ฌ์ฉํฉ๋๋ค.
SpringArm->bUsePawnControlRotation = true;
// ์ปจํธ๋กค๋ฌ์ ํ์ ์ค Yaw, Pitch ํ์ ์ ์ฌ์ฉํฉ๋๋ค.
SpringArm->bInheritYaw = true;
SpringArm->bInheritPitch = true;
// SpringArm ์คํ์
์ ์ค์ ํฉ๋๋ค.
SpringArm->TargetOffset = FVector::UpVector * 70.0f;
// ์บ๋ฆญํฐ ๊ธฐ๋ณธ ์์น / ํ์ ์ค์
GetMesh()->SetRelativeLocationAndRotation(
FVector::DownVector * 88.0f,
FRotator(0.0f, -90.0f, 0.0f));
// ์ด ์กํฐ์ ํ์ ์ด ์ปจํธ๋กค๋ฌ์ Yaw ํ์ ์ ์ฌ์ฉํ์ง ์๋๋ก ํฉ๋๋ค.
bUseControllerRotationYaw = false;
// ์ด๋ํ๋ ๋ฐฉํฅ์ผ๋ก ์บ๋ฆญํฐ๋ฅผ ํ์ ์ํต๋๋ค.
GetCharacterMovement()->bOrientRotationToMovement = true;
// ํ์ ์๋๋ฅผ ์ง์ ํฉ๋๋ค.
GetCharacterMovement()->RotationRate = FRotator(0.0f, 450.0f, 0.0f);
// ์ ๋ ์ธ์คํด์ค ํด๋์ค ์ค์
GetMesh()->SetAnimClass(BP_PlayerCharacterAnimInst);
Tags.Add(PLAYER_ACTOR_TAG);
}
void APlayerCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
PlayerInputComponent->BindAction(TEXT("Run"), EInputEvent::IE_Pressed,
GetCharacterMovementHelper(), &UCharacterMovementHelperComponent::RunKeyPressed);
PlayerInputComponent->BindAction(TEXT("Run"), EInputEvent::IE_Released,
GetCharacterMovementHelper(), &UCharacterMovementHelperComponent::RunKeyReleased);
PlayerInputComponent->BindAction(TEXT("Jump"), EInputEvent::IE_Pressed,
GetCharacterMovementHelper(), &UCharacterMovementHelperComponent::JumpKeyPressed);
PlayerInputComponent->BindAction(TEXT("Interact"), EInputEvent::IE_Pressed,
GetPlayerInteract(), &UPlayerInteractComponent::TryInteraction);
PlayerInputComponent->BindAxis(TEXT("MouseWheel"),
SpringArm, &UZoomableSpringArmComponent::ZoomCamera);
PlayerInputComponent->BindAxis(TEXT("Horizontal"),
GetCharacterMovementHelper(), &UCharacterMovementHelperComponent::InputHorizontal);
PlayerInputComponent->BindAxis(TEXT("Vertical"),
GetCharacterMovementHelper(), &UCharacterMovementHelperComponent::InputVertical);
}
|
#include "Tuning.h"
Tuning::Tuning(int tuning) { this->setTuning(tuning); }
Tuning::~Tuning() {}
void Tuning::generateEqualTemperament(float degree) {
this->currentTuning.clear();
for (float i = 0.f; i <= degree; i++)
this->currentTuning.push_back(pow(2.f, i / degree));
}
float Tuning::getFreqFromMIDI(int step, int rootDegree, float rootFreq) {
if (step == rootDegree)
return rootFreq;
else {
float tuningSize = this->currentTuning.size() - 1;
int stepsAway = abs(step - rootDegree),
octavesAway = stepsAway / ((int)tuningSize),
degreesAway = stepsAway % ((int)tuningSize);
if (step < rootDegree) {
octavesAway = (octavesAway + 1) * -1;
degreesAway = ((int)tuningSize) - degreesAway;
}
rootFreq *= pow(2, octavesAway);
return rootFreq * this->currentTuning[degreesAway] *
(justTuning ? pow(PYTHAGOREAN_COMMA, octavesAway) : 1.f);
}
}
void Tuning::setTuning(int tuning, float degree) {
switch (tuning) {
case JUST_TUNING:
this->currentTuning = just;
break;
case EQUAL_TUNING:
this->generateEqualTemperament(degree);
break;
}
justTuning = (tuning == JUST_TUNING);
}
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <quic/QuicConstants.h>
#include <quic/api/QuicPacketScheduler.h>
#include <quic/flowcontrol/QuicFlowController.h>
#include <cstdint>
namespace {
using namespace quic;
/**
* A helper iterator adaptor class that starts iteration of streams from a
* specific stream id.
*/
class MiddleStartingIterationWrapper {
public:
using MapType = std::set<StreamId>;
class MiddleStartingIterator
: public boost::iterator_facade<
MiddleStartingIterator,
const MiddleStartingIterationWrapper::MapType::value_type,
boost::forward_traversal_tag> {
friend class boost::iterator_core_access;
public:
using MapType = MiddleStartingIterationWrapper::MapType;
MiddleStartingIterator() = delete;
MiddleStartingIterator(
const MapType* streams,
const MapType::key_type& start)
: streams_(streams) {
itr_ = streams_->lower_bound(start);
checkForWrapAround();
// We don't want to mark it as wrapped around initially, instead just
// act as if start was the first element.
wrappedAround_ = false;
}
MiddleStartingIterator(const MapType* streams, MapType::const_iterator itr)
: streams_(streams), itr_(itr) {
checkForWrapAround();
// We don't want to mark it as wrapped around initially, instead just
// act as if start was the first element.
wrappedAround_ = false;
}
FOLLY_NODISCARD const MapType::value_type& dereference() const {
return *itr_;
}
FOLLY_NODISCARD MapType::const_iterator rawIterator() const {
return itr_;
}
FOLLY_NODISCARD bool equal(const MiddleStartingIterator& other) const {
return wrappedAround_ == other.wrappedAround_ && itr_ == other.itr_;
}
void increment() {
++itr_;
checkForWrapAround();
}
void checkForWrapAround() {
if (itr_ == streams_->cend()) {
wrappedAround_ = true;
itr_ = streams_->cbegin();
}
}
private:
friend class MiddleStartingIterationWrapper;
bool wrappedAround_{false};
const MapType* streams_{nullptr};
MapType::const_iterator itr_;
};
MiddleStartingIterationWrapper(
const MapType& streams,
const MapType::key_type& start)
: streams_(streams), start_(&streams_, start) {}
MiddleStartingIterationWrapper(
const MapType& streams,
const MapType::const_iterator& start)
: streams_(streams), start_(&streams_, start) {}
FOLLY_NODISCARD MiddleStartingIterator cbegin() const {
return start_;
}
FOLLY_NODISCARD MiddleStartingIterator cend() const {
MiddleStartingIterator itr(start_);
itr.wrappedAround_ = true;
return itr;
}
private:
const MapType& streams_;
const MiddleStartingIterator start_;
};
} // namespace
namespace quic {
bool hasAcksToSchedule(const AckState& ackState) {
folly::Optional<PacketNum> largestAckSend = largestAckToSend(ackState);
if (!largestAckSend) {
return false;
}
if (!ackState.largestAckScheduled) {
// Never scheduled an ack, we need to send
return true;
}
return *largestAckSend > *(ackState.largestAckScheduled);
}
folly::Optional<PacketNum> largestAckToSend(const AckState& ackState) {
if (ackState.acks.empty()) {
return folly::none;
}
return ackState.acks.back().end;
}
// Schedulers
FrameScheduler::Builder::Builder(
QuicConnectionStateBase& conn,
EncryptionLevel encryptionLevel,
PacketNumberSpace packetNumberSpace,
folly::StringPiece name)
: conn_(conn),
encryptionLevel_(encryptionLevel),
packetNumberSpace_(packetNumberSpace),
name_(std::move(name)) {}
FrameScheduler::Builder& FrameScheduler::Builder::streamFrames() {
streamFrameScheduler_ = true;
return *this;
}
FrameScheduler::Builder& FrameScheduler::Builder::ackFrames() {
ackScheduler_ = true;
return *this;
}
FrameScheduler::Builder& FrameScheduler::Builder::resetFrames() {
rstScheduler_ = true;
return *this;
}
FrameScheduler::Builder& FrameScheduler::Builder::windowUpdateFrames() {
windowUpdateScheduler_ = true;
return *this;
}
FrameScheduler::Builder& FrameScheduler::Builder::blockedFrames() {
blockedScheduler_ = true;
return *this;
}
FrameScheduler::Builder& FrameScheduler::Builder::cryptoFrames() {
cryptoStreamScheduler_ = true;
return *this;
}
FrameScheduler::Builder& FrameScheduler::Builder::simpleFrames() {
simpleFrameScheduler_ = true;
return *this;
}
FrameScheduler::Builder& FrameScheduler::Builder::pingFrames() {
pingFrameScheduler_ = true;
return *this;
}
FrameScheduler::Builder& FrameScheduler::Builder::datagramFrames() {
datagramFrameScheduler_ = true;
return *this;
}
FrameScheduler::Builder& FrameScheduler::Builder::immediateAckFrames() {
immediateAckFrameScheduler_ = true;
return *this;
}
FrameScheduler FrameScheduler::Builder::build() && {
FrameScheduler scheduler(name_, conn_);
if (streamFrameScheduler_) {
scheduler.streamFrameScheduler_.emplace(StreamFrameScheduler(conn_));
}
if (ackScheduler_) {
scheduler.ackScheduler_.emplace(
AckScheduler(conn_, getAckState(conn_, packetNumberSpace_)));
}
if (rstScheduler_) {
scheduler.rstScheduler_.emplace(RstStreamScheduler(conn_));
}
if (windowUpdateScheduler_) {
scheduler.windowUpdateScheduler_.emplace(WindowUpdateScheduler(conn_));
}
if (blockedScheduler_) {
scheduler.blockedScheduler_.emplace(BlockedScheduler(conn_));
}
if (cryptoStreamScheduler_) {
scheduler.cryptoStreamScheduler_.emplace(CryptoStreamScheduler(
conn_, *getCryptoStream(*conn_.cryptoState, encryptionLevel_)));
}
if (simpleFrameScheduler_) {
scheduler.simpleFrameScheduler_.emplace(SimpleFrameScheduler(conn_));
}
if (pingFrameScheduler_) {
scheduler.pingFrameScheduler_.emplace(PingFrameScheduler(conn_));
}
if (datagramFrameScheduler_) {
scheduler.datagramFrameScheduler_.emplace(DatagramFrameScheduler(conn_));
}
if (immediateAckFrameScheduler_) {
scheduler.immediateAckFrameScheduler_.emplace(
ImmediateAckFrameScheduler(conn_));
}
return scheduler;
}
FrameScheduler::FrameScheduler(
folly::StringPiece name,
QuicConnectionStateBase& conn)
: name_(name), conn_(conn) {}
SchedulingResult FrameScheduler::scheduleFramesForPacket(
PacketBuilderInterface&& builder,
uint32_t writableBytes) {
builder.encodePacketHeader();
// We need to keep track of writable bytes after writing header.
writableBytes = writableBytes > builder.getHeaderBytes()
? writableBytes - builder.getHeaderBytes()
: 0;
// We cannot return early if the writablyBytes drops to 0 here, since pure
// acks can skip writableBytes entirely.
PacketBuilderWrapper wrapper(builder, writableBytes);
bool cryptoDataWritten = false;
bool rstWritten = false;
if (cryptoStreamScheduler_ && cryptoStreamScheduler_->hasData()) {
cryptoDataWritten = cryptoStreamScheduler_->writeCryptoData(wrapper);
}
if (rstScheduler_ && rstScheduler_->hasPendingRsts()) {
rstWritten = rstScheduler_->writeRsts(wrapper);
}
// Long time ago we decided RST has higher priority than Acks.
if (hasPendingAcks()) {
if (cryptoDataWritten || rstWritten) {
// If packet has non ack data, it is subject to congestion control. We
// need to use the wrapper/
ackScheduler_->writeNextAcks(wrapper);
} else {
// If we start with writing acks, we will let the ack scheduler write
// up to the full packet space. If the ack bytes exceeds the writable
// bytes, this will be a pure ack packet and it will skip congestion
// controller. Otherwise, we will give other schedulers an opportunity to
// write up to writable bytes.
ackScheduler_->writeNextAcks(builder);
}
}
// Immediate ACK frames are subject to congestion control but should be sent
// before other frames to maximize their chance of being included in the
// packet since they are time sensitive
if (immediateAckFrameScheduler_ &&
immediateAckFrameScheduler_->hasPendingImmediateAckFrame()) {
immediateAckFrameScheduler_->writeImmediateAckFrame(wrapper);
}
if (windowUpdateScheduler_ &&
windowUpdateScheduler_->hasPendingWindowUpdates()) {
windowUpdateScheduler_->writeWindowUpdates(wrapper);
}
if (blockedScheduler_ && blockedScheduler_->hasPendingBlockedFrames()) {
blockedScheduler_->writeBlockedFrames(wrapper);
}
// Simple frames should be scheduled before stream frames and retx frames
// because those frames might fill up all available bytes for writing.
// If we are trying to send a PathChallenge frame it may be blocked by those,
// causing a connection to proceed slowly because of path validation rate
// limiting.
if (simpleFrameScheduler_ &&
simpleFrameScheduler_->hasPendingSimpleFrames()) {
simpleFrameScheduler_->writeSimpleFrames(wrapper);
}
if (pingFrameScheduler_ && pingFrameScheduler_->hasPingFrame()) {
pingFrameScheduler_->writePing(wrapper);
}
if (streamFrameScheduler_ && streamFrameScheduler_->hasPendingData()) {
streamFrameScheduler_->writeStreams(wrapper);
}
if (datagramFrameScheduler_ &&
datagramFrameScheduler_->hasPendingDatagramFrames()) {
datagramFrameScheduler_->writeDatagramFrames(wrapper);
}
if (builder.hasFramesPending()) {
const LongHeader* longHeader = builder.getPacketHeader().asLong();
bool initialPacket =
longHeader && longHeader->getHeaderType() == LongHeader::Types::Initial;
if (initialPacket) {
// This is the initial packet, we need to fill er up.
while (builder.remainingSpaceInPkt() > 0) {
writeFrame(PaddingFrame(), builder);
}
}
const ShortHeader* shortHeader = builder.getPacketHeader().asShort();
if (shortHeader) {
size_t paddingModulo = conn_.transportSettings.paddingModulo;
if (paddingModulo > 0) {
size_t paddingIncrement = wrapper.remainingSpaceInPkt() % paddingModulo;
for (size_t i = 0; i < paddingIncrement; i++) {
writeFrame(PaddingFrame(), builder);
}
QUIC_STATS(conn_.statsCallback, onShortHeaderPadding, paddingIncrement);
}
}
}
return SchedulingResult(folly::none, std::move(builder).buildPacket());
}
void FrameScheduler::writeNextAcks(PacketBuilderInterface& builder) {
ackScheduler_->writeNextAcks(builder);
}
bool FrameScheduler::hasData() const {
return hasPendingAcks() || hasImmediateData();
}
bool FrameScheduler::hasPendingAcks() const {
return ackScheduler_ && ackScheduler_->hasPendingAcks();
}
bool FrameScheduler::hasImmediateData() const {
return (cryptoStreamScheduler_ && cryptoStreamScheduler_->hasData()) ||
(streamFrameScheduler_ && streamFrameScheduler_->hasPendingData()) ||
(rstScheduler_ && rstScheduler_->hasPendingRsts()) ||
(windowUpdateScheduler_ &&
windowUpdateScheduler_->hasPendingWindowUpdates()) ||
(blockedScheduler_ && blockedScheduler_->hasPendingBlockedFrames()) ||
(simpleFrameScheduler_ &&
simpleFrameScheduler_->hasPendingSimpleFrames()) ||
(pingFrameScheduler_ && pingFrameScheduler_->hasPingFrame()) ||
(datagramFrameScheduler_ &&
datagramFrameScheduler_->hasPendingDatagramFrames()) ||
(immediateAckFrameScheduler_ &&
immediateAckFrameScheduler_->hasPendingImmediateAckFrame());
}
folly::StringPiece FrameScheduler::name() const {
return name_;
}
bool StreamFrameScheduler::writeStreamLossBuffers(
PacketBuilderInterface& builder,
QuicStreamState& stream) {
bool wroteStreamFrame = false;
for (auto buffer = stream.lossBuffer.cbegin();
buffer != stream.lossBuffer.cend();
++buffer) {
auto bufferLen = buffer->data.chainLength();
auto dataLen = writeStreamFrameHeader(
builder,
stream.id,
buffer->offset,
bufferLen, // writeBufferLen -- only the len of the single buffer.
bufferLen, // flowControlLen -- not relevant, already flow controlled.
buffer->eof,
folly::none /* skipLenHint */,
stream.groupId);
if (dataLen) {
wroteStreamFrame = true;
writeStreamFrameData(builder, buffer->data, *dataLen);
VLOG(4) << "Wrote loss data for stream=" << stream.id
<< " offset=" << buffer->offset << " bytes=" << *dataLen
<< " fin=" << (buffer->eof && *dataLen == bufferLen) << " "
<< conn_;
} else {
// Either we filled the packet or ran out of data for this stream (EOF?)
break;
}
}
return wroteStreamFrame;
}
StreamFrameScheduler::StreamFrameScheduler(QuicConnectionStateBase& conn)
: conn_(conn) {}
bool StreamFrameScheduler::writeSingleStream(
PacketBuilderInterface& builder,
QuicStreamState& stream,
uint64_t& connWritableBytes) {
if (!stream.lossBuffer.empty()) {
if (!writeStreamLossBuffers(builder, stream)) {
return false;
}
}
if (stream.hasWritableData() && connWritableBytes > 0) {
if (!writeStreamFrame(builder, stream, connWritableBytes)) {
return false;
}
}
return true;
}
StreamId StreamFrameScheduler::writeStreamsHelper(
PacketBuilderInterface& builder,
const std::set<StreamId>& writableStreams,
StreamId nextScheduledStream,
uint64_t& connWritableBytes,
bool streamPerPacket) {
MiddleStartingIterationWrapper wrapper(writableStreams, nextScheduledStream);
auto writableStreamItr = wrapper.cbegin();
// This will write the stream frames in a round robin fashion ordered by
// stream id. The iterator will wrap around the collection at the end, and we
// keep track of the value at the next iteration. This allows us to start
// writing at the next stream when building the next packet.
while (writableStreamItr != wrapper.cend()) {
auto stream = conn_.streamManager->findStream(*writableStreamItr);
CHECK(stream);
if (!writeSingleStream(builder, *stream, connWritableBytes)) {
break;
}
writableStreamItr++;
if (streamPerPacket) {
break;
}
}
return *writableStreamItr;
}
void StreamFrameScheduler::writeStreamsHelper(
PacketBuilderInterface& builder,
PriorityQueue& writableStreams,
uint64_t& connWritableBytes,
bool streamPerPacket) {
// Fill a packet with non-control stream data, in priority order
for (size_t index = 0; index < writableStreams.levels.size() &&
builder.remainingSpaceInPkt() > 0;
index++) {
PriorityQueue::Level& level = writableStreams.levels[index];
if (level.empty()) {
// No data here, keep going
continue;
}
level.iterator->begin();
do {
auto streamId = level.iterator->current();
auto stream = CHECK_NOTNULL(conn_.streamManager->findStream(streamId));
if (!stream->hasSchedulableData() && stream->hasSchedulableDsr()) {
// We hit a DSR stream
return;
}
CHECK(stream) << "streamId=" << streamId
<< "inc=" << uint64_t(level.incremental);
if (!writeSingleStream(builder, *stream, connWritableBytes)) {
break;
}
auto remainingSpaceAfter = builder.remainingSpaceInPkt();
// If we wrote a stream frame and there's still space in the packet,
// that implies we ran out of data or flow control on the stream and
// we should bypass the nextsPerStream in the priority queue.
bool forceNext = remainingSpaceAfter > 0;
level.iterator->next(forceNext);
if (streamPerPacket) {
return;
}
} while (!level.iterator->end());
}
}
void StreamFrameScheduler::writeStreams(PacketBuilderInterface& builder) {
DCHECK(conn_.streamManager->hasWritable());
uint64_t connWritableBytes = getSendConnFlowControlBytesWire(conn_);
// Write the control streams first as a naive binary priority mechanism.
const auto& controlWriteQueue = conn_.streamManager->controlWriteQueue();
if (!controlWriteQueue.empty()) {
conn_.schedulingState.nextScheduledControlStream = writeStreamsHelper(
builder,
controlWriteQueue,
conn_.schedulingState.nextScheduledControlStream,
connWritableBytes,
conn_.transportSettings.streamFramePerPacket);
}
auto& writeQueue = conn_.streamManager->writeQueue();
if (!writeQueue.empty()) {
writeStreamsHelper(
builder,
writeQueue,
connWritableBytes,
conn_.transportSettings.streamFramePerPacket);
// If the next non-control stream is DSR, record that fact in the scheduler
// so that we don't try to write a non DSR stream again. Note that this
// means that in the presence of many large control streams and DSR
// streams, we won't completely prioritize control streams but they
// will not be starved.
auto streamId = writeQueue.getNextScheduledStream();
auto stream = conn_.streamManager->findStream(streamId);
if (stream && !stream->hasSchedulableData()) {
nextStreamDsr_ = true;
}
}
}
bool StreamFrameScheduler::hasPendingData() const {
return !nextStreamDsr_ &&
(conn_.streamManager->hasNonDSRLoss() ||
(conn_.streamManager->hasNonDSRWritable() &&
getSendConnFlowControlBytesWire(conn_) > 0));
}
bool StreamFrameScheduler::writeStreamFrame(
PacketBuilderInterface& builder,
QuicStreamState& stream,
uint64_t& connWritableBytes) {
if (builder.remainingSpaceInPkt() == 0) {
return false;
}
// hasWritableData is the condition which has to be satisfied for the
// stream to be in writableList
CHECK(stream.hasWritableData());
uint64_t flowControlLen =
std::min(getSendStreamFlowControlBytesWire(stream), connWritableBytes);
uint64_t bufferLen = stream.writeBuffer.chainLength();
// We should never write a FIN from the non-DSR scheduler for a DSR stream.
bool canWriteFin = stream.finalWriteOffset.has_value() &&
bufferLen <= flowControlLen && stream.writeBufMeta.offset == 0;
auto writeOffset = stream.currentWriteOffset;
auto dataLen = writeStreamFrameHeader(
builder,
stream.id,
writeOffset,
bufferLen,
flowControlLen,
canWriteFin,
folly::none /* skipLenHint */,
stream.groupId);
if (!dataLen) {
return false;
}
writeStreamFrameData(builder, stream.writeBuffer, *dataLen);
VLOG(4) << "Wrote stream frame stream=" << stream.id
<< " offset=" << stream.currentWriteOffset
<< " bytesWritten=" << *dataLen
<< " finWritten=" << (canWriteFin && *dataLen == bufferLen) << " "
<< conn_;
connWritableBytes -= dataLen.value();
return true;
}
AckScheduler::AckScheduler(
const QuicConnectionStateBase& conn,
const AckState& ackState)
: conn_(conn), ackState_(ackState) {}
folly::Optional<PacketNum> AckScheduler::writeNextAcks(
PacketBuilderInterface& builder) {
// Use default ack delay for long headers. Usually long headers are sent
// before crypto negotiation, so the peer might not know about the ack delay
// exponent yet, so we use the default.
uint8_t ackDelayExponentToUse =
builder.getPacketHeader().getHeaderForm() == HeaderForm::Long
? kDefaultAckDelayExponent
: conn_.transportSettings.ackDelayExponent;
auto largestAckedPacketNum = *largestAckToSend(ackState_);
auto ackingTime = Clock::now();
DCHECK(ackState_.largestRecvdPacketTime.hasValue())
<< "Missing received time for the largest acked packet";
// assuming that we're going to ack the largest received with highest pri
auto receivedTime = *ackState_.largestRecvdPacketTime;
std::chrono::microseconds ackDelay =
(ackingTime > receivedTime
? std::chrono::duration_cast<std::chrono::microseconds>(
ackingTime - receivedTime)
: 0us);
WriteAckFrameMetaData meta = {
ackState_, /* ackState*/
ackDelay, /* ackDelay */
static_cast<uint8_t>(ackDelayExponentToUse), /* ackDelayExponent */
conn_.connectionTime, /* connect timestamp */
};
folly::Optional<WriteAckFrameResult> ackWriteResult;
bool isAckReceiveTimestampsSupported =
conn_.transportSettings.maybeAckReceiveTimestampsConfigSentToPeer &&
conn_.maybePeerAckReceiveTimestampsConfig;
uint64_t peerRequestedTimestampsCount =
conn_.maybePeerAckReceiveTimestampsConfig.has_value()
? conn_.maybePeerAckReceiveTimestampsConfig.value()
.maxReceiveTimestampsPerAck
: 0;
// If ack_receive_timestamps are not enabled on *either* end-points OR
// the peer requests 0 timestamps, we fall-back to using FrameType::ACK
if (!isAckReceiveTimestampsSupported || !peerRequestedTimestampsCount) {
ackWriteResult = writeAckFrame(meta, builder, FrameType::ACK);
} else {
ackWriteResult = writeAckFrameWithReceivedTimestamps(
meta,
builder,
conn_.transportSettings.maybeAckReceiveTimestampsConfigSentToPeer
.value(),
peerRequestedTimestampsCount);
}
if (!ackWriteResult) {
return folly::none;
}
return largestAckedPacketNum;
}
bool AckScheduler::hasPendingAcks() const {
return hasAcksToSchedule(ackState_);
}
RstStreamScheduler::RstStreamScheduler(const QuicConnectionStateBase& conn)
: conn_(conn) {}
bool RstStreamScheduler::hasPendingRsts() const {
return !conn_.pendingEvents.resets.empty();
}
bool RstStreamScheduler::writeRsts(PacketBuilderInterface& builder) {
bool rstWritten = false;
for (const auto& resetStream : conn_.pendingEvents.resets) {
auto bytesWritten = writeFrame(resetStream.second, builder);
if (!bytesWritten) {
break;
}
rstWritten = true;
}
return rstWritten;
}
SimpleFrameScheduler::SimpleFrameScheduler(const QuicConnectionStateBase& conn)
: conn_(conn) {}
bool SimpleFrameScheduler::hasPendingSimpleFrames() const {
return conn_.pendingEvents.pathChallenge ||
!conn_.pendingEvents.frames.empty();
}
bool SimpleFrameScheduler::writeSimpleFrames(PacketBuilderInterface& builder) {
auto& pathChallenge = conn_.pendingEvents.pathChallenge;
if (pathChallenge &&
!writeSimpleFrame(QuicSimpleFrame(*pathChallenge), builder)) {
return false;
}
bool framesWritten = false;
for (auto& frame : conn_.pendingEvents.frames) {
auto bytesWritten = writeSimpleFrame(QuicSimpleFrame(frame), builder);
if (!bytesWritten) {
break;
}
framesWritten = true;
}
return framesWritten;
}
PingFrameScheduler::PingFrameScheduler(const QuicConnectionStateBase& conn)
: conn_(conn) {}
bool PingFrameScheduler::hasPingFrame() const {
return conn_.pendingEvents.sendPing;
}
bool PingFrameScheduler::writePing(PacketBuilderInterface& builder) {
return 0 != writeFrame(PingFrame(), builder);
}
DatagramFrameScheduler::DatagramFrameScheduler(QuicConnectionStateBase& conn)
: conn_(conn) {}
bool DatagramFrameScheduler::hasPendingDatagramFrames() const {
return !conn_.datagramState.writeBuffer.empty();
}
bool DatagramFrameScheduler::writeDatagramFrames(
PacketBuilderInterface& builder) {
bool sent = false;
for (size_t i = 0; i <= conn_.datagramState.writeBuffer.size(); ++i) {
auto& payload = conn_.datagramState.writeBuffer.front();
auto len = payload.chainLength();
uint64_t spaceLeft = builder.remainingSpaceInPkt();
QuicInteger frameTypeQuicInt(static_cast<uint8_t>(FrameType::DATAGRAM_LEN));
QuicInteger datagramLenInt(len);
auto datagramFrameLength =
frameTypeQuicInt.getSize() + len + datagramLenInt.getSize();
if (folly::to<uint64_t>(datagramFrameLength) <= spaceLeft) {
auto datagramFrame = DatagramFrame(len, payload.move());
auto res = writeFrame(datagramFrame, builder);
// Must always succeed since we have already checked that there is enough
// space to write the frame
CHECK_GT(res, 0);
QUIC_STATS(conn_.statsCallback, onDatagramWrite, len);
conn_.datagramState.writeBuffer.pop_front();
sent = true;
}
if (conn_.transportSettings.datagramConfig.framePerPacket) {
break;
}
}
return sent;
}
WindowUpdateScheduler::WindowUpdateScheduler(
const QuicConnectionStateBase& conn)
: conn_(conn) {}
bool WindowUpdateScheduler::hasPendingWindowUpdates() const {
return conn_.streamManager->hasWindowUpdates() ||
conn_.pendingEvents.connWindowUpdate;
}
void WindowUpdateScheduler::writeWindowUpdates(
PacketBuilderInterface& builder) {
if (conn_.pendingEvents.connWindowUpdate) {
auto maxDataFrame = generateMaxDataFrame(conn_);
auto maximumData = maxDataFrame.maximumData;
auto bytes = writeFrame(std::move(maxDataFrame), builder);
if (bytes) {
VLOG(4) << "Wrote max_data=" << maximumData << " " << conn_;
}
}
for (const auto& windowUpdateStream : conn_.streamManager->windowUpdates()) {
auto stream = conn_.streamManager->findStream(windowUpdateStream);
if (!stream) {
continue;
}
auto maxStreamDataFrame = generateMaxStreamDataFrame(*stream);
auto maximumData = maxStreamDataFrame.maximumData;
auto bytes = writeFrame(std::move(maxStreamDataFrame), builder);
if (!bytes) {
break;
}
VLOG(4) << "Wrote max_stream_data stream=" << stream->id
<< " maximumData=" << maximumData << " " << conn_;
}
}
BlockedScheduler::BlockedScheduler(const QuicConnectionStateBase& conn)
: conn_(conn) {}
bool BlockedScheduler::hasPendingBlockedFrames() const {
return !conn_.streamManager->blockedStreams().empty() ||
conn_.pendingEvents.sendDataBlocked;
}
void BlockedScheduler::writeBlockedFrames(PacketBuilderInterface& builder) {
if (conn_.pendingEvents.sendDataBlocked) {
// Connection is write blocked due to connection level flow control.
DataBlockedFrame blockedFrame(
conn_.flowControlState.peerAdvertisedMaxOffset);
auto result = writeFrame(blockedFrame, builder);
if (!result) {
// If there is not enough room to write data blocked frame in the
// current packet, we won't be able to write stream blocked frames either
// so just return.
return;
}
}
for (const auto& blockedStream : conn_.streamManager->blockedStreams()) {
auto bytesWritten = writeFrame(blockedStream.second, builder);
if (!bytesWritten) {
break;
}
}
}
CryptoStreamScheduler::CryptoStreamScheduler(
const QuicConnectionStateBase& conn,
const QuicCryptoStream& cryptoStream)
: conn_(conn), cryptoStream_(cryptoStream) {}
bool CryptoStreamScheduler::writeCryptoData(PacketBuilderInterface& builder) {
bool cryptoDataWritten = false;
uint64_t writableData =
folly::to<uint64_t>(cryptoStream_.writeBuffer.chainLength());
// We use the crypto scheduler to reschedule the retransmissions of the
// crypto streams so that we know that retransmissions of the crypto data
// will always take precedence over the crypto data.
for (const auto& buffer : cryptoStream_.lossBuffer) {
auto res = writeCryptoFrame(buffer.offset, buffer.data, builder);
if (!res) {
return cryptoDataWritten;
}
VLOG(4) << "Wrote retransmitted crypto"
<< " offset=" << buffer.offset << " bytes=" << res->len << " "
<< conn_;
cryptoDataWritten = true;
}
if (writableData != 0) {
auto res = writeCryptoFrame(
cryptoStream_.currentWriteOffset, cryptoStream_.writeBuffer, builder);
if (res) {
VLOG(4) << "Wrote crypto frame"
<< " offset=" << cryptoStream_.currentWriteOffset
<< " bytesWritten=" << res->len << " " << conn_;
cryptoDataWritten = true;
}
}
return cryptoDataWritten;
}
bool CryptoStreamScheduler::hasData() const {
return !cryptoStream_.writeBuffer.empty() ||
!cryptoStream_.lossBuffer.empty();
}
ImmediateAckFrameScheduler::ImmediateAckFrameScheduler(
const QuicConnectionStateBase& conn)
: conn_(conn) {}
bool ImmediateAckFrameScheduler::hasPendingImmediateAckFrame() const {
return conn_.pendingEvents.requestImmediateAck;
}
bool ImmediateAckFrameScheduler::writeImmediateAckFrame(
PacketBuilderInterface& builder) {
return 0 != writeFrame(ImmediateAckFrame(), builder);
}
CloningScheduler::CloningScheduler(
FrameScheduler& scheduler,
QuicConnectionStateBase& conn,
const folly::StringPiece name,
uint64_t cipherOverhead)
: frameScheduler_(scheduler),
conn_(conn),
name_(name),
cipherOverhead_(cipherOverhead) {}
bool CloningScheduler::hasData() const {
return frameScheduler_.hasData() ||
conn_.outstandings.numOutstanding() > conn_.outstandings.dsrCount;
}
SchedulingResult CloningScheduler::scheduleFramesForPacket(
PacketBuilderInterface&& builder,
uint32_t writableBytes) {
// The writableBytes in this function shouldn't be limited by cwnd, since
// we only use CloningScheduler for the cases that we want to bypass cwnd for
// now.
bool hasData = frameScheduler_.hasData();
if (conn_.version.has_value() &&
conn_.version.value() != QuicVersion::QUIC_V1) {
hasData = frameScheduler_.hasImmediateData();
}
if (hasData) {
// Note that there is a possibility that we end up writing nothing here. But
// if frameScheduler_ hasData() to write, we shouldn't invoke the cloning
// path if the write fails.
return frameScheduler_.scheduleFramesForPacket(
std::move(builder), writableBytes);
}
// TODO: We can avoid the copy & rebuild of the header by creating an
// independent header builder.
auto header = builder.getPacketHeader();
std::move(builder).releaseOutputBuffer();
// Look for an outstanding packet that's no larger than the writableBytes
for (auto& outstandingPacket : conn_.outstandings.packets) {
if (outstandingPacket.declaredLost || outstandingPacket.isDSRPacket) {
continue;
}
auto opPnSpace = outstandingPacket.packet.header.getPacketNumberSpace();
// Reusing the RegularQuicPacketBuilder throughout loop bodies will lead to
// frames belong to different original packets being written into the same
// clone packet. So re-create a RegularQuicPacketBuilder every time.
// TODO: We can avoid the copy & rebuild of the header by creating an
// independent header builder.
auto builderPnSpace = builder.getPacketHeader().getPacketNumberSpace();
if (opPnSpace != builderPnSpace) {
continue;
}
size_t prevSize = 0;
if (conn_.transportSettings.dataPathType ==
DataPathType::ContinuousMemory) {
ScopedBufAccessor scopedBufAccessor(conn_.bufAccessor);
prevSize = scopedBufAccessor.buf()->length();
}
// Reusing the same builder throughout loop bodies will lead to frames
// belong to different original packets being written into the same clone
// packet. So re-create a builder every time.
std::unique_ptr<PacketBuilderInterface> internalBuilder;
if (conn_.transportSettings.dataPathType == DataPathType::ChainedMemory) {
internalBuilder = std::make_unique<RegularQuicPacketBuilder>(
conn_.udpSendPacketLen,
header,
getAckState(conn_, builderPnSpace).largestAckedByPeer.value_or(0));
} else {
CHECK(conn_.bufAccessor && conn_.bufAccessor->ownsBuffer());
internalBuilder = std::make_unique<InplaceQuicPacketBuilder>(
*conn_.bufAccessor,
conn_.udpSendPacketLen,
header,
getAckState(conn_, builderPnSpace).largestAckedByPeer.value_or(0));
}
// If the packet is already a clone that has been processed, we don't clone
// it again.
if (outstandingPacket.associatedEvent &&
conn_.outstandings.packetEvents.count(
*outstandingPacket.associatedEvent) == 0) {
continue;
}
// I think this only fail if udpSendPacketLen somehow shrinks in the middle
// of a connection.
if (outstandingPacket.metadata.encodedSize >
writableBytes + cipherOverhead_) {
continue;
}
internalBuilder->accountForCipherOverhead(cipherOverhead_);
internalBuilder->encodePacketHeader();
PacketRebuilder rebuilder(*internalBuilder, conn_);
// TODO: It's possible we write out a packet that's larger than the packet
// size limit. For example, when the packet sequence number has advanced to
// a point where we need more bytes to encoded it than that of the original
// packet. In that case, if the original packet is already at the packet
// size limit, we will generate a packet larger than the limit. We can
// either ignore the problem, hoping the packet will be able to travel the
// network just fine; Or we can throw away the built packet and send a ping.
// Rebuilder will write the rest of frames
auto rebuildResult = rebuilder.rebuildFromPacket(outstandingPacket);
if (rebuildResult) {
return SchedulingResult(
std::move(rebuildResult), std::move(*internalBuilder).buildPacket());
} else if (
conn_.transportSettings.dataPathType ==
DataPathType::ContinuousMemory) {
// When we use Inplace packet building and reuse the write buffer, even if
// the packet rebuild has failed, there might be some bytes already
// written into the buffer and the buffer tail pointer has already moved.
// We need to roll back the tail pointer to the position before the packet
// building to exclude those bytes. Otherwise these bytes will be sitting
// in between legit packets inside the buffer and will either cause errors
// further down the write path, or be sent out and then dropped at peer
// when peer fail to parse them.
internalBuilder.reset();
CHECK(conn_.bufAccessor && conn_.bufAccessor->ownsBuffer());
ScopedBufAccessor scopedBufAccessor(conn_.bufAccessor);
auto& buf = scopedBufAccessor.buf();
buf->trimEnd(buf->length() - prevSize);
}
}
return SchedulingResult(folly::none, folly::none);
}
folly::StringPiece CloningScheduler::name() const {
return name_;
}
} // namespace quic
|
/**************************************************************
* File Name : myplaylistitem.cpp
* Author : ThreeDog
* Date : Wed Jun 07 15:04:46 2017
* Description : ๆญๆพๅ่กจ็ๆก็ฎ็ฑป
*
**************************************************************/
#include "myplaylistitem.h"
#include <QFileInfo>
#include <QHBoxLayout>
MyPlayListItem::MyPlayListItem(QWidget *parent)
:TDListWidgetItem("",parent)
{
//้่ฟ้ผ ๆ ๅๅป่ทๅ็ฆ็น
this->setFocusPolicy(Qt::ClickFocus);
this->m_bIsSelected = false;
this->setAutoFillBackground(true);
this->setMouseTracking(true);
//่ฎพ็ฝฎ่ๆฏ้ๆ
QPalette palette;
palette.setBrush(QPalette::Background, QBrush(QPixmap(":/image/trans.png")));
this->setPalette(palette);
this->setFixedSize(360,34);
//r = RightKeyMenu::shareRightKeyMenu(0,QString(""),this);
QHBoxLayout * h = new QHBoxLayout;
m_pLeftLabel = new QLabel(this);
m_pLeftLabel->setFixedWidth(260);
h->addStretch(1);
h->addWidget(m_pLeftLabel,6,Qt::AlignLeft);
h->addStretch(3);
m_pMVButton = NULL;
this->setLayout(h);
}
void MyPlayListItem::setText(const QString &text)
{
this->m_pLeftLabel->setText(text);
}
QString MyPlayListItem::getLeftText()
{
return m_pLeftLabel->text();
}
void MyPlayListItem::setPath(const QString &path)
{
this->m_sPath = path;
//ๅๆถๆๅฎไปฅไธๆญๆฒ็MVๅ็งฐใ
m_sMVName = m_sPath.remove(path.right(3)) + "wmv";
}
void MyPlayListItem::setMusicIndex(const int &index)
{
this->m_iMusicIndex = index;
}
int MyPlayListItem::getMusicIndex()
{
return this->m_iMusicIndex;
}
QString MyPlayListItem::getPath()
{
return this->m_sPath;
}
void MyPlayListItem::openMV()
{
}
MyPlayListItem::~MyPlayListItem()
{
}
void MyPlayListItem::mouseDoubleClickEvent(QMouseEvent *e)
{
if(e->button() == Qt::LeftButton)
emit doubleClick(this->m_iMusicIndex);
}
//็ฉบๅฝๆฐไฝ๏ผๆ ๆๅ็ถ็ฑป็ๆญคๅฝๆฐ๏ผ
void MyPlayListItem::mousePressEvent(QMouseEvent *)
{
}
void MyPlayListItem::mouseReleaseEvent(QMouseEvent *e)
{
/* if(e->button()==Qt::RightButton){
r = RightKeyMenu::shareRightKeyMenu(this->music_index,this->path,this);
QDesktopWidget *desktop_widget =
QApplication::desktop();
//ๅพๅฐๅฎขๆทๅบ็ฉๅฝข
QRect client_rect = desktop_widget->availableGeometry();
//ๅพๅฐๅบ็จ็จๅบ็ฉๅฝข
//QRect application_rect = desktop_widget->screenGeometry();
int win_width = client_rect.width();
int win_height = client_rect.height();
if((e->globalY()+r->height()>win_height)&&(e->globalX()+r->width()>win_width)){
r->move(win_width-r->width(),win_height-r->height());
r->show();
r->setFocus();
return ;
}
if(e->globalY()+r->height()>win_height){
r->move(e->globalX(),win_height-r->height());
r->show();
r->setFocus();
return ;
}
if(e->globalX()+r->width()>win_width){
r->move(win_width-r->width(),e->globalY());
r->show();
r->setFocus();
return ;
}
r->move(e->globalPos());
r->show();
r->setFocus();
return ;
}
*/
}
void MyPlayListItem::focusInEvent(QFocusEvent *)
{
m_bIsSelected = true;
QPalette palette;
palette.setColor(QPalette::Background, QColor("#80585858"));
this->setPalette(palette);
}
void MyPlayListItem::focusOutEvent(QFocusEvent *)
{
QPalette palette;
palette.setBrush(QPalette::Background, QBrush(QPixmap(":/image/trans.png")));
this->setPalette(palette);
m_pMVButton->hide();
m_bIsSelected = false;
}
void MyPlayListItem::enterEvent(QEvent *)
{
if(!m_bIsSelected){
QPalette palette;
palette.setColor(QPalette::Background, QColor("#802a2a2a"));
this->setPalette(palette);
//้่ฟMVๆฏๅฆๅญๅจ็ๆๅฏนๅบๆ้ฎ
QFileInfo fi(m_sMVName);
if(fi.exists()){
if(m_pMVButton == NULL){
m_pMVButton = new TDPushButton(":/image/mv_normal.png",
":/image/mv_hover.png",
":/image/mv_press.png",
this);
m_pMVButton->move(300,2);
m_pMVButton->setCallback(this,my_selector(MyPlayListItem::openMV));
}
}else {
if(NULL == m_pMVButton){
m_pMVButton = new TDPushButton(":/image/mvdisable.png",
":/image/mvdisable.png",
":/image/mvdisable.png",
this);
m_pMVButton->move(300,2);
}
}
m_pMVButton->show();
}
}
void MyPlayListItem::leaveEvent(QEvent *)
{
if(!m_bIsSelected){
QPalette palette;
palette.setBrush(QPalette::Background, QBrush(QPixmap(":/image/trans.png")));
this->setPalette(palette);
m_pMVButton->hide();
}
}
|
#pragma once
#include "LoadBalancing-cpp/inc/Client.h"
#include "BaseView.h"
#define PLAYER_UPDATE_INTERVAL_MS 500
using namespace ExitGames::Common;
using namespace ExitGames::LoadBalancing;
struct LocalPlayer
{
LocalPlayer();
int x;
int y;
int z;
unsigned long lastUpdateTime;
};
class LoadBalancingListener : public ExitGames::LoadBalancing::Listener
{
public:
LoadBalancingListener(BaseView* pView);
~LoadBalancingListener();
void setLBC(ExitGames::LoadBalancing::Client* pLbc);
void connect(const ExitGames::Common::JString& userName);
void disconnect();
void createRoom(void);
void service();
//ไฝใใใฎใคใใณใใ้ไฟกใใ้ขๆฐใๅฎ็พฉ
void raiseSomeEvent();
//ใขใณในใฟใผใฎใใผใฟใ้ใใ
void raiseMonData();
void raiseMonAIs();
void raiseVisualAIsData();
void raiseRating();
//
int GetOnlinePlayerCount() {
return mpLbc->getCountPlayersOnline();
}
/*
้ใใขใณในใฟใผใฎใใผใฟใใปใใใใ
args:
num:ไฝ็ช็ฎใฎใขใณในใฟใผใ
monID:ใขใณในใฟใผใฎID
*/
void SetMonData(int num, int monID)
{
m_monNUM = num;
m_monID = monID;
}
void SetText(const char* text,int id)
{
delete[] m_text[id];
m_text[id] = (char*)malloc(sizeof(char)*(strlen(text) + 1));
strcpy(m_text[id], text);
}
void SetVisualAiData(JString data, int id) {
nByte idkey = 104;
nByte datakey = 109;
m_visualAisData[id] = data;
m_datas[id].put(idkey, id);
m_datas[id].put(datakey, data);
/* delete[] m_visualAisData[id];
m_visualAisData[id] = (char*)malloc(sizeof(char) * (sizeof(data) + 1));
strcpy(m_visualAisData[id], data);*/
//for (int i = 0; i < 1024; i++) {
// m_visualAisData[id][i] = data[i];
//}
//datas[id].put((nByte)104, id);
//datas[id].put((nByte)109, data,1024);
}
int* GetEnemyAiModes() {
return m_enemyAimode;
}
void SetAiMode(int aimode, int id) {
m_aimode[id] = aimode;
}
//้ใใใฆใใใขใณในใฟใผใฎใใณใใผใใใใใ
int GetMonNum()
{
return m_hangMNUM;
}
bool isGotEnemyPythonCodes();
//้ใใใฆใใใขใณในใฟใผใฎIDใ่ฟใใ
int GetMonID()
{
return m_hangMID;
}
//็นใใฃใฆใใพใใ
bool isConect()
{
return misConect;
}
//ใใผใฟใ้ใใใฆใใฆใใใใฉใใใ
//ใใใใๆขใใฆใใใ ใ
bool isHang()
{
return misHang;
}
bool CanStartGame() {
return m_isEnemyLoadedMyData && isGotEnemyPythonCodes();
}
bool isEnemyLoadedMydata() {
return m_isEnemyLoadedMyData;
}
void SetEnemyLoadedMyDate(bool flag) {
m_isEnemyLoadedMyData = flag;
}
bool raiseMyLoadingState();
//012
void SetTeamMonsterInfo(int info[3]);
float GetEnemyRate() {
return m_enemyRate;
}
int* GetEnemyTeamIDs() {
return m_enemyTeamData;
}
bool isJoining() { return m_isJoining; }
void DataReset();
bool isEnemyAbandoned(){
return m_enemyAbandoned;
}
private:
//From Common::BaseListener
// receive and print out debug out here
virtual void debugReturn(int debugLevel, const ExitGames::Common::JString& string);
//From LoadBalancing::LoadBalancingListener
// implement your error-handling here
virtual void connectionErrorReturn(int errorCode);
virtual void clientErrorReturn(int errorCode);
virtual void warningReturn(int warningCode);
virtual void serverErrorReturn(int errorCode);
// events, triggered by certain operations of all players in the same room
virtual void joinRoomEventAction(int playerNr, const ExitGames::Common::JVector<int>& playernrs, const ExitGames::LoadBalancing::Player& player);
virtual void leaveRoomEventAction(int playerNr, bool isInactive);
virtual void customEventAction(int playerNr, nByte eventCode, const ExitGames::Common::Object& eventContent);
// callbacks for operations on PhotonLoadBalancing server
virtual void connectReturn(int errorCode, const ExitGames::Common::JString& errorString, const ExitGames::Common::JString& region, const ExitGames::Common::JString& cluster);
virtual void disconnectReturn(void);
virtual void createRoomReturn(int localPlayerNr, const ExitGames::Common::Hashtable& gameProperties, const ExitGames::Common::Hashtable& playerProperties, int errorCode, const ExitGames::Common::JString& errorString);
virtual void joinOrCreateRoomReturn(int localPlayerNr, const ExitGames::Common::Hashtable& gameProperties, const ExitGames::Common::Hashtable& playerProperties, int errorCode, const ExitGames::Common::JString& errorString);
virtual void joinRoomReturn(int localPlayerNr, const ExitGames::Common::Hashtable& gameProperties, const ExitGames::Common::Hashtable& playerProperties, int errorCode, const ExitGames::Common::JString& errorString);
virtual void joinRandomRoomReturn(int localPlayerNr, const ExitGames::Common::Hashtable& gameProperties, const ExitGames::Common::Hashtable& playerProperties, int errorCode, const ExitGames::Common::JString& errorString);
virtual void leaveRoomReturn(int errorCode, const ExitGames::Common::JString& errorString);
virtual void gotQueuedReturn(void);
virtual void joinLobbyReturn(void);
virtual void leaveLobbyReturn(void);
virtual void onRoomListUpdate(void);
virtual void onLobbyStatsUpdate(const ExitGames::Common::JVector<ExitGames::LoadBalancing::LobbyStatsResponse>& lobbyStats);
virtual void onLobbyStatsResponse(const ExitGames::Common::JVector<ExitGames::LoadBalancing::LobbyStatsResponse>& lobbyStats);
virtual void onRoomPropertiesChange(const ExitGames::Common::Hashtable& changes);
void updateState(void);
void afterRoomJoined(int localPlayerNr);
private:
enum EnEvetCode
{
enText = 5,
enMonData,
enRateData,
enVisualAiData,
enLoadState,
};
int m_toRaiseTeamData[3] = { 0 , 0 , 0};
int m_enemyTeamData[3] = { -1 , -1 , -1 };
std::string m_pythonCode;
ExitGames::LoadBalancing::Client* mpLbc;
BaseView* mpView;
int mMap = 1; //ใซใผใ ไฝๆๆใซไฝฟใKey
int m_val = 10; //้ไฟกใใๅคใชใฉใ้ฉๅฝใซๅฎ็พฉ
int m_maxPlayer = 2;
int m_monNUM = 0; //ใขใณในใฟใผใฎใใณใใผ
int m_monID = 0; //ใขใณในใฟใผใฎID
int m_hangMNUM = 0; //้ใใใฆใใใขใณในใฟใผใฎใใณใใผ
int m_hangMID = 0; //้ใใใฆใใใขใณในใฟใผใฎID
char* m_text[3] = { nullptr, nullptr, nullptr }; //้ใใใญในใใใผใฟใ
JString m_visualAisData[3];
char* m_hangPY = nullptr; //้ใใใฆๆฅใใใญในใใใผใฟใ
int m_aimode[3] = { 0,0,0 }; //้ใAIใขใผใ
int m_enemyAimode[3] = { 0,0,0 }; //้ใใใฆใใenemy Ai Mode(VA)
int mLocalPlayerNr; //Photonใใ่ชๅใซๅฒใๆฏใใใใใฌใคใคใผใใณใใผ
LocalPlayer mLocalPlayer;
bool misConect = false; //ใคใชใใฃใฆใใ๏ผ
bool m_enemyAbandoned = false;
bool misHang = false; //ไฝใ้ใใใฆใใฆใ๏ผ
bool m_isEnemyLoadedMyData = false;
bool m_isAiLoaded[3] = { false, false, false };
float m_enemyRate = 0.f;
bool m_isJoining = false;
Hashtable m_datas[3];
};
|
// File: main.cpp
// Date: 09/10/2014
// Description: Manage the entree point function
// Author: roboticslab - UC3M
// http://roboticslab.uc3m.es/
#include "Humabot.hpp"
#include <cstdlib>
using namespace webots;
int main(int argc, char **argv)
{
Humabot *controller = new Humabot();
controller->run();
delete controller;
return EXIT_FAILURE;
}
|
#ifndef FIELD_H
#define FIELD_H
#include <QObject>
#include "Array.h"
class Sight;
class Object;
class Force;
class QTimer;
class Field : public QObject
{
Q_OBJECT
public:
class Event;
class MoveEvent;
class CrashEvent;
class ForceEvent;
private:
static Field* field;
Field(void);
Field(const Field&);
virtual ~Field(void);
public:
static Field* getInstance(void);
static void deleteInstance(void);
void open(void);
Object* getObject(int);
int getObjectNum(void);
void addObject(Object*);
void deleteObject(Object*);
void addForce(Force*);
void deleteForce(Object*);
public slots:
void execTimeEvent(void);
void timeControl(void);
private:
Sight* sight;
QTimer* time;
Array<Object*> object;
Array<Force*> force;
Event* forceEvent;
Event* crashEvent;
Event* moveEvent;
};
#endif
|
#include <iostream>
#include <algorithm>
using namespace std;
long factors[1001] = { 0 };
long pos[1001];
void preCalcDivisors() {
long count = 0;
long n = 0;
long divisors = 1;
for (long j = 1; j <= 1001; j++) {
count = 0;
n = j;
divisors = 1;
for (long i = 2; i*i <= n; i++) {
count = 0;
while (n%i == 0)
{
n /= i;
count++;
}
if (count) {
count++;
divisors *= count;
}
}
if (n > 1) {
count = 1;
count++;
divisors *= count;
}
factors[j] = divisors;
}
}
bool myfunc(long i, long j) {
if(factors[i] == factors[j])
return j < i;
return factors[i] < factors[j];
}
int main() {
ios_base::sync_with_stdio(false);
preCalcDivisors();
for (int i = 0; i < 1000; i++)
pos[i] = i + 1;
sort(pos, pos + 1000, myfunc);
int t, n;
cin >> t;
for (int tc = 1; tc <= t; tc++) {
cin >> n;
cout << "Case " << tc << ": " << pos[n - 1] << "\n";
}
}
|
#ifndef __DE__EMITTER_H__
#define __DE__EMITTER_H__
#include <map>
#include <functional>
#include <string>
namespace de {
struct __nodata {};
template <class T = struct __nodata>
class Emitter
{
typedef std::function< void(T) > event_cb;
typedef std::multimap<std::string, event_cb> mm_t;
mm_t consumers;
protected:
Emitter()
{
}
public:
typedef typename mm_t::iterator id_t;
id_t on(std::string event, event_cb cb)
{
return consumers.insert(std::make_pair(event, cb));
}
void off(id_t id)
{
consumers.erase(id);
}
void disable(std::string event)
{
consumers.erase(event);
}
void emit(std::string event, T data)
{
mm_t tmp = consumers;
auto range = tmp.equal_range(event);
auto it = range.first;
while (it != range.second) {
auto current = it++;
(current->second)(data);
}
}
};
template <>
class Emitter <struct __nodata>
{
typedef std::function< void() > event_cb;
typedef std::multimap<std::string, event_cb> mm_t;
mm_t consumers;
protected:
Emitter()
{
}
public:
typedef typename mm_t::iterator id_t;
id_t on(std::string event, event_cb cb)
{
return consumers.insert(std::make_pair(event, cb));
}
void off(id_t id)
{
consumers.erase(id);
}
void disable(std::string event)
{
consumers.erase(event);
}
void emit(std::string event)
{
mm_t tmp = consumers;
auto range = tmp.equal_range(event);
auto it = range.first;
while (it != range.second) {
auto current = it++;
(current->second)();
}
}
};
};
#endif
|
#define BOOST_TEST_MODULE GraphLaplacian
#include <boost/test/unit_test.hpp>
#include <utility>
#include <vector>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/numeric/ublas/assignment.hpp>
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <graph_laplacian.hpp>
// An matrix equality check copied from: http://lists.boost.org/Archives/boost/2005/11/96235.php
template<class E>
bool equal(boost::numeric::ublas::matrix<E> lhs, boost::numeric::ublas::matrix<E> rhs)
{
if (&lhs == &rhs) { return true; }
if (lhs.size1() != rhs.size1()) { return false; }
if (lhs.size2() != rhs.size2()) { return false; }
typename boost::numeric::ublas::matrix<E>::iterator1 l(lhs.begin1());
typename boost::numeric::ublas::matrix<E>::iterator1 r(rhs.begin1());
while (l != lhs.end1()) {
if (*l != *r) { return false; }
++l;
++r;
}
return true;
}
using Graph = boost::adjacency_list<boost::setS, boost::vecS, boost::undirectedS>;
using Matrix = boost::numeric::ublas::matrix<int>;
BOOST_AUTO_TEST_SUITE(TestGraphLaplacian)
// An empty graph produces an empty matrix
BOOST_AUTO_TEST_CASE(EmptyGraphTest)
{
Graph g;
BOOST_CHECK(equal(graph_laplacian(g), Matrix(0, 0)));
}
// A graph with n vertices and no edges produces an (n x n)-zero matrix
BOOST_AUTO_TEST_CASE(NoEdgesTest)
{
Graph g(5);
BOOST_CHECK(equal(graph_laplacian(g), Matrix(5, 5, 0)));
}
// A graph with two vertices and an edge connecting them produces the following Laplacian matrix:
// 1 -1
// -1 1
BOOST_AUTO_TEST_CASE(TwoVerticesOneEdgeGraphTest)
{
using Edge = std::pair<int, int>;
std::vector<Edge> edges { Edge(0, 1) };
Graph g(edges.begin(), edges.end(), 2);
Matrix expected_mat(2, 2);
expected_mat <<= 1, -1,
-1, 1;
BOOST_CHECK(equal(graph_laplacian(g), expected_mat));
}
// A free tree on 3 vertices (vertex 1 is the center vertex) produces following Laplacian matrix:
// 1 -1 0
// -1 2 -1
// 0 -1 1
BOOST_AUTO_TEST_CASE(ThreeVerticesFreeTreeTest)
{
using Edge = std::pair<int, int>;
std::vector<Edge> edges { Edge(0, 1), Edge(1, 2) };
Graph g(edges.begin(), edges.end(), 3);
Matrix expected_mat(3, 3);
expected_mat <<= 1, -1, 0,
-1, 2, -1,
0, -1, 1;
BOOST_CHECK(equal(graph_laplacian(g), expected_mat));
}
// A free tree on 4 vertices (vertices 1, 2 are the middle vertices) produces following
// Laplacian matrix:
// 1 -1 0 0
// -1 2 -1 0
// 0 -1 2 -1
// 0 0 -1 1
BOOST_AUTO_TEST_CASE(FourVerticesFreeTreeTest)
{
using Edge = std::pair<int, int>;
std::vector<Edge> edges { Edge(0, 1), Edge(1, 2), Edge(2, 3) };
Graph g(edges.begin(), edges.end(), 4);
Matrix expected_mat(4, 4);
expected_mat <<= 1, -1, 0, 0,
-1, 2, -1, 0,
0, -1, 2, -1,
0, 0, -1, 1;
BOOST_CHECK(equal(graph_laplacian(g), expected_mat));
}
// A graph forming a square with 4 vertices produces follwoing Laplacian matrix:
// 2 -1 0 -1
// -1 2 -1 0
// 0 -1 2 -1
// -1 0 -1 2
BOOST_AUTO_TEST_CASE(SquareTest)
{
using Edge = std::pair<int, int>;
std::vector<Edge> edges { Edge(0, 1), Edge(1, 2), Edge(2, 3), Edge(3, 0) };
Graph g(edges.begin(), edges.end(), 4);
Matrix expected_mat(4, 4);
expected_mat <<= 2, -1, 0, -1,
-1, 2, -1, 0,
0, -1, 2, -1,
-1, 0, -1, 2;
BOOST_CHECK(equal(graph_laplacian(g), expected_mat));
}
BOOST_AUTO_TEST_SUITE_END() // TestGraphLaplacian
|
// Touchboard.h
#ifndef _TOUCHBOARD_h
#define _TOUCHBOARD_h
#include "Config.h"
#include "Output.h"
#include "PinConfig.h"
#ifndef TEENSY
#include "CapacitiveSensor.h"
#endif
#include <EEPROM.h>
#include <FastLED.h>
#define CALIBRATION_SAMPLES 75
#define CALIBRATION_DETECTION_THRESHOLD 8
#define CALIBRATION_FLAG 0xFF
#define DEFAULT_SENSITIVITY 97
extern CRGB leds[31];
class AutoTouchboard
{
private:
#ifndef TEENSY
CapacitiveSensor sensor;
#endif
uint8_t sensitivity;
uint16_t key_values[32];
uint16_t lowest_key_values[32];
uint16_t single_thresholds[32];
uint16_t double_thresholds[32];
public:
AutoTouchboard();
void scan();
void loadConfig();
void saveConfig();
KeyState update(int key);
uint16_t getRawValue(int key);
void calibrateKeys(bool forceCalibrate = false);
void setSensitivity(uint8_t sensitivity);
uint8_t getSensitivity();
};
#endif
|
/*
* File: test.cpp
* Author: Richard Fussenegger
* Author: Markus Deutschl
*
* Created on November 19, 2012, 10:50 PM
*/
#include <iostream>
#include <list>
#include <vector>
#include "skiplist.h"
using namespace std;
int main() {
/** Iterator and random key variable. */
int i = 0, randKey;
/** Our skiplist to test. */
skiplist<int, int> skiplistObj(5);
// Fill something into our skiplist.
cout << endl << "Inserting keys and values into our skiplist:" << endl;
for (; i < 10; ++i) {
randKey = rand() % 100;
skiplistObj.insert(randKey, i);
cout << "Inserted key " << randKey << " with value " << i << "." << endl;
}
// Show me!
cout << endl << "Using the print method of our skiplist:" << endl;
skiplistObj.print();
// Use the list.
cout << endl << "Iterating over our key list:" << endl;
list<int> skiplistKeyList = skiplistObj.getKeyList();
list<int>::const_iterator listIterator;
for (listIterator = skiplistKeyList.begin(); listIterator != skiplistKeyList.end(); ++listIterator) {
cout << *listIterator << endl;
}
// Use the vector.
cout << endl << "Iterating over our key vector:" << endl;
vector<int> skiplistKeyVector = skiplistObj.getKeyVector();
vector<int>::const_iterator vectorIterator;
for (vectorIterator = skiplistKeyVector.begin(); vectorIterator != skiplistKeyVector.end(); ++vectorIterator) {
cout << *vectorIterator << endl;
}
return 0;
}
|
#include <cstring>
#include <ostream>
#include <string>
#include <sstream>
#include <vector>
#include "profile_util.h"
#include "timer.h"
void debug_timer_dump(char const *timer)
{
if (!TIMER_EXISTS(timer)) {
debug("TIMER (" + std::string(timer) + "): never invoked");
return;
}
std::ostream *os = TIMER_GET_OUT();
std::stringstream ss;
TIMER_SET_OUT(&ss);
TIMER_DUMP(timer);
auto str(ss.str());
debug(str.substr(0u, str.size() - 1u));
TIMER_SET_OUT(os);
}
std::vector<std::string> split(std::string const &str, char const *delim)
{
if (str.find(delim) == std::string::npos)
return {str};
std::vector<std::string> res;
std::size_t pos = 0u, nextpos;
for (;;) {
nextpos = str.find(delim, pos);
if (nextpos == std::string::npos) {
res.push_back(str.substr(pos, str.size() - pos));
break;
} else {
res.push_back(str.substr(pos, nextpos - pos));
}
pos = nextpos + strlen(delim);
}
return res;
}
std::string join(std::vector<std::string> const &strs, char const *delim)
{
if (strs.empty())
return "";
std::string res(strs[0]);
for (auto i = 1u; i < strs.size(); ++i)
res += delim + strs[i];
return res;
}
|
#include<stdio.h>
#include<string.h>
char s[200000000];
int main()
{
int len;
scanf("%s",&s);
len = strlen(s);
if (len<=3)
{
if (len==3)
printf("%c%c%c\n",s[0],s[1],s[2]);
else if (len==2)
printf("%c%c\n",s[0],s[1]);
else printf("%c\n",s[0]);
}
else if (len<=6)
{
if (len==6)
printf("%c%c%c,%c%c%c\n",s[0],s[1],s[2],s[3],s[4],s[5]);
else if(len==5)
printf("%c%c,%c%c%c\n",s[0],s[1],s[2],s[3],s[4]);
else if (len==4)
printf("%c,%c%c%c\n",s[0],s[1],s[2],s[3]);
}
else
{
if (len==9)
printf("%c%c%c,%c%c%c,%c%c%c\n",s[0],s[1],s[2],s[3],s[4],s[5],s[6],s[7],s[8]);
else if (len==8)
printf("%c%c,%c%c%c,%c%c%c\n",s[0],s[1],s[2],s[3],s[4],s[5],s[6],s[7]);
else if(len==7)
printf("%c,%c%c%c,%c%c%c\n",s[0],s[1],s[2],s[3],s[4],s[5],s[6]);
}
return 0;
}
|
#include<iostream>
using namespace std;
class Node {
/*class Node to create a pointer
*that points to next element of the queue and data
*that has to be stored in the node */
public:
int data;
Node* next;
Node() { //constructor.
data = 0;
next = NULL;
}
};
class Stack {
/*
* Class for Stack data structure.
* Contains two pointers namely head and tail, which point
* to the first and the last element of the list.
* A integer variable named size stores the number of
* items of the linked list.
*/
private:
Node* head;
Node* tail;
int n;
public:
Stack() { //Constructor.
head = NULL;
tail = NULL;
n = 0;
}
void push(int x);
void pop();
void display();
};
void Stack::push(int x) {
/*
* Inserts a new Node
* at the end of the Stack.
*/
Node* temp = new Node;
temp->data = x;
temp->next = NULL;
if (head == NULL) { //Steps done when the Stack is empty
head = temp;
tail = temp;
++n;
} else { //Steps done when the Stack is not empty
tail->next = temp;
tail = temp;
++n;
}
}
void Stack::pop() {
/*Remove the node from the end in the Stack.*/
Node* temp= head;
for (int j=0; j<n-2; ++j)
temp=temp->next;
temp->next = NULL;
tail = temp;
--n;
}
void Stack::display() {
/*
* Displays all the elements of the linked list.
*/
if (head == NULL) {
cout << "There are no elements in the stack." << endl;
} else {
Node*p = head;
while(p != NULL) {
cout << p->data <<"->";
p = p->next;
}
cout<<"NULL"<<endl;
}
}
int main() {
/*main function to check
*whether the code is correct or not*/
Stack s1;
int p=0;
cout << "Enter five elements to the list: " << endl;
for (int i=0; i<5; ++i) {
cin >> p;
s1.push(p);
}
s1.display();
s1.push(25);
s1.display();
s1.pop();
s1.display();
return 0;
}
|
/**
* Write a program to calculate sum of n numbers using thread library.
*
*/
#include <cstdlib>
#include <iostream>
#include <pthread.h>
using namespace std;
long long sum;
void *runner(void *number);
int main(int argc, char **argv)
{
if (argc != 2)
{
cerr << "Usage: ./main <upper>" << endl;
exit(1);
}
if (atoi(argv[1]) < 0)
{
cerr << "Argument must be non-negative." << endl;
exit(1);
}
pthread_t tid;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_create(&tid, &attr, runner, (void *)argv[1]);
pthread_join(tid, NULL);
cout << "Sum from 1 to " << atoi(argv[1])
<< " is " << sum << endl;
return 0;
}
void *runner(void *upper)
{
int num = atoi((const char *)(upper));
for (int i = 1; i <= num; i++)
sum += i;
pthread_exit(0);
return nullptr;
}
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <quic/dsr/Types.h>
namespace quic {
WriteStreamFrame sendInstructionToWriteStreamFrame(
const SendInstruction& sendInstruction,
uint64_t streamPacketIdx) {
WriteStreamFrame frame(
sendInstruction.streamId,
sendInstruction.streamOffset,
sendInstruction.len,
sendInstruction.fin);
frame.fromBufMeta = true;
frame.streamPacketIdx = streamPacketIdx;
return frame;
}
} // namespace quic
|
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Portions of this file are from JUCE.
Copyright (c) 2013 - Raw Material Software Ltd.
Please visit http://www.juce.com
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef BEAST_MACADDRESS_H_INCLUDED
#define BEAST_MACADDRESS_H_INCLUDED
//==============================================================================
/**
A wrapper for a streaming (TCP) socket.
This allows low-level use of sockets; for an easier-to-use messaging layer on top of
sockets, you could also try the InterprocessConnection class.
@see DatagramSocket, InterprocessConnection, InterprocessConnectionServer
*/
class BEAST_API MACAddress
{
public:
//==============================================================================
/** Populates a list of the MAC addresses of all the available network cards. */
static void findAllAddresses (Array<MACAddress>& results);
//==============================================================================
/** Creates a null address (00-00-00-00-00-00). */
MACAddress();
/** Creates a copy of another address. */
MACAddress (const MACAddress& other);
/** Creates a copy of another address. */
MACAddress& operator= (const MACAddress& other);
/** Creates an address from 6 bytes. */
explicit MACAddress (const uint8 bytes[6]);
/** Returns a pointer to the 6 bytes that make up this address. */
const uint8* getBytes() const noexcept { return address; }
/** Returns a dash-separated string in the form "11-22-33-44-55-66" */
String toString() const;
/** Returns the address in the lower 6 bytes of an int64.
This uses a little-endian arrangement, with the first byte of the address being
stored in the least-significant byte of the result value.
*/
int64 toInt64() const noexcept;
/** Returns true if this address is null (00-00-00-00-00-00). */
bool isNull() const noexcept;
bool operator== (const MACAddress& other) const noexcept;
bool operator!= (const MACAddress& other) const noexcept;
//==============================================================================
private:
uint8 address[6];
};
#endif // BEAST_MACADDRESS_H_INCLUDED
|
#include<bits/stdc++.h>
using namespace std;
#define maxn 55
typedef long long ll;
ll dp[maxn][5];
ll ans[maxn];
void init(){
ans[1]=2;
ans[2]=3;
dp[2][0]=1;
dp[2][1]=1;
dp[2][2]=1;
for(int i=3;i<52;i++){
dp[i][0]=dp[i-1][0]+dp[i-1][2];
dp[i][1]=dp[i-1][0]+dp[i-1][2];
dp[i][2]=dp[i-1][1];
ans[i]=dp[i][0]+dp[i][1]+dp[i][2];
// printf("00 %d\n01 %d\n10 %d\ni=%d ans=%d\n",dp[i][0],dp[i][1],dp[i][2],i,ans[i]);
}
}
int main(){
init();
int n;
scanf("%d",&n);
int cnt=1;
while(n--){
int x;
scanf("%d",&x);
printf("Scenario #%d:\n%lld\n\n",cnt,ans[x]);
cnt++;
}
return 0;
}
//0->00
//1->01
//2->10
|
//็ฎๆณ๏ผๆฐ่ฎบ
//ๅ
ๅฐ่พๅ
ฅx๏ผy่ฟ่ก่ดจๅ ๆฐๅ่งฃ
//็ถๅๆฏ่พๅ่งฃๅๆฏไธไธช่ดจๆฐ็ๅบ็ฐๆฌกๆฐ:
//ๅฆๆxx[i]<yy[i],ans*=2;
//ๅฆๆxx[i]>yy[i],่ฏๆ็ปๅบๆฐๆฎไธๅๆณ,ๆฒกๆ็ญๆก
#include <cstdio>
#include <cmath>
#include <algorithm>
const int N = 1050;
int xx[N],yy[N];
void split(int x,int *s)//ๆๅ
{
int n=sqrt(x);
for(int i=2;i<=n;i++)
while(x%i==0)
x/=i,s[i]++;
if(x!=1)s[x]++;
}
int main()
{
int x,y;
long long ans=1;
scanf("%d%d",&x,&y);
split(x,xx);
split(y,yy);
for(int i=2;i<=1000;i++)
{
if(xx[i]>yy[i]) ans=0;
if(xx[i]<yy[i]) ans*=2;
}
printf("%lld",ans);
}
|
#ifndef DPREVIEWWINDOW_H
#define DPREVIEWWINDOW_H
#include <QAbstractNativeEventFilter>
#include <QQuickItem>
#include <QMutex>
#include <QPointer>
class DPreviewWindow : public QQuickItem
{
Q_OBJECT
Q_DISABLE_COPY(DPreviewWindow)
Q_PROPERTY(quint32 xid READ xid WRITE setXid NOTIFY xidChanged)
public:
DPreviewWindow(QQuickItem *parent = 0);
~DPreviewWindow();
quint32 xid() { return m_xid; }
void setXid(quint32 xid);
Q_SIGNAL void xidChanged(quint32);
private:
Q_SLOT void onXidChanged(quint32 xid);
friend class Monitor;
QSGNode *updatePaintNode(QSGNode *, UpdatePaintNodeData *);
void markDamaged() { m_damaged=true;}
void bindTexture();
quint32 pixmap() { return m_pixmap; }
void updatePixmap();
void releasePixmap();
void updateWinSize(quint32 width, quint32 height);
QRect getDisplayRect();
quint16 win_width;
quint16 win_height;
quint32 m_xid;
quint32 m_texture;
quint32 m_pixmap;
quint32 m_glx_pixmap;
quint32 m_fbconfig;
bool m_damaged;
};
#endif // DPREVIEWWINDOW_H
|
// Created on: 2001-01-06
// Created by: OCC Team
// Copyright (c) 2001-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 _Message_Printer_HeaderFile
#define _Message_Printer_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <Message_Gravity.hxx>
#include <Standard_Transient.hxx>
#include <Standard_SStream.hxx>
class TCollection_ExtendedString;
class TCollection_AsciiString;
class Message_Printer;
DEFINE_STANDARD_HANDLE(Message_Printer, Standard_Transient)
//! Abstract interface class defining printer as output context for text messages
//!
//! The message, besides being text string, has associated gravity
//! level, which can be used by printer to decide either to process a message or ignore it.
class Message_Printer : public Standard_Transient
{
DEFINE_STANDARD_RTTIEXT(Message_Printer, Standard_Transient)
public:
//! Return trace level used for filtering messages;
//! messages with lover gravity will be ignored.
Message_Gravity GetTraceLevel() const { return myTraceLevel; }
//! Set trace level used for filtering messages.
//! By default, trace level is Message_Info, so that all messages are output
void SetTraceLevel (const Message_Gravity theTraceLevel) { myTraceLevel = theTraceLevel; }
//! Send a string message with specified trace level.
//! The last Boolean argument is deprecated and unused.
//! Default implementation redirects to send().
Standard_EXPORT virtual void Send (const TCollection_ExtendedString& theString,
const Message_Gravity theGravity) const;
//! Send a string message with specified trace level.
//! The last Boolean argument is deprecated and unused.
//! Default implementation redirects to send().
Standard_EXPORT virtual void Send (const Standard_CString theString,
const Message_Gravity theGravity) const;
//! Send a string message with specified trace level.
//! The last Boolean argument is deprecated and unused.
//! Default implementation redirects to send().
Standard_EXPORT virtual void Send (const TCollection_AsciiString& theString,
const Message_Gravity theGravity) const;
//! Send a string message with specified trace level.
//! Stream is converted to string value.
//! Default implementation calls first method Send().
Standard_EXPORT virtual void SendStringStream (const Standard_SStream& theStream, const Message_Gravity theGravity) const;
//! Send a string message with specified trace level.
//! The object is converted to string in format: <object kind> : <object pointer>.
//! Default implementation calls first method Send().
Standard_EXPORT virtual void SendObject (const Handle(Standard_Transient)& theObject, const Message_Gravity theGravity) const;
protected:
//! Empty constructor with Message_Info trace level
Standard_EXPORT Message_Printer();
//! Send a string message with specified trace level.
//! This method must be redefined in descendant.
Standard_EXPORT virtual void send (const TCollection_AsciiString& theString,
const Message_Gravity theGravity) const = 0;
protected:
Message_Gravity myTraceLevel;
};
#endif // _Message_Printer_HeaderFile
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
// version1
/*
std::vector<int> countBits(int num)
{
std::vector<int> ret;
for (int i = 0; i <= num; ++i) {
int count = 0;
int n = i;
while (n > 0) {
if ((n & 1) == 1) {
++count;
}
n >>= 1;
}
ret.push_back(count);
//std::cout << count << std::endl;
}
return ret;
}
*/
// version2
/*
std::vector<int> countBits(int num){
std::vector<int> ret;
for (int i = 0; i <= num; ++i){
int count;
int n = i;
for(count = 0; n; ++count){
n &= (n - 1);
}
ret.push_back(count);
}
return ret;
}
*/
//version3
std::vector<int> countBits(int num){
std::vector<int> ret;
for(int i = 0; i <= num; ++i)
ret.push_back(__builtin_popcount(i));
return ret;
}
int main(int argc, char const *argv[])
{
std::ostream_iterator<int> outiter(std::cout, " ");
std::vector<int> res;
res = countBits(3);
std::copy(res.begin(), res.end(), outiter);
std::cout << std::endl;
return 0;
}
|
/***************************************************************************
* Copyright (C) 2009 by Dario Freddi *
* drf@chakra-project.org *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
#ifndef WORKER_P_H
#define WORKER_P_H
#include <QObject>
#include <QVariantList>
#include <QProcess>
#include <QtDBus/QDBusContext>
#include <QtDBus/QDBusConnection>
#include <QtDBus/QDBusMessage>
#include <alpm.h>
#include "TemporizedApplication_p.h"
#include "../Globals.h"
#include <QueueItem.h>
namespace AqpmWorker
{
class Worker : public QObject, protected QDBusContext, private TemporizedApplication
{
Q_OBJECT
public:
explicit Worker(bool temporized, QObject *parent = 0);
virtual ~Worker();
bool isWorkerReady();
public Q_SLOTS:
void processQueue(const QVariantList &packages, int flags);
void downloadQueue(const QVariantList &packages);
void retrieveTargetsForQueue(const QVariantList &packages, int flags);
void updateDatabase();
void systemUpgrade(int flags, bool downgrade);
void setAnswer(int answer);
void performMaintenance(int type);
void interruptTransaction();
void setAqpmRoot(const QString& root, bool toConfiguratio);
void setUpAlpm();
QDBusConnection dbusConnection() const;
QString dbusService() const;
private:
void operationPerformed(bool result);
bool addTransTarget(const QString &target);
bool performTransaction();
pmtransflag_t processFlags(Aqpm::Globals::TransactionFlags flags);
bool prepareTransaction(alpm_list_t *data);
bool commitTransaction(alpm_list_t *data);
Aqpm::QueueItem::List targets(alpm_list_t *packages, Aqpm::QueueItem::Action action);
private Q_SLOTS:
void processFinished(int exitCode, QProcess::ExitStatus exitStatus);
void errorOutput();
void standardOutput();
Q_SIGNALS:
void workerReady();
void workerResult(bool);
void dbStatusChanged(const QString &repo, int action);
void dbQty(const QStringList &db);
void streamTransProgress(int event, const QString &pkgname, int percent,
int howmany, int remain);
void streamTransEvent(int event, const QVariantMap &args);
void streamTransQuestion(int event, const QVariantMap &args);
void streamTotalOffset(int offset);
void errorOccurred(int code, const QVariantMap &details);
void messageStreamed(const QString &msg);
void logMessageStreamed(const QString &msg);
void targetsRetrieved(const QVariantMap &targets);
void streamAnswer(int answer);
private:
class Private;
Private *d;
};
}
#endif /* WORKER_P_H */
|
๏ปฟ#ifndef _CBankGetMoney_h_
#define _CBankGetMoney_h_
#pragma once
#include "CHttpRequestHandler.h"
#include <string>
class CBankGetMoney : public CHttpRequestHandler
{
public:
CBankGetMoney(){}
~CBankGetMoney(){}
virtual int do_request(const Json::Value& root, char *client_ip, HttpResult& out);
private:
};
#endif
|
//้พๅผๅๅๆ
//ST<int,MAXN<<1> st;
int dfn[MAXN<<1];//ๆฌงๆๅบๅ,ๅณdfs้ๅ็้กบๅบ,้ฟๅบฆไธบ2*n-1,ไธๆ ไป1ๅผๅง
int id[MAXN];//็นiๅจdfnไธญ็ฌฌไธๆฌกๅบ็ฐ็ไฝ็ฝฎ
int stamp;
void dfs(int u,int pre,int dep) {
dfn[++stamp]=u;
st.data[stamp]=dep;
id[u]=stamp;
for(int i=head[u]; ~i ;i = edge[i].next) {
int v=edge[i].to;
if(v==pre)continue;
dfs(v,u,dep+1);
dfn[++stamp]=u;
st.data[stamp]=dep;
}
}
void LCA_init(int root,int n){
stamp=0;
dfs(root,root,0);
st.build(2*n-1);
}//ๆฅ่ฏขLCAๅ็ๅๅงๅ,่ฎฐๅพๅ
่ฐ็จ
int query_lca(int u,int v){
return dfn[st.query(id[u],id[v])];
}//ๆฅ่ฏขu,v็lca็ผๅท
|
#include "mainwindow.h"
#include <QApplication>
#include <QtSql/QSqlDatabase>
#include <iostream>
#include <QDebug>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
// qDebug() << QCoreApplication::libraryPaths ();
// QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL");
// db.setHostName("localhost");
// db.setDatabaseName("postgres");
// db.setUserName("postgres");
// db.setPassword("eminem123");
// bool ok = db.open();
// if(ok){
// printf("dsds");
// }
// QTableView table_view;
// MyModel model(0);
// table_view.setModel(&model);
// table_view.show();
// return 0;
return a.exec();
}
|
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
using namespace cv;
int main(int, char**)
{
const char* gst = "nvcamerasrc ! video/x-raw(memory:NVMM), width=(int)1280, height=(int)720, format=(string)I420, framerate=(fraction)120/1 ! \
nvvidconv flip-method=0 ! video/x-raw, format=(string)BGRx ! \
videoconvert ! video/x-raw, format=(string)BGR ! \
appsink";
VideoCapture cap(gst);
if (!cap.isOpened()) return -1;
Mat frame, edges;
namedWindow("edges",1);
for(;;)
{
cap >> frame;
cvtColor(frame, edges, COLOR_BGR2GRAY);
GaussianBlur(edges, edges, Size(7,7), 1.5, 1.5);
Canny(edges, edges, 0, 30, 3);
imshow("edges", edges);
if(waitKey(30) >= 0) break;
}
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2012 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* @author Arjan van Leeuwen (arjanl)
*/
#ifndef GTK_SKIN_ELEMENT_H
#define GTK_SKIN_ELEMENT_H
#include "platforms/quix/toolkits/NativeSkinElement.h"
#include "platforms/quix/toolkits/gtk2/GtkPorting.h"
#include <gtk/gtk.h>
#ifdef GTK3
# define OP_PI (3.14159265)
#endif
class GtkSkinElement : public NativeSkinElement
{
public:
GtkSkinElement() : m_layout(0), m_widget(0), m_all_widgets(0) {}
virtual ~GtkSkinElement();
void SetLayout(GtkWidget* layout) { m_layout = layout; }
virtual void Draw(uint32_t* bitmap, int width, int height, const NativeRect& clip_rect, int state);
virtual void ChangeDefaultPadding(int& left, int& top, int& right, int& bottom, int state) {}
virtual void ChangeDefaultMargin(int& left, int& top, int& right, int& bottom, int state);
virtual void ChangeDefaultSize(int& width, int& height, int state) {}
virtual void ChangeDefaultTextColor(uint8_t& red, uint8_t& green, uint8_t& blue, uint8_t& alpha, int state) {}
virtual void ChangeDefaultSpacing(int &spacing, int state) {}
protected:
GdkWindow* GetGdkWindow() { return IsTopLevel() ? gtk_widget_get_window(m_widget) : gtk_widget_get_parent_window(m_widget); }
virtual void GtkDraw(op_gdk_surface *pixmap, int width, int height, GdkRectangle& clip_rect, GtkWidget* widget, GtkStyle* style, int state) = 0;
virtual GtkWidget* CreateWidget() = 0;
virtual bool RespectAlpha() { return true; }
virtual bool IsTopLevel() { return false; }
void ChangeTextColor(uint8_t& red, uint8_t& green, uint8_t& blue, uint8_t& alpha, int state);
bool CreateInternalWidget();
/**
* Return style name, that should be passed to gtk_style_context_add_class in order to access
* widget-specific properties (e.g font colour).
*/
virtual const char* GetStyleContextClassName() const { return NULL; }
virtual GtkWidget* GetTextWidget() const { return NULL; }
#ifdef GTK3
virtual GtkStateFlags GetGtkStateFlags(int state);
void CairoDraw(uint32_t* bitmap, int width, int height, GtkStyle* style, int state);
#else
void DrawWithAlpha(uint32_t* bitmap, int width, int height, GdkRectangle& clip_rect, GtkStyle* style, int state);
void DrawSolid(uint32_t* bitmap, int width, int height, GdkRectangle& clip_rect, GtkStyle* style, int state);
#if defined(GTK2_DEPRECATED)
GdkPixbuf* DrawOnBackground(GdkGC* background_gc, int width, int height, GdkRectangle& clip_rect, GtkStyle* style, int state);
#else
GdkPixbuf* DrawOnBackground(double red, double green, double blue, int width, int height, GdkRectangle& clip_rect, GtkStyle* style, int state);
#endif // GTK2_DEPRECATED
static inline uint32_t GetARGB(guchar* pixel, uint8_t alpha = 0xff) { return (alpha << 24) | (pixel[0] << 16) | (pixel[1] << 8) | pixel[2]; }
static inline uint32_t GetARGB(guchar* black_pixel, guchar* white_pixel) { return GetARGB(black_pixel, black_pixel[0] - white_pixel[0] + 255); }
#endif // !GTK3
virtual GtkStateType GetGtkState(int state);
static int Round(double num);
#ifdef DEBUG
static void PrintState(int state);
#endif
static void RealizeSubWidgets(GtkWidget* widget, gpointer widget_table);
GtkWidget* m_layout;
GtkWidget* m_widget;
GHashTable* m_all_widgets;
};
namespace GtkSkinElements
{
class EmptyElement : public GtkSkinElement
{
virtual void Draw(uint32_t* bitmap, int width, int height, const NativeRect& clip_rect, int state);
virtual void GtkDraw(op_gdk_surface *pixmap, int width, int height, GdkRectangle& clip_rect, GtkWidget* widget, GtkStyle* style, int state) {}
virtual GtkWidget* CreateWidget() { return 0; }
};
class ScrollbarElement : public GtkSkinElement
{
public:
enum Orientation
{
HORIZONTAL,
VERTICAL
};
ScrollbarElement(Orientation orientation) : m_orientation(orientation) {}
virtual GtkWidget* CreateWidget()
{
#ifdef GTK3
return gtk_scrollbar_new(m_orientation == VERTICAL ? GTK_ORIENTATION_VERTICAL : GTK_ORIENTATION_HORIZONTAL, NULL);
#else
return m_orientation == VERTICAL ? gtk_vscrollbar_new(0) : gtk_hscrollbar_new(0);
#endif
}
protected:
Orientation m_orientation;
};
class ScrollbarDirection : public ScrollbarElement
{
public:
enum Direction
{
UP,
DOWN,
LEFT,
RIGHT
};
ScrollbarDirection(Direction direction) : ScrollbarElement(direction < LEFT ? VERTICAL : HORIZONTAL), m_direction(direction) {}
virtual void GtkDraw(op_gdk_surface *pixmap, int width, int height, GdkRectangle& clip_rect, GtkWidget* widget, GtkStyle* style, int state);
private:
GtkArrowType GetArrow();
Direction m_direction;
};
class ScrollbarKnob : public ScrollbarElement
{
public:
ScrollbarKnob(Orientation orientation) : ScrollbarElement(orientation) {}
virtual void GtkDraw(op_gdk_surface *pixmap, int width, int height, GdkRectangle& clip_rect, GtkWidget* widget, GtkStyle* style, int state);
};
class ScrollbarBackground : public ScrollbarElement
{
public:
ScrollbarBackground(Orientation orientation) : ScrollbarElement(orientation) {}
virtual void GtkDraw(op_gdk_surface *pixmap, int width, int height, GdkRectangle& clip_rect, GtkWidget* widget, GtkStyle* style, int state);
virtual bool RespectAlpha() { return false; }
virtual void ChangeDefaultSize(int& width, int& height, int state);
};
class DropdownButton : public EmptyElement
{
virtual void GtkDraw(op_gdk_surface *pixmap, int width, int height, GdkRectangle& clip_rect, GtkWidget* widget, GtkStyle* style, int state) {}
virtual GtkWidget* CreateWidget() { return gtk_combo_box_new_with_entry(); }
virtual void ChangeDefaultSize(int& width, int& height, int state);
};
class Dropdown : public GtkSkinElement
{
virtual void GtkDraw(op_gdk_surface *pixmap, int width, int height, GdkRectangle& clip_rect, GtkWidget* widget, GtkStyle* style, int state);
virtual GtkWidget* CreateWidget() { return gtk_combo_box_new(); }
virtual void ChangeDefaultPadding(int& left, int& top, int& right, int& bottom, int state);
virtual void ChangeDefaultTextColor(uint8_t& red, uint8_t& green, uint8_t& blue, uint8_t& alpha, int state) { ChangeTextColor(red, green, blue, alpha, state); }
};
class DropdownEdit : public GtkSkinElement
{
virtual void GtkDraw(op_gdk_surface *pixmap, int width, int height, GdkRectangle& clip_rect, GtkWidget* widget, GtkStyle* style, int state);
virtual void ChangeDefaultPadding(int& left, int& top, int& right, int& bottom, int state);
virtual GtkWidget* CreateWidget()
{
// unfortunately, we can't use gtk_combo_box_entry_new as drop-in replacement in here
// it has different style and completely different arrow
#ifdef GTK3
return gtk_combo_box_new_with_entry();
#else
return gtk_combo_box_entry_new();
#endif
}
};
class PushButton : public GtkSkinElement
{
public:
PushButton(bool focused) : m_focused(focused) {}
virtual void GtkDraw(op_gdk_surface *pixmap, int width, int height, GdkRectangle& clip_rect, GtkWidget* widget, GtkStyle* style, int state);
virtual GtkWidget* CreateWidget() { return gtk_button_new_with_label("OK"); }
virtual void ChangeDefaultSize(int& width, int& height, int state);
virtual void ChangeDefaultTextColor(uint8_t& red, uint8_t& green, uint8_t& blue, uint8_t& alpha, int state) { ChangeTextColor(red, green, blue, alpha, state); }
bool m_focused;
};
class RadioButton : public GtkSkinElement
{
virtual void GtkDraw(op_gdk_surface *pixmap, int width, int height, GdkRectangle& clip_rect, GtkWidget* widget, GtkStyle* style, int state);
virtual GtkWidget* CreateWidget() { return gtk_radio_button_new(0); }
};
class CheckBox : public GtkSkinElement
{
virtual void GtkDraw(op_gdk_surface *pixmap, int width, int height, GdkRectangle& clip_rect, GtkWidget* widget, GtkStyle* style, int state);
virtual GtkWidget* CreateWidget() { return gtk_check_button_new(); }
};
class EditField : public GtkSkinElement
{
virtual void GtkDraw(op_gdk_surface *pixmap, int width, int height, GdkRectangle& clip_rect, GtkWidget* widget, GtkStyle* style, int state);
virtual GtkWidget* CreateWidget() { return gtk_entry_new(); }
virtual bool RespectAlpha() { return false; } // DSK-316828
};
class MultiLineEditField : public EditField
{
virtual void ChangeDefaultPadding(int& left, int& top, int& right, int& bottom, int state);
};
class Label : public EmptyElement
{
virtual void ChangeDefaultMargin(int& left, int& top, int& right, int& bottom, int state);
};
class Browser : public GtkSkinElement
{
virtual void GtkDraw(op_gdk_surface *pixmap, int width, int height, GdkRectangle& clip_rect, GtkWidget* widget, GtkStyle* style, int state);
virtual GtkWidget* CreateWidget() { return gtk_hbox_new(1, 1); }
};
class Dialog : public GtkSkinElement
{
virtual void GtkDraw(op_gdk_surface *pixmap, int width, int height, GdkRectangle& clip_rect, GtkWidget* widget, GtkStyle* style, int state);
virtual void ChangeDefaultPadding(int& left, int& top, int& right, int& bottom, int state);
virtual GtkWidget* CreateWidget() { return gtk_label_new(NULL); }
};
class DialogPage : public EmptyElement
{
virtual void ChangeDefaultPadding(int& left, int& top, int& right, int& bottom, int state) { left = top = right = bottom = 0; }
virtual void ChangeDefaultMargin(int& left, int& top, int& right, int& bottom, int state);
};
class DialogButtonStrip : public EmptyElement
{
virtual void ChangeDefaultPadding(int& left, int& top, int& right, int& bottom, int state) { left = top = right = bottom = 0; }
virtual void ChangeDefaultMargin(int& left, int& top, int& right, int& bottom, int state);
};
class DialogTabPage : public GtkSkinElement
{
virtual void GtkDraw(op_gdk_surface *pixmap, int width, int height, GdkRectangle& clip_rect, GtkWidget* widget, GtkStyle* style, int state);
virtual void ChangeDefaultPadding(int& left, int& top, int& right, int& bottom, int state);
virtual GtkWidget* CreateWidget() { return gtk_notebook_new(); }
};
class TabButton : public GtkSkinElement
{
virtual void GtkDraw(op_gdk_surface *pixmap, int width, int height, GdkRectangle& clip_rect, GtkWidget* widget, GtkStyle* style, int state);
virtual void ChangeDefaultPadding(int& left, int& top, int& right, int& bottom, int state);
virtual void ChangeDefaultMargin(int& left, int& top, int& right, int& bottom, int state);
virtual GtkWidget* CreateWidget() { return gtk_notebook_new(); }
};
class TabSeparator : public GtkSkinElement
{
virtual void GtkDraw(op_gdk_surface *pixmap, int width, int height, GdkRectangle& clip_rect, GtkWidget* widget, GtkStyle* style, int state);
virtual void ChangeDefaultPadding(int& left, int& top, int& right, int& bottom, int state) { left = 0; }
virtual GtkWidget* CreateWidget() { return gtk_notebook_new(); }
};
class Menu : public GtkSkinElement
{
virtual void GtkDraw(op_gdk_surface *pixmap, int width, int height, GdkRectangle& clip_rect, GtkWidget* widget, GtkStyle* style, int state);
virtual GtkWidget* CreateWidget() { return gtk_menu_bar_new(); }
};
class MenuButton : public GtkSkinElement
{
virtual void GtkDraw(op_gdk_surface *pixmap, int width, int height, GdkRectangle& clip_rect, GtkWidget* widget, GtkStyle* style, int state);
virtual void ChangeDefaultTextColor(uint8_t& red, uint8_t& green, uint8_t& blue, uint8_t& alpha, int state) { ChangeTextColor(red, green, blue, alpha, state); }
virtual GtkWidget* CreateWidget();
GtkWidget* m_window;
#ifdef GTK3
virtual GtkStateFlags GetGtkStateFlags(int state);
virtual GtkWidget* GetTextWidget() const { return gtk_bin_get_child(GTK_BIN(m_widget)); }
#else
virtual GtkStateType GetGtkState(int state);
#endif
public:
MenuButton() : m_window(0) {}
~MenuButton() { gtk_widget_destroy(m_window); m_window = 0; m_widget = 0; }
};
class PopupMenu : public GtkSkinElement
{
virtual void GtkDraw(op_gdk_surface *pixmap, int width, int height, GdkRectangle& clip_rect, GtkWidget* widget, GtkStyle* style, int state);
virtual GtkWidget* CreateWidget() { return gtk_menu_new(); }
};
class PopupMenuButton : public GtkSkinElement
{
virtual void GtkDraw(op_gdk_surface *pixmap, int width, int height, GdkRectangle& clip_rect, GtkWidget* widget, GtkStyle* style, int state);
virtual void ChangeDefaultTextColor(uint8_t& red, uint8_t& green, uint8_t& blue, uint8_t& alpha, int state) { ChangeTextColor(red, green, blue, alpha, state); }
protected:
virtual GtkWidget* CreateWidget();
GtkWidget* m_menu;
public:
PopupMenuButton() : m_menu(0) {}
~PopupMenuButton(){ gtk_widget_destroy(m_menu); m_menu = 0; m_widget = 0; /* m_widget is a child of m_menu*/ }
};
class MenuRightArrow : public PopupMenuButton
{
virtual void GtkDraw(op_gdk_surface *pixmap, int width, int height, GdkRectangle& clip_rect, GtkWidget* widget, GtkStyle* style, int state);
};
class ListItem : public PopupMenuButton
{
virtual void GtkDraw(op_gdk_surface *pixmap, int width, int height, GdkRectangle& clip_rect, GtkWidget* widget, GtkStyle* style, int state);
virtual void ChangeDefaultTextColor(uint8_t& red, uint8_t& green, uint8_t& blue, uint8_t& alpha, int state) { ChangeTextColor(red, green, blue, alpha, state); }
virtual void ChangeDefaultMargin(int& left, int& top, int& right, int& bottom, int state) {}
};
class SliderTrack : public GtkSkinElement
{
public:
SliderTrack(bool horizontal) : GtkSkinElement(),m_horizontal(horizontal){}
private:
virtual void GtkDraw(op_gdk_surface *pixmap, int width, int height, GdkRectangle& clip_rect, GtkWidget* widget, GtkStyle* style, int state);
virtual void ChangeDefaultSize(int& width, int& height, int state)
{
if(m_horizontal)
{
width = 0;
height = 5;
}
else
{
width = 5;
height = 0;
}
}
virtual GtkWidget* CreateWidget()
{
if (m_horizontal)
return gtk_hscale_new_with_range(0.0, 100.0, 1.0);
else
return gtk_vscale_new_with_range(0.0, 100.0, 1.0);
}
private:
bool m_horizontal;
};
class SliderKnob : public GtkSkinElement
{
public:
SliderKnob(bool horizontal) : GtkSkinElement(),m_horizontal(horizontal){}
private:
virtual void GtkDraw(op_gdk_surface *pixmap, int width, int height, GdkRectangle& clip_rect, GtkWidget* widget, GtkStyle* style, int state);
virtual void ChangeDefaultSize(int& width, int& height, int state);
virtual GtkWidget* CreateWidget()
{
if (m_horizontal)
return gtk_hscale_new_with_range(0.0, 100.0, 1.0);
else
return gtk_vscale_new_with_range(0.0, 100.0, 1.0);
}
private:
bool m_horizontal;
};
class HeaderButton : public GtkSkinElement
{
virtual void GtkDraw(op_gdk_surface *pixmap, int width, int height, GdkRectangle& clip_rect, GtkWidget* widget, GtkStyle* style, int state);
virtual GtkWidget* CreateWidget();
virtual void ChangeDefaultTextColor(uint8_t& red, uint8_t& green, uint8_t& blue, uint8_t& alpha, int state) { ChangeTextColor(red, green, blue, alpha, state); }
};
class Toolbar : public GtkSkinElement
{
virtual void GtkDraw(op_gdk_surface *pixmap, int width, int height, GdkRectangle& clip_rect, GtkWidget* widget, GtkStyle* style, int state);
virtual GtkWidget* CreateWidget() { return gtk_toolbar_new(); }
};
class MainbarButton : public GtkSkinElement
{
public:
virtual void GtkDraw(op_gdk_surface *pixmap, int width, int height, GdkRectangle& clip_rect, GtkWidget* widget, GtkStyle* style, int state);
virtual void ChangeDefaultTextColor(uint8_t& red, uint8_t& green, uint8_t& blue, uint8_t& alpha, int state) { ChangeTextColor(red, green, blue, alpha, state); }
virtual void ChangeDefaultPadding(int& left, int& top, int& right, int& bottom, int state);
virtual void ChangeDefaultSpacing(int &spacing, int state);
virtual GtkWidget* CreateWidget() {return gtk_button_new(); }
};
class PersonalbarButton : public MainbarButton
{
};
class Tooltip : public GtkSkinElement
{
virtual void GtkDraw(op_gdk_surface *pixmap, int width, int height, GdkRectangle& clip_rect, GtkWidget* widget, GtkStyle* style, int state);
virtual GtkWidget* CreateWidget();
virtual void ChangeDefaultTextColor(uint8_t& red, uint8_t& green, uint8_t& blue, uint8_t& alpha, int state) { ChangeTextColor(red, green, blue, alpha, state); }
virtual bool IsTopLevel() { return true; }
virtual const char* GetStyleContextClassName() const { return "tooltip"; }
};
class MenuSeparator : public GtkSkinElement
{
virtual void GtkDraw(op_gdk_surface *pixmap, int width, int height, GdkRectangle& clip_rect, GtkWidget* widget, GtkStyle* style, int state);
virtual GtkWidget* CreateWidget() { return gtk_separator_menu_item_new(); }
void ChangeDefaultSize(int& width, int& height, int state);
};
#ifdef DEBUG
/** @brief Debug skin element that draws RED everywhere */
class RedElement : public GtkSkinElement
{
virtual void Draw(uint32_t* bitmap, int width, int height, const NativeRect& clip_rect, int state);
virtual void GtkDraw(op_gdk_surface *pixmap, int width, int height, GdkRectangle& clip_rect, GtkWidget* widget, GtkStyle* style, int state) {}
virtual GtkWidget* CreateWidget() { return 0; }
};
#endif // DEBUG
};
#endif // GTK_SKIN_ELEMENT_H
|
#pragma once
#include <core/encoding/Utf8.h>
namespace launcher {
namespace cli {
namespace error {
struct BatOption {
using Superset = core::encoding::Utf8;
Superset option;
operator Superset const&() const noexcept {
return option;
}
operator Superset &() noexcept {
return option;
}
};
}
}
}
|
#include "Statistica.h"
#include "Util.h"
#include "Pisica.h"
#include "Caine.h"
#include "Iepure.h"
#include "testoasa.h"
#include "papagal.h"
#include "iguana.h"
#include "corb.h"
#include "caracatita.h"
#include "peste.h"
#include "porumbel.h"
#include "sarpe.h"
#include "foca.h"
Statistica* Statistica::instance=0;
int Statistica::get_nr_pisici()
{
return Pisica::get_numar_animale();
}
int Statistica::get_nr_caini()
{
return Caine::get_numar_animale();
}
int Statistica::get_nr_iepuri()
{
return Iepure::get_numar_animale();
}
int Statistica::get_nr_testoase()
{
return Testoasa::get_numar_animale();
}
int Statistica::get_nr_papagali()
{
return Papagal::get_numar_animale();
}
int Statistica::get_nr_iguane()
{
return Iguana::get_numar_animale();
}
int Statistica::get_nr_corbi()
{
return Corb::get_numar_animale();
}
int Statistica::get_nr_caracatite()
{
return Caracatita::get_numar_animale();
}
int Statistica::get_nr_foci()
{
return Foca::get_numar_animale();
}
int Statistica::get_nr_pesti()
{
return Peste::get_numar_animale();
}
int Statistica::get_nr_porumbei()
{
return Porumbel::get_numar_animale();
}
int Statistica::get_nr_serpi()
{
return Sarpe::get_numar_animale();
}
void Statistica::Calcul()
{
int total=0;
total+=(get_nr_pisici()+get_nr_caini()+get_nr_iepuri()+get_nr_pesti()+get_nr_foci()+get_nr_caracatite()+get_nr_porumbei()+get_nr_corbi()+get_nr_papagali()+get_nr_iguane()+get_nr_testoase()+get_nr_serpi());
cout<<"\nStatistica vanzarilor\n";
cout<<"\nProcentaj pisici vandute: "<<(float)(get_nr_pisici()*100)/total<<"%";
cout<<"\nProcentaj caini vanduti: "<<(float)(get_nr_caini()*100)/total<<"%";
cout<<"\nProcentaj iepuri vanduti: "<<(float)(get_nr_iepuri()*100)/total<<"%";
cout<<"\nProcentaj foci vandute: "<<(float)(get_nr_foci()*100)/total<<"%";
cout<<"\nProcentaj caracatite vandute: "<<(float)(get_nr_caracatite()*100)/total<<"%";
cout<<"\nProcentaj porumbei vanduti: "<<(float)(get_nr_porumbei()*100)/total<<"%";
cout<<"\nProcentaj corbi vandute: "<<(float)(get_nr_corbi()*100)/total<<"%";
cout<<"\nProcentaj papagali vanduti: "<<(float)(get_nr_papagali()*100)/total<<"%";
cout<<"\nProcentaj iguane vandute: "<<(float)(get_nr_iguane()*100)/total<<"%";
cout<<"\nProcentaj testoase vandute: "<<(float)(get_nr_testoase()*100)/total<<"%";
cout<<"\nProcentaj serpi vanduti: "<<(float)(get_nr_serpi()*100)/total<<"%";
cout<<"\nProcentaj pesti vanduti: "<<(float)(get_nr_pesti()*100)/total<<"%";
pause(10);
}
|
๏ปฟ#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <algorithm>
using namespace std;
int main(void)
{
int arr[3];
char ABC[4];
for(int i = 0; i < 3; i++)
{
scanf("%d", &arr[i]);
}
for (int i = 0; i < 3; i++)
{
scanf(" %c", &ABC[i]);
}
sort(arr, arr + 3);
for (int i = 0; i < 3; i++)
{
switch (ABC[i])
{
case 'A':
printf("%d ", arr[0]);
break;
case 'B':
printf("%d ", arr[1]);
break;
case 'C':
printf("%d ", arr[2]);
break;
}
}
printf("\n");
return 0;
}
|
#include <string>
#include <algorithm>
#include <cctype>
#include <iostream>
#include <numeric>
#include <exception>
class Kata {
public:
std::string encrypt(std::string text);
std::string decrypt(std::string encryptedText);
private:
const static int a = 0;
const static std::string code;
};
const std::string Kata::code =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789"
".,:;-?! '()$%&\""; // space know a little => bitch
std::string Kata::encrypt(std::string text)
{
std::string ret = text;
// std::transform(text.begin(), text.end(),
// [=](char ch){ })
for(std::string::size_type i = 0; i < ret.size(); i += 1) {
if(i % 2 && isupper(ret[i])) {
text[i] = ret[i] = tolower(ret[i]);
} else if(i % 2 && islower(ret[i])) {
text[i] = ret[i] = toupper(ret[i]);
} else if(code.find(ret[i]) == std::string::npos) {
throw std::exception();
}
// find throw?
}
for(std::string::size_type i = 1; i < ret.size(); i++) {
int difference = int(code.find(text[i - 1])) - int(code.find(text[i]));
if(difference < 0) difference += 77;
//std::cout << "ret[i] = " << ret[i] << ", code[d] = " << code[difference] << std::endl;
ret[i] = code[difference];
}
ret[0] = code[76 - code.find(ret[0])];
return ret;
}
std::string Kata::decrypt(std::string encryptedText)
{
std::string ret = encryptedText;
if(ret.size() && code.find(ret[0]) == std::string::npos) throw std::exception();
ret[0] = code[76 - code.find(ret[0])];
// std::accumulate(ret.begin(), ret.end(),
// [](char before, char cur)->char{ })
for(std::string::size_type i = 1; i < ret.size(); i++) {
if(code.find(ret[i]) == std::string::npos) throw std::exception();
int difference = int(code.find(ret[i - 1])) - int(code.find(ret[i]));
if(difference < 0) difference += 77;
ret[i] = code[difference];
}
for(std::string::size_type i = 1; i < ret.size(); i += 2) {
if(isupper(ret[i])) {
ret[i] = tolower(ret[i]);
} else if(islower(ret[i])) {
ret[i] = toupper(ret[i]);
}
}
return ret;
}
int main()
{
Kata k;
std::cout << k.decrypt(k.encrypt("Business")) << std::endl;
return 0;
}
|
#pragma once
#include "afxwin.h"
#include <iphlpapi.h>
// MyTrafficDlg ๅฏน่ฏๆก
class MyTrafficDlg : public CDialogEx
{
DECLARE_DYNAMIC(MyTrafficDlg)
public:
MyTrafficDlg(CWnd* pParent = NULL); // ๆ ๅๆ้ ๅฝๆฐ
virtual ~MyTrafficDlg();
// ๅฏน่ฏๆกๆฐๆฎ
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_TRAFFIC_DIALOG };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV ๆฏๆ
DECLARE_MESSAGE_MAP()
public:
virtual BOOL OnInitDialog();
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
CStatic m_Static_Down;
CStatic m_Static_Up;
DWORD TIMER_REFRESHTRAFFIC = 0x888;
BOOL GetNetTraffic();
typedef DWORD(__stdcall *GIT)(PMIB_IFTABLE, PULONG, BOOL);
GIT lpGetIfTable;
afx_msg void OnTimer(UINT_PTR nIDEvent);
afx_msg void OnClose();
virtual BOOL PreTranslateMessage(MSG* pMsg);
afx_msg void OnRButtonUp(UINT nFlags, CPoint point);
};
|
#pragma once
#include "cdll_int.h"
#include "globalvars_base.h"
struct edict_t;
class CBotCmd
{
public:
int command_number;
int tick_count;
QAngle viewangles;
float forwardmove;
float sidemove;
float upmove;
int buttons;
byte impulse;
int weaponselect;
int weaponsubtype;
int random_seed;
short mousedx;
short mousedy;
bool hasbeenpredicted;
};
class IPlayerInfo
{
public:
virtual const char *GetName() = 0;
virtual int GetUserID() = 0;
virtual const char *GetNetworkIDString() = 0;
virtual int GetTeamIndex() = 0;
virtual void ChangeTeam(int iTeamNum) = 0;
virtual int GetFragCount() = 0;
virtual int GetDeathCount() = 0;
virtual bool IsConnected() = 0;
virtual int GetArmorValue() = 0;
virtual bool IsHLTV() = 0;
virtual bool IsPlayer() = 0;
virtual bool IsFakeClient() = 0;
virtual bool IsDead() = 0;
virtual bool IsInAVehicle() = 0;
virtual bool IsObserver() = 0;
virtual const Vector GetAbsOrigin() = 0;
virtual const QAngle GetAbsAngles() = 0;
virtual const Vector GetPlayerMins() = 0;
virtual const Vector GetPlayerMaxs() = 0;
virtual const char *GetWeaponName() = 0;
virtual const char *GetModelName() = 0;
virtual const int GetHealth() = 0;
virtual const int GetMaxHealth() = 0;
virtual CBotCmd GetLastUserCommand() = 0;
virtual bool IsReplay() = 0;
};
class IPlayerInfoManager
{
public:
virtual IPlayerInfo *GetPlayerInfo(edict_t *pEdict) = 0;
virtual CGlobalVarsBase *GetGlobalVars() = 0;
};
namespace I { inline IPlayerInfoManager *PlayerInfoManager; }
|
#include<Arduino.h>
#include<AntaresESP8266HTTP.h> // Inisiasi library HTTP Antares
#define ACCESSKEY "017c7e810b75e05b:0932f32db0c81348" // Ganti dengan access key akun Antares anda
#define WIFISSID "TP-LINK 2" // Ganti dengan SSID WiFi anda
#define PASSWORD "asdf1234" // Ganti dengan password WiFi anda
#define projectName "antaresChallenge" // Ganti dengan application name Antares yang telah dibuat
#define deviceName "sensorRead" // Ganti dengan device Antares yang telah dibuat
AntaresESP8266HTTP antares(ACCESSKEY); // Buat objek antares
void setup() {
Serial.begin(115200); // Buka komunikasi serial dengan baudrate 115200
antares.setDebug(true); // Nyalakan debug. Set menjadi "false" jika tidak ingin pesan-pesan tampil di serial monitor
antares.wifiConnection(WIFISSID,PASSWORD); // Mencoba untuk menyambungkan ke WiFi
}
void loop() {
// Isi variabel dengan nilai acak, dengan tipe data yang berbeda
int temp = random(25,30) ;
int hum = random(75,90);
float windsp = float(random(20, 30))/3.33;
float rainlv = float(random(0, 20))/6.99;
String lat = "-6.8718189";
String lon = "107.5872477";
// Memasukkan nilai-nilai variabel ke penampungan data sementara
antares.add("temperature", temp);
antares.add("humidity", hum);
antares.add("wind_speed", windsp);
antares.add("rain_level", rainlv);
antares.add("latitude", lat);
antares.add("longitude", lon);
// Kirim dari penampungan data ke Antares
antares.send(projectName, deviceName);
delay(10000);
}
|
/*********************************************************\
* Copyright (c) 2012-2018 The Unrimp Team
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\*********************************************************/
//[-------------------------------------------------------]
//[ Header guard ]
//[-------------------------------------------------------]
#pragma once
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include "Direct3D10Renderer/D3D10.h"
//[-------------------------------------------------------]
//[ Forward declarations ]
//[-------------------------------------------------------]
namespace Direct3D10Renderer
{
class Direct3D10Renderer;
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace Direct3D10Renderer
{
//[-------------------------------------------------------]
//[ Classes ]
//[-------------------------------------------------------]
/**
* @brief
* Direct3D 9 runtime linking
*/
class Direct3D9RuntimeLinking final
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor
*
* @param[in] direct3D10Renderer
* Owner Direct3D 10 renderer instance
*/
explicit Direct3D9RuntimeLinking(Direct3D10Renderer& direct3D10Renderer);
/**
* @brief
* Destructor
*/
~Direct3D9RuntimeLinking();
/**
* @brief
* Return whether or not Direct3D 9 is available
*
* @return
* "true" if Direct3D 9 is available, else "false"
*/
bool isDirect3D9Avaiable();
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
explicit Direct3D9RuntimeLinking(const Direct3D9RuntimeLinking& source) = delete;
Direct3D9RuntimeLinking& operator =(const Direct3D9RuntimeLinking& source) = delete;
/**
* @brief
* Load the shared library
*
* @return
* "true" if all went fine, else "false"
*/
bool loadSharedLibrary();
/**
* @brief
* Load the D3D9 entry points
*
* @return
* "true" if all went fine, else "false"
*/
bool loadD3D9EntryPoints();
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
Direct3D10Renderer& mDirect3D10Renderer; ///< Owner Direct3D 10 renderer instance
void* mD3D9SharedLibrary; ///< D3D9 shared library, can be a null pointer
bool mEntryPointsRegistered; ///< Entry points successfully registered?
bool mInitialized; ///< Already initialized?
};
//[-------------------------------------------------------]
//[ D3D9 core functions ]
//[-------------------------------------------------------]
#ifdef DIRECT3D9_DEFINERUNTIMELINKING
#define FNDEF_D3D9(retType, funcName, args) retType (WINAPI *funcPtr_##funcName) args
#else
#define FNDEF_D3D9(retType, funcName, args) extern retType (WINAPI *funcPtr_##funcName) args
#endif
// Debug
FNDEF_D3D9(DWORD, D3DPERF_GetStatus, (void));
FNDEF_D3D9(void, D3DPERF_SetOptions, (DWORD));
FNDEF_D3D9(void, D3DPERF_SetMarker, (D3DCOLOR, LPCWSTR));
FNDEF_D3D9(int, D3DPERF_BeginEvent, (D3DCOLOR, LPCWSTR));
FNDEF_D3D9(int, D3DPERF_EndEvent, (void));
//[-------------------------------------------------------]
//[ Macros & definitions ]
//[-------------------------------------------------------]
#ifndef FNPTR
#define FNPTR(name) funcPtr_##name
#endif
// Redirect D3D9* function calls to funcPtr_D3D9*
// Debug
#define D3DPERF_GetStatus FNPTR(D3DPERF_GetStatus)
#define D3DPERF_SetOptions FNPTR(D3DPERF_SetOptions)
#define D3DPERF_SetMarker FNPTR(D3DPERF_SetMarker)
#define D3DPERF_BeginEvent FNPTR(D3DPERF_BeginEvent)
#define D3DPERF_EndEvent FNPTR(D3DPERF_EndEvent)
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // Direct3D10Renderer
|
#ifndef CAR_H
#define CAR_H
#include <string>
#include "driver.h"
class SteeringWheel{
};
class Car{
Driver *dere;
SteeringWheel s_wheel; //composition is demonstrated here
std::string car_type;
public:
Car(std::string ct, Driver *driver = NULL) :
dere(driver), car_type(ct){}
Car(Driver *driver=NULL) : Car("Mercedes", driver){}
std::string whosDriving();
};
#endif
|
/******************************************
* AUTHOR : Abhishek Naidu *
* NICK : abhisheknaiidu *
******************************************/
#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
using namespace std;
#define all(n) n.begin(),n.end()
#define pii pair<int,int>
#define vi vector<int>
#define mii map<int,int>
#define ps(x,y) fixed<<setprecision(y)<<x
#define mk(arr,n,type) type *arr=new type[n];
#define w(x) int x; cin>>x; while(x--)
#define pqb priority_queue<int>
#define pqs priority_queue<int,vi,greater<int> >
#define setbits(x) __builtin_popcountll(x)
#define zrobits(x) __builtin_ctzll(x)
#define mod 1000000007
#define f first
#define s second
#define ll long long int
#define pb push_back
#define mp make_pair
#define inf 1e18
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds;
void abhisheknaiidu()
{
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
bool check(int a, int n) {
int c = 0, f = 5;
while (f <= a) {
c += a / f;
f *= 5;
}
return (c >= n);
}
int main()
{
abhisheknaiidu();
w(x) {
int n;
cin >> n;
// if (n == 1) {
// return 5;
// }
// cout << n;
// For binary Search
int start = 0;
int end = 5 * n;
int mid;
while ( start < end) {
mid = start + (end - start) / 2;
if (check(mid, n))
end = mid;
else {
start = mid + 1;
}
// cout << "end " << end << endl;
// cout << "start " << start << endl;
}
cout << start << endl;
}
return 0;
}
|
#include<iostream>
#include<map>
#include<cstring>
#define hashmap map<char,node*>
using namespace std;
class node
{
public:
char data;
bool isTerminal;
hashmap h;
node(char d)
{
data=d;
isTerminal=false;
}
};
class trie
{
public:
node *root;
trie()
{
root=new node(' ');;
}
void insert(string s)
{
int len=s.length();
node *temp=root;
for(int i=0;i<len;i++)
{
char ch=s[i];
if(temp->h.count(ch)==0)
{
node *child=new node(ch);
temp->h[ch]=child;
temp=child;
}
else
temp=temp->h[ch];
}
temp->isTerminal=true;
}
bool search(string s)
{
int len=s.length();
node *temp=root;
for(int i=0;i<len;i++)
{
char ch=s[i];
if(temp->h.count(ch)>0)
{
temp=temp->h[ch];
}
else
return false;
}
return temp->isTerminal;
}
};
int main()
{
trie t;
int n;
cin>>n;
for(int i=0;i<n;i++)
{
string st;
cin>>st;
t.insert(st);
}
cout<<"Enter the string to be searched"<<endl;
string s;
cin>>s;
if(t.search(s))
cout<<"Successful"<<endl;
return 0;
}
|
/*
* ้ข็ฎ๏ผ2. ไธคๆฐ็ธๅ
* ้พๆฅ๏ผhttps://leetcode-cn.com/problems/add-two-numbers/
* ็ฅ่ฏ็น๏ผ้พ่กจ
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *tHead = new ListNode(-1);
ListNode *cur = tHead;
// ๅค็็ธๅ
int add = 0;
while (l1 && l2) {
int sum = l1->val + l2->val + add;
add = sum / 10;
ListNode *node = new ListNode(sum % 10);
cur->next = node;
cur = cur->next;
l1 = l1->next;
l2 = l2->next;
}
// ๅค็้ฟๅบๆฅ็้จๅ
ListNode *t = (l1 != nullptr) ? l1 : l2;
while (t) {
int sum = t->val + add;
add = sum / 10;
ListNode *node = new ListNode(sum % 10);
cur->next = node;
cur = cur->next;
t = t->next;
}
// ๅค็ๆๅ็่ฟไฝ
if (add == 1) {
ListNode *node = new ListNode(1);
cur->next = node;
}
return tHead->next;
}
};
|
/*
compute the Restricted Voronoi Diagram
and Update the seeds
with Cuda to accelerate the program
starting time : 2016.7.25
*/
#include "Command_line.h"
#include "Mesh.h"
#include "Mesh_io.h"
#include "Points.h"
using namespace P_RVD;
int main(int argc, char** argv)
{
std::vector<std::string> filenames;
if (!Cmd::parse_argu(argc, argv, filenames))
{
fprintf(stderr, "cannot parse the argument into filename!");
return -1;
}
std::string mesh_filename = filenames[0];
std::string points_filename = filenames[0];
std::string output_filename;
if (filenames.size() >= 2){
points_filename = filenames[1];
}
output_filename = (filenames.size() == 3) ? filenames[2] : "out.eobj";
Mesh M_out, points_in;
Mesh M_in;
if (!mesh_load(mesh_filename, M_in))
{
fprintf(stderr, "cannot load Mesh into M_in!");
return -1;
}
if (!mesh_load(points_filename, points_in, false))
{
fprintf(stderr, "cannot load points into points_in!");
return -1;
}
Points points(points_in);
Points points_out(points_in);
return 0;
}
|
//kadane algorithm
class Solution {
public:
int maxSubArray(vector<int>& nums)
{
int a=0,m=INT_MIN;
for(int x : nums)
{
a += x;
m = max(a,m);
a = max(a,0);
}
return m;
}
};
|
//====================================================================================
// @Title: GAME MANAGER
//------------------------------------------------------------------------------------
// @Location: /prolix/framework/include/cGame.h
// @Author: Kevin Chen
// @Rights: Copyright(c) 2011 Visionary Games
//------------------------------------------------------------------------------------
// @Description:
//
// The Game Manager integrates all of the managing game components (including
// PROLIX) as a central hub of communication between all managers.
//
//====================================================================================
#ifndef __PROLIX_FRAMEWORK_H__
#define __PROLIX_FRAMEWORK_H__
#include "../../engine/include/PrlxEngine.h"
#include "../include/cAssetMgr.h"
#include "../include/cGameDataMgr.h"
#include "../include/cLocMgr.h"
#include "../include/cLogMgr.h"
#include "../include/cPlayerDataMgr.h"
#include "../include/cPlayerPreferenceMgr.h"
#include "../include/cTweenMgr.h"
#include "../../engine/include/PrlxEngine.h"
// singleton accessor
#define Game cGame::GetInstance()
//====================================================================================
// cGame
//====================================================================================
class cGame
{
typedef PrlxGraphics Graphics;
static cGame *mInstance; // instance of the singleton class
void Initialize(); // Initialize application managers
cGame(); // Constructor
cGame(const cGame &){} // Copy constructor
cGame &operator= (cGame &){} // Assignment operator
~cGame(); // Destructor
public:
static cGame *GetInstance(); // get instance of the singleton class
bool Loop(); // the game loop
void InitScene(); // start the rendering phase
void ExitScene(); // end the rendering phase
};
#endif
|
// Created on: 1993-01-29
// Created by: Isabelle GRIGNON
// Copyright (c) 1993-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 _IntPatch_PolyLine_HeaderFile
#define _IntPatch_PolyLine_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <gp_Pnt2d.hxx>
#include <IntPatch_IType.hxx>
#include <Standard_Boolean.hxx>
#include <IntPatch_Polygo.hxx>
#include <Standard_Real.hxx>
#include <Standard_Integer.hxx>
class IntPatch_WLine;
class IntPatch_RLine;
class IntPatch_PolyLine : public IntPatch_Polygo
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT IntPatch_PolyLine();
Standard_EXPORT IntPatch_PolyLine(const Standard_Real InitDefle);
Standard_EXPORT void SetWLine (const Standard_Boolean OnFirst, const Handle(IntPatch_WLine)& Line);
Standard_EXPORT void SetRLine (const Standard_Boolean OnFirst, const Handle(IntPatch_RLine)& Line);
Standard_EXPORT void ResetError();
Standard_EXPORT Standard_Integer NbPoints() const;
Standard_EXPORT gp_Pnt2d Point (const Standard_Integer Index) const;
protected:
private:
Standard_EXPORT void Prepare();
gp_Pnt2d pnt;
IntPatch_IType typ;
Standard_Boolean onfirst;
Handle(IntPatch_WLine) wpoly;
Handle(IntPatch_RLine) rpoly;
};
#endif // _IntPatch_PolyLine_HeaderFile
|
#include"functions.h"
#include"stamping.h"
int AinverseB(vector<vector<double> > &Ad,vector<vector<double> > &Bd,vector<vector<double> > &Cd)
{
int sizeA=Ad.size();
int Nd=sizeA;
int colB=(Bd[0]).size();
int NRHSd=colB;
int LDAd =Nd;
int LDBd=Nd;
int IPIVd[Nd];
int INFOd;
double ad[LDAd*Nd],bd[LDBd*NRHSd];
int kd=0;
int ld=0;
for(int i=0;i!=(Ad[0]).size();++i)
for(int j=0;j!=Ad.size();++j)
ad[kd++]=Ad[j][i];
for(int i=0;i!=(Bd[0]).size();++i)
for(int j=0;j!=Bd.size();++j)
bd[ld++]=Bd[j][i];
dgesv_( &Nd, &NRHSd, ad, &LDAd, IPIVd, bd, &LDBd, &INFOd );
if( INFOd > 0 ) {
cout<<"The diagonal element of the triangular factor of A,\n";
cout<< "U("<<INFOd<<","<<INFOd<<" is jero, so that A is singular;\n";
cout<<( "the solution could not be computed.\n" );
// return(1);
}
// cout << "===============================IN AINVERSEB 1" << endl;
vector<double>tempd;
for(int i=0;i!=Nd;++i)
{
for(int j=0;j!=NRHSd;++j)
tempd.push_back(bd[i+j*LDBd]);
Cd.push_back(tempd);
tempd.clear();
}
// cout << "===============================IN AINVERSEB 2" << endl;
return 15;
}
int QR_factorization(vector<vector<double> > &a,vector<vector<double> > &E)
{
vector<double> u;
for(int i=0;i!=(a[0]).size();++i){
for(int j=0;j!=a.size();++j)
u.push_back(a[j][i]);
// cout<<"printing"<< i+1 <<"u vector"<<endl;
// for(int r=0;r!=u.size();++r)
// cout<<u[r]<<" ";
// cout<<endl;
if(i==0)
{
double sum=0;
for(int k=0;k!=u.size();++k)
sum+=u[k]*u[k];
for(int k=0;k!=u.size();++k){
double root=sqrt(sum);
double value=u[k]/root;
E.push_back(vector<double>(1,value));
}
u.clear();
}
else{
double sum=0;
for(int k=0;k!=i;++k)
{
double prod=0;
for(int z=0;z!=u.size();++z)
prod+=a[z][i]*E[z][k];
for(int z=0;z!=u.size();++z)
u[z]=u[z]-(prod*E[z][k]);
}
for(int k=0;k!=u.size();++k)
sum+=u[k]*u[k];
for(int k=0;k!=u.size();++k){
double root=sqrt(sum);
double value=u[k]/root;
E[k].push_back(value);
}
u.clear();
}
}
return 16;
}
int vectormultiplication(vector<vector<double> > &a,vector<vector<double> > &b,vector<vector<double> > &c)
{
if(((a.at(0)).size())!=b.size()){
cout<<"columns of 1st matrix and row of 2nd matrix does not match"<<endl;
cout<<((a.at(0)).size())<<";;;;;;;;;;;;;;;;;;;"<<b.size()<<endl;
}
else{
vector<double>temp;
int row=a.size();
int column=(b[0]).size();
int inner=b.size();
for(int i=0;i!=row;++i){
for(int j=0;j!=column;++j){
double sum=0;
for(int k=0;k!=inner;++k){
sum+=a[i][k]*b[k][j];
}
temp.push_back(sum);
}
c.push_back(temp);
temp.clear();
}
}
return 17;
}
int vector_transpose(vector<vector<double> > &a,vector<vector<double> > &b)
{
vector<double>temp;
for(int i=0;i!=(a[0]).size();++i)
{
for(int j=0;j!=a.size();++j)
{
temp.push_back(a[j][i]);
}
b.push_back(temp);
temp.clear();
}
return 18;
}
int blockArnoldi(vector<vector<double> > &G,vector<vector<double> > &C,vector<vector<double> > &B,vector<vector<double> > &X,int &q_value, vector<double> &range)
{
vector<double> insert;
vector<vector<double> > R,Q,V,X_temp,Z,X_transpose,H,XH;
AinverseB(G,B,R);
// cout << "HERE------------------------------------------->>>>>>>>>>>>>>>>>" << endl;
QR_factorization(R,Q);
cout<<"the number of columns in one moment are :"<<(Q.at(0)).size()<<" and row are :"<<Q.size()<<endl;
int q,n,input1,input2;
// cout << "===============Q=" << Q.size() << endl;
X=Q;
// cout << "===============X=" << X.size() << endl;
// cout<<"printing the X 0"<<endl;
cout<<"done computing X0"<<endl;
// print(X);
Q.clear();
R.clear();
range.push_back((X[0]).size());
cout<<"Enter the value of q"<<endl;
// cin>>q;
q=q_value;
cout<<"the value of q is "<<q<<endl;
if((q%((B[0]).size()))==0)
n=q/((B[0]).size());
else
n=floor(q/((B[0]).size()))+1;
cout<<"the value of n is :"<<n<<endl;
for(int kA=1;kA<=n;++kA)
{
// cout<<"getting previous columsn"<<endl;
input1=kA-1;
if(input1==0){
for(int l=0;l!=X.size();++l)
{
for(int m=0;m!=range[input1];++m)
insert.push_back(X[l][m]);
X_temp.push_back(insert);
insert.clear();
}
}
else{
for(int l=0;l!=X.size();++l)
{
for(int m=range[input1-1];m!=range[input1];++m)
insert.push_back(X[l][m]);
X_temp.push_back(insert);
insert.clear();
}
}
// cout<<"done getting previous column"<<endl;
// cout<<"performing vector multiplication"<<endl;
vectormultiplication(C,X_temp,V);
X_temp.clear();
// cout<<"doing inverse"<<endl;
AinverseB(G,V,Z);
V.clear();
for(int pass=1;pass<=2;++pass)
{
for(int jA=1;jA<=kA;++jA)
{
input2=kA-jA;
if(input2==0){
for(int l=0;l!=X.size();++l)
{
for(int m=0;m!=range[input2];++m)
insert.push_back(X[l][m]);
X_temp.push_back(insert);
insert.clear();
}
}
else{
for(int l=0;l!=X.size();++l)
{
for(int m=range[input2-1];m!=range[input2];++m)
insert.push_back(X[l][m]);
X_temp.push_back(insert);
insert.clear();
}
}
vector_transpose(X_temp,X_transpose);
vectormultiplication(X_transpose,Z,H);
vectormultiplication(X_temp,H,XH);
for(int i_A=0;i_A!=Z.size();++i_A)
for(int j_A=0;j_A!=(Z[0]).size();++j_A)
Z[i_A][j_A]=Z[i_A][j_A]-XH[i_A][j_A];
X_temp.clear();
X_transpose.clear();
XH.clear();
H.clear();
}
}
// cout<<"doing QrR"<<endl;
QR_factorization(Z,Q);
for(int iAB=0;iAB!=Q.size();++iAB)
for(int jAB=0;jAB!=(Q[0]).size();++jAB)
(X[iAB]).push_back(Q[iAB][jAB]);
range.push_back((X[0]).size());
cout<<"printing the X"<<kA<<endl;
// print(Q);
Q.clear();
Z.clear();
}
return 19;
}
int block_inverse(vector<vector<double> > A_real,vector<vector<double> > A_imag,vector<vector<double> > B,vector<vector<double> > &vec_soln,double expansion_frequency)
{
int N=A_real.size();
complex<double> a[N*N];
int k1=0;
//cout<<"combining:-----------------------------------------------------"<<endl;
for(int i=0;i<N;++i){
for(int j=0;j<N;++j)
{
a[k1++]=complex<double>(A_real[j][i],2*pi*expansion_frequency*A_imag[j][i]);
//cout<<complex<double>(A_real[j][i],2*pi*expansion_frequency*A_imag[j][i])<<" ";
}
//cout<<endl;
}
//cout<<"B ===================================================="<<endl;
complex<double> b[N*(B.at(0)).size()];
int k2=0;
for(int i=0;i<(B.at(0)).size();++i)
{
for(int j=0;j<N;++j)
{
b[k2++]=complex<double>(B[j][i],0);
//cout<<complex<double>(B[j][i],0)<<" ";
}
//cout<<endl;
}
int n=N;
int nrhs=(B.at(0)).size();
int lda=n,ldb=n,info;
int ipiv[n];
zgesv_( &n, &nrhs, a, &lda, ipiv, b, &ldb, &info );
complex<double> sol[n][nrhs];
//cout<<"array==================================="<<endl;
for(int i=0;i<n;++i)
{
for(int j=0;j<nrhs;++j)
{
sol[i][j]=b[i+j*ldb];
//cout<<sol[i][j]<<" ";
}
//cout<<endl;
}
vector<double> temp;
for(int i=0;i<n;++i)
{
for(int j=0;j<nrhs;++j)
{
temp.push_back(real(sol[i][j]));
temp.push_back(imag(sol[i][j]));
}
vec_soln.push_back(temp);
temp.clear();
}
return 20;
}
int complex_vector_multiplication(vector<vector<complex<double> > > a,vector<vector<complex<double> > > b,vector<vector<complex<double> > > &c)
{
if((a.at(0)).size()!=b.size()){
cout<<"columns of 1st matrix and row of 2nd matrix does not match"<<endl;
cout<<(a.at(0)).size()<<"''''''''''''''''''''''"<<b.size()<<endl;
}
else{
vector<complex<double> > temp;
int row=a.size();
int column=(b.at(0)).size();
int inner=b.size();
for(int i=0;i<row;++i)
{
for(int j=0;j<column;++j){
complex<double> sum=0;
for(int k=0;k<inner;++k)
{
sum+=a[i][k]*b[k][j];
}
temp.push_back(sum);
}
c.push_back(temp);
temp.clear();
}
}
return 21;
}
int multi_Arnoldi(vector<vector<double> > G,vector<vector<double> > C,vector<vector<double> > B,vector<vector<double> > &X,int q_value, double expansion_frequency)
{
vector<double> insert,temp;
vector<vector<double> > V_sep,GinverseC,GinverseB,Z,X_sep,X_transpose,complex_sep,H,Q,XH;
vector<complex<double> >c1,c2;
vector<vector<complex<double> > > GinverseC_complex,V,Z_complex;
//doing Ginverc
//cout<<X.size()<<"-------------------------------"<<(X.at(0)).size()<<endl;
//cout<<"performing Ginversc-----------------------------------------------"<<endl;
block_inverse(G,C,C,GinverseC,expansion_frequency);
//converting to complex
//cout<<"size of GinversC "<<(GinverseC.at(0)).size()<<"---------------------------"<<GinverseC.size()<<"----------------------------------------"<<endl;
//cout<<"-------------------------------------------------------------"<<endl;
for(int i=0;i<GinverseC.size();++i)
{
for(int j=0;j<((GinverseC.at(0)).size())/2;++j)
{
c1.push_back(complex<double> (GinverseC[i][2*j],GinverseC[i][(2*j)+1]));
}
GinverseC_complex.push_back(c1);
c1.clear();
}
//cout<<"size of GinversCcomlex "<<(GinverseC_complex.at(0)).size()<<"------------------------"<<GinverseC_complex.size()<<"---------------------------------------------"<<endl;
//Ginverse B
block_inverse(G,C,B,GinverseB,expansion_frequency);
cout<<"the number of columns in moments( GinversB) are : "<<(GinverseB.at(0)).size()<<" and the number of rows are :-"<<GinverseB.size()<<"-------------------"<<endl;
for(int i=0;i<(GinverseB.at(0)).size();++i)
{//#getting the each columns of GinverseB
for(int j=0;j<GinverseB.size();++j)
{
insert.push_back(GinverseB[j][i]);
Z.push_back(insert);
insert.clear();
}
//cout<<i+1<<"---------------"<<Z.size()<<"-----------------------------"<<(Z.at(0)).size()<<endl;
for(int pass=1;pass<=2;++pass)
{
//cout<<pass<<"::::::::::::::::::::::::::::::::::::::::::"<<endl;
//cout<<"X...."<<X.size()<<"-------------------------------"<<(X.at(0)).size()<<endl;
for(int j=(((X.at(0)).size())-1);j>=0;--j)
{
for(int k=0;k<X.size();++k)
{
//cout<<k<<" ";
insert.push_back(X[k][j]);
X_sep.push_back(insert);
insert.clear();
}
//cout<<j<<"---"<<X_sep.size()<<"--------------------------------------------------"<<(X_sep.at(0)).size()<<endl;
vector_transpose(X_sep,X_transpose);
vectormultiplication(X_transpose,Z,H);
vectormultiplication(X_sep,H,XH);
for(int i_A=0;i_A<Z.size();++i_A)
{
for(int j_A=0;j_A<(Z.at(0)).size();++j_A)
{
Z[i_A][j_A]=Z[i_A][j_A]-XH[i_A][j_A];
}
}
X_transpose.clear();
XH.clear();
H.clear();
X_sep.clear();
}
}
QR_factorization(Z,Q);
Z.clear();
for(int iAB=0;iAB<Q.size();++iAB)
{
for(int jAB=0;jAB<(Q.at(0)).size();++jAB)
{
(X[iAB]).push_back(Q[iAB][jAB]);
}
}
//cout<<"X"<<(X.at(0)).size()<<endl;
if(complex_sep.empty())
{
complex_sep=Q;
Q.clear();
}
else{
for(int iAB=0;iAB<Q.size();++iAB)
{
for(int jAB=0;jAB<(Q.at(0)).size();++jAB)
{
(complex_sep[iAB]).push_back(Q[iAB][jAB]);
}
}
Q.clear();
}
}
cout<<"printing the X0"<<endl;
// cout<<"size of X "<<(X.at(0)).size()<<"---------------------------"<<X.size()<<"----------------------------------------"<<endl;
// cout<<"size of complex_sep "<<(complex_sep.at(0)).size()<<"---------------------------"<<complex_sep.size()<<"----------------------------------------"<<endl;
//cout<<"Enter the value of q"<<endl;
cout<<"the value of q is "<<q_value<<endl;
int n;
if((q_value%((B[0]).size()))==0)
n=q_value/((B[0]).size());
else
n=floor(q_value/((B[0]).size()))+1;
cout<<"the value of n is :"<<n<<endl;
//staring the GinversC part from here
for(int k=1;k<=n;++k)
{
for(int i=0;i<complex_sep.size();++i)
{
for(int j=0;j<((complex_sep.at(0)).size()/2);++j)
{
c2.push_back(complex<double>(complex_sep[i][2*j],complex_sep[i][(2*j)+1]));
}
V.push_back(c2);
c2.clear();
}
complex_sep.clear();
//cout<<"size of V :"<<V.size()<<"----------------------------------"<<(V.at(1)).size()<<endl;
complex_vector_multiplication(GinverseC_complex,V,Z_complex);
//cout<<"size of Z_complex :"<<Z_complex.size()<<"----------------------------------"<<(Z_complex.at(0)).size()<<endl;
V.clear();
for(int i=0;i<Z_complex.size();++i)
{
for(int j=0;j<(Z_complex.at(0)).size();++j)
{
temp.push_back((Z_complex[i][j]).real());
temp.push_back((Z_complex[i][j]).imag());
}
V_sep.push_back(temp);
temp.clear();
}
//cout<<"size of V_sep :"<<V_sep.size()<<"----------------------------------"<<(V_sep.at(0)).size()<<endl;
Z_complex.clear();
for(int i=0;i<(V_sep.at(0)).size();++i)
{//#getting the each columns of GinverseB
for(int j=0;j<V_sep.size();++j)
{
insert.push_back(V_sep[j][i]);
Z.push_back(insert);
insert.clear();
}
for(int pass=1;pass<=2;++pass)
{
for(int j=((X.at(0)).size()-1);j>=0;--j)
{
for(int k=0;k<X.size();++k)
{
insert.push_back(X[k][j]);
X_sep.push_back(insert);
insert.clear();
}
vector_transpose(X_sep,X_transpose);
vectormultiplication(X_transpose,Z,H);
vectormultiplication(X_sep,H,XH);
for(int i_A=0;i_A<Z.size();++i_A)
{
for(int j_A=0;j_A<(Z.at(0)).size();++j_A)
{
Z[i_A][j_A]=Z[i_A][j_A]-XH[i_A][j_A];
}
}
X_transpose.clear();
XH.clear();
H.clear();
X_sep.clear();
}
}
QR_factorization(Z,Q);
Z.clear();
for(int iAB=0;iAB<Q.size();++iAB)
{
for(int jAB=0;jAB<(Q.at(0)).size();++jAB)
{
(X[iAB]).push_back(Q[iAB][jAB]);
}
}
if(complex_sep.empty())
{
complex_sep=Q;
Q.clear();
}
else{
for(int iAB=0;iAB<Q.size();++iAB)
{
for(int jAB=0;jAB<(Q.at(0)).size();++jAB)
{
(complex_sep[iAB]).push_back(Q[iAB][jAB]);
}
}
Q.clear();
}
}
V_sep.clear();
cout<<"printing the X"<<k<<endl;
}
return 24;
}
int original_plus_MOR_giving_X_big(vector<vector<double> > &X_big,double frequency_max,double frequency_min, double points,string input_file)
{
double interval;
interval=(frequency_max-frequency_min)/(points-1);
string in_1,in_2,in_3;
cout<<"ENTER THE MAIN NETLIST FILE : ";
// cin>>in_1;
in_1=input_file;
// cout<<"enter the file containing INPUT TERMINAL : " ;
// cin>>in_2;
// cout<<"enter the file containing OUTPUT TERMINALS : ";
// cin>>in_3;
cout<<"1) MAIN NETLIST FILE : "<<in_1<<endl;//<<"2) INPUT TERMINAL FILE : "<<in_2<<endl<<"3) OUTPUT TERMINAL FILE : "<<in_3<<endl;
cout<<" DID U CHANGE THE FREQUENCY"<<endl/*<<"REMEMBER ARRAY IS A BITCH"<<endl*/<<"First enter RGC irrespective of the order,then enter L,then independent sources and then dependent sources"<<endl<<"R or r for resistance"<<endl<<"G or g for admittance"<<endl<<"C or c for capacitance"<<endl<<"L or l for inductance"<<endl<<"J or j for current source"<<endl<<"E or e for VCVS"<<endl<<"Z or z for VCCS"<<endl<<"H or h for CCVS"<<endl<<"V or v for independent voltage source"<<endl<<"PRESS ENTER TWICE AFTER DONE ENTERING THE CIRCUIT INFORAMTION IN THE FORM OF SPICE INPUT"<<endl;
vector<complex<double> > u_MATRIX;
vector<vector<double> >G_MATRIX;
vector<vector<double> >C_MATRIX;
vector<vector<double> >B_MATRIX;
G_MATRIX.clear();
C_MATRIX.clear();
B_MATRIX.clear();
//reading the input and output node from files created from pul.c code
vector<double> input_node,output_node;
read_nodes("input_terminal.txt", input_node);
read_nodes("output_terminal.txt", output_node);
//printing the nodes
for(int i=0;i<input_node.size();++i)
cout<<input_node[i]<<" ";
cout<<endl;
for(int i=0;i<output_node.size();++i)
cout<<output_node[i]<<" ";
cout<<endl;
double t1=clock();
populate_matrices(in_1, G_MATRIX, C_MATRIX, B_MATRIX,u_MATRIX);
string C_matrix="SERIAL_C_"+in_1;
string G_matrix="SERIAL_G_"+in_1;
file_write(C_matrix,C_MATRIX);
file_write(G_matrix,G_MATRIX);
cout<<" C_MATRIX AND G_MATRIX written in "<<C_matrix<<" and "<<G_matrix<<endl;
double t2=clock();
cout<<" TIME taken to populate G,C and B matrices is : "<<(t2-t1)/double(CLOCKS_PER_SEC) << "seconds" <<endl;
// cout<<"G MATRIX"<<endl;
// print(G_MATRIX);
// cout<<endl;
// cout<<"C MATRIX"<<endl;
// print(C_MATRIX);
cout<<"THE NUMBER OF VARIABLE ARE :"<<G_MATRIX.size()<<endl;
// cout<<endl<<"B MATRIX"<<endl;
// print(B_MATRIX);
// cout<<endl<<"u complex vector"<<endl;
// printcomplexvector(u_MATRIX);
/*converting ucomplex vectro matrix into ucomplex array matrix*/
complex<double> uarraymatrix[(u_MATRIX).size()][1];
for(int i=0;i<(u_MATRIX).size();++i)
uarraymatrix[i][0]=u_MATRIX[i];
//printing tht ucomplexaray
// cout<<endl<<"ucomplexarray"<<endl;
// for(int i=0;i!=(u_MATRIX).size();++i)
// cout<<uarraymatrix[i][0]<<endl;
//converting the B VECTOR MATRIX to B ARRAY MATRIX
complex<double> B_COMPLEXARRAYMATRIX[(B_MATRIX).size()][(u_MATRIX).size()];
for(int i=0;i<(B_MATRIX).size();++i)
for(int j=0;j!=(u_MATRIX).size();++j)
B_COMPLEXARRAYMATRIX[i][j]=complex<double>(B_MATRIX[i][j],0);
// print the the B ARRAY MATRIX
// cout<<endl<<"B_COMPLEXARRAYMATRIX"<<endl;
// for(int i=0;i!=(B_MATRIX).size();++i){
// for(int j=0;j!=(u_MATRIX).size();++j)
// cout<<B_COMPLEXARRAYMATRIX[i][j]<<" ";
// cout<<endl;}
//multiplying the B_COMPLEXARRAY AND uarraymatrix
complex<double> Bucomplexmultiple[(B_MATRIX).size()][1];
for(int i=0;i!=(B_MATRIX).size();++i)
for(int j=0;j!=(u_MATRIX).size();++j)
Bucomplexmultiple[i][0]+=B_COMPLEXARRAYMATRIX[i][j]*uarraymatrix[j][0];
/* //comment for original solving starts here
fstream result11("MATLAB_result_at_output_node_at_multiple_frequencies.txt",fstream::out);
if(result11.is_open() )
{
double frequency;
int timer1=0;
while(timer1<points)
{
cout<<"original"<<timer1+1<<endl;
frequency=frequency_min+(interval*timer1);
result11<<frequency<<'\t';
//combining G_MATRIX and C_MATRIX into GplussC_MATRIX
complex<double> GplussC_MATRIX[(G_MATRIX).size()][(G_MATRIX).size()];
for(int i=0;i<(G_MATRIX).size();++i)
{
for(int j=0;j<(G_MATRIX).size();++j)
{
GplussC_MATRIX[i][j]=complex<double>(G_MATRIX[i][j],(2*pi*frequency*C_MATRIX[i][j]));
}
}
//copying elements of GplusC_MATRIX in a one dimension array a
complex<double> a[(G_MATRIX.size())*(G_MATRIX.size())];
int k=0;
for(int i=0;i!=(G_MATRIX).size();++i)
for(int j=0;j!=(G_MATRIX).size();++j)
a[k++]=GplussC_MATRIX[j][i];
//printing the one dimension a matrix
// cout<<endl<<" one dimension 'a' matrix"<<endl;
// for(int i=0;i!=((G_MATRIX.size())*(G_MATRIX.size()));++i)
// cout<<a[i]<<" ";
// cout<<endl;
//
//copying elements of Bucomplexmultiple into b one dimension matrix
complex<double> b[B_MATRIX.size()];
for(int i=0;i!=(B_MATRIX).size();++i)
b[i]=Bucomplexmultiple[i][0];
// printing the b one dimension matrix
// cout<<"one dimension b matrix"<<endl;
// for(int i=0;i!=(B_MATRIX).size();++i)
// cout<<b[i];
// cout<<endl;
//computing ax=b using zgesv routine
// cout<<"computing Ax=b of orginal solution"<<endl;
int n=G_MATRIX.size();
int nrhs=1;
int lda=n;
int ldb=n;
int info;
int ipiv[n];
// printf( " ZGESV Program Results\n" );
zgesv_( &n, &nrhs, a, &lda, ipiv, b, &ldb, &info );
// Check for the exact singularity
if( info > 0 ) {
printf( "The diagonal element of the triangular factor of A,\n" );
printf( "U(%i,%i) is zero, so that A is singular;\n", info, info );
printf( "the solution could not be computed.\n" );
return( 1 );
}
// cout<<"done computing Ax=B of orginal solution"<<endl;
complex<double> original_solution[n][1];
for(int i=0;i<n;++i)
{
for(int j=0;j<nrhs;++j)
{
original_solution[i][j]=b[i+j*ldb];
}
}
for(int i=0;i<G_MATRIX.size();++i)
{
for(int k=0;k<output_node.size();++k)
{
if(i==(output_node[k]-1)){
if((original_solution[i][0]).imag()>=0)
result11<<(original_solution[i][0]).real()<<'+'<<(original_solution[i][0]).imag()<<'i'<<'\t';
else
result11<<(original_solution[i][0]).real()<<(original_solution[i][0]).imag()<<'i'<<'\t';
}
}
}
result11<<';'<<endl;
++timer1;
}//for loop of frequency ends here
}
else cout<<"unable to open file"<<endl;
cout<<"done computing Ax=b of original solution for different frequencies and writing for MATLAB READING in MATLAB_result_at_output_node_at_multiple_frequencies.txt"<<endl;
*/ //comment for original model solving ends here
//function to generate the X matrices containing the genrerated perpendicular columns for MOR
cout<<endl<<"STARTING THE MOR FROM HERE"<<endl;
char answer='y';//while loop starts here
while(answer=='y')
{
int expansion=1;
cout<<"enter the number of expansion points :"<<expansion<<endl;
// cout<<"enter the number of expansion points :";
// cin>>expansion;
double abcd[expansion],efgh[expansion],expan_freq;
int q_val;
for(int i=0;i<expansion;++i)
{
expan_freq=0;
cout<<"enter the "<<i+1<<" expansion frequency: "<<expan_freq<<endl;
// cout<< enter the "<<i+1<<" expansion frequency: ";
// cin>>expan_freq;
abcd[i]=expan_freq;
q_val=414;
cout<<"enter the value of q : "<<q_val<<endl;
// cout<<"enter the value of q : ";
//cin>>q_val;
efgh[i]=q_val;
}
vector<vector<double> > X_MATRIX;
vector<double>range;
cout<<"computing the orthonormal matrices using block Arnoldi algorithm"<<endl;
for(int count_Q=0;count_Q<expansion;++count_Q)
{
double expansion_frequency;
expansion_frequency=abcd[count_Q];
int Q_value;
Q_value=efgh[count_Q];
if(count_Q==0)
blockArnoldi(G_MATRIX,C_MATRIX,B_MATRIX,X_MATRIX,Q_value,range);
else{
cout<<"entering...................................................."<<endl;
// cout<<X_MATRIX.size()<<"................................."<<(X_MATRIX.at(0)).size()<<endl;
multi_Arnoldi(G_MATRIX,C_MATRIX,B_MATRIX,X_MATRIX,Q_value,expansion_frequency);
cout<<"out..........................................................."<<endl;
}
cout<<"the number of rows in "<< count_Q+1<<" are: "<<X_MATRIX.size()<<" the number of columns are :"<<(X_MATRIX.at(0)).size()<<endl;
}
cout<<"the number of rows in X_MATRIX are: "<<X_MATRIX.size()<<" the number of columns are :"<<(X_MATRIX[0]).size()<<endl;
string s1="SERIAL_X_MATRIX_"+in_1;
file_write(s1,X_MATRIX);
cout<<"written X_MATRIX in "<<s1<<endl;
//blockArnoldi(G_MATRIX,C_MATRIX,B_MATRIX,X_MATRIX);
// cout<<"printing the X_MATIRIX"<<endl;
// print(X_MATRIX);
//checking each coulumvnis orthnormal to each other
/* cout<<"done computing the orthonormal matrices using block Arnoldi algorithm"<<endl;
cout<<"checking the mtrices generated is orthonormal or not"<<endl;
vector<vector<double> > X_MATRIX_TRANSPOSE,IDENTITY;
vector_transpose(X_MATRIX,X_MATRIX_TRANSPOSE);
vectormultiplication(X_MATRIX_TRANSPOSE,X_MATRIX,IDENTITY);
cout<<"checking the orthonormality"<<endl;
fstream wr_o("orthonormality_check.txt",fstream::out);
if(wr_o.is_open())
{
for(int i=0;i<IDENTITY.size();++i)
{
for(int j=0;j<(IDENTITY.at(0)).size();++j)
{
wr_o<<IDENTITY[i][j]<<'\t';
}
wr_o<<endl;
}
wr_o.close();
}
else cout<<"unable to open file"<<endl;
cout<<" wrting the results of orthonormality check in orthonormality_check.txt"<<endl;
//generating the reduced matrices
cout<<"generating the reduced Matrices of orginal matrices"<<endl;
vector<vector<double> > X_transpose,multiple,G_cap,C_cap,B_cap;
vector_transpose(X_MATRIX,X_transpose);
vectormultiplication(X_transpose,X_MATRIX,multiple);
// cout<<"printing the multiplication of Z matrices and its transpose"<<endl;
// print(multiple);
multiple.clear();
vectormultiplication(X_transpose,G_MATRIX,multiple);
vectormultiplication(multiple,X_MATRIX,G_cap);
multiple.clear();
vectormultiplication(X_transpose,C_MATRIX,multiple);
vectormultiplication(multiple,X_MATRIX,C_cap);
multiple.clear();
vectormultiplication(X_transpose,B_MATRIX,B_cap);
// cout<<"printing the Gcap"<<endl;
// print(G_cap);
// cout<<"printing the Ccap"<<endl;
// print(C_cap);
// cout<<"printing the Bcap"<<endl;
// print(B_cap);
cout<<"done generating the reduced Matrices of orginal matrices"<<endl;
X_transpose.clear();
vector_transpose(X_MATRIX,X_transpose);
cout<<"the number of X reduced are :"<<G_cap.size()<<endl;
double t5=clock();
fstream result22("MATLAB_MORresult_at_output_node_at_multiple_frequencies.txt",fstream::out);
if(result22.is_open() )
{
double frequency;
int timer2=0;
while(timer2<points)
{
cout<<"computing MOR at "<<timer2+1<<" frequency point"<<endl;
frequency=frequency_min+(interval*timer2);
result22<<frequency<<'\t';
// Combining G_cap and C_cap into G_capplussC_cap
complex<double> G_capplussC_cap[(G_cap).size()][(G_cap).size()];
for(int i=0;i<(G_cap).size();++i){
for(int j=0;j<(G_cap).size();++j)
{
G_capplussC_cap[i][j]=complex<double>(G_cap[i][j],(2*pi*frequency*C_cap[i][j]));
}
}
//copying elements of GcapplusCcap in a one dimension array acap
complex<double> a_cap[(G_cap.size())*(G_cap.size())];
int k_cap=0;
for(int i=0;i<(G_cap).size();++i)
for(int j=0;j<(G_cap).size();++j)
a_cap[k_cap++]=G_capplussC_cap[j][i];
//converting the B_cap VECTOR MATRIX to B_cap ARRAY MATRIX
complex<double> B_cap_COMPLEXARRAYMATRIX[(B_cap).size()][(u_MATRIX).size()];
for(int i=0;i<(B_cap).size();++i)
for(int j=0;j<(u_MATRIX).size();++j)
B_cap_COMPLEXARRAYMATRIX[i][j]=complex<double>(B_cap[i][j],0);
//multiplying the B_COMPLEXARRAY AND uarraymatrix
complex<double> B_capucomplexmultiple[(B_cap).size()][1];
for(int i=0;i<(B_cap).size();++i)
for(int j=0;j<(u_MATRIX).size();++j)
B_capucomplexmultiple[i][0]+=B_cap_COMPLEXARRAYMATRIX[i][j]*uarraymatrix[j][0];
//copying elements of B_capucomplexmultiple into b_cap one dimension matrix
complex<double> b_cap[(B_cap).size()];
for(int i=0;i<(B_cap).size();++i)
b_cap[i]=B_capucomplexmultiple[i][0];
//computing a_capx=b_cap using cgesv routine
int n_cap=G_cap.size();
int nrhs_cap=1;
int lda_cap=n_cap;
int ldb_cap=n_cap;
int info_cap;
int ipiv_cap[n_cap];
zgesv_( &n_cap, &nrhs_cap, a_cap, &lda_cap, ipiv_cap, b_cap, &ldb_cap, &info_cap );
if( info_cap > 0 ) {
printf( "The diagonal element of the triangular factor of A,\n" );
printf( "U(%i,%i) is Jero, so that A is singular;\n", info_cap, info_cap );
printf( "the solution could not be computed.\n" );
return( 1 );
}
//converting X_matrix into X complex arary matrices
complex<double> X_complexarray[X_MATRIX.size()][(X_MATRIX[0]).size()];
for(int i=0;i<X_MATRIX.size();++i)
for(int j=0;j<(X_MATRIX[0]).size();++j)
X_complexarray[i][j]=complex<double>(X_MATRIX[i][j],0);
//converting b_cap from inverse into x_cap 2 dimension array
complex<double> x_cap[G_cap.size()][1];
for(int i=0;i<n_cap;++i)
for(int j=0;j<nrhs_cap;++j)
x_cap[i][j]=b_cap[i+j*ldb_cap];
complex<double>MORsolutioncompare[X_MATRIX.size()][1];
for(int i=0;i<X_MATRIX.size();++i)
for(int j=0;j<(X_MATRIX[0]).size();++j)
MORsolutioncompare[i][0]+=X_MATRIX[i][j]*x_cap[j][0];
for(int i=0;i<G_MATRIX.size();++i)
{
for(int k=0;k<output_node.size();++k)
{
if(i==(output_node[k]-1)){
if((MORsolutioncompare[i][0]).imag()>=0)
result22<<(MORsolutioncompare[i][0]).real()<<'+'<<(MORsolutioncompare[i][0]).imag()<<'i'<<'\t';
else
result22<<(MORsolutioncompare[i][0]).real()<<(MORsolutioncompare[i][0]).imag()<<'i'<<'\t';
}
}
}
result22<<';'<<endl;
++timer2;
}
result22.close();
}
else cout<<"unable top open file"<<endl;
double t6=clock();
cout<<" TIME taken to compute MOR from individual orhtonormal matrices is : "<<(t6-t5)/double(CLOCKS_PER_SEC) << "seconds"<<endl;
cout<<"done computing Ax=b of MOR solution for different frequencies and writing for MATLAB READING in MATLAB_MORresult_at_output_node_at_multiple_frequencies.txt "<<endl;
//cout<<"the size of Original solution is :"<<original_solution.size()<<" and the size of MOR solution compare is :"<<MORsolutioncompare.size()<<endl;
// out<<" the original and MOR solution written in result.out"<<endl;
*/
answer='n';
cout<<"do you want to continue for new value of Q (y/n)---- -:"<<answer<<endl;
// cin>>answer;
if(answer=='n')
{
if(X_big.empty())
X_big=X_MATRIX;
else
{
for(int i=0;i<X_MATRIX.size();++i)
{
for(int j=0;j<(X_MATRIX.at(0)).size();++j)
{
(X_big[i]).push_back(X_MATRIX[i][j]);
}
}
}
}
}//whille loop
return 30;
}
int SVD(vector<vector<double> > &X_svd,vector<double> &sigma,vector<vector<double> >X_big)
{
int m=X_big.size();
int n=(X_big.at(0)).size();
int lda =m,ldu=m,ldvt=n,info,lwork;
double wkopt;
double* work;
int sn;
if(m>n) sn=n;
else sn=m;
double s[sn],u[ldu*m],vt[ldvt*n],a[lda*n];
int count=0;
for(int i=0;i<(X_big.at(0)).size();++i)
{
for(int j=0;j<X_big.size();++j)
{
a[count++]=X_big[j][i];
}
}
lwork = -1;
dgesvd_( "All", "All", &m, &n, a, &lda, s, u, &ldu, vt, &ldvt, &wkopt, &lwork, &info );
lwork = (int)wkopt;
work = (double*)malloc( lwork*sizeof(double) );
/* Compute SVD */
dgesvd_( "All", "All", &m, &n, a, &lda, s, u, &ldu, vt, &ldvt, work, &lwork,&info );
if( info > 0 ) {
printf( "The algorithm computing SVD failed to converge.\n" );
}
vector<double> temp;
for(int i=0;i<sn;++i)
{
sigma.push_back(s[i]);
}
for(int i=0;i<m;++i)
{
for(int j=0;j<sn;++j)
{
temp.push_back(u[i+j*ldu]);
}
X_svd.push_back(temp);
temp.clear();
}
return 31;
}
int retrun_X_MATRIX(vector<vector<double> > &X_MATRIX,vector<vector<double> > X_svd,int count)
{
vector<double> temp_svd;
for(int i=0;i<X_svd.size();++i)
{
for(int j=0;j<count;++j)
{
temp_svd.push_back(X_svd[i][j]);
}
X_MATRIX.push_back(temp_svd);
temp_svd.clear();
}
return 32;
}
int original_plus_MOR_sending_X_MATRIX(vector<vector<double> > X_MATRIX,double frequency_max,double frequency_min, double points)
{
double interval;
interval=(frequency_max-frequency_min)/(points-1);
string in_1,in_2,in_3;
cout<<"ENTER THE MAIN NETLIST FILE : ";
cin>>in_1;
// cout<<"enter the file containing INPUT TERMINAL : " ;
// cin>>in_2;
// cout<<"enter the file containing OUTPUT TERMINALS : ";
// cin>>in_3;
cout<<"1) MAIN NETLIST FILE : "<<in_1;//<<endl<<"2) INPUT TERMINAL FILE : "<<in_2<<endl<<"3) OUTPUT TERMINAL FILE : "<<in_3<<endl;
cout<<" DID U CHANGE THE FREQUENCY"<<endl/*<<"REMEMBER ARRAY IS A BITCH"<<endl*/<<"First enter RGC irrespective of the order,then enter L,then independent sources and then dependent sources"<<endl<<"R or r for resistance"<<endl<<"G or g for admittance"<<endl<<"C or c for capacitance"<<endl<<"L or l for inductance"<<endl<<"J or j for current source"<<endl<<"E or e for VCVS"<<endl<<"Z or z for VCCS"<<endl<<"H or h for CCVS"<<endl<<"V or v for independent voltage source"<<endl<<"PRESS ENTER TWICE AFTER DONE ENTERING THE CIRCUIT INFORAMTION IN THE FORM OF SPICE INPUT"<<endl;
vector<complex<double> > u_MATRIX;
vector<vector<double> >G_MATRIX;
vector<vector<double> >C_MATRIX;
vector<vector<double> >B_MATRIX;
G_MATRIX.clear();
C_MATRIX.clear();
B_MATRIX.clear();
//reading the input and output node from files created from pul.c code
vector<double> input_node,output_node;
read_nodes("input_terminal.txt", input_node);
read_nodes("output_terminal.txt", output_node);
//printing the nodes
for(int i=0;i<input_node.size();++i)
cout<<input_node[i]<<" ";
cout<<endl;
for(int i=0;i<output_node.size();++i)
cout<<output_node[i]<<" ";
cout<<endl;
populate_matrices(in_1, G_MATRIX, C_MATRIX, B_MATRIX,u_MATRIX);
// cout<<"G MATRIX"<<endl;
// print(G_MATRIX);
// cout<<endl;
// cout<<"C MATRIX"<<endl;
// print(C_MATRIX);
cout<<"THE NUMBER OF VARIABLE ARE :"<<G_MATRIX.size()<<endl;
// cout<<endl<<"B MATRIX"<<endl;
// print(B_MATRIX);
// cout<<endl<<"u complex vector"<<endl;
// printcomplexvector(u_MATRIX);
/*converting ucomplex vectro matrix into ucomplex array matrix*/
complex<double> uarraymatrix[(u_MATRIX).size()][1];
for(int i=0;i<(u_MATRIX).size();++i)
uarraymatrix[i][0]=u_MATRIX[i];
//printing tht ucomplexaray
// cout<<endl<<"ucomplexarray"<<endl;
// for(int i=0;i!=(u_MATRIX).size();++i)
// cout<<uarraymatrix[i][0]<<endl;
//converting the B VECTOR MATRIX to B ARRAY MATRIX
complex<double> B_COMPLEXARRAYMATRIX[(B_MATRIX).size()][(u_MATRIX).size()];
for(int i=0;i<(B_MATRIX).size();++i)
for(int j=0;j!=(u_MATRIX).size();++j)
B_COMPLEXARRAYMATRIX[i][j]=complex<double>(B_MATRIX[i][j],0);
// print the the B ARRAY MATRIX
// cout<<endl<<"B_COMPLEXARRAYMATRIX"<<endl;
// for(int i=0;i!=(B_MATRIX).size();++i){
// for(int j=0;j!=(u_MATRIX).size();++j)
// cout<<B_COMPLEXARRAYMATRIX[i][j]<<" ";
// cout<<endl;}
//multiplying the B_COMPLEXARRAY AND uarraymatrix
complex<double> Bucomplexmultiple[(B_MATRIX).size()][1];
for(int i=0;i!=(B_MATRIX).size();++i)
for(int j=0;j!=(u_MATRIX).size();++j)
Bucomplexmultiple[i][0]+=B_COMPLEXARRAYMATRIX[i][j]*uarraymatrix[j][0];
/* //comment for original solving starts here
char answe;
cout<<"DO YOU WANT TO SOLVE FOR THE ORIGINAL VARIABLES(y/n) :";
cin>>answe;
if(answe=='y')
{
double t1=clock();
fstream result11("SVD_MATLAB_result_at_output_node_at_multiple_frequencies.txt",fstream::out);
if(result11.is_open() )
{
double frequency;
int timer1=0;
while(timer1<points)
{
cout<<"original"<<timer1+1<<endl;
frequency=frequency_min+(interval*timer1);
result11<<frequency<<'\t';
//combining G_MATRIX and C_MATRIX into GplussC_MATRIX
complex<double> GplussC_MATRIX[(G_MATRIX).size()][(G_MATRIX).size()];
for(int i=0;i<(G_MATRIX).size();++i)
{
for(int j=0;j<(G_MATRIX).size();++j)
{
GplussC_MATRIX[i][j]=complex<double>(G_MATRIX[i][j],(2*pi*frequency*C_MATRIX[i][j]));
}
}
//copying elements of GplusC_MATRIX in a one dimension array a
complex<double> a[(G_MATRIX.size())*(G_MATRIX.size())];
int k=0;
for(int i=0;i!=(G_MATRIX).size();++i)
for(int j=0;j!=(G_MATRIX).size();++j)
a[k++]=GplussC_MATRIX[j][i];
//printing the one dimension a matrix
// cout<<endl<<" one dimension 'a' matrix"<<endl;
// for(int i=0;i!=((G_MATRIX.size())*(G_MATRIX.size()));++i)
// cout<<a[i]<<" ";
// cout<<endl;
//
//copying elements of Bucomplexmultiple into b one dimension matrix
complex<double> b[B_MATRIX.size()];
for(int i=0;i!=(B_MATRIX).size();++i)
b[i]=Bucomplexmultiple[i][0];
// printing the b one dimension matrix
// cout<<"one dimension b matrix"<<endl;
// for(int i=0;i!=(B_MATRIX).size();++i)
// cout<<b[i];
// cout<<endl;
//computing ax=b using zgesv routine
// cout<<"computing Ax=b of orginal solution"<<endl;
int n=G_MATRIX.size();
int nrhs=1;
int lda=n;
int ldb=n;
int info;
int ipiv[n];
// printf( " ZGESV Program Results\n" );
zgesv_( &n, &nrhs, a, &lda, ipiv, b, &ldb, &info );
// Check for the exact singularity
if( info > 0 ) {
printf( "The diagonal element of the triangular factor of A,\n" );
printf( "U(%i,%i) is zero, so that A is singular;\n", info, info );
printf( "the solution could not be computed.\n" );
return( 1 );
}
// cout<<"done computing Ax=B of orginal solution"<<endl;
complex<double> original_solution[n][1];
for(int i=0;i<n;++i)
{
for(int j=0;j<nrhs;++j)
{
original_solution[i][j]=b[i+j*ldb];
}
}
for(int i=0;i<G_MATRIX.size();++i)
{
for(int k=0;k<output_node.size();++k)
{
if(i==(output_node[k]-1)){
if((original_solution[i][0]).imag()>=0)
result11<<(original_solution[i][0]).real()<<'+'<<(original_solution[i][0]).imag()<<'i'<<'\t';
else
result11<<(original_solution[i][0]).real()<<(original_solution[i][0]).imag()<<'i'<<'\t';
}
}
}
result11<<';'<<endl;
++timer1;
}//for loop of frequency ends here
}
else cout<<"unable to open file"<<endl;
double t2=clock();
cout<<" TIME taken to compute the original model is : "<<(t2-t1)/double(CLOCKS_PER_SEC) << "seconds "<<endl;
cout<<"done computing Ax=b of original solution for different frequencies and writing for MATLAB READING in SVD_MATLAB_result_at_output_node_at_multiple_frequencies.txt"<<endl;
}
*/ //comment for original model solving ends here
cout<<"checking the mtrices generated is orthonormal or not"<<endl;
vector<vector<double> > X_MATRIX_TRANSPOSE,IDENTITY;
vector_transpose(X_MATRIX,X_MATRIX_TRANSPOSE);
vectormultiplication(X_MATRIX_TRANSPOSE,X_MATRIX,IDENTITY);
cout<<"checking the orthonormality"<<endl;
fstream wr_o("SVD_orthonormality_check.txt",fstream::out);
if(wr_o.is_open())
{
for(int i=0;i<IDENTITY.size();++i)
{
for(int j=0;j<(IDENTITY.at(0)).size();++j)
{
wr_o<<IDENTITY[i][j]<<'\t';
}
wr_o<<endl;
}
wr_o.close();
}
else cout<<"unable to open file"<<endl;
cout<<" wrting the results of orthonormality check in SVD_orthonormality_check.txt"<<endl;
//generating the reduced matrices
cout<<"generating the reduced Matrices of orginal matrices"<<endl;
vector<vector<double> > X_transpose,multiple,G_cap,C_cap,B_cap;
vector_transpose(X_MATRIX,X_transpose);
vectormultiplication(X_transpose,X_MATRIX,multiple);
// cout<<"printing the multiplication of Z matrices and its transpose"<<endl;
// print(multiple);
multiple.clear();
vectormultiplication(X_transpose,G_MATRIX,multiple);
vectormultiplication(multiple,X_MATRIX,G_cap);
multiple.clear();
vectormultiplication(X_transpose,C_MATRIX,multiple);
vectormultiplication(multiple,X_MATRIX,C_cap);
multiple.clear();
vectormultiplication(X_transpose,B_MATRIX,B_cap);
// cout<<"printing the Gcap"<<endl;
// print(G_cap);
// cout<<"printing the Ccap"<<endl;
// print(C_cap);
// cout<<"printing the Bcap"<<endl;
// print(B_cap);
cout<<"done generating the reduced Matrices of orginal matrices"<<endl;
X_transpose.clear();
vector_transpose(X_MATRIX,X_transpose);
cout<<"the number of X reduced are :"<<G_cap.size()<<endl;
double t3=clock();
fstream result22("SVD_MATLAB_MORresult_at_output_node_at_multiple_frequencies.txt",fstream::out);
if(result22.is_open() )
{
double frequency;
int timer2=0;
while(timer2<points)
{
cout<<"computing MOR at "<<timer2+1<<" frequency point"<<endl;
frequency=frequency_min+(interval*timer2);
result22<<frequency<<'\t';
// Combining G_cap and C_cap into G_capplussC_cap
complex<double> G_capplussC_cap[(G_cap).size()][(G_cap).size()];
for(int i=0;i<(G_cap).size();++i){
for(int j=0;j<(G_cap).size();++j)
{
G_capplussC_cap[i][j]=complex<double>(G_cap[i][j],(2*pi*frequency*C_cap[i][j]));
}
}
//copying elements of GcapplusCcap in a one dimension array acap
complex<double> a_cap[(G_cap.size())*(G_cap.size())];
int k_cap=0;
for(int i=0;i<(G_cap).size();++i)
for(int j=0;j<(G_cap).size();++j)
a_cap[k_cap++]=G_capplussC_cap[j][i];
//converting the B_cap VECTOR MATRIX to B_cap ARRAY MATRIX
complex<double> B_cap_COMPLEXARRAYMATRIX[(B_cap).size()][(u_MATRIX).size()];
for(int i=0;i<(B_cap).size();++i)
for(int j=0;j<(u_MATRIX).size();++j)
B_cap_COMPLEXARRAYMATRIX[i][j]=complex<double>(B_cap[i][j],0);
//multiplying the B_COMPLEXARRAY AND uarraymatrix
complex<double> B_capucomplexmultiple[(B_cap).size()][1];
for(int i=0;i<(B_cap).size();++i)
for(int j=0;j<(u_MATRIX).size();++j)
B_capucomplexmultiple[i][0]+=B_cap_COMPLEXARRAYMATRIX[i][j]*uarraymatrix[j][0];
//copying elements of B_capucomplexmultiple into b_cap one dimension matrix
complex<double> b_cap[(B_cap).size()];
for(int i=0;i<(B_cap).size();++i)
b_cap[i]=B_capucomplexmultiple[i][0];
//computing a_capx=b_cap using cgesv routine
int n_cap=G_cap.size();
int nrhs_cap=1;
int lda_cap=n_cap;
int ldb_cap=n_cap;
int info_cap;
int ipiv_cap[n_cap];
zgesv_( &n_cap, &nrhs_cap, a_cap, &lda_cap, ipiv_cap, b_cap, &ldb_cap, &info_cap );
if( info_cap > 0 ) {
printf( "The diagonal element of the triangular factor of A,\n" );
printf( "U(%i,%i) is Jero, so that A is singular;\n", info_cap, info_cap );
printf( "the solution could not be computed.\n" );
return( 1 );
}
//converting X_matrix into X complex arary matrices
complex<double> X_complexarray[X_MATRIX.size()][(X_MATRIX[0]).size()];
for(int i=0;i<X_MATRIX.size();++i)
for(int j=0;j<(X_MATRIX[0]).size();++j)
X_complexarray[i][j]=complex<double>(X_MATRIX[i][j],0);
//converting b_cap from inverse into x_cap 2 dimension array
complex<double> x_cap[G_cap.size()][1];
for(int i=0;i<n_cap;++i)
for(int j=0;j<nrhs_cap;++j)
x_cap[i][j]=b_cap[i+j*ldb_cap];
complex<double>MORsolutioncompare[X_MATRIX.size()][1];
for(int i=0;i<X_MATRIX.size();++i)
for(int j=0;j<(X_MATRIX[0]).size();++j)
MORsolutioncompare[i][0]+=X_MATRIX[i][j]*x_cap[j][0];
for(int i=0;i<G_MATRIX.size();++i)
{
for(int k=0;k<output_node.size();++k)
{
if(i==(output_node[k]-1)){
if((MORsolutioncompare[i][0]).imag()>=0)
result22<<(MORsolutioncompare[i][0]).real()<<'+'<<(MORsolutioncompare[i][0]).imag()<<'i'<<'\t';
else
result22<<(MORsolutioncompare[i][0]).real()<<(MORsolutioncompare[i][0]).imag()<<'i'<<'\t';
}
}
}
result22<<';'<<endl;
++timer2;
}
result22.close();
}
else cout<<"unable top open file"<<endl;
double t4=clock();
cout<<" TIME taken to compute the MOR from SVD MATRIX solution is :"<<(t4-t3)/double(CLOCKS_PER_SEC) << "seconds"<<endl;
cout<<"done computing Ax=b of MOR solution for different frequencies and writing for MATLAB READING in SVD_MATLAB_MORresult_at_output_node_at_multiple_frequencies.txt "<<endl;
//cout<<"the size of Original solution is :"<<original_solution.size()<<" and the size of MOR solution compare is :"<<MORsolutioncompare.size()<<endl;
// out<<" the original and MOR solution written in result.out"<<endl;
return 33;
}
|
#ifndef SOLUTION_H
#define SOLUTION_H
#include <iostream>
#include <vector>
#include "utils.h"
#include "mTree.h"
#include "mList.h"
#include "mNode.h"
using namespace std;
class Solution
{
public:
//#4 findMedianSortedArrays
double findMedianSortedArrays(vector<int> &nums1, vector<int> &nums2);
//#5 longestPalindrome
string longestPalindrome(string s);
//#6 convert
string convert(string s, int numRows);
//#7 reverse
int reverse(int x);
//#8 myAtoi
int myAtoi(string str);
//#9 isPalindrome
bool isPalindrome(int x);
//#10 isMatch
bool isMatch(string s, string p);
//#11 ็ๆๅคๆฐด็ๅฎนๅจ
int maxArea(vector<int> &height);
//#226 invertTree
TreeNode *invertTree(TreeNode *root);
//#538 convertBST
TreeNode* convertBST(TreeNode* root);
//#617 mergeTrees
TreeNode *mergeTrees(TreeNode *t1, TreeNode *t2);
//#968 minCameraCover
int minCameraCover(TreeNode* root);
int minCameraCover2(TreeNode* root);
//#1431 kidsWithCandies
vector<bool> kidsWithCandies(vector<int>& candies, int extraCandies);
//#1470 shuffle
vector<int> shuffle(vector<int>& nums, int n);
//#1480 runningSum
vector<int> runningSum(vector<int>& nums);
//#1512 numIdenticalPairs
int numIdenticalPairs(vector<int>& nums);
//#501 findMode
vector<int> findMode(TreeNode *root);
//#235 ไบๅๆ็ดขๆ ็ๆ่ฟๅ
ฌๅ
ฑ็ฅๅ
TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q);
//# 117. ๅกซๅ
ๆฏไธช่็น็ไธไธไธชๅณไพง่็นๆ้ II
Node* connect(Node* root);
};
#endif
|
/*
* Scythe Statistical Library Copyright (C) 2000-2002 Andrew D. Martin
* and Kevin M. Quinn; 2002-present Andrew D. Martin, Kevin M. Quinn,
* and Daniel Pemstein. All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify under the terms of the GNU General Public License as
* published by Free Software Foundation; either version 2 of the
* License, or (at your option) any later version. See the text files
* COPYING and LICENSE, distributed with this source code, for further
* information.
* --------------------------------------------------------------------
* scythestat/matrix_random_access_iterator.h
*
* Random access iterators for the matrix class.
*
*/
/*! \file matrix_random_access_iterator.h
* \brief Definitions of STL-compliant random access iterators for
* the Matrix class.
*
* Contains definitions of const_matrix_random_access_iterator,
* matrix_random_access_iterator, and related operators. See a
* Standard Template Library reference, such as Josuttis (1999), for a
* full description of the capabilities of random access iterators.
*
* These iterators are templated on the type, order and style of the
* Matrix they iterate over and their own order, which need not match
* the iterated-over matrix. Same-order iteration over concrete
* matrices is extremely fast. Cross-grain concrete and/or view
* iteration is slower.
*/
#ifndef SCYTHE_MATRIX_RANDOM_ACCESS_ITERATOR_H
#define SCYTHE_MATRIX_RANDOM_ACCESS_ITERATOR_H
#include <iterator>
#ifdef SCYTHE_COMPILE_DIRECT
#include "defs.h"
#include "error.h"
#include "matrix.h"
#else
#include "scythestat/defs.h"
#include "scythestat/error.h"
#include "scythestat/matrix.h"
#endif
/* The const_matrix_iterator and matrix_iterator classes are
* essentially identical, except for the return types of the *, ->,
* and [] operators. matrix_iterator extends const_matrix_iterator,
* overriding most of its members. */
/* TODO Current setup uses template argument based branches to
* handle views and cross-grained orderings differently than simple
* in-order concrete matrices. The work for this gets done at
* compile time, but we end with a few unused instance variables in
* the concrete case. It might be better to specialize the entire
* class, although this will lead to a lot of code duplication. We
* should bench the difference down the road and see if it is worth
* the maintenance hassle.
*
* At the moment this is looking like it won't be worth it.
* Iterator-based operations on concretes provide comparable
* performance to element-access based routines in previous versions
* of the library, indicating little performance penalty.
*/
namespace scythe {
/* convenience typedefs */
namespace { // local to this file
typedef unsigned int uint;
}
/* forward declaration of the matrix class */
template <typename T_type, matrix_order ORDER, matrix_style STYLE>
class Matrix;
/*! \brief An STL-compliant const random access iterator for Matrix.
*
* Provides random access iteration over const Matrix objects. See
* Josuttis (1999), or some other STL reference, for a full
* description of the random access iterator interface.
*
* \see Matrix
* \see matrix_random_access_iterator
* \see const_matrix_forward_iterator
* \see matrix_forward_iterator
* \see const_matrix_bidirectional_iterator
* \see matrix_bidirectional_iterator
*/
template <typename T_type, matrix_order ORDER, matrix_order M_ORDER,
matrix_style M_STYLE>
class const_matrix_random_access_iterator
// : public std::iterator<std::random_access_iterator_tag, T_type>
{
public:
using iterator_category = std::random_access_iterator_tag;
using value_type = T_type;
using difference_type = T_type;
using pointer = T_type*;
using reference = T_type&;
/**** TYPEDEFS ***/
typedef const_matrix_random_access_iterator<T_type, ORDER,
M_ORDER, M_STYLE> self;
/* These are a little formal, but useful */
// typedef typename std::iterator_traits<self>::value_type
// value_type;
// typedef typename std::iterator_traits<self>::iterator_category
// iterator_category;
// typedef typename std::iterator_traits<self>::difference_type
// difference_type;
// typedef typename std::iterator_traits<self>::pointer pointer;
// typedef typename std::iterator_traits<self>::reference reference;
/**** CONSTRUCTORS ****/
/* Default constructor */
const_matrix_random_access_iterator ()
{}
/* Standard constructor */
const_matrix_random_access_iterator
( const Matrix<value_type, M_ORDER, M_STYLE> &M)
: start_ (M.getArray())
{
SCYTHE_CHECK_30 (start_ == 0, scythe_null_error,
"Requesting iterator to NULL matrix");
pos_ = start_;
/* The basic story is: when M_STYLE == Concrete and ORDER ==
* M_ORDER, we only need pos_ and start_ and iteration will be
* as fast as possible. All other types of iteration need
* more variables to keep track of things and are slower.
*/
if (M_STYLE != Concrete || M_ORDER != ORDER) {
offset_ = 0;
if (ORDER == Col) {
lead_length_ = M.rows();
lead_inc_ = M.rowstride();
trail_inc_ = M.colstride();
} else {
lead_length_ = M.cols();
lead_inc_ = M.colstride();
trail_inc_ = M.rowstride();
}
jump_ = trail_inc_ + (1 - lead_length_) * lead_inc_;
}
#if SCYTHE_DEBUG > 2
size_ = M.size();
#endif
}
/* Copy constructor */
const_matrix_random_access_iterator (const self &mi)
: start_ (mi.start_),
pos_ (mi.pos_)
{
if (M_STYLE != Concrete || M_ORDER != ORDER) {
offset_ = mi.offset_;
lead_length_ = mi.lead_length_;
lead_inc_ = mi.lead_inc_;
trail_inc_ = mi.trail_inc_;
jump_ = mi.jump_;
}
#if SCYTHE_DEBUG > 2
size_ = mi.size_;
#endif
}
/**** FORWARD ITERATOR FACILITIES ****/
inline self& operator= (const self& mi)
{
start_ = mi.start_;
pos_ = mi.pos_;
if (M_STYLE != Concrete || M_ORDER != ORDER) {
offset_ = mi.offset_;
lead_length_ = mi.lead_length_;
lead_inc_ = mi.lead_inc_;
trail_inc_ = mi.trail_inc_;
jump_ = mi.jump_;
}
#if SCYTHE_DEBUG > 2
size_ = mi.size_;
#endif
return *this;
}
inline const reference operator* () const
{
SCYTHE_ITER_CHECK_BOUNDS();
return *pos_;
}
inline const pointer operator-> () const
{
SCYTHE_ITER_CHECK_BOUNDS();
return pos_;
}
inline self& operator++ ()
{
if (M_STYLE == Concrete && ORDER == M_ORDER)
++pos_;
else if (++offset_ % lead_length_ == 0)
pos_ += jump_;
else
pos_ += lead_inc_;
return *this;
}
inline self operator++ (int)
{
self tmp = *this;
++(*this);
return tmp;
}
/* == is only defined for iterators of the same template type
* that point to the same matrix. Behavior for any other
* comparison is undefined.
*
* Note that we have to be careful about iterator comparisons
* when working with views and cross-grain iterators.
* Specifically, we always have to rely on the offset value.
* Obviously, with <> checks pos_ can jump all over the place in
* cross-grain iterators, but also end iterators point to the
* value after the last in the matrix. In some cases, the
* equation in += and -= will actually put pos_ inside the
* matrix (often in an early position) in this case.
*/
inline bool operator== (const self& x) const
{
if (M_STYLE == Concrete && ORDER == M_ORDER) {
return pos_ == x.pos_;
} else {
return offset_ == x.offset_;
}
}
/* Again, != is only officially defined for iterators over the
* same matrix although the test will be trivially true for
* matrices that don't view the same data, by implementation.
*/
inline bool operator!= (const self &x) const
{
return !(*this == x);
}
/**** BIDIRECTIONAL ITERATOR FACILITIES ****/
inline self& operator-- ()
{
if (M_STYLE == Concrete && ORDER == M_ORDER)
--pos_;
else if (offset_-- % lead_length_ == 0)
pos_ -= jump_;
else
pos_ -= lead_inc_;
return *this;
}
inline self operator-- (int)
{
self tmp = *this;
--(*this);
return tmp;
}
/**** RANDOM ACCESS ITERATOR FACILITIES ****/
inline const reference operator[] (difference_type n) const
{
if (M_STYLE == Concrete && ORDER == M_ORDER) {
SCYTHE_ITER_CHECK_OFFSET_BOUNDS(start_ + n);
return *(start_ + n);
} else {
uint trailing = n / lead_length_;
uint leading = n % lead_length_;
T_type* place = start_ + leading * lead_inc_
+ trailing * trail_inc_;
SCYTHE_ITER_CHECK_POINTER_BOUNDS(place);
return *place;
}
}
inline self& operator+= (difference_type n)
{
if (M_STYLE == Concrete && ORDER == M_ORDER) {
pos_ += n;
} else {
offset_ += n;
uint trailing = offset_ / lead_length_;
uint leading = offset_ % lead_length_;
pos_ = start_ + leading * lead_inc_
+ trailing * trail_inc_;
}
return *this;
}
inline self& operator-= (difference_type n)
{
if (M_STYLE == Concrete && ORDER == M_ORDER) {
pos_ -= n;
} else {
offset_ -= n;
uint trailing = offset_ / lead_length_;
uint leading = offset_ % lead_length_;
pos_ = start_ + leading * lead_inc_
+ trailing * trail_inc_;
}
return *this;
}
/* + and - difference operators are outside the class */
inline difference_type operator- (const self& x) const
{
if (M_STYLE == Concrete && ORDER == M_ORDER) {
return pos_ - x.pos_;
} else {
return offset_ - x.offset_;
}
}
inline difference_type operator< (const self& x) const
{
if (M_STYLE == Concrete && ORDER == M_ORDER) {
return pos_ < x.pos_;
} else {
return offset_ < x.offset_;
}
}
inline difference_type operator> (const self& x) const
{
if (M_STYLE == Concrete && ORDER == M_ORDER) {
return pos_ > x.pos_;
} else {
return offset_ > x.offset_;
}
}
inline difference_type operator<= (const self& x) const
{
if (M_STYLE == Concrete && ORDER == M_ORDER) {
return pos_ <= x.pos_;
} else {
return offset_ <= x.offset_;
}
}
inline difference_type operator>= (const self& x) const
{
if (M_STYLE == Concrete && ORDER == M_ORDER) {
return pos_ >= x.pos_;
} else {
return offset_ >= x.offset_;
}
}
protected:
/**** INSTANCE VARIABLES ****/
T_type* start_; // pointer to beginning of data array
T_type* pos_; // pointer to current position in array
uint offset_; // Logical offset into matrix
// TODO Some of these can probably be uints
int lead_length_; // Logical length of leading dimension
int lead_inc_; // Memory distance between vectors in ldim
int trail_inc_; // Memory distance between vectors in tdim
int jump_; // Memory distance between end of one ldim vector and
// begin of next
// Size variable for range checking
#if SCYTHE_DEBUG > 2
uint size_; // Logical matrix size
#endif
};
/*! \brief An STL-compliant random access iterator for Matrix.
*
* Provides random access iteration over Matrix objects. See
* Josuttis (1999), or some other STL reference, for a full
* description of the random access iterator interface.
*
* \see Matrix
* \see const_matrix_random_access_iterator
* \see const_matrix_forward_iterator
* \see matrix_forward_iterator
* \see const_matrix_bidirectional_iterator
* \see matrix_bidirectional_iterator
*/
template <typename T_type, matrix_order ORDER, matrix_order M_ORDER,
matrix_style M_STYLE>
class matrix_random_access_iterator
: public const_matrix_random_access_iterator<T_type, ORDER,
M_ORDER, M_STYLE>
{
/**** TYPEDEFS ***/
typedef matrix_random_access_iterator<T_type, ORDER, M_ORDER,
M_STYLE> self;
typedef const_matrix_random_access_iterator<T_type, ORDER,
M_ORDER, M_STYLE> Base;
public:
/* These are a little formal, but useful */
typedef typename std::iterator_traits<Base>::value_type
value_type;
typedef typename std::iterator_traits<Base>::iterator_category
iterator_category;
typedef typename std::iterator_traits<Base>::difference_type
difference_type;
typedef typename std::iterator_traits<Base>::pointer pointer;
typedef typename std::iterator_traits<Base>::reference reference;
/**** CONSTRUCTORS ****/
/* Default constructor */
matrix_random_access_iterator ()
: Base ()
{}
/* Standard constructor */
matrix_random_access_iterator (const Matrix<value_type, M_ORDER,
M_STYLE> &M)
: Base(M)
{}
/* Copy constructor */
matrix_random_access_iterator (const self &mi)
: Base (mi)
{}
/**** FORWARD ITERATOR FACILITIES ****/
/* We have to override a lot of these to get return values
* right.*/
inline self& operator= (const self& mi)
{
start_ = mi.start_;
pos_ = mi.pos_;
if (M_STYLE != Concrete || M_ORDER != ORDER) {
offset_ = mi.offset_;
lead_length_ = mi.lead_length_;
lead_inc_ = mi.lead_inc_;
trail_inc_ = mi.trail_inc_;
jump_ = mi.jump_;
}
#if SCYTHE_DEBUG > 2
size_ = mi.size_;
#endif
return *this;
}
inline reference operator* () const
{
SCYTHE_ITER_CHECK_BOUNDS();
return *pos_;
}
inline pointer operator-> () const
{
SCYTHE_ITER_CHECK_BOUNDS();
return pos_;
}
inline self& operator++ ()
{
Base::operator++();
return *this;
}
inline self operator++ (int)
{
self tmp = *this;
++(*this);
return tmp;
}
/**** BIDIRECTIONAL ITERATOR FACILITIES ****/
inline self& operator-- ()
{
Base::operator--();
return *this;
}
inline self operator-- (int)
{
self tmp = *this;
--(*this);
return tmp;
}
/**** RANDOM ACCESS ITERATOR FACILITIES ****/
inline reference operator[] (difference_type n) const
{
if (M_STYLE == Concrete && ORDER == M_ORDER) {
SCYTHE_ITER_CHECK_POINTER_BOUNDS(start_ + n);
return *(start_ + n);
} else {
uint trailing = n / lead_length_;
uint leading = n % lead_length_;
T_type* place = start_ + leading * lead_inc_
+ trailing * trail_inc_;
SCYTHE_ITER_CHECK_POINTER_BOUNDS(place);
return *place;
}
}
inline self& operator+= (difference_type n)
{
Base::operator+=(n);
return *this;
}
inline self& operator-= (difference_type n)
{
Base::operator-= (n);
return *this;
}
/* + and - difference_type operators are outside the class */
private:
/* Get handles to base members. It boggles the mind */
using Base::start_;
using Base::pos_;
using Base::offset_;
using Base::lead_length_;
using Base::lead_inc_;
using Base::trail_inc_;
using Base::jump_;
#if SCYTHE_DEBUG > 2
using Base::size_;
#endif
};
template <class T_type, matrix_order ORDER, matrix_order M_ORDER,
matrix_style STYLE>
inline
const_matrix_random_access_iterator<T_type, ORDER, M_ORDER, STYLE>
operator+ (const_matrix_random_access_iterator<T_type, ORDER, M_ORDER, STYLE> x, int n)
{
x += n;
return x;
}
template <class T_type, matrix_order ORDER, matrix_order M_ORDER,
matrix_style STYLE>
inline
const_matrix_random_access_iterator<T_type, ORDER, M_ORDER, STYLE>
operator+ (int n, const_matrix_random_access_iterator<T_type, ORDER,
M_ORDER,
STYLE> x)
{
x += n;
return x;
}
template <class T_type, matrix_order ORDER, matrix_order M_ORDER,
matrix_style STYLE>
inline
const_matrix_random_access_iterator<T_type, ORDER, M_ORDER, STYLE>
operator- (const_matrix_random_access_iterator<T_type, ORDER, M_ORDER, STYLE> x, int n)
{
x -= n;
return x;
}
template <class T_type, matrix_order ORDER, matrix_order M_ORDER,
matrix_style STYLE>
inline matrix_random_access_iterator<T_type, ORDER, M_ORDER, STYLE>
operator+ (matrix_random_access_iterator<T_type, ORDER, M_ORDER,
STYLE> x, int n)
{
x += n;
return x;
}
template <class T_type, matrix_order ORDER, matrix_order M_ORDER,
matrix_style STYLE>
inline matrix_random_access_iterator<T_type, ORDER, M_ORDER, STYLE>
operator+ (int n, matrix_random_access_iterator<T_type, ORDER,
M_ORDER, STYLE> x)
{
x += n;
return x;
}
template <class T_type, matrix_order ORDER, matrix_order M_ORDER,
matrix_style STYLE>
inline matrix_random_access_iterator<T_type, ORDER, M_ORDER, STYLE>
operator- (matrix_random_access_iterator<T_type, ORDER, M_ORDER,
STYLE> x, int n)
{
x -= n;
return x;
}
} // namespace scythe
#endif /* SCYTHE_MATRIX_ITERATOR_H */
|
/*
ID: stevenh6
TASK: stall4
LANG: C++
*/
#define problemname "stall4"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using db = double;
using pi = pair<int, int>;
using pl = pair<ll, ll>;
using pd = pair<db, db>;
using vi = vector<int>;
using vb = vector<bool>;
using vl = vector<ll>;
using vd = vector<db>;
using vs = vector<string>;
using vpi = vector<pi>;
using vpl = vector<pl>;
using vpd = vector<pd>;
#define FOR(i, a, b) for (int i = (a); i < (b); ++i)
#define FOR0(i, a) FOR(i, 0, a)
#define FOR1(i, a) for (int i = 1; i <= (a); ++i)
#define RFOR(i, a, b) for (int i = (b)-1; i >= (a); --i)
#define RFOR0(i, a) ROF(i, 0, a)
#define pb push_back;
ofstream fout;
ifstream fin;
// End of template
int n, m, sol;
int pref[201][201];
int nextstall[200];
int occu[200];
int greedy(int a) {
FOR1(j, m) {
if (pref[a][j] && !occu[j]) {
occu[j] = 1;
if (!nextstall[j] || greedy(nextstall[j])) {
nextstall[j] = a;
return 1;
}
}
}
return 0;
}
void solve()
{
cin >> n >> m;
sol = 0;
memset(nextstall, 0, sizeof(nextstall));
memset(pref, 0, sizeof(pref));
FOR1(i, n) {
int np;
cin >> np;
FOR1(j, np) {
int p;
cin >> p;
pref[i][p] = 1;
}
}
FOR1(i, n) {
memset(occu, 0, sizeof(occu));
sol += greedy(i);
}
cout << sol << endl;
}
int main()
{
ios_base::sync_with_stdio();
cin.tie(0);
freopen(problemname ".in", "r", stdin);
freopen(problemname ".out", "w", stdout);
solve();
return 0;
}
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <quic/congestion_control/TokenlessPacer.h>
#include <quic/congestion_control/CongestionControlFunctions.h>
namespace quic {
TokenlessPacer::TokenlessPacer(
const QuicConnectionStateBase& conn,
uint64_t minCwndInMss)
: conn_(conn),
minCwndInMss_(minCwndInMss),
batchSize_(conn.transportSettings.writeConnectionDataPacketsLimit),
pacingRateCalculator_(calculatePacingRate) {}
void TokenlessPacer::refreshPacingRate(
uint64_t cwndBytes,
std::chrono::microseconds rtt,
TimePoint /*currentTime*/) {
if (rtt == kDefaultMinRtt) {
return;
}
uint64_t targetRateBytesPerSec = (rtt == 0us)
? std::numeric_limits<uint64_t>::max()
: cwndBytes * 1s / rtt;
if (targetRateBytesPerSec > maxPacingRateBytesPerSec_) {
return setPacingRate(maxPacingRateBytesPerSec_);
} else if (rtt < conn_.transportSettings.pacingTickInterval) {
writeInterval_ = 0us;
batchSize_ = conn_.transportSettings.writeConnectionDataPacketsLimit;
} else {
rtt *= rttFactorNumerator_;
rtt /= rttFactorDenominator_;
const PacingRate pacingRate =
pacingRateCalculator_(conn_, cwndBytes, minCwndInMss_, rtt);
writeInterval_ = pacingRate.interval;
batchSize_ = pacingRate.burstSize;
}
if (conn_.qLogger) {
conn_.qLogger->addPacingMetricUpdate(batchSize_, writeInterval_);
}
if (!experimental_) {
lastWriteTime_.reset();
}
}
// rate_bps is *bytes* per second
void TokenlessPacer::setPacingRate(uint64_t rateBps) {
if (rateBps > maxPacingRateBytesPerSec_) {
rateBps = maxPacingRateBytesPerSec_;
}
if (rateBps == 0) {
batchSize_ = 0;
writeInterval_ = conn_.transportSettings.pacingTickInterval;
} else {
batchSize_ = conn_.transportSettings.writeConnectionDataPacketsLimit;
uint64_t interval =
(batchSize_ * conn_.udpSendPacketLen * 1000000) / rateBps;
writeInterval_ = std::max(
std::chrono::microseconds(interval),
conn_.transportSettings.pacingTickInterval);
}
if (conn_.qLogger) {
conn_.qLogger->addPacingMetricUpdate(batchSize_, writeInterval_);
}
if (!experimental_) {
lastWriteTime_.reset();
}
}
void TokenlessPacer::setMaxPacingRate(uint64_t maxRateBytesPerSec) {
maxPacingRateBytesPerSec_ = maxRateBytesPerSec;
// Current rate in bytes per sec =
// batchSize * packetLen * (1 second / writeInterval)
// if writeInterval = 0, current rate is std::numeric_limits<uint64_t>::max()
uint64_t currentRateBytesPerSec = (writeInterval_ == 0us)
? std::numeric_limits<uint64_t>::max()
: (batchSize_ * conn_.udpSendPacketLen * std::chrono::seconds(1)) /
writeInterval_;
if (currentRateBytesPerSec > maxPacingRateBytesPerSec_) {
// Current rate is faster than max. Enforce the maxPacingRate.
return setPacingRate(maxPacingRateBytesPerSec_);
}
}
void TokenlessPacer::reset() {
// We call this after idle, so we actually want to start writing immediately.
lastWriteTime_.reset();
}
void TokenlessPacer::setRttFactor(uint8_t numerator, uint8_t denominator) {
rttFactorNumerator_ = numerator;
rttFactorDenominator_ = denominator;
}
void TokenlessPacer::onPacketSent() {}
void TokenlessPacer::onPacketsLoss() {}
std::chrono::microseconds TokenlessPacer::getTimeUntilNextWrite(
TimePoint now) const {
// If we don't have a lastWriteTime_, we want to write immediately.
auto timeSinceLastWrite =
std::chrono::duration_cast<std::chrono::microseconds>(
now - lastWriteTime_.value_or(now - 2 * writeInterval_));
if (timeSinceLastWrite >= writeInterval_) {
return 0us;
}
return std::max(
writeInterval_ - timeSinceLastWrite,
conn_.transportSettings.pacingTickInterval);
}
uint64_t TokenlessPacer::updateAndGetWriteBatchSize(TimePoint currentTime) {
auto sendBatch = batchSize_;
if (lastWriteTime_.hasValue() && writeInterval_ > 0us &&
conn_.congestionController &&
!conn_.congestionController->isAppLimited()) {
// The pacer timer is expected to trigger every writeInterval_
auto timeSinceLastWrite =
std::chrono::duration_cast<std::chrono::microseconds>(
currentTime - lastWriteTime_.value());
if (conn_.congestionController &&
!conn_.congestionController->isAppLimited() &&
timeSinceLastWrite > (writeInterval_ * 110 / 100)) {
// Log if connection is not application-limited and the timer has been
// delayed by more than 10% of the expected write interval
QUIC_STATS(conn_.statsCallback, onPacerTimerLagged);
}
if (experimental_) {
sendBatch = (timeSinceLastWrite / writeInterval_ >= maxBurstIntervals)
? batchSize_ * maxBurstIntervals
: batchSize_ * timeSinceLastWrite / writeInterval_;
}
}
lastWriteTime_ = currentTime;
return sendBatch;
}
uint64_t TokenlessPacer::getCachedWriteBatchSize() const {
return batchSize_;
}
void TokenlessPacer::setPacingRateCalculator(
PacingRateCalculator pacingRateCalculator) {
pacingRateCalculator_ = std::move(pacingRateCalculator);
}
void TokenlessPacer::setExperimental(bool experimental) {
experimental_ = experimental;
}
} // namespace quic
|
/*
* Copyright (C) 2013 Tom Wong. All rights reserved.
*/
#include "gtabstractdocument.h"
#include <QtCore/QString>
GT_BEGIN_NAMESPACE
GtAbstractPage::GtAbstractPage()
{
}
GtAbstractPage::~GtAbstractPage()
{
}
GtAbstractOutline::GtAbstractOutline()
{
}
GtAbstractOutline::~GtAbstractOutline()
{
}
void* GtAbstractOutline::childNode(void *node)
{
Q_UNUSED(node);
return 0;
}
void GtAbstractOutline::freeNode(void *node)
{
Q_UNUSED(node);
}
GtAbstractDocument::GtAbstractDocument()
{
}
GtAbstractDocument::~GtAbstractDocument()
{
}
QString GtAbstractDocument::title()
{
return QString();
}
GtAbstractOutline* GtAbstractDocument::loadOutline()
{
return 0;
}
GT_END_NAMESPACE
|
/************************************
* sort_lib.h
* Header for sorting library
* Author : Aditya Patwardhan
*/
#ifndef __SORT_LIB_H__
#define __SORT_LIB_H__
#include <iostream>
#include <vector>
/*
* APIs for sorting arrays
*/
namespace sortLib
{
class MySortLib
{
public:
void quickSort(std::vector<int> &array);
};
}
#endif
|
#include <stdio.h>
#include <stdlib.h>
/*NUMERO DE TENTATIVAS ESTA COM ERRO*/
main ()
{
int senha, tentativas;
tentativas = 0;
printf ("Informe a senha: \n");
scanf ("%d", &senha);
if (senha==1234)
{
printf ("ACESSO PERMITIDO\n");
tentativas = tentativas + 1;
}
else
{
while (senha!=1234)
{ printf ("ACESSO NEGADO\n");
printf ("Informe a senha: \n");
scanf ("%d", &senha);
tentativas = tentativas + 1;
}
}
printf ("Quantas vezes a senha foi informada: %d\n", tentativas);
system ("pause");
}
|
#ifndef GAME_PLAYERACTIONLISTENER_HPP
#define GAME_PLAYERACTIONLISTENER_HPP
#include "playeractions.hpp"
namespace Game
{
class PlayerActionListener: public PlayerActions
{
};
};
#endif
|
#include<bits/stdc++.h>
using namespace std;
#define maxn 1005
int dp[maxn][maxn];
string a,b;
int lcs(int i,int j){
if(i==-1||j==-1) return 0;
if(dp[i][j]!=0) return dp[i][j];
if(i>=0&&j>=0&&a[i]==b[j]){
dp[i][j]=lcs(i-1,j-1)+1;
return dp[i][j];
}
if(i>=0&&j>=0&&a[i]!=b[j]){
dp[i][j]=max(lcs(i-1,j),lcs(i,j-1));
return dp[i][j];
}
return dp[i][j];
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
while(getline(cin,a),getline(cin,b)){
memset(dp,0,sizeof(dp));
int la=a.length();
int lb=b.length();
int ans=lcs(la-1,lb-1);
printf("%d\n",ans);
}
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2006 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"
#ifdef M2_SUPPORT
#ifdef _BITTORRENT_SUPPORT_
#include "modules/util/gen_math.h"
#include "adjunct/m2/src/engine/engine.h"
//#include "irc-message.h"
#include "adjunct/m2/src/engine/account.h"
#include "modules/ecmascript/ecmascript.h"
# include "modules/util/OpLineParser.h"
#include "adjunct/m2/src/util/autodelete.h"
#include "adjunct/m2/src/util/str/strutil.h"
#include "bt-util.h"
#include "bt-globals.h"
#if defined(_DEBUG) && defined (MSWIN)
uni_char g_tmp[2000];
#endif
void OutputDebugLogging(const uni_char *x, char *y)
{
OpString str;
str.Set(y);
OutputDebugLogging(x, str.CStr());
}
void OutputDebugLogging(const uni_char *x, ...)
{
#if defined(_DEBUG) && defined (MSWIN)
{
uni_char *tmp = OP_NEWA(uni_char, 500);
int num = 0;
va_list ap;
va_start( ap, x );
if(tmp)
{
num = uni_vsnprintf( tmp, 499, x, ap );
if(num != -1)
{
tmp[499] = '\0';
OutputDebugString(tmp);
}
OP_DELETEA(tmp);
}
va_end(ap);
}
#endif
#if defined(BT_FILELOGGING_ENABLED)
{
if(g_BTFileLogging->IsEnabled())
{
OpString8 tmp;
tmp.AppendFormat(x, y);
OpString str;
str.Set(tmp);
g_BTFileLogging->WriteLogEntry(str);
}
}
#endif
}
//********************************************************************
//
// SHA wrapper code
//
//********************************************************************
/*
SSL_Hash_Pointer hash(digest_fields.digest);
hash->InitHash();
hash->CalculateHash(GetUser());
hash->CalculateHash(":");
hash->CalculateHash(GetRealm());
hash->CalculateHash(":");
if(password.CStr())
hash->CalculateHash(password.CStr());
*/
BTSHA::BTSHA()
{
m_hash.Set(SSL_SHA);
Reset();
BT_RESOURCE_ADD("BTSHA", this);
}
BTSHA::~BTSHA()
{
BT_RESOURCE_REMOVE(this);
}
void BTSHA::Reset()
{
m_hash->InitHash();
}
void BTSHA::GetHash(SHAStruct* pHash)
{
memcpy(pHash->b, m_md, SHA_DIGEST_LENGTH);
#ifdef _DEBUG
// test stuff
/*
SHAStruct hash;
Reset();
Add("abc", 3);
Finish();
memcpy(hash.b, m_md, SHA_DIGEST_LENGTH);
OpString str;
HashToHexString(&hash, str);
*/
#endif
/*
Test Vectors (from FIPS PUB 180-1)
"abc"
A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D
"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1
*/
}
OP_STATUS BTSHA::Add(void *pData, UINT32 nLength)
{
m_hash->CalculateHash((const byte *)pData, nLength);
return OpStatus::OK;
}
OP_STATUS BTSHA::Finish()
{
m_hash->ExtractHash(m_md);
return OpStatus::OK;
}
//////////////////////////////////////////////////////////////////////
// get hash string (Base64)
void BTSHA::GetHashString(OpString& outstr)
{
SHAStruct pHash;
GetHash( &pHash );
HashToString( &pHash, outstr);
}
//////////////////////////////////////////////////////////////////////
// convert hash to string (Base64)
void BTSHA::HashToString(const SHAStruct *pHashIn, OpString& outstr)
{
static const char *pszBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
char hashbuffer[64]; // 32 + 1 is used
char *hash = (char *)hashbuffer;
byte * pHash = (byte *)pHashIn;
int nShift = 7;
for ( int nChar = 32 ; nChar ; nChar-- )
{
BYTE nBits = 0;
for ( int nBit = 0 ; nBit < 5 ; nBit++ )
{
if ( nBit ) nBits <<= 1;
nBits |= ( *pHash >> nShift ) & 1;
if ( ! nShift-- )
{
nShift = 7;
pHash++;
}
}
*hash++ = pszBase64[ nBits ];
}
*hash = '\0';
outstr.Append((char *)hashbuffer);
}
//////////////////////////////////////////////////////////////////////
// SHA convert hash to string (hex)
void BTSHA::HashToHexString(const SHAStruct* pHashIn, OpString& outstr)
{
static const char *pszHex = "0123456789ABCDEF";
byte *pHash = (byte *)pHashIn;
OpString8 strHash;
char *pszHash = strHash.Reserve( 40 );
if (!pszHash)
return;
for ( int nByte = 0 ; nByte < 20 ; nByte++, pHash++ )
{
*pszHash++ = pszHex[ *pHash >> 4 ];
*pszHash++ = pszHex[ *pHash & 15 ];
}
outstr.Append(strHash);
}
//////////////////////////////////////////////////////////////////////
// SHA parse hash from string (Base64)
BOOL BTSHA::HashFromString(char *pszHash, SHAStruct* pHashIn)
{
if ( ! pszHash || strlen( pszHash ) < 32 ) return FALSE; //Invalid hash
if ( op_strnicmp(pszHash, "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", 32 ) == 0 ) return FALSE; //Bad hash
SHAStruct Hash;
byte *pHash = (byte *)&Hash;
UINT32 nBits = 0;
INT32 nCount = 0;
for ( INT32 nChars = 32 ; nChars-- ; pszHash++ )
{
if ( *pszHash >= 'A' && *pszHash <= 'Z' )
nBits |= ( *pszHash - 'A' );
else if ( *pszHash >= 'a' && *pszHash <= 'z' )
nBits |= ( *pszHash - 'a' );
else if ( *pszHash >= '2' && *pszHash <= '7' )
nBits |= ( *pszHash - '2' + 26 );
else
return FALSE;
nCount += 5;
if ( nCount >= 8 )
{
*pHash++ = (byte)( nBits >> ( nCount - 8 ) );
nCount -= 8;
}
nBits <<= 5;
}
*pHashIn = Hash;
return TRUE;
}
BOOL BTSHA::IsNull(SHAStruct* pHash)
{
SHAStruct Blank;
memset( &Blank, 0, sizeof(SHAStruct) );
if ( *pHash == Blank ) return TRUE;
return FALSE;
}
#endif // _BITTORRENT_SUPPORT_
#endif //M2_SUPPORT
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "MyCharacter.h"
// Sets default values
AMyCharacter::AMyCharacter()
{
// Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
}
// Called when the game starts or when spawned
void AMyCharacter::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void AMyCharacter::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
// Called to bind functionality to input
void AMyCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
PlayerInputComponent->BindAxis("MoveForward",this,&AMyCharacter::MoveForward);
PlayerInputComponent->BindAxis("MoveRight",this,&AMyCharacter::MoveRight);
PlayerInputComponent->BindAxis("Turn",this, &AMyCharacter::AddControllerYawInput);
PlayerInputComponent->BindAxis("LookUp",this, &AMyCharacter::AddControllerPitchInput);
PlayerInputComponent->BindAction("Jump",IE_Pressed,this,&AMyCharacter::StartJump);
PlayerInputComponent->BindAction("Jump",IE_Released,this,&AMyCharacter::StopJump);
}
void AMyCharacter::MoveForward(float value)
{
FVector Direction = FRotationMatrix(Controller->GetControlRotation()).GetScaledAxis(EAxis::X);
AddMovementInput(Direction,value);
}
void AMyCharacter::MoveRight(float value)
{
FVector Direction = FRotationMatrix(Controller->GetControlRotation()).GetScaledAxis(EAxis::Y);
AddMovementInput(Direction,value);
}
void AMyCharacter::StartJump()
{
bPressedJump=true;
}
void AMyCharacter::StopJump()
{
bPressedJump=false;
}
|
#ifndef _D3D_SAMPLE_WIN_H_
#define _D3D_SAMPLE_WIN_H_
#include "d3dsamplebase.h"
#include "win32nativewindow.h"
#include "nativeappbase.h"
GRAPHIC_BEGIN_NAMESPACE(Graphic)
class D3DSampleWin final : public D3DSampleBase
{
public:
virtual LRESULT HandleWin32Message(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_SYSKEYDOWN:
if ( (wParam == VK_RETURN) && (lParam & (1 << 29)) )
{
ToggleFullScreenWindow();
return 0;
}
break;
case WM_KEYDOWN:
switch (wParam)
{
//case VK_F2:
//{
// if ()
// {
// }
//}
default:
break;
}
}
struct WindowsMessageData
{
HWND hWnd;
UINT message;
WPARAM wParam;
LPARAM lParam;
}MsgData = { hWnd, message, wParam, lParam };
//TODO:
}
virtual void OnWindowCreated(HWND hWnd, LONG WindowWidth, LONG WindowHeight)
{
m_hWnd = hWnd;
try
{
Win32NativeWindow window{ hWnd };
Initialize(&window);
}
catch (const std::exception&)
{
//LOG_ERROR("Failed to initialize Diligent Engine.");
}
}
protected:
void ToggleFullScreenWindow()
{
if (fullScreenWindow)
{
return;
}
fullScreenWindow = !fullScreenWindow;
if (fullScreenWindow)
{
GetWindowRect(m_hWnd, &windowRect);
windowStyle = GetWindowLong(m_hWnd, GWL_STYLE);
// Make the window borderless so that the client area can fill the screen.
SetWindowLong(m_hWnd, GWL_STYLE, windowStyle & ~(WS_CAPTION | WS_MAXIMIZEBOX | WS_MINIMIZEBOX | WS_SYSMENU | WS_THICKFRAME));
DEVMODE devMode = {};
devMode.dmSize = sizeof(DEVMODE);
EnumDisplaySettings(nullptr, ENUM_CURRENT_SETTINGS, &devMode);
SetWindowPos(
m_hWnd,
HWND_TOPMOST,
devMode.dmPosition.x,
devMode.dmPosition.y,
devMode.dmPosition.x + devMode.dmPelsWidth,
devMode.dmPosition.y + devMode.dmPelsHeight,
SWP_FRAMECHANGED | SWP_NOACTIVATE);
ShowWindow(m_hWnd, SW_MAXIMIZE);
}
else
{
// Restore the window's attributes and size.
SetWindowLong(m_hWnd, GWL_STYLE, windowStyle);
SetWindowPos(
m_hWnd,
HWND_NOTOPMOST,
windowRect.left,
windowRect.top,
windowRect.right - windowRect.left,
windowRect.bottom - windowRect.top,
SWP_FRAMECHANGED | SWP_NOACTIVATE);
ShowWindow(m_hWnd, SW_NORMAL);
}
}
virtual void SetFullscreenMode()
{
if (fullScreenWindow)
{
ToggleFullScreenWindow();
}
//TODO:
//D3DSampleBase::
}
virtual void SetWindowMode()
{
if (fullScreenWindow)
{
ToggleFullScreenWindow();
}
//TODO:
}
bool fullScreenWindow = false;
HWND m_hWnd = 0;
public:
virtual bool Initialize(const Win32NativeWindow* window);
virtual void OnResize() override;
virtual void Update();
virtual void Render();
private:
RECT windowRect = {};
LONG windowStyle = 0;
};
GRAPHIC_END_NAMESPACE
#endif
|
#pragma once
#include "calculateproteinprobability.h"
class CCalProteinProbUnique :
public CCalculateProteinProbability
{
public:
CCalProteinProbUnique(CListMassPeptideXcorr* pLMX,CListProtein* pLP):CCalculateProteinProbability(pLMX,pLP){};
void calculateProteinProbability();
~CCalProteinProbUnique(void);
};
|
/*--------------------------------------------------------------------
Project: Restaurant Check
File: main.cpp
Kathryn Brusewitz
--------------------------------------------------------------------*/
#include <iostream> // Defines objects and classes used for stream I/O
#include <iomanip> // Defines output stream manipulators
#include "RestaurantCheck.h" // Defines data members of class: RestaurantCheck
int main() {
double taxRate;
double tipRate;
int index = 0;
RestaurantCheck myRestaurant;
std::cout << "PROG-111: Project #8, Version 2 Solution" << std::endl;
do {
std::cout << "Enter the tax rate, as a %: ";
std::cin >> taxRate;
} while (!myRestaurant.testTaxRate(taxRate));
do {
std::cout << "Enter the tip, as a %: ";
std::cin >> tipRate;
} while (!myRestaurant.testTipRate(tipRate));
myRestaurant.setTaxRate(taxRate);
myRestaurant.setTipRate(tipRate);
std::cout << "Here are our current menu items:" << std::endl;
std::cout << std::fixed << std::showpoint << std::setprecision(2);
myRestaurant.presentMenu();
myRestaurant.placeOrder();
myRestaurant.issueCheck();
std::cout << std::endl << "Press \"Enter\" to Exit the program: ";
std::cin.get();
return 0;
}
|
//
// L-Systems example (D0L Systems as described in Prusinkiewicz et al.
// "L-systems: from the Theory to Visual Models of Plants"
// Created by J. Andreas Bรฆrentzen on 08/02/12.
// Copyright 2012 __MyCompanyName__. All rights reserved.
//
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#include <cmath>
#include <CGLA/Vec3f.h>
#include <CGLA/Mat4x4f.h>
#include <GLGraphics/ShaderProgram.h>
#define SOLUTION_CODE
#include "lsys.h"
using namespace std;
using namespace CGLA;
using namespace GLGraphics;
// Produce the mesh for a truncated cone
// Produce the mesh for a truncated cone
void truncated_cone(const Mat4x4f& m, // transformation matrix used for the points
float l, // length of truncated cone
float w0, // width at base
float w1, // width at top
vector<Vec3f>& vertex_data)
{
float len = sqrt(l*l + sqr(w0-w1));
float a = l/len;
float b = (w0-w1)/len;
const int N = 10;
for(int i=0;i<=N;++i)
{
float alpha = 2.0*M_PI*float(i)/N;
Vec3f p0 = m.mul_3D_point(Vec3f(w0*cos(alpha), w0*sin(alpha), 0));
Vec3f p1 = m.mul_3D_point(Vec3f(w1*cos(alpha), w1*sin(alpha), l));
Vec3f n0 = m.mul_3D_vector(a*Vec3f(cos(alpha), sin(alpha), b));
Vec3f n1 = n0;
alpha = 2.0*M_PI*float(i+1)/N;
Vec3f p2 = m.mul_3D_point(Vec3f(w0*cos(alpha), w0*sin(alpha), 0));
Vec3f p3 = m.mul_3D_point(Vec3f(w1*cos(alpha), w1*sin(alpha), l));
Vec3f n2 = m.mul_3D_vector(a*Vec3f(cos(alpha), sin(alpha), b));
Vec3f n3 = n2;
if(i==0){
if(vertex_data.size() >= 2) {
//Interleave
int vert_size = vertex_data.size();
vertex_data.push_back(vertex_data[vert_size-2]);
vertex_data.push_back(vertex_data[vert_size-1]);
vertex_data.push_back(p1);
vertex_data.push_back(n1);
}
//Interleave
vertex_data.push_back(p1);
vertex_data.push_back(n1);
vertex_data.push_back(p0);
vertex_data.push_back(n0);
}
//Interleave
vertex_data.push_back(p3);
vertex_data.push_back(n3);
vertex_data.push_back(p2);
vertex_data.push_back(n2);
if (i==N) {
vertex_data.push_back(p2);
vertex_data.push_back(n2);
}
}
}
// Symbols used for L-Systems
enum LSSymbol { LS_TURN = '+', LS_ROLL = '/', LS_WIDTH = '!', LS_A = 'A',
LS_LEFT_BRACKET = '[', LS_RIGHT_BRACKET = ']', LS_DRAW = 'F'};
// LSElement is an LSSymbol and associated parameters.
struct LSElement
{
LSSymbol symbol;
double datum1, datum2;
int data;
LSElement(LSSymbol _symbol): symbol(_symbol), data(0) {}
LSElement(LSSymbol _symbol, double _datum1): symbol(_symbol), datum1(_datum1), data(1) {}
LSElement(LSSymbol _symbol, double _datum1, double _datum2): symbol(_symbol), datum1(_datum1), datum2(_datum2), data(2) {}
void print(ostream& os)
{
os << static_cast<char>(symbol);
if(data>0)
{
os << "(" << datum1;
if(data>1)
os << "," << datum2;
os << ")";
}
}
};
// This class represents a single rule with some parameters that can be tuned to
// create specific structures. See Fig. 8 and Table 1 in Prusinkiewicz's paper.
class Rule
{
float alpha1, alpha2, phi1, phi2, r1, r2, q, e, smin;
public:
Rule(float _alpha1, float _alpha2, float _phi1, float _phi2,
float _r1, float _r2, float _q, float _e, float _smin):
alpha1(_alpha1), alpha2(_alpha2), phi1(_phi1), phi2(_phi2),
r1(_r1), r2(_r2), q(_q), e(_e), smin(_smin) {}
bool apply(const LSElement elem, vector<LSElement>& out)
{
if(elem.symbol == LS_A)
{
float s = elem.datum1;
float w = elem.datum2;
if(s>=smin)
{
//Working tree rule
out.push_back(LSElement(LS_WIDTH, w));
out.push_back(LSElement(LS_DRAW, s));
out.push_back(LSElement(LS_LEFT_BRACKET));
out.push_back(LSElement(LS_TURN, alpha1));
out.push_back(LSElement(LS_ROLL, phi1));
out.push_back(LSElement(LS_A, s*r1, w*pow(q,e)));
out.push_back(LSElement(LS_RIGHT_BRACKET));
out.push_back(LSElement(LS_LEFT_BRACKET));
out.push_back(LSElement(LS_TURN, alpha2));
out.push_back(LSElement(LS_ROLL, phi2));
out.push_back(LSElement(LS_A, s*r2, w*pow(1-q,e)));
out.push_back(LSElement(LS_RIGHT_BRACKET));
return true;
}
}
else out.push_back(elem);
return false;
}
};
// The state used for turtle graphics
struct TurtleState
{
float w;
Mat4x4f M;
float alpha;
float phi;
TurtleState(float w0, const Mat4x4f& M0): w(w0), M(M0), alpha(0.0), phi(0.0) {}
};
// The turtle. Contains state and functions for crawling in 3D.
class Turtle
{
TurtleState turtle_state;
stack<TurtleState> tss;
public:
Turtle(float w0): turtle_state(w0, identity_Mat4x4f()) {}
void turn(float angle) {
float rad_angle = M_PI/180.0*angle;
turtle_state.M = turtle_state.M*rotation_Mat4x4f(YAXIS, -rad_angle);
turtle_state.alpha += rad_angle;
}
void roll(float angle) {
float rad_angle = M_PI/180.0*angle;
turtle_state.M = turtle_state.M*rotation_Mat4x4f(ZAXIS, -rad_angle);
turtle_state.phi += rad_angle;
}
void move(float dist) {
turtle_state.M = turtle_state.M*translation_Mat4x4f(dist*Vec3f(0,0,1));
}
void push() {
tss.push(turtle_state);
}
void pop() {
turtle_state = tss.top();
tss.pop();
}
void set_width(float w) {turtle_state.w = w;}
float get_width() const {return turtle_state.w;}
const Mat4x4f& get_transform() const {return turtle_state.M;}
};
// This function uses the turtle graphics approach to generate a skeletal representation of the tree.
void interpret(vector<LSElement> str, float w0,
vector<Vec3f>& triangles, vector<Vec3f>& normals)
{
Turtle turtle(w0);
for(size_t i=0;i<str.size(); ++i)
{
LSElement elem = str[i];
switch(elem.symbol)
{
case LS_DRAW:
truncated_cone(turtle.get_transform(), elem.datum1,
turtle.get_width(), turtle.get_width()*0.75,
triangles);
turtle.move(elem.datum1);
break;
case LS_WIDTH:
turtle.set_width(elem.datum1);
break;
case LS_LEFT_BRACKET:
turtle.push();
break;
case LS_RIGHT_BRACKET:
turtle.pop();
break;
case LS_TURN:
turtle.turn(elem.datum1);
break;
case LS_ROLL:
turtle.roll(elem.datum1);
break;
case LS_A:
turtle.set_width(elem.datum2);
truncated_cone(turtle.get_transform(), elem.datum1,
turtle.get_width(), turtle.get_width()*0.75,
triangles);
turtle.move(elem.datum1);
break;
}
}
}
// Create an OpenGL vertex array from a vector of triangles and normals
GLuint create_vertex_array_object(vector<Vec3f>& vertex_data)
{
GLuint VAO, VBO[2];
GLuint vert_attrib = ShaderProgramDraw::get_generic_attrib_location("vertex");
GLuint norm_attrib = ShaderProgramDraw::get_generic_attrib_location("normal");
GLuint texcoord_attrib = ShaderProgramDraw::get_generic_attrib_location("texcoord");
glGenVertexArrays(1, &VAO);
glGenBuffers(2, &VBO[0]);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO[0]);
int sizeOfFloat = sizeof(Vec3f);
int vertexSize = 1 * sizeOfFloat;
const int stride = 2*vertexSize;
void* offsetPosition = (void*)0;
void* offsetNormal = (void*)vertexSize;
glBufferData(GL_ARRAY_BUFFER,vertex_data.size()*sizeof(Vec3f), &vertex_data[0],GL_STATIC_DRAW);
glVertexAttribPointer(vert_attrib, 3, GL_FLOAT, GL_FALSE, stride, offsetPosition);
glBindBuffer(GL_ARRAY_BUFFER, VBO[1]);
glBufferData(GL_ARRAY_BUFFER,vertex_data.size()*sizeof(Vec3f), &vertex_data[0],GL_STATIC_DRAW);
glVertexAttribPointer(norm_attrib, 3, GL_FLOAT, GL_FALSE, stride, offsetNormal);
glVertexAttrib3f(texcoord_attrib, 0, 0,0);
glEnableVertexAttribArray(vert_attrib);
glEnableVertexAttribArray(norm_attrib);
return VAO;
}
// make_tree ties it all together producing a vertex array object with the geometry of a tree
// model created using L-Systems.
GLuint make_tree (GLint& count)
{
float w0 = 20; // Initial branch width
vector<LSElement> str; // Initial string
str.push_back(LSElement(LS_A, 100, w0)); // Push the initial symbol
// Rules for a coarse example tree
Rule ex(40,-40,90,-90,0.5,0.5,0.5,0.5,0.5);
// Now apply the rule a number of times.
for(int iter=0;iter<8;++iter)
{
vector<LSElement> out_str;
for(size_t e=0;e<str.size(); ++e)
ex.apply(str[e], out_str);
str = out_str;
}
// Interpret the string producing a vector of triangles and normals
vector<Vec3f> triangles, normals;
interpret(str, w0, triangles, normals);
// Generate a vertex array object and return that.
count = static_cast<GLint>(triangles.size());
return create_vertex_array_object(triangles);
}
|
#ifndef CtaBanc_h
#define CtaBanc_h
using namespace std;
class CtaBanc {
public: //constructores
CtaBanc(); //constructor por default
CtaBanc(string,double); //establece cada parametro (no tipo) de la clase
//metodos de acceso
string getNombre();
double getSaldo();
//metodos de modificacion
void setNombre(string);
void setSaldo(double);
//metodos de operacion
void Deposita(double);
bool Retira(double);
private: //atributos
string nombre;
double saldo;
};
/////////////
//codificacion de valores iniciales
CtaBanc::CtaBanc(){
nombre="helena";
saldo=0;
}
string CtaBanc::getNombre() {
return nombre;
}
double CtaBanc::getSaldo() {
return saldo;
}
/////////////
//codificacion de valores declarados
CtaBanc::CtaBanc(string nombre, double saldo){
this->nombre=nombre; //si el parametro y el atributo se llaman igual, se puede
//usar "this->" alado de tu atributo para diferenciarlos
//y especificar que quieres que el valor del parametro
//se guarde en el atributo de tu objeto
this->saldo=saldo;
}
void CtaBanc::setNombre(string nombre) {
this->nombre=nombre;
}
void CtaBanc::setSaldo(double saldo){
this->saldo=saldo;
}
/////////////
//codificacion de funciones para la cuenta de banco
void CtaBanc::Deposita(double money) {
saldo+=money;
}
bool CtaBanc::Retira(double money) {
if (saldo>=money) {
saldo-=money;
cout<<"Retiro "<<money<<" pesos. Le queda un saldo de "<<saldo<<endl;
return true;
}
else {
cout<<"No tiene suficiente saldo"<<endl;
return false;
}
}
#endif /* CtaBanc_h */
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2009 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#ifndef MODULES_UTIL_OPAUTOPTR_H
#define MODULES_UTIL_OPAUTOPTR_H
#if defined _WIN32_WCE && defined ARM
# define THROWCLAUSE
#else
# define THROWCLAUSE throw()
#endif
/**
* Utility class to make sure objects allocated on the heap are
* released when they are no longer used.
*
* This is an implementation of the Standard C++ Library auto_ptr.
* based on "The Standard C++ Library, a tutorial and reference", by
* Nicolai M. Josuttis, the GNU stdc++ library and the ISO C++
* standard.
*
* Do not modify this class unless you checked the behaviour of
* Standard C++ auto_ptr and know this implementation is wrong!
*
* @author Petter Reinholdtsen <pere@opera.com>
*/
template<class T> class OpAutoPtr {
private:
T* ap; /// Pointer to the owned object
template<class Y> struct OpAutoPtrRef {
Y* yp;
OpAutoPtrRef(Y* rhs) : yp(rhs) {};
};
public:
typedef T element_type;
explicit OpAutoPtr(T* ptr = 0) THROWCLAUSE : ap(ptr) {};
/**
* Copy constructor for non-constant parameter, acquire the ownership
* of the object currently owned by the argument OpAutoPtr.
*/
OpAutoPtr(OpAutoPtr& rhs) THROWCLAUSE : ap(rhs.release()) {};
/**
* Assignment without implicit conversion.
*/
OpAutoPtr& operator=(OpAutoPtr& rhs) THROWCLAUSE
{
reset(rhs.release());
return *this;
};
/**
* Destructor. Delete object owned by this OpAutoPtr.
*/
~OpAutoPtr() THROWCLAUSE
{
OP_DELETE(ap);
};
/**
* Return pointer to the object currently owned by this OpAutoPtr.
*
* @return element_type pointer
*/
T* get() const THROWCLAUSE
{
return ap;
};
T& operator*() const THROWCLAUSE
{
return *ap;
};
T* operator->() const THROWCLAUSE
{
return ap;
};
/**
* Release ownership of the object pointed to by this OpAutoPtr.
* @return pointer to the object.
*/
T* release() THROWCLAUSE
{
T* tmp = ap;
ap = 0;
return tmp;
};
/**
* Replace the object owned by this OpAutoPtr with the object pointed
* to by ptr. Delete the object currently owned by this OpAutoPtr
* before taking the new ownership.
*
* @param ptr pointer to 'new' object.
*/
void reset(T* ptr=0) THROWCLAUSE
{
if (ap != ptr)
{
OP_DELETE(ap);
ap = ptr;
}
};
/**
* Special conversions with auxiliary type to enable copies and
* assigments.
*/
OpAutoPtr(OpAutoPtrRef<T> rhs) THROWCLAUSE : ap(rhs.yp) {};
OpAutoPtr& operator=(OpAutoPtrRef<T> rhs) THROWCLAUSE
{
reset(rhs.yp);
return *this;
};
template<class Y> operator OpAutoPtrRef<Y>() THROWCLAUSE
{
return OpAutoPtrRef<Y>(release());
}
template<class Y> operator OpAutoPtr<Y>() THROWCLAUSE
{
return OpAutoPtr<Y>(release());
}
};
/**
* Utility class to make sure arrays allocated on the heap are
* released when they are no longer used.
*
* This is an adaption of the OpAutoPtr above to handle
* heap-allocated arrays of objects.
*
* @author Johan Herland <johanh@opera.com>
*/
template<class T> class OpAutoArray {
private:
T* ap; /// Pointer to the owned object
template<class Y> struct OpAutoArrayRef {
Y* yp;
OpAutoArrayRef(Y* rhs) : yp(rhs) {};
};
public:
typedef T element_type;
explicit OpAutoArray(T* ptr = 0) THROWCLAUSE : ap(ptr) {};
/**
* Copy constructor for non-constant parameter, acquire the ownership
* of the object currently owned by the argument OpAutoArray.
*/
OpAutoArray(OpAutoArray& rhs) THROWCLAUSE : ap(rhs.release()) {};
/**
* Assignment without implicit conversion.
*/
OpAutoArray& operator=(OpAutoArray& rhs) THROWCLAUSE
{
reset(rhs.release());
return *this;
};
/**
* Destructor. Delete object owned by this OpAutoArray.
*/
~OpAutoArray() THROWCLAUSE
{
OP_DELETEA(ap);
};
/**
* Return pointer to the object currently owned by this OpAutoArray.
*
* @return element_type pointer
*/
T* get() const THROWCLAUSE
{
return ap;
};
T& operator*() const THROWCLAUSE
{
return *ap;
};
T* operator->() const THROWCLAUSE
{
return ap;
};
T& operator[](int index) const THROWCLAUSE
{
return ap[index];
};
/**
* Release ownership of the object pointed to by this OpAutoArray.
* @return pointer to the object.
*/
T* release() THROWCLAUSE
{
T* tmp = ap;
ap = 0;
return tmp;
};
/**
* Replace the object owned by this OpAutoArray with the object pointed
* to by ptr. Delete the object currently owned by this OpAutoArray
* before taking the new ownership.
*
* @param ptr pointer to 'new' object.
*/
void reset(T* ptr=0) THROWCLAUSE
{
if (ap != ptr)
{
OP_DELETEA(ap);
ap = ptr;
}
};
/**
* Special conversions with auxiliary type to enable copies and
* assigments.
*/
OpAutoArray(OpAutoArrayRef<T> rhs) THROWCLAUSE : ap(rhs.yp) {};
OpAutoArray& operator=(OpAutoArrayRef<T> rhs) THROWCLAUSE
{
reset(rhs.yp);
return *this;
};
template<class Y> operator OpAutoArrayRef<Y>() THROWCLAUSE
{
return OpAutoArrayRef<Y>(release());
}
template<class Y> operator OpAutoArray<Y>() THROWCLAUSE
{
return OpAutoArray<Y>(release());
}
};
#endif // !MODULES_UTIL_OPAUTOPTR_H
|
//@bref: ๅทฅไฝ็บฟ็จๆฑ ๏ผๅ่ฐ่ฟ่กๅทฅไฝใ
//@func: process() ๏ผhandlerๅฎ็ฐprocess๏ผ๏ผๆนๆณ๏ผๅทฅไฝ็บฟ็จ้่ฟ่ฐ็จprocess่ฟ่กๅค็ใ
//@func: init๏ผ๏ผๆนๆณๅๅงๅ็บฟ็จๆฑ ็ธๅ
ณ่ตๆบใ
//@func๏ผappend() ๆนๆณๅฎ็ฐๅฐhandlerๆ้ๅ ๅ
ฅ็บฟ็จๆฑ ใ
//
#ifndef MINI_SERVER_THREAD_POOL_H
#define MINI_SERVER_THREAD_POOL_H
#include <queue>
#include <cstdio>
#include <exception>
#include <new>
#include <stdint.h>
#include <pthread.h>
#include "easylogging++.h"
#include "locker.h"
#include "connection.h"
namespace miniserver {
template <typename T>
class ThreadPool {
public:
ThreadPool();
~ThreadPool();
bool append(T *request);
void run();
void askToQuit();
// @func: init ๅๅงๅ็บฟ็จๆฑ ใ
// @param: max_thread ็บฟ็จๆฑ ไธญ็ๅทฅไฝ็บฟ็จ็ไธชๆฐใ
// @param: max_request ่ฏทๆฑ้ๅไธญๅ
่ฎธ็ๆๅคง็็บฟ็จๆฐ้ใ
bool init(uint32_t max_thread, uint64_t max_requests);
private:
static void* _thread_handler(void *arg);
void _destroy();
uint32_t _max_thread; // ็บฟ็จๆฑ ไธญๆๅคงๅทฅไฝ็บฟ็จ็ๆฐ้.
uint64_t _max_requets; // ่ฏทๆฑ้ๅไธญๅ
่ฎธ็ๆๅคง่ฏทๆฑๆฐ.
pthread_t *_work_threads; // ๅทฅไฝ็บฟ็จๅญๅจๆฐ็ป
std::queue<T*> _request_queue; // ่ฏทๆฑ้ๅ
Locker _queue_lck; // ่ฏทๆฑ้ๅ้๏ผ่งฃๅณ้ๅ็ซไบใ
Semaphore _queue_stat; // ไฟกๅท้ๆฅๅค้่ขซ็บฟ็จใ
bool _is_running; // ๅทฅไฝ่ฟ่กๆ ๅฟใ
};
template <typename T>
ThreadPool<T>::ThreadPool() :
_max_thread(0), _max_requets(0),
_work_threads(nullptr), _request_queue(),
_queue_lck(), _queue_stat(), _is_running(false) {}
template <typename T>
ThreadPool<T>::~ThreadPool() {
_destroy();
}
template <typename T>
void ThreadPool<T>::askToQuit() {
_is_running = false;
}
template <typename T>
void ThreadPool<T>::_destroy() {
if (_work_threads != nullptr) {
delete[] _work_threads;
}
_is_running = false;
}
template <typename T>
bool ThreadPool<T>::init(uint32_t max_thread, uint64_t max_requests) {
if (max_thread < 0 || max_requests < 0) {
LOG(WARNING) << "[ThreadPllo::init]: invalid parameter";
}
_max_thread = max_thread;
_max_requets = max_requests;
_work_threads = new(std::nothrow) pthread_t[max_thread];
if (_work_threads == nullptr) {
LOG(WARNING) << "[ThreadPool::init]: new _work_thread failed";
return false;
}
LOG(WARNING) << "Create " << _max_thread << " threads in thread pool";
for (int i = 0; i < _max_thread; ++i) {
if (pthread_create(_work_threads + i, nullptr, _thread_handler, this) != 0) {
LOG(WARNING) << "[ThreadPool::init]: pthread_crate failed";
_destroy();
return false;
}
if (pthread_detach(_work_threads[i] != 0)) {
LOG(WARNING) << "[ThreadPool::init]: pthread_detach failed";
_destroy();
return false;
}
}
_is_running = false;
return true;
}
template <typename T>
bool ThreadPool<T>::append(T *request) {
if (!_queue_lck.lock()) {
LOG(WARNING) << "[ThreadPool::append]: lock failed";
return false;
}
if (_request_queue.size() > _max_requets) {
if (!_queue_lck.unlock()) {
LOG(WARNING) << "[ThreadPool::append]: unlock failed in size > _max_requets";
return false;
}
}
_request_queue.push(request);
if (!_queue_lck.unlock()) {
LOG(WARNING) << "[ThreadPool::append]: unlock failed";
return false;
}
if (!_queue_stat.post()) {
LOG(WARNING) << "[ThreadPool::append]: semaphore post failed";
return false;
}
return true;
}
template <typename T>
void ThreadPool<T>::run() {
while (_is_running) {
_queue_stat.wait();
if (!_queue_lck.lock()) {
LOG(WARNING) << "[ThreadPool::run]: _queue_lck lock failed";
return ;
}
if (_request_queue.empty()) {
_queue_lck.unlock();
continue;
}
T *request = _request_queue.front();
_request_queue.pop();
if (!_queue_lck.unlock()) {
LOG(WARNING) << "[ThreadPool::run]: _queue_lck unlock failed";
return ;
}
if (request == nullptr) {
continue;
}
request->process();
}
}
template <typename T>
void* ThreadPool<T>::_thread_handler(void *arg) {
if (arg == nullptr) {
LOG(WARNING) << "[ThreadPool::_thread_handler]: arg null";
return nullptr;
}
ThreadPool *thread_pool = reinterpret_cast<ThreadPool*>(arg);
if (thread_pool == nullptr) {
LOG(WARNING) << "[ThreadPool::_thread_handler]: cast failed";
return nullptr;
}
thread_pool->run();
return thread_pool;
}
}
#endif
|
#ifndef BUFFERWINDOW_H
#define BUFFERWINDOW_H
#include <QWidget>
namespace Ui {
class BufferWindow;
}
class BufferWindow : public QWidget
{
Q_OBJECT
public:
explicit BufferWindow(QWidget *parent = 0);
~BufferWindow();
private:
Ui::BufferWindow *ui;
int cnt;
int id;
void showEvent(QShowEvent* event);
void timerEvent(QTimerEvent* event);
void closeEvent(QCloseEvent* event);
signals:
void bufferComplete();
private slots:
void moveWindow();
};
#endif // BUFFERWINDOW_H
|
#include "Product.h"
template<typename CodeType> Product<CodeType>::Product()
:m_tPdCode(T(0)), m_sPdName("(NULL)"), m_nPdPrice(0){}
template<typename CodeType> CodeType Product<CodeType>::getCode() {
return m_tPdCode;
}
|
#include "MyWinThread.h"
MY_IMPLEMENT_DYNAMIC(CMyWinThread, CMyCmdTarget)
CMyWinThread::CMyWinThread()
{
MyOutPutDebugString(_T("CMyWinThread::CMyWinThread()"));
}
CMyWinThread::~CMyWinThread()
{
MyOutPutDebugString(_T("CMyWinThread::~CMyWinThread()"));
}
BOOL CMyWinThread::InitInstance()
{
return FALSE;
}
int CMyWinThread::ExitInstance()
{
return 0;
}
/*
* รรปรยขรยญยปยท
*/
int CMyWinThread::Run()
{
MSG msg;
BOOL bRet;
while ((bRet = GetMessage(&msg, NULL, 0, 0)) != 0)
{
if (bRet == -1)
{
break;
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return 0;
}
|
#include "router_hal.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void printMAC(macaddr_t mac) {
printf("%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3],
mac[4], mac[5]);
}
uint8_t packet[2048];
bool cont = false;
// 10.0.0.1 ~ 10.0.3.1
in_addr_t addrs[N_IFACE_ON_BOARD] = {0x0100000a, 0x0101000a, 0x0102000a,
0x0103000a};
void interrupt(int _) {
printf("Interrupt\n");
cont = false;
return;
}
int main() {
fprintf(stderr, "HAL init: %d\n", HAL_Init(1, addrs));
for (int i = 0; i < N_IFACE_ON_BOARD; i++) {
macaddr_t mac;
HAL_GetInterfaceMacAddress(i, mac);
fprintf(stderr, "%d: %02X:%02X:%02X:%02X:%02X:%02X\n", i, mac[0], mac[1],
mac[2], mac[3], mac[4], mac[5]);
}
while (1) {
int mask = (1 << N_IFACE_ON_BOARD) - 1;
macaddr_t src_mac;
macaddr_t dst_mac;
int if_index;
int res = HAL_ReceiveIPPacket(mask, packet, sizeof(packet), src_mac,
dst_mac, 1000, &if_index);
if (res > 0) {
for (int i = 0; i < N_IFACE_ON_BOARD;i++) {
HAL_SendIPPacket(i, packet, res, src_mac);
}
} else if (res == 0) {
fprintf(stderr, "Timeout\n");
} else {
fprintf(stderr, "Error: %d\n", res);
break;
}
}
return 0;
}
|
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int L, int R) {
if(root==NULL) return NULL;
if(root->val<L)
{
root->left=NULL;//Left subtree will not have potential nodes-change it to NULL-So left traversal avoided
return trimBST(root->right,L,R);
}
else if(root->val>R)
{
root->right=NULL;//Right subtree will not have potential nodes-change it to NULL-So right traversal avoided
return trimBST(root->left,L,R);
}
//In all other cases, we have to include the current node
root->left=trimBST(root->left,L,R);
root->right=trimBST(root->right,L,R);
return root;
}
};
|
#include "stdafx.h"
#include "StatsData.h"
#include "DijkstraMatrixAlgorithm.h"
#include "DijkstraListAlgorithm.h"
#include "BelmannFordMatrixAlgorithm.h"
#include "BelmannFordListAlgorithm.h"
#include "PrimMatrixAlgorithm.h"
#include "PrimListAlgorithm.h"
#include "KruskalMatrixAlgorithm.h"
#include "KruskalListAlgorithm.h"
#include <fstream>
#include <iostream>
#include <omp.h>
StatsData::StatsData()
{
vecDM = new std::vector<arg>();
vecDL = new std::vector<arg>();
vecBM = new std::vector<arg>();
vecBL = new std::vector<arg>();
vecPM = new std::vector<arg>();
vecPL = new std::vector<arg>();
vecKM = new std::vector<arg>();
vecKL = new std::vector<arg>();
}
StatsData::~StatsData()
{
}
void StatsData::doData()
{
pokryciaStats();
}
void StatsData::pokryciaStats()
{
for each (int i in pokrycia)
{
std::cout << "pokrycia " << i << "\n";
rozmiaryStats(i);
}
//for(int i = 0; i < val; i++)
//stats
}
void StatsData::rozmiaryStats(int pokrycie)
{
for each (int i in rozmiary)
{
std::cout << "rozmiary " << i << "\n";
stats(i, pokrycie);
}
}
void StatsData::stats(int vertex, int pokrycie)
{
int i;
//#pragma omp parallel for schedule(dynamic) num_threads(4) default (none) private(i)
for (i = 0; i < val; i++)
{
Graph g;
g.generateGraph(vertex, pokrycie);
//std::cout << " " << vertex << " " << pokrycie;
//Graph2 g2;
//g2.generateGraph(vertex, pokrycie);
arg a;
a.pokrycie = pokrycie;
a.vertex = vertex;
std::cout << "Grafy\n";//
/*timer.startCountingQPC();
DijkstraMatrixAlgorithm dMA(g);
dMA.startAlgorithm();
timer.stopCountingQPC();
a.time = timer.getSecTime();
vecDM->push_back(a);
std::cout << "Dij\n";//
timer.startCountingQPC();
DijkstraListAlgorithm dLA(g);
dLA.startAlgorithm();
timer.stopCountingQPC();
a.time = timer.getSecTime();
vecDL->push_back(a);
std::cout << "Dij\n";//
*/timer.startCountingQPC();
BelmannFordMatrixAlgorithm bMA(g);
bMA.startAlgorithm();
timer.stopCountingQPC();
a.time = timer.getSecTime();
vecBM->push_back(a);
std::cout << "bel\n";//
timer.startCountingQPC();
BelmannFordListAlgorithm bLA(g);
bLA.startAlgorithm();
timer.stopCountingQPC();
a.time = timer.getSecTime();
vecBL->push_back(a);
std::cout << "bel\n";
/* timer.startCountingQPC();
PrimMatrixAlgorithm pMA(g2);
pMA.startAlgorithm(0);
timer.stopCountingQPC();
a.time = timer.getSecTime();
vecPM->push_back(a);
std::cout << "prim\n";
timer.startCountingQPC();
PrimListAlgorithm pLA(g2);
pLA.startAlgorithm(0);
timer.stopCountingQPC();
a.time = timer.getSecTime();
vecPL->push_back(a);
std::cout << "prim\n";//
timer.startCountingQPC();
KruskalMatrixAlgorithm kMA(g2);
kMA.startAlgorithm();
timer.stopCountingQPC();
a.time = timer.getSecTime();
vecKM->push_back(a);
std::cout << "kruskal\n";
timer.startCountingQPC();
KruskalListAlgorithm kLA(g2);
kLA.startAlgorithm();
timer.stopCountingQPC();
a.time = timer.getSecTime();
vecKL->push_back(a);
std::cout << "kruskal\n";*/
//system("Pause");
//std::cout << "o: " << omp_get_thread_num() << std::endl;
}
//std::cout << vecKL->size() << "www\n";
}
void StatsData::saveToFiles()
{
vecs.push_back(vecDM);
vecs.push_back(vecDL);
vecs.push_back(vecBM);
vecs.push_back(vecBL);
vecs.push_back(vecPM);
vecs.push_back(vecPL);
vecs.push_back(vecKM);
vecs.push_back(vecKL);
int i = 0;
for each(std::string s in names)
{
saveToFile(*(vecs[i]), s);
++i;
}
}
void StatsData::saveToFile(std::vector<arg> dataVec, std::string nameFile)
{
std::fstream file;
file.open(nameFile, std::ios::out | std::ios::app);
if (file.is_open())
{
file << "time[ms]\tpop_size\n";
for (int i = 0; i < dataVec.size(); i++)
{
file << dataVec[i].vertex << "\t" << dataVec[i].pokrycie << "\t" << dataVec[i].time << std::endl;
}
file.close();
}
else
std::cout << "FILE OPEN ERROR";
}
|
#include <FastLED.h>
#include <ADC.h>
#include <Audio.h>
#include <SoftwareSerial.h>
#include <Adafruit_Pixie.h>
#include "Adafruit_Trellis.h"
#include <Adafruit_Sensor.h>
#include <Adafruit_LSM9DS0.h>
#include <Adafruit_Simple_AHRS.h>
#include <math.h>
#define ARRAY_SIZE(A) (sizeof(A) / sizeof((A)[0]))
#define POTENTIOMETER_PIN 37
#define MIC_PIN 17
// analog - digital
ADC *adc = new ADC();
// motion sensor
Adafruit_LSM9DS0 lsm = Adafruit_LSM9DS0(&Wire2, 1000);
Adafruit_Simple_AHRS ahrs(&lsm.getAccel(), &lsm.getMag());
// button board
Adafruit_Trellis matrix0 = Adafruit_Trellis();
Adafruit_TrellisSet pad = Adafruit_TrellisSet(&matrix0);
#define PAD_CONNECTED true
// 3W pixels
SoftwareSerial pixieSerial(-1, 5);
SoftwareSerial pixieSerial2(-1, 20);
SoftwareSerial pixieSerial3(-1, 21);
Adafruit_Pixie eyes = Adafruit_Pixie(1, &pixieSerial);
Adafruit_Pixie fiberHead = Adafruit_Pixie(1, &pixieSerial3);
Adafruit_Pixie fiberTail = Adafruit_Pixie(1, &pixieSerial2);
#define NUM_LEDS 600
#define NUM_LEDS_PER_STRIP 120
#define NUM_STRIPS 5
#define MAX_BRIGHTNESS 55
#define TEENSY_LED 13
CRGB leds[NUM_LEDS];
#include "segment.h"
typedef void (*Mode[2])(void);
// leds per strip
uint8_t ledsPerStrip[] = {68, 68, 100, 95};
// buttons
#define EYE_STATE 15
// active or not active
uint8_t buttonState[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
// global state
int8_t currentMode = 0;
int8_t previousMode = 0;
uint8_t currentBrightness = MAX_BRIGHTNESS;
uint16_t currentDelay = 0; // delay between frames
uint8_t shouldClear = 1; // clear all leds between frames
uint8_t shouldShow = 1;
uint8_t usePixies = 0; // pixies on
uint8_t usePotentiometer = 1; // use potentiometer to get brightness value for next frame
CRGB *overridePixieColor = 0; // override the default pixie red
// Debug stuff to count LEDS properly
static int globalP = 0;
int accelTestMV = 0;
void none() {}
Mode modes[] = {
// {accelLerp, accelLerpSetup}, // y
// {wingTest, none},
// {accelOrientation, accelOrientationSetup},
// {newAccel, newAccelSetup},
// {runner, none},
{fiberPulse, fiberPulseSetup}, // ?
{fiberBlink, fiberBlinkSetup},
{heartbeat, heartbeatSetup}, //y
{sinelon, sinelonSetup}, // y
{newLerp, newLerpSetup}, // Y
{lerpTest, lerpTestSetup}, // y
{pride, prideSetup}, // ?
// {colorWheelPulsing, colorWheelPulsingSetup},
{colorWheelNew, colorWheelNewSetup}, //y
{iceSparks, iceSparksSetup},
{fire, fireSetup}, // ?
{accelLerp, accelLerpSetup}, // y
{betterAudio, betterAudioSetup},
{newAudio, newAudioSetup},
// {juggle, juggleSetup},
// {flash2, flash2Setup},
// {bpm, bpmSetup}, // ? /
// {fireWithPotentiometer, fireWithPotentiometerSetup}, // y
// {fiberMode, fiberModeSetup}, // ?
// {none, none},
// {fibertest, none},
// {wingTest, none},
// {thunder, thunderSetup},
// {moveToOuter, moveToOuterSetup},
// {colorWheelWithSparkels, colorWheelWithSparkelsSetup}, // Y
// {ftest, none},
// {wingTest, none},
// {simpleAudio, simpleAudioSetup}, // y
// {wingTest, none},
// {linearTest, none},
// {pixieTest, pixieTestSetup},
// {ftest, none},
// {none, none},
// {sparks, sparksSetup},
// {rainbowSparks, rainbowSparksSetup},
// {randomBluePixels, randomBluePixelsSetup},
// {none, none},
// {flashTest, flashTestSetup},
// {simpleAudio, simpleAudioSetump}, // y
// {fireNoise, fireNoiseSetup},
};
#include "libs/util.cpp"
// the setup routine runs once when you press reset:
void setup()
{
while (!Serial && (millis() <= 2000))
; // Wait for Serial interface
Serial.begin(115200);
Serial.println("boot bird");
Serial.println("LED init");
// init all other leds
// FastLED.addLeds<OCTOWS2811>(leds, NUM_LEDS_PER_STRIP);
// FastLED.addLeds<LED_TYPE,DATA_PIN,CLK_PIN,COLOR_ORDER>
FastLED.addLeds<WS2811_PORTD, NUM_STRIPS>(leds, NUM_LEDS_PER_STRIP);
FastLED.setMaxPowerInVoltsAndMilliamps(5, 5000);
FastLED.setBrightness(MAX_BRIGHTNESS);
clear();
FastLED.clear();
FastLED.show();
if (PAD_CONNECTED)
{
Serial.println("pad init");
// init button pads and flash them once
pad.begin(0x70);
for (uint8_t i = 0; i < 16; i++)
{
pad.setLED(i);
pad.writeDisplay();
delay(25);
}
for (uint8_t i = 0; i < 16; i++)
{
pad.clrLED(i);
pad.writeDisplay();
delay(25);
}
}
else
{
Serial.println("pad disabled!");
}
Serial.println("motion init");
delay(100);
// init motion sensor
if (lsm.begin())
{
lsm.setupAccel(lsm.LSM9DS0_ACCELRANGE_2G);
lsm.setupMag(lsm.LSM9DS0_MAGGAIN_2GAUSS);
lsm.setupGyro(lsm.LSM9DS0_GYROSCALE_245DPS);
}
else
{
Serial.println("LSM SENSOR ERROR!");
}
// initialize the digital pin as an output.
pinMode(TEENSY_LED, OUTPUT);
Serial.println("3W LED init");
// init 3w leds serial connection
pixieSerial.begin(115200);
pixieSerial2.begin(115200);
pixieSerial3.begin(115200);
adc->setAveraging(16, ADC_1); // set number of averages
adc->setResolution(16, ADC_1); // set bits of resolution
adc->setConversionSpeed(ADC_CONVERSION_SPEED::LOW_SPEED, ADC_1); // change the conversion speed
adc->setSamplingSpeed(ADC_SAMPLING_SPEED::LOW_SPEED, ADC_1); // change the sampling speed
adc->setReference(ADC_REFERENCE::REF_3V3, ADC_1);
adc->adc1->recalibrate();
AudioMemory(8);
// adc->setAveraging(16, ADC_1);
// adc->setSamplingSpeed(ADC_SAMPLING_SPEED::MED_SPEED, ADC_1);
// adc->setResolution(10, ADC_1); // adc->setResolution(10, ADC_1):
delay(10); // if we fucked it up - great idea by fastled :D
// start with mode number 0
modes[0][1]();
}
void PrintE()
{
float e, n;
int b, bands, bins, count = 0, d;
bands = 30; // Frequency bands; (Adjust to desired value)
bins = 512; // FFT bins; (Adjust to desired value)
e = FindE(bands, bins); // Find calculated E value
if (e)
{ // If a value was returned continue
Serial.printf("E = %4.4f\n", e); // Print calculated E value
for (b = 0; b < bands; b++)
{ // Test and print the bins from the calculated E
n = pow(e, b);
d = int(n + 0.5);
Serial.printf("%4d ", count); // Print low bin
count += d - 1;
Serial.printf("%4d\n", count); // Print high bin
++count;
}
}
else
Serial.println("Error\n"); // Error, something happened
}
float FindE(int bands, int bins)
{
float increment = 0.1, eTest, n;
int b, count, d;
for (eTest = 1; eTest < bins; eTest += increment)
{ // Find E through brute force calculations
count = 0;
for (b = 0; b < bands; b++)
{ // Calculate full log values
n = pow(eTest, b);
d = int(n + 0.5);
count += d;
}
if (count > bins)
{ // We calculated over our last bin
eTest -= increment; // Revert back to previous calculation increment
increment /= 10.0; // Get a finer detailed calculation & increment a decimal point lower
}
else if (count == bins) // We found the correct E
return eTest; // Return calculated E
if (increment < 0.0000001) // Ran out of calculations. Return previous E. Last bin will be lower than (bins-1)
return (eTest - increment);
}
return 0; // Return error 0
}
void checkSerial()
{
if (Serial.available() > 0)
{
Serial.read();
//nextMode(1);
// Serial.println(currentMode);
globalP++;
Serial.print("CURRENT POS");
Serial.println(globalP);
nextMode(1);
// accelTestMV = 1;
}
}
static uint16_t potentiometer = 0;
void checkPotentiometer()
{
potentiometer = adc->analogRead(POTENTIOMETER_PIN, ADC_1);
uint8_t brightness = map(potentiometer, 0, 65535, 0, 255); // potentiometer / 4;
// Serial.println(brightness);
currentBrightness = brightness;
if (usePotentiometer == 1)
{
LEDS.setBrightness(brightness);
// fiberHead.setBrightness(brightness);
// fiberTail.setBrightness(brightness);
}
}
void fiberModeSetup()
{
currentDelay = 25;
}
void fiberMode()
{
static int8_t hue = 0;
hue++;
CRGB c;
c.setHSV(hue, 240, 255);
fiberHead.setPixelColor(0, c.r, c.g, c.b);
fiberTail.setPixelColor(0, c.r, c.g, c.b);
fiberHead.setBrightness(currentBrightness);
fiberTail.setBrightness(currentBrightness);
// fibertest();
fiberHead.show();
fiberTail.show();
leds[fiberleft(0)] = CHSV(hue * 2, 240, 255);
leds[fiberleft(1)] = CHSV(hue, 240, 255);
leds[fiberleft(2)] = CHSV(hue * 3, 200, 255);
leds[fiberleft(3)] = CHSV(hue, 140, 255);
leds[fiberright(0)] = CHSV(hue * 2, 240, 255);
leds[fiberright(1)] = CHSV(hue, 240, 255);
leds[fiberright(2)] = CHSV(hue * 3, 200, 255);
leds[fiberright(3)] = CHSV(hue, 140, 255);
}
void checkButtons()
{
if (pad.readSwitches())
{
// if (pad.justPressed(0))
// {
// nextMode(1);
// return;
// }
// debug
// if (pad.justPressed(0))
// {
// globalP = 0;
// }
// if (pad.justPressed(1))
// {
// globalP++;
// }
// if (pad.justPressed(2))
// {
// globalP--;
// if (globalP < 0)
// {
// globalP = 0;
// }
// }
// Serial.println(globalP);
// return;
// buttons with a direct mode mapping
for (uint8_t i = 0; i < 15; i++)
{
if (pad.justPressed(i))
{
// Serial.print("BUTTON ");
// Serial.println(i);
pad.setLED(i);
// if (i == 8)
// {
// nextMode(1);
// }
// else if (i == 9)
// {
// nextMode(-1);
// }
// else
if (i == 12)
{
// globalP++;
flash();
}
else if (i == 13)
{
// globalP = 0;
strobo();
}
else if (i < 12 || i == 14)
{
if (i == 14)
setMode(12);
else
setMode(i);
}
}
if (pad.justReleased(i))
{
pad.clrLED(i);
}
}
}
for (uint8_t i = 15; i < 16; i++)
{
if (pad.justPressed(i))
{
if (pad.isLED(i))
{
pad.clrLED(i);
buttonState[i] = 0;
}
else
{
pad.setLED(i);
buttonState[i] = 1;
}
}
}
pad.writeDisplay();
}
void colorWheel()
{
static uint8_t hue = 0;
hue++;
for (int i = 0; i < NUM_STRIPS; i++)
{
for (int j = 0; j < NUM_LEDS_PER_STRIP; j++)
{
leds[(i * NUM_LEDS_PER_STRIP) + j] = CHSV(255, 255, 255);
// leds[(i * NUM_LEDS_PER_STRIP) + j] = CHSV((32 * i) + hue + j, 192, 255);
}
}
}
void flashTestSetup()
{
// currentDelay = 2;
currentDelay = 5;
shouldClear = false;
}
void flashTest()
{
// clear();
fadeToBlackBy(leds, NUM_LEDS, 2);
EVERY_N_MILLISECONDS(1000)
{
for (int j = 0; j < 20; j++)
{
int x = random(0, NUM_LEDS);
leds[x] = CRGB::White;
}
}
}
void randomBluePixelsSetup()
{
// currentDelay = 2;
currentDelay = 0;
shouldClear = false;
}
void randomBluePixels()
{
// clear();
fadeToBlackBy(leds, NUM_LEDS, 40);
for (int j = 0; j < 3; j++)
{
int x = random(0, NUM_LEDS);
leds[x] = CRGB::Blue;
}
}
uint16_t stripoffset(uint8_t n)
{
return NUM_LEDS_PER_STRIP * n;
}
// looking from behind
// left:
// strip outside - 0
// front: 1-45 (first pixel is dead), (running outwards)
// up-down 46-71 (running outwards)
// down-up: 72-94 (running inwards)
// fiber: 95-98
// strip inside - 1 (+120)
// down-up: 0-31 (running outwards)
// top-down 31-62 (running inwards)
// right:
// strip outside - 2 (+240)
// front: 0-44 (running outwards)
// up-down: 45-71 (going outwards)
// down-up: 72-99 (running inwards)
// fiber: 100-103
// strip inside - 3 (+360)
// up-down: 0-33 (going outwards)
// down->up: 34-67 (running inwards)
// body:
// strip 4 (+480)
// back 0-35
// front 36-67
void fill(uint16_t from, uint16_t to, CRGB c)
{
fill_solid(leds + from, to - from, c);
}
void wingTest()
{
lwFrontInner.lerpTo(255, CRGB::Green);
lwFrontOuter.lerpTo(255, CRGB::Red);
// lwMiddleTop.lerpTo(255, CRGB::Blue);
// lwBackTop.lerpTo(255, CRGB::Yellow);
// rwMiddleTop.lerpTo(255, CRGB::Blue);
// rwMiddleBottom.lerpTo(255, CRGB::Green);
// rwBackTop.lerpTo(255, CRGB::Yellow);
// rwBackBottom.lerpTo(255, CRGB::Green);
// fill(LW_FRONT_START, LW_FRONT_PEAK, CRGB::Green);
// fill(LW_FRONT_PEAK, LW_FRONT_END, CRGB::Red);
// fill(LW_MIDDLE_START, LW_MIDDLE_PEAK, CRGB::Yellow);
// fill(LW_MIDDLE_PEAK, LW_MIDDLE_END, CRGB::Red);
// fill(LW_BACK_START, LW_BACK_PEAK, CRGB::Red);
// fill(LW_BACK_PEAK, LW_BACK_END + 20, CRGB::Yellow);
// fill(RW_FRONT_START, RW_FRONT_PEAK, CRGB::Green);
// fill(RW_FRONT_PEAK, RW_FRONT_END, CRGB::Red);
// fill(RW_MIDDLE_START, RW_MIDDLE_PEAK, CRGB::Green);
// fill(RW_MIDDLE_PEAK, RW_MIDDLE_END, CRGB::Red);
// fill(RW_BACK_START, RW_BACK_PEAK, CRGB::Red);
// fill(RW_BACK_PEAK, RW_BACK_END + 20, CRGB::Green);
// fill(BODY_FRONT_START, BODY_FRONT_END, CRGB::Red);
// fill(BODY_BACK_START, BODY_BACK_END, CRGB::Green);
// fill(HEAD_LEFT_START, HEAD_LEFT_END, CRGB::Green);
// fill(HEAD_RIGHT_START, HEAD_RIGHT_END, CRGB::Blue);
// fill(BODY_START, BODY_END, CRGB::Green);
// fill(HEAD_START, HEAD_END, CRGB::Red);
}
// #define LW_S1A_START 46
// #define LW_S1A_END 71
// #define LW_S1B_START 72
// #define LW_S1B_END 94
// #define LW_S2A_START 0 + NUM_LEDS_PER_STRIP
// #define LW_S2A_END 31 + NUM_LEDS_PER_STRIP
// #define LW_S2B_START 32 + NUM_LEDS_PER_STRIP
// #define LW_S2B_END 62 + NUM_LEDS_PER_STRIP
// #define RW_FRONT_START (0 + (NUM_LEDS_PER_STRIP * 2))
// #define RW_FRONT_END (44 + (NUM_LEDS_PER_STRIP * 2))
// #define RW_S1A_START (45 + (NUM_LEDS_PER_STRIP * 2))
// #define RW_S1A_END (71 + (NUM_LEDS_PER_STRIP * 2))
// #define RW_S1B_START (72 + (NUM_LEDS_PER_STRIP * 2))
// #define RW_S1B_END (99 + (NUM_LEDS_PER_STRIP * 2))
// #define RW_S2A_START (0 + (NUM_LEDS_PER_STRIP * 3))
// #define RW_S2A_END (33 + (NUM_LEDS_PER_STRIP * 3))
// #define RW_S2B_START (34 + (NUM_LEDS_PER_STRIP * 3))
// #define RW_S2B_END (67 + (NUM_LEDS_PER_STRIP * 3))
// #define BODY_FRONT_START (36 + NUM_LEDS_PER_STRIP * 4)
// #define BODY_FRONT_END (67 + NUM_LEDS_PER_STRIP * 4)
// #define BODY_BACK_START (0 + NUM_LEDS_PER_STRIP * 4)
// #define BODY_BACK_END (35 + NUM_LEDS_PER_STRIP * 4)
// 5 leds per wing at the same position (0-255)
void leftWingLinear(uint8_t x, CRGB c)
{
leds[lerp8by8(LW_FRONT_START, LW_FRONT_PEAK, x)] += c;
leds[lerp8by8(LW_MIDDLE_START, LW_MIDDLE_PEAK, x)] += c;
leds[lerp8by8(LW_MIDDLE_END, LW_MIDDLE_PEAK, x)] += c;
if (float(x) > LW_LERP_OFFSET)
{
uint8_t xx = uint8_t((float(x) - LW_LERP_OFFSET) * (255.0 / (255.0 - LW_LERP_OFFSET)));
leds[lerp8by8(LW_BACK_START, LW_BACK_PEAK, xx)] += c;
leds[lerp8by8(LW_BACK_END, LW_BACK_PEAK, xx)] += c;
}
}
void rightWingLinear(uint8_t x, CRGB c)
{
leds[lerp16by8(RW_FRONT_START, RW_FRONT_PEAK, x)] += c;
leds[lerp16by8(RW_MIDDLE_START, RW_MIDDLE_PEAK, x)] += c;
leds[lerp16by8(RW_MIDDLE_END, RW_MIDDLE_PEAK, x)] += c;
if (float(x) > RW_LERP_OFFSET)
{
uint8_t xx = uint8_t((float(x) - RW_LERP_OFFSET) * (255.0 / (255.0 - RW_LERP_OFFSET)));
leds[lerp16by8(RW_BACK_START, RW_BACK_PEAK, xx)] += c;
leds[lerp16by8(RW_BACK_END, RW_BACK_PEAK, xx)] += c;
}
}
void linearTest()
{
leftWingLinear(globalP * 4, CRGB::Red);
rightWingLinear(globalP * 4, CRGB::Green);
}
// void bodyFront(uint8_t x, CRGB c)
// {
// leds[lerp16by8(BODY_FRONT_START, BODY_FRONT_END, x)] += c;
// }
// void bodyBack(uint8_t x, CRGB c)
// {
// leds[lerp16by8(BODY_BACK_END, BODY_BACK_START, x)] += c;
// }
void accelOrientationSetup()
{
currentDelay = 3;
usePixies = false;
shouldClear = false;
}
#define LERP_ACCEL_START 60
void accelOrientation()
{
fadeToBlackBy(leds, NUM_LEDS, 7);
sensors_vec_t orientation;
if (ahrs.getOrientation(&orientation))
{
Serial.print("Orientation: ");
Serial.print(orientation.roll);
Serial.print(" ");
Serial.print(orientation.pitch);
Serial.print(" ");
Serial.print(orientation.heading);
Serial.println("");
float p0 = orientation.pitch - 90.0;
Serial.print("p0: ");
Serial.print(p0);
Serial.println();
if (p0 > 0)
{
bodyFront.lerpTo(p0 * 2, CRGB::Blue);
}
else
{
bodyBack.lerpToReverse(p0 * -2, CRGB::Blue);
}
}
// pitch is 89 when strait
// int p = LERP_ACCEL_START + mv * 15.0;
// Serial.print(mv);
// Serial.print(" ");
// Serial.println(p);
// wingLinearLerpTo(p, CHSV(HUE_BLUE + p, 230, p));
// if (p > 220)
// {
// lwFrontOuter.lerpTo(255, CHSV(HUE_BLUE + p, 230, p));
// rwFrontOuter.lerpTo(255, CHSV(HUE_BLUE + p, 230, p));
// }
// for (int i = 0; i < f2; i += 5)
// {
// wingLinearLerp(i, CHSV(hue2 + i / 2, 255, 255));
// // leftWingLinear(i, CHSV(hue2 + 100, 255, 255));
// // rightWingLinear(i, CHSV(hue2 + 100, 255, 255));
// // bodyFront(i, CHSV(hue2 + 100, 255, 255));
// // bodyBack(i, CHSV(hue2 + 100, 255, 255));
// }
}
void newAccelSetup()
{
currentDelay = 2;
usePixies = false;
shouldClear = false;
}
#define LERP_ACCEL_START 60
void newAccel()
{
fadeToBlackBy(leds, NUM_LEDS, 7);
sensors_event_t accel, mag, gyro, temp;
lsm.getEvent(&accel, &mag, &gyro, &temp);
float mv = accel.acceleration.x + (9.81 + 0.9);
Serial.print(accel.gyro.x, 4);
Serial.print(" ");
Serial.print(accel.gyro.y, 4);
Serial.print(" ");
Serial.print(accel.gyro.z, 4);
Serial.println("");
// Serial.print(accel.acceleration.x, 4);
// Serial.print(" ");
// Serial.print(accel.acceleration.y, 4);
// Serial.print(" ");
// Serial.print(accel.acceleration.z, 4);
// Serial.println("");
// static uint8_t hue1 = 0;
// hue1++;
// uint8_t hue2 = hue1;
// uint8_t f2 = uint8_t(LERP_ACCEL_START + (mv * 10.0));
int p = LERP_ACCEL_START + mv * 15.0;
// Serial.print(mv);
// Serial.print(" ");
// Serial.println(p);
wingLinearLerpTo(p, CHSV(HUE_BLUE + p, 230, p));
// if (p > 220)
// {
// lwFrontOuter.lerpTo(255, CHSV(HUE_BLUE + p, 230, p));
// rwFrontOuter.lerpTo(255, CHSV(HUE_BLUE + p, 230, p));
// }
// for (int i = 0; i < f2; i += 5)
// {
// wingLinearLerp(i, CHSV(hue2 + i / 2, 255, 255));
// // leftWingLinear(i, CHSV(hue2 + 100, 255, 255));
// // rightWingLinear(i, CHSV(hue2 + 100, 255, 255));
// // bodyFront(i, CHSV(hue2 + 100, 255, 255));
// // bodyBack(i, CHSV(hue2 + 100, 255, 255));
// }
if (mv > 10)
{
strobo();
}
}
enum StroboState
{
NextOn,
On,
NextOff,
Off
};
class ConcurrentStrobo
{
public:
elapsedMillis timer;
int c;
StroboState state;
ConcurrentStrobo()
{
c = 0;
timer = 0;
state = Off;
}
void trigger()
{
// only if not running anyway
if (c > 0)
return;
c = 5;
timer = 0;
state = NextOn;
usePixies = 1;
}
void advance()
{
switch (state)
{
case On:
if (timer > 50)
{
timer = 0;
state = NextOff;
}
break;
case Off:
if (timer > 100 && c > 0)
{
timer = 0;
state = NextOn;
}
break;
case NextOn:
eyes.setBrightness(255);
eyes.setPixelColor(0, 255, 255, 255);
eyes.show();
state = On;
timer = 0;
c--;
break;
case NextOff:
eyes.setBrightness(0);
eyes.show();
state = Off;
timer = 0;
if (c == 0)
usePixies = 0;
break;
}
}
};
void accelLerpSetup()
{
currentDelay = 3;
// usePixies = false;
usePixies = 1;
shouldClear = false;
}
#define LERP_ACCEL_START 50
void accelLerp()
{
static ConcurrentStrobo s;
fadeToBlackBy(leds, NUM_LEDS, 35);
sensors_event_t accel, mag, gyro, temp;
lsm.getEvent(&accel, &mag, &gyro, &temp);
float mv = accel.acceleration.x + (9.81 + 0.9);
if (accelTestMV == 1)
{
accelTestMV = 0;
mv = 15;
}
// Serial.println(accel.acceleration.x);
static uint8_t hue1 = 0;
hue1++;
uint8_t hue2 = hue1;
uint8_t f2 = uint8_t(LERP_ACCEL_START + (mv * 12.0));
f2 = constrain(f2, 0, 245);
for (int i = 0; i < f2; i += 5)
{
CRGB c = CHSV(hue2 + i / 2, 255, 255);
wingLinearLerp(i, c);
bodyFront.lerpAt(i, c);
bodyBack.lerpAt(255 - i, c);
// leftWingLinear(i, CHSV(hue2 + 100, 255, 255));
// rightWingLinear(i, CHSV(hue2 + 100, 255, 255));
// bodyFront(i, CHSV(hue2 + 100, 255, 255));
// bodyBack(i, CHSV(hue2 + 100, 255, 255));
}
if (mv > 10)
{
s.trigger();
headLeft.fill(CHSV(240, 240, 255));
headRight.fill(CHSV(240, 240, 255));
lwFrontOuter.fill(CHSV(240, 240, 255));
rwFrontOuter.fill(CHSV(240, 240, 255));
// strobo();
}
s.advance();
}
void lerpTestSetup()
{
currentDelay = 10;
shouldClear = false;
}
void lerpTest()
{
static uint8_t hue1 = 0;
hue1++;
uint8_t hue2 = hue1;
fadeToBlackBy(leds, NUM_LEDS, 25);
// for (int i = 0; i < 2; i++)
// {
// uint8_t f = ease8InOutCubic(p + i);
uint8_t f = beatsin8(100, 0, 255);
leftWingLinear(f, CHSV(hue1, 255, 255));
rightWingLinear(f, CHSV(hue1, 255, 255));
bodyFront.lerpAt(f, CHSV(hue1, 255, 255));
bodyBack.lerpAt(255 - f, CHSV(hue1, 255, 255));
uint8_t f2 = beatsin8(50, 20, 220);
leftWingLinear(f2, CHSV(hue2 + 100, 255, 255));
rightWingLinear(f2, CHSV(hue2 + 100, 255, 255));
// bodyFront(f2, CHSV(hue2 + 100, 255, 255));
// bodyBack(f2, CHSV(hue2 + 100, 255, 255));
// }
}
void ftest()
{
clear();
CRGB stripColor[5] = {CRGB::Green, CRGB::Red, CRGB::Blue, CRGB::Yellow, CRGB::White};
for (int i = 0; i < 5; i++)
{
leds[globalP + stripoffset(i)] = stripColor[i];
// CRGB c;
// // for (int j = 64 + 26 + 5; j < 64 + 4 + 26 + 5; j++)
// // for (int j = 64 + 26 + 5; j < 64 + 4 + 26 + 5; j++)
// for (int j = 0; j < NUM_LEDS_PER_STRIP; j++)
// // for (int j = 0; j < globalP; j++)
// {
// if (i % 4 == 0)
// {
// c = CRGB::Green;
// }
// if (i % 4 == 1)
// {
// c = CRGB::Blue;
// }
// if (i % 4 == 2)
// {
// c = CRGB::Red;
// }
// if (i % 4 == 3)
// {
// c = CRGB::Yellow;
// }
// leds[j + stripoffset(i)] = c;
// }
}
}
uint16_t xy60x6(uint8_t x, uint8_t y)
{
if (y > 29)
{
x = x + 6;
y = 59 - y;
}
return (x * 30) + y;
}
uint16_t xy(uint8_t x, uint8_t y)
{
if (x % 2 != 0)
return (x % 12) * 30 + (y % 30);
else
return (x % 12) * 30 + (29 - (y % 30));
}
// looking from front
uint16_t fiberright(int8_t n)
{
// maybe +2
return NUM_LEDS_PER_STRIP * 2 + 96 + n;
}
uint16_t fiberleft(uint8_t n)
{
return 101 + n;
}
void fibertest()
{
// leds[fiberright(-5)] = CRGB::Green;
// leds[fiberright(-3)] = CRGB::Green;
// leds[fiberright(-3)] = CRGB::Green;
// leds[fiberright(-2)] = CRGB::Green;
// leds[fiberright(-1)] = CRGB::Green;
leds[fiberright(0)] = CRGB::Green;
leds[fiberright(1)] = CRGB::Blue;
leds[fiberright(2)] = CRGB::Red;
leds[fiberright(3)] = CRGB::Yellow;
leds[fiberleft(0)] = CRGB::Green;
leds[fiberleft(1)] = CRGB::Blue;
leds[fiberleft(2)] = CRGB::Red;
leds[fiberleft(3)] = CRGB::Yellow;
// leds[fiberright(4)] = CRGB::Yellow;
// leds[fiberright(5)] = CRGB::Yellow;
// leds[fiberright(6)] = CRGB::Yellow;
// leds[fiberright(7)] = CRGB::Yellow;
// leds[fiberleft(0)] = CRGB::Green;
// leds[fiberleft(1)] = CRGB::Blue;
// leds[fiberleft(2)] = CRGB::Red;
// leds[fiberleft(3)] = CRGB::Yellow;
// leds[fiberright(0)] = CRGB::Green;
// leds[fiberright(1)] = CRGB::Blue;
// leds[fiberright(2)] = CRGB::Red;
// leds[fiberright(3)] = CRGB::Yellow;
}
void runner()
{
static int pos = 0;
static uint8_t hue = 0;
hue++;
for (int i = 0; i < NUM_STRIPS; i++)
{
for (int j = 0; j < NUM_LEDS_PER_STRIP; j++)
{
// char r, g, b;
// if (j % 3 == 0)
// {
// r = 255;
// }
// else if (j % 3 == 1)
// {
// g = 255;
// }
// else if (j % 3 == 2)
// {
// b = 255;
// }
// leds[(i * NUM_LEDS_PER_STRIP) + j] = CRGB(0, 255, 0);
leds[(i * NUM_LEDS_PER_STRIP) + j] = CHSV(hue + j, 255, 255);
//leds[(i * NUM_LEDS_PER_STRIP) + j] = CRGB(255, 255, 255);
// leds[(i * NUM_LEDS_PER_STRIP) + j] = CRGB(r, g, b);
// leds[(i * NUM_LEDS_PER_STRIP) + j] = CRGB(0, 255, 0) ;
}
// leds[(i * NUM_LEDS_PER_STRIP) + pos] = CRGB(255, 0, 0);
// leds[(i * NUM_LEDS_PER_STRIP) + ((pos + 1) % NUM_LEDS_PER_STRIP)] = CRGB(0, 255, 0);
// leds[(i * NUM_LEDS_PER_STRIP) + ((pos + 2) % NUM_LEDS_PER_STRIP)] = CRGB(0, 0, 255);
// leds[(i * NUM_LEDS_PER_STRIP) + ((pos + 3) % NUM_LEDS_PER_STRIP)] = CRGB(0, 255, 0);
}
// pos++;
}
uint16_t fps = 0;
void showFps()
{
Serial.println(fps);
fps = 0;
}
void prideSetup()
{
currentDelay = 50;
}
void pride()
{
static uint16_t sPseudotime = 0;
static uint16_t sLastMillis = 0;
static uint16_t sHue16 = 0;
static uint8_t start = 0;
start++;
// EVERY_N_MILLISECONDS(60) { start++; }
start = start % 2;
uint8_t sat8 = beatsin88(87, 220, 250);
uint8_t brightdepth = beatsin88(341, 96, 224);
uint16_t brightnessthetainc16 = beatsin88(203, (25 * 256), (40 * 256));
uint8_t msmultiplier = beatsin88(147, 23, 60);
uint16_t hue16 = sHue16; //gHue * 256;
uint16_t hueinc16 = beatsin88(113, 1, 3000);
uint16_t ms = millis();
uint16_t deltams = ms - sLastMillis;
sLastMillis = ms;
sPseudotime += deltams * msmultiplier;
sHue16 += deltams * beatsin88(400, 5, 9);
uint16_t brightnesstheta16 = sPseudotime;
for (uint16_t i = start; i < NUM_LEDS; i += 2)
{
hue16 += hueinc16;
uint8_t hue8 = hue16 / 256;
brightnesstheta16 += brightnessthetainc16;
uint16_t b16 = sin16(brightnesstheta16) + 32768;
uint16_t bri16 = (uint32_t)((uint32_t)b16 * (uint32_t)b16) / 65536;
uint8_t bri8 = (uint32_t)(((uint32_t)bri16) * brightdepth) / 65536;
bri8 += (255 - brightdepth);
CRGB newcolor = CHSV(hue8, sat8, qadd8(bri8, 100));
uint16_t pixelnumber = i;
pixelnumber = (NUM_LEDS - 1) - pixelnumber;
nblend(leds[pixelnumber], newcolor, 64);
}
}
void colorWheelPulsingSetup()
{
currentDelay = 40;
}
void colorWheelPulsing()
{
static uint8_t hue = 0;
uint8_t pulse = beatsin8(60, 40, 255);
hue++;
hue++;
for (int i = 0; i < NUM_LEDS; i++)
{
leds[i] = CHSV(5 * i + hue, 240, pulse);
}
}
void thunderSetup()
{
currentDelay = 20;
shouldClear = false;
}
void thunder()
{
fadeToBlackBy(leds, NUM_LEDS, 10);
EVERY_N_MILLISECONDS(3000)
{
fill_solid(leds, NUM_LEDS, CHSV(255, 10, 100));
FastLED.show();
delay(25);
clear();
for (int i = 0; i < random8(100); i++)
{
leds[random16(NUM_LEDS)] = CHSV(HUE_BLUE + random8(20), 50 + random(50), 155 + random(100));
}
}
}
void newLerpSetup()
{
currentDelay = 10;
shouldClear = false;
}
class Wave
{
public:
float speed;
CHSV color;
float pos;
Wave()
{
randomize();
}
void randomize()
{
pos = 0;
speed = random(10, 100) / 10.0;
color = blend(CHSV(HUE_RED, 240, 100), CHSV(HUE_BLUE, 240, 100), random8());
}
void advance()
{
pos += speed;
if (pos >= 255)
{
randomize();
}
}
void draw()
{
color.v = 100 + map(pos, 0, 255, 0, 150);
// rightWingLinearLerp(pos, color);
bodyBack.lerpAt(pos, color);
bodyFront.lerpAt(pos, color);
wingLinearLerp(pos, color);
}
};
#define WAVES 5
void newLerp()
{
fadeToBlackBy(leds, NUM_LEDS, 25);
static Wave waves[WAVES];
for (int i = 0; i < WAVES; i++)
{
waves[i].advance();
waves[i].draw();
}
fiberLeft.fill(waves[0].color);
fiberRight.fill(waves[0].color);
// uint8_t x = 0;
// x++;
// uint8_t v = map(beatsin8(30), 0, 255, 130, 30);
// CHSV c = CHSV(212, 240, 170);
// CRGB cc = c;
// cc %= 230;
// bodyFront.fill(cc);
// bodyBack.fill(cc);
headLeft.fill(CRGB::BlueViolet);
headRight.fill(CRGB::DarkRed);
// } int b = beat8(120);
// leftWingLinearLerp(b, CRGB::Red);
// int b2 = beat8(140);
// leftWingLinearLerp(b2, CRGB::Green);
}
void moveToOuterSetup()
{
currentDelay = 3;
shouldClear = false;
}
void moveToOuter()
{
static int x = 0;
static int maxX = 255;
x += 3;
if (x >= maxX)
{
x = 0;
maxX -= 5;
if (maxX < 0)
{
maxX = 255;
clear();
}
}
int idx = lwFrontInner.lerp(x);
fadeToBlackBy(leds + lwFrontInner.start, map(maxX, 0, 255, 0, lwFrontInner.size), 15);
leds[idx] = CRGB::Red;
// Serial.print("x=");
// Serial.print(x);
// Serial.print(" maxx=");
// Serial.print(maxX);
// Serial.print(" idx=");
// Serial.print(idx);
// Serial.print(" start=");
// Serial.print(lwFrontInner.start);
// Serial.print(" mapped=");
// Serial.println(map(maxX, 0, 255, 0, lwFrontInner.size));
}
void colorWheelWithSparkelsSetup()
{
currentDelay = 20;
}
void colorWheelWithSparkels()
{
static uint8_t hue = 0;
hue++;
hue++;
for (int i = 0; i < NUM_LEDS; i++)
{
leds[i] = CHSV(5 * i + hue, 240, 150);
}
for (int j = 0; j < 3; j++)
{
int x = random(0, NUM_LEDS);
leds[x] = CRGB::White;
}
}
void colorWheelNewSetup()
{
currentDelay = 20;
}
void colorWheelNew()
{
for (int i = 0; i < NUM_LEDS; i++)
{
leds[i] = CHSV(5 * i + beat8(17), 240, 150);
}
CRGB c = leds[bodyBack.end - 1];
fiberTail.setPixelColor(0, c.r, c.g, c.b);
fiberTail.setBrightness(255);
fiberTail.show();
}
void iceSparksSetup()
{
static CRGB c = CRGB(10, 10, 240);
usePotentiometer = 0;
FastLED.setBrightness(255);
currentDelay = 50;
shouldClear = false;
overridePixieColor = &c;
}
void iceSparks()
{
fadeToBlackBy(leds, NUM_LEDS, 128);
static uint8_t sat = 0;
sat++;
for (int j = 0; j < 35; j++)
{
leds[random(0, NUM_LEDS)] = CHSV(170 + (random(20) - 10), random(255), 250);
}
}
void basicPowerLedMode()
{
CRGB c(255, 0, 0);
if (overridePixieColor)
c = *overridePixieColor;
if (buttonState[EYE_STATE] == 1)
{
eyes.setBrightness(beatsin8(20, 50, 120));
}
else
{
eyes.setBrightness(0);
}
eyes.setPixelColor(0, c.r, c.g, c.b);
eyes.show();
}
void sparksSetup()
{
FastLED.setBrightness(255);
currentDelay = 10;
usePotentiometer = 0;
}
void sparks()
{
for (int j = 0; j < 30; j++)
{
leds[random(0, NUM_LEDS)] = CRGB::White;
}
}
void fiberBlinkSetup()
{
FastLED.setBrightness(255);
currentDelay = 5;
usePotentiometer = 0;
shouldClear = true;
fiberHead.setBrightness(0);
fiberTail.setBrightness(0);
}
void fiberBlink()
{
int fiber = random(0, 4 + 4 + 2);
fiberHead.setBrightness(0);
fiberTail.setBrightness(0);
if (fiber < 4)
{
leds[fiberleft(fiber)] = CRGB(255, 255, 255);
// leds[fiberleft(fiber)] = CRGB(0, 0, 255);
}
else if (fiber >= 4 && fiber < 8)
{
// leds[fiberright(fiber - 4)] = CRGB(255, 0, 0);
leds[fiberright(fiber - 4)] = CRGB(255, 255, 255);
}
else if (fiber == 8)
{
fiberTail.setPixelColor(0, 255, 255, 255);
fiberTail.setBrightness(200);
}
else if (fiber == 9)
{
fiberHead.setPixelColor(0, 255, 255, 255);
fiberHead.setBrightness(100);
}
fiberHead.show();
fiberTail.show();
}
void pixieTestSetup()
{
usePixies = 1;
currentDelay = 10;
shouldClear = true;
}
void pixieTest()
{
eyes.setPixelColor(0, 255, 0, 0);
fiberTail.setPixelColor(0, 0, 255, 0);
fiberHead.setPixelColor(0, 0, 0, 255);
eyes.setBrightness(50);
fiberTail.setBrightness(0);
fiberHead.setBrightness(0);
// EVERY_N_MILLISECONDS(500)
// {
// all three must be shown in this order - otherwise it will flicker
fiberTail.show();
fiberHead.show();
eyes.show();
// }
}
void fiberPulseSetup()
{
usePixies = 1;
FastLED.setBrightness(255);
currentDelay = 10;
usePotentiometer = 0;
shouldClear = true;
fiberHead.setBrightness(0);
fiberTail.setBrightness(0);
}
void fiberPulse()
{
static uint8_t hue = 0;
static uint8_t pulse = 255;
static int8_t dir = -1;
static int dirs[10] = {-1, 1, -1, 1, -1, 1, -1, 1, -1, 1};
static byte pulses[10] = {random8(), random8(), random8(), random8(), random8(), random8(), random8(), random8(), random8(), random8()};
hue++;
for (int i = 0; i < 10; i++)
{
pulses[i] += dirs[i];
if (pulses[i] < 10)
{
dirs[i] = 1;
}
if (pulses[i] > 253)
{
dirs[i] = -1;
}
CRGB c = CHSV(16 * i + hue, 240, pulses[i]);
if (i < 4)
{
leds[fiberleft(i)] = c;
// leds[fiberleft(fiber)] = CRGB(0, 0, 255);
}
else if (i >= 4 && i < 8)
{
// leds[fiberright(fiber - 4)] = CRGB(255, 0, 0);
leds[fiberright(i - 4)] = c;
}
else if (i == 8)
{
fiberTail.setPixelColor(0, c.r, c.g, c.b);
fiberTail.setBrightness(255);
}
else if (i == 9)
{
fiberHead.setPixelColor(0, c.r, c.g, c.b);
fiberHead.setBrightness(255);
}
}
fiberHead.show();
fiberTail.show();
}
void rainbowSparksSetup()
{
FastLED.setBrightness(255);
currentDelay = 15;
usePotentiometer = 0;
}
void rainbowSparks()
{
static uint8_t hue = 0;
hue++;
for (int j = 0; j < 40; j++)
{
leds[random(0, NUM_LEDS)] = CHSV(hue, 210, 255);
}
}
void bpmSetup()
{
currentDelay = 10;
}
void bpm()
{
sensors_event_t accel, mag, gyro, temp;
lsm.getEvent(&accel, &mag, &gyro, &temp);
// float mv = accel.acceleration.x + accel.acceleration.y + accel.acceleration.z + 9.81;
float mv = accel.acceleration.x + (9.81 + 0.9);
// Serial.println(mv);
if (mv > 10)
{
strobo();
}
static uint8_t gHue = 0;
uint8_t BeatsPerMinute = 100;
CRGBPalette16 palette = PartyColors_p;
uint8_t beat = beatsin8(BeatsPerMinute, 32, 255);
for (int i = 0; i < NUM_LEDS; i++)
{
leds[i] = ColorFromPalette(palette, gHue + (i * 4), beat - gHue + (i * 10));
}
EVERY_N_MILLISECONDS(20) { gHue++; }
}
void juggleSetup()
{
currentDelay = 50;
}
void juggle()
{
static uint8_t gHue = 0;
fadeToBlackBy(leds, NUM_LEDS, 20);
byte dothue = 0;
for (int i = 0; i < 8; i++)
{
leds[beatsin16(i + 7, 0, NUM_LEDS)] |= CHSV(dothue, 200, 255);
dothue += 32;
}
}
void pixiesOff()
{
eyes.setBrightness(0);
eyes.show();
fiberTail.setBrightness(0);
fiberTail.show();
fiberHead.setBrightness(0);
fiberHead.show();
}
void sinelonSetup()
{
shouldClear = false;
FastLED.setBrightness(220);
usePotentiometer = false;
pixiesOff();
}
void sinelon()
{
static uint8_t gHue = 0;
fadeToBlackBy(leds, NUM_LEDS, 20);
// int pos = beatsin16(16, 0, NUM_LEDS);
int pos = beatsin16(map(potentiometer, 0, 65535, 2, 60), 0, NUM_LEDS);
leds[pos] += CHSV(gHue, 255, 192);
EVERY_N_MILLISECONDS(3) { gHue++; }
}
void flash()
{
eyes.setBrightness(255);
eyes.setPixelColor(0, 255, 255, 255);
eyes.show();
delay(100);
eyes.setBrightness(0);
eyes.show();
}
CRGB stroboC[5] = {CRGB(0, 0, 255), CRGB(255, 0, 0), CRGB(0, 255, 255), CRGB(255, 0, 255), CRGB(255, 255, 255)};
void strobo()
{
for (int i = 0; i < 5; i++)
{
delay(50);
eyes.setBrightness(255);
eyes.setPixelColor(0, 255, 255, 255);
// eyes.setPixelColor(0, 126, 6, 229);
// eyes.setPixelColor(0, stroboC[i].r, stroboC[i].g, stroboC[i].b);
eyes.show();
delay(50);
eyes.setBrightness(0);
eyes.show();
}
}
CRGBPalette16 firePal;
void fireSetup()
{
currentDelay = 40;
usePixies = 1;
// firePal = CRGBPalette16(CRGB::Black, CRGB::Red, CRGB::Yellow, CRGB::Grey);
// firePal = CRGBPalette16(CRGB::Black, CRGB::Red, CRGB::Yellow, CRGB::White);
// firePal = CRGBPalette16(CRGB::Black, CRGB::Red, CRGB::Yellow, CRGB::White);
// firePal = CRGBPalette16(CRGB::Black,
// CRGB::Black,
// CRGB::Black,
// CRGB::DarkBlue,
// CRGB::MidnightBlue,
// CRGB::Black,
// CRGB::MediumBlue,
// CRGB::Teal,
// CRGB::CadetBlue,
// CRGB::Blue,
// CRGB::DarkCyan,
// CRGB::CornflowerBlue,
// CRGB::Aquamarine,
// CRGB::SeaGreen,
// CRGB::Aqua,
// CRGB::LightSkyBlue);
// firePal = LavaColors_p;
firePal = HeatColors_p;
// firePal = ForestColors_p;
// firePal = OceanColors_p;
}
#define COOLING 4
#define SPARKING 80
void fire()
{
static byte heat[NUM_LEDS];
random16_add_entropy(random());
// cool down
for (int x = 0; x < NUM_LEDS; x++)
{
heat[x] = qsub8(heat[x], random8(0, COOLING));
}
for (int x = 0; x < NUM_LEDS; x++)
{
if (x == 0)
{
heat[0] = (heat[0] + heat[1]) / 2;
}
if (x == NUM_LEDS - 1)
{
heat[NUM_LEDS - 1] = (heat[NUM_LEDS - 1] + heat[NUM_LEDS - 2]) / 2;
}
if (x > 0 && x < NUM_LEDS - 1)
{
heat[x] = (heat[x - 1] + heat[x] + heat[x + 1]) / 3;
}
}
// // drift up and difuse
// for (int x = 0; x < X; x++)
// {
// for (int k = Y - 1; k >= 2; k--)
// {
// int kk = k;
// int dir = 1;
// if (x % 2 != 0)
// {
// kk = 29 - k;
// dir = -1;
// }
// heat[(kk + x * Y)] = (heat[(kk + x * Y) - dir] + heat[(kk + x * Y) - (2 * dir)] + heat[(kk + x * Y) - (2 * dir)]) / 3;
// }
// }
// ignite wings
for (int i = 0; i < 5; i++)
{
if (random8() < SPARKING)
{
int x = random16(NUM_LEDS_PER_STRIP * 4);
heat[x] = qadd8(heat[x], random8(50, 150));
}
}
if (random8() < SPARKING)
{
int x = random16(NUM_LEDS_PER_STRIP * 4);
heat[x] = qadd8(heat[x], random8(80, 190));
}
// corpus
for (int i = 0; i < 6; i++)
{
if (random8() < SPARKING)
{
int x = random16(NUM_LEDS_PER_STRIP * 4, NUM_LEDS_PER_STRIP * 5);
heat[x] = qadd8(heat[x], random8(50, 150));
}
}
// tail
byte colorindex = scale8(heat[NUM_LEDS_PER_STRIP], 240);
CRGB c = ColorFromPalette(firePal, colorindex);
fiberTail.setPixelColor(0, c.r, c.g, c.b);
fiberTail.setBrightness(255);
fiberTail.show();
// eyes
// if (buttonState[EYE_STATE] == 1)
// {
byte ci = scale8(heat[NUM_LEDS_PER_STRIP + 40], 240);
CRGB cc = ColorFromPalette(firePal, ci);
// eyes.setBrightness(currentBrightness / 3);
eyes.setBrightness(100);
eyes.setPixelColor(0, cc.r, cc.g, cc.b);
// }
// else
// {
// eyes.setBrightness(0);
// }
eyes.show();
// map to pixels
for (int j = 0; j < NUM_LEDS; j++)
{
byte colorindex = scale8(heat[j], 240);
CRGB color = ColorFromPalette(firePal, colorindex);
leds[j] = color;
}
}
void fireWithPotentiometerSetup()
{
fireSetup();
usePotentiometer = 0;
}
void fireWithPotentiometer()
{
int sparking = potentiometer / 4;
int bodyCooling = 5;
int wingCooling = 7;
static byte heat[NUM_LEDS];
random16_add_entropy(random());
// cool down
for (int x = 0; x < NUM_LEDS; x++)
{
heat[x] = qsub8(heat[x], random8(0, wingCooling));
}
for (int x = NUM_LEDS * 4; x < NUM_LEDS_PER_STRIP * 5; x++)
{
heat[x] = qsub8(heat[x], random8(0, bodyCooling));
}
for (int x = 0; x < NUM_LEDS; x++)
{
if (x == 0)
{
heat[0] = (heat[0] + heat[1]) / 2;
}
if (x == NUM_LEDS - 1)
{
heat[NUM_LEDS - 1] = (heat[NUM_LEDS - 1] + heat[NUM_LEDS - 2]) / 2;
}
if (x > 0 && x < NUM_LEDS - 1)
{
heat[x] = (heat[x - 1] + heat[x] + heat[x + 1]) / 3;
}
// if (x > 1 && x < NUM_LEDS - 2)
// {
// heat[x] = (heat[x - 2] + heat[x - 1] + heat[x] + heat[x + 1] + heat[x + 2]) / 5;
// }
}
// // drift up and difuse
// for (int x = 0; x < X; x++)
// {
// for (int k = Y - 1; k >= 2; k--)
// {
// int kk = k;
// int dir = 1;
// if (x % 2 != 0)
// {
// kk = 29 - k;
// dir = -1;
// }
// heat[(kk + x * Y)] = (heat[(kk + x * Y) - dir] + heat[(kk + x * Y) - (2 * dir)] + heat[(kk + x * Y) - (2 * dir)]) / 3;
// }
// }
// ignite wings
for (int i = 0; i < 7; i++)
{
if (random8() < sparking)
{
int x = random16(NUM_LEDS_PER_STRIP * 4);
heat[x] = qadd8(heat[x], random8(50, 190));
}
}
// corpus
for (int i = 0; i < 6; i++)
{
if (random8() < sparking)
{
int x = random16(NUM_LEDS_PER_STRIP * 4, NUM_LEDS_PER_STRIP * 5);
heat[x] = qadd8(heat[x], random8(50, 150));
}
}
// tail
byte colorindex = scale8(heat[NUM_LEDS_PER_STRIP], 240);
CRGB c = ColorFromPalette(firePal, colorindex);
fiberTail.setPixelColor(0, c.r, c.g, c.b);
fiberTail.setBrightness(255);
fiberTail.show();
// eyes
// if (buttonState[EYE_STATE] == 1)
// {
byte ci = scale8(heat[NUM_LEDS_PER_STRIP + 40], 240);
CRGB cc = ColorFromPalette(firePal, ci);
// eyes.setBrightness(currentBrightness / 3);
eyes.setBrightness(100);
eyes.setPixelColor(0, cc.r, cc.g, cc.b);
// }
// else
// {
// eyes.setBrightness(0);
// }
eyes.show();
// map to pixels
for (int j = 0; j < NUM_LEDS; j++)
{
byte colorindex = scale8(heat[j], 240);
CRGB color = ColorFromPalette(firePal, colorindex);
leds[j] = color;
}
}
uint8_t frequency = 20;
uint8_t flashes = 8;
unsigned int dimmer = 1;
uint16_t ledstart;
uint8_t ledlen;
void flash2Setup()
{
currentDelay = 0;
}
void flash2()
{
ledstart = random16(NUM_LEDS);
ledlen = random16(NUM_LEDS - ledstart);
for (int flashCounter = 0; flashCounter < random8(3, flashes); flashCounter++)
{
if (flashCounter == 0)
dimmer = 5;
else
dimmer = random8(1, 3);
fill_solid(leds + ledstart, ledlen, CHSV(255, 0, 255 / dimmer));
FastLED.show();
delay(random8(4, 10));
fill_solid(leds + ledstart, ledlen, CHSV(255, 0, 0));
FastLED.show();
if (flashCounter == 0)
delay(150);
delay(50 + random8(100));
}
delay(random8(frequency) * 100);
}
void reportSensor()
{
sensors_event_t accel, mag, gyro, temp;
lsm.getEvent(&accel, &mag, &gyro, &temp);
// print out accelleration data
Serial.print("Accel X: ");
Serial.print(accel.acceleration.x);
Serial.print(" ");
Serial.print(" \tY: ");
Serial.print(accel.acceleration.y);
Serial.print(" ");
Serial.print(" \tZ: ");
Serial.print(accel.acceleration.z);
Serial.println(" \tm/s^2");
// print out gyroscopic data
Serial.print("Gyro X: ");
Serial.print(gyro.gyro.x);
Serial.print(" ");
Serial.print(" \tY: ");
Serial.print(gyro.gyro.y);
Serial.print(" ");
Serial.print(" \tZ: ");
Serial.print(gyro.gyro.z);
Serial.println(" \tdps");
// print out temperature data
Serial.print("Temp: ");
Serial.print(temp.temperature);
Serial.println(" *C");
Serial.println("**********************\n");
}
void fireNoiseSetup()
{
currentDelay = 20;
shouldClear = false;
}
CRGBPalette16 fireNoisePal = CRGBPalette16(
CRGB::Black, CRGB::Black, CRGB::Black, CHSV(0, 255, 4),
CHSV(0, 255, 8), CRGB::Red, CRGB::Red, CRGB::Red,
CRGB::DarkOrange, CRGB::Orange, CRGB::Orange, CRGB::Orange,
CRGB::Yellow, CRGB::Yellow, CRGB::Gray, CRGB::Gray);
uint32_t xscale = 20; // How far apart they are
uint32_t yscale = 3; // How fast they move
void fireNoise()
{
uint8_t index = 0;
for (int i = 0; i < NUM_LEDS; i++)
{
index = inoise8(i * xscale, millis() * yscale * NUM_LEDS / 255); // X location is constant, but we move along the Y at the rate of millis()
leds[i] = ColorFromPalette(fireNoisePal, min(i * (index) >> 6, 255), i * 255 / NUM_LEDS, LINEARBLEND); // With that value, look up the 8 bit colour palette value and assign it to the current LED.
}
// // tail
// byte colorindex = scale8(heat[NUM_LEDS_PER_STRIP], 240);
// CRGB c = ColorFromPalette(firePal, colorindex);
// fiberTail.setPixelColor(0, c.r, c.g, c.b);
// fiberTail.setBrightness(255);
// fiberTail.show();
// // eyes
// // if (buttonState[EYE_STATE] == 1)
// // {
// byte ci = scale8(heat[NUM_LEDS_PER_STRIP + 40], 240);
// CRGB cc = ColorFromPalette(firePal, ci);
// // eyes.setBrightness(currentBrightness / 3);
// eyes.setBrightness(100);
// eyes.setPixelColor(0, cc.r, cc.g, cc.b);
// // }
// // else
// // {
// // eyes.setBrightness(0);
// // }
// eyes.show();
// // map to pixels
// for (int j = 0; j < NUM_LEDS; j++)
// {
// byte colorindex = scale8(heat[j], 240);
// CRGB color = ColorFromPalette(firePal, colorindex);
// leds[j] = color;
// }
// void fill_noise8 (CRGB *leds, int num_leds, uint8_t octaves, uint16_t x, int scale, uint8_t hue_octaves, uint16_t hue_x, int hue_scale, uint16_t time)
}
// void betterAudioSetup()
// {
// currentDelay = 10;
// shouldClear = false;
// }
// elapsedMillis audioFps = 0;
// void betterAudio()
// {
// static uint8_t hue = 0;
// fadeToBlackBy(leds, NUM_LEDS, 25);
// hue++;
// if (audioFps > 25)
// {
// if (audioPeak.available())
// {
// audioFps = 0;
// int monoPeak = audioPeak.read();
// Serial.println(monoPeak);
// for (int cnt = 0; cnt < monoPeak; cnt++)
// {
// leftWingLinear(cnt, CHSV(hue, 255, 255));
// }
// }
// }
// }
// ---------------------------------
// Functional test
#include "effects/tests.cpp"
AudioInputAnalog adc1(MIC_PIN);
AudioAnalyzePeak audioPeak;
AudioConnection patchCord1(adc1, audioPeak);
// AudioAnalyzeRMS rms;
// AudioConnection patchCord3(adc1, rms);
// AudioAnalyzeFFT256 fft;
// AudioConnection patchCord2(adc1, fft);
#define AUDIO_SAMPLES 60 // samples for the mic buffer
#define MIN_DIST_AUDIO_LEVELS 0.1
#define MIN_AUDIO_LEVEL 0.01
float audioSamples[AUDIO_SAMPLES];
float minAudioAvg = 0;
float maxAudioAvg = 5.0;
byte audioSampleIdx = 0;
void audioUpdate(float sample)
{
float min, max;
if (sample < MIN_AUDIO_LEVEL)
sample = 0;
audioSamples[audioSampleIdx] = sample;
if (++audioSampleIdx >= AUDIO_SAMPLES)
audioSampleIdx = 0;
min = max = audioSamples[0];
for (uint8_t i = 1; i < AUDIO_SAMPLES; i++)
{
if (audioSamples[i] < min)
min = audioSamples[i];
else if (audioSamples[i] > max)
max = audioSamples[i];
}
if ((max - min) < MIN_DIST_AUDIO_LEVELS)
max = min + MIN_DIST_AUDIO_LEVELS;
minAudioAvg = (minAudioAvg * (AUDIO_SAMPLES - 1) + min) / AUDIO_SAMPLES;
maxAudioAvg = (maxAudioAvg * (AUDIO_SAMPLES - 1) + max) / AUDIO_SAMPLES;
}
// void leftWingLinearUpto(uint8_t x, CRGB c)
// {
// leds[lerp8by8(LW_FRONT_START, LW_FRONT_PEAK, x)] += c;
// leds[lerp8by8(LW_MIDDLE_START, LW_MIDDLE_PEAK, x)] += c;
// leds[lerp8by8(LW_MIDDLE_END, LW_MIDDLE_PEAK, x)] += c;
// if (float(x) > LW_LERP_OFFSET)
// {
// uint8_t xx = uint8_t((float(x) - LW_LERP_OFFSET) * (255.0 / (255.0 - LW_LERP_OFFSET)));
// leds[lerp8by8(LW_BACK_START, LW_BACK_PEAK, xx)] += c;
// leds[lerp8by8(LW_BACK_END, LW_BACK_PEAK, xx)] += c;
// }
// }
void betterAudioSetup()
{
currentDelay = 2; // 500Hz
shouldClear = false;
usePixies = false;
}
void betterAudio()
{
fadeToBlackBy(leds, NUM_LEDS, 7);
// fill(HEAD_LEFT_START, HEAD_LEFT_END, CRGB::Green);
// fill(HEAD_RIGHT_START, HEAD_RIGHT_END, CRGB::Blue);
static uint8_t hue = 0;
static float lastPeak = 0;
hue++;
hue %= 128;
CRGB c = CRGB::Purple;
CRGB c2 = CRGB::Red;
bodyBack.fill(c.nscale8_video(10));
bodyFront.fill(c.nscale8_video(10));
headLeft.fill(c2.nscale8_video(30));
headRight.fill(c2.nscale8_video(30));
// headLeft.fill(c);
// headRight.fill(c);
if (audioPeak.available())
{
float peak = audioPeak.read();
audioUpdate(peak);
if (peak < minAudioAvg)
{
peak = minAudioAvg;
}
int p = 128.0 * (peak - minAudioAvg) / (maxAudioAvg - minAudioAvg);
wingLinearLerpTo(p, CHSV(HUE_BLUE + p, 230, p));
if (p > 220)
{
lwFrontOuter.lerpTo(255, CHSV(HUE_BLUE + p, 230, p));
rwFrontOuter.lerpTo(255, CHSV(HUE_BLUE + p, 230, p));
}
// lwFrontInner.lerpTo(p, CHSV(HUE_BLUE + p, 230, p));
// lwMiddleTop.lerpTo(p, CHSV(HUE_BLUE + p, 230, p));
// leftWingLinear(p, CHSV(HUE_BLUE + p, 230, p));
// leftWingLinear(p, CHSV(HUE_BLUE + p, 230, p));
// rightWingLinear(p, CHSV(HUE_BLUE + p, 230, p));
// bodyFront(p, CHSV(HUE_BLUE + p, 230, p));
// bodyBack(p, CHSV(HUE_BLUE + p, 230, p));
// if (p > 210)
// {
// fill(LW_BACK_PEAK, LW_BACK_END + 20, CRGB::Yellow);
// }
// if (p > 190)
// {
// eyes.setPixelColor(0, 155, 0, 0);
// fiberTail.setPixelColor(0, 0, 255, 0);
// fiberHead.setPixelColor(0, 0, 0, 255);
// eyes.setBrightness(50);
// fiberTail.setBrightness(p);
// fiberHead.setBrightness(p);
// // all three must be shown in this order - otherwise it will flicker
// fiberTail.show();
// fiberHead.show();
// eyes.show();
// }
// if (peak > lastPeak)
// {
// lastPeak = peak;
// }
// // leftWingLinear(peak * 255.0, CHSV(255, 255, 255));
// // rightWingLinear(peak * 255.0, CHSV(255, 255, 255));
// lastPeak *= 0.99;
}
}
void audioUpdate2(float sample)
{
float min, max;
if (sample < MIN_AUDIO_LEVEL)
sample = 0;
audioSamples[audioSampleIdx] = sample;
if (++audioSampleIdx >= AUDIO_SAMPLES)
audioSampleIdx = 0;
min = max = audioSamples[0];
for (uint8_t i = 1; i < AUDIO_SAMPLES; i++)
{
if (audioSamples[i] < min)
min = audioSamples[i];
else if (audioSamples[i] > max)
max = audioSamples[i];
}
if ((max - min) < MIN_DIST_AUDIO_LEVELS)
max = min + MIN_DIST_AUDIO_LEVELS;
minAudioAvg = (minAudioAvg * (AUDIO_SAMPLES - 1) + min) / AUDIO_SAMPLES;
maxAudioAvg = (maxAudioAvg * (AUDIO_SAMPLES - 1) + max) / AUDIO_SAMPLES;
}
elapsedMicros audioSamplingTimer;
elapsedMillis audioShowTimer;
boolean beatDetected = false;
AudioAnalyzeRMS rms;
// AudioConnection patchCord2(adc1, rms);
AudioAnalyzeFFT1024 fft;
AudioConnection patchCord3(adc1, fft);
#define AUDIO_SAMPLES 100
int sampleCount = 0;
#define BEAT_BANDS 30
#define LONGTERM_SAMPLES 120 // ~1s
#define SHORTTERM_SAMPLES 2
#define BEAT_COUNTER_SAMPLES 400
#define BEAT_SAMPLES 100
#define CUTOFF 3
// #define DELTA_SAMPLES 300 // 3s
#define DELTA_SAMPLES 150
#define MAX_TIME 200
float deltaSamples[BEAT_BANDS][DELTA_SAMPLES];
float deltas[BEAT_BANDS];
float longtermSamples[BEAT_BANDS][LONGTERM_SAMPLES];
float avgSamples[LONGTERM_SAMPLES];
float delta[BEAT_BANDS];
float longtermAvg[BEAT_BANDS];
float shorttermSamples[BEAT_BANDS][SHORTTERM_SAMPLES];
float band[BEAT_BANDS];
int count[BEAT_BANDS];
int beatSpread[MAX_TIME];
float c[BEAT_BANDS];
int beatCounter[BEAT_COUNTER_SAMPLES];
int beatsArray[BEAT_SAMPLES];
int bandMap[BEAT_BANDS][2] = {
{0, 0},
{1, 1},
{2, 2},
{3, 4},
{5, 6},
{7, 8},
{9, 10},
{11, 13},
{14, 16},
{17, 20},
{21, 24},
{25, 29},
{30, 35},
{36, 42},
{43, 50},
{51, 59},
{60, 70},
{71, 82},
{83, 96},
{97, 112},
{113, 131},
{132, 153},
{154, 178},
{179, 207},
{208, 241},
{242, 280},
{281, 326},
{327, 379},
{380, 440},
{441, 511}};
float bandCorrection[BEAT_BANDS] = {
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0};
// 0,
// 0.02,
// 0.01,
// 0.01,
// 0.08,
// 0.02,
// 0.02};
float beatsGlobalAvg;
int longPos = 0;
int shortPos = 0;
int deltaPos = 0;
int beatCounterPos = 0;
int nextBeatCounter = 0;
int beat = 0;
int beatPos = 0;
float threshold = 0;
float predictiveInfluenceConstant = .1;
float predictiveInfluence;
int cyclePerBeatIntensity;
float standardDeviation;
int cyclesPerBeat;
void newAudioSetup()
{
currentDelay = 0;
// shouldClear = true;
shouldClear = false;
shouldShow = true;
usePotentiometer = 0;
usePixies = 1;
FastLED.setBrightness(255);
for (int i = 0; i < BEAT_BANDS; i += 1)
{
count[i] = 1;
longtermAvg[i] = 0;
delta[i] = 0;
c[i] = 1.5;
}
}
// 60 fps => 16-17ms
// our fps is => 86 => 11-12ms
elapsedMicros fps0;
void newAudio()
{
static int fb = 0;
fadeToBlackBy(leds, NUM_LEDS, 5);
if (fft.available())
{
// return;
// Serial.println(fps0);
// int old = fps0;
// fps0 = 0;
// Serial.print(" ");
longPos++;
if (longPos >= LONGTERM_SAMPLES)
longPos = 0;
shortPos++;
if (shortPos >= SHORTTERM_SAMPLES)
shortPos = 0;
deltaPos++;
if (deltaPos >= DELTA_SAMPLES)
deltaPos = 0;
beatPos++;
if (beatPos >= BEAT_SAMPLES)
beatPos = 0;
float currentAvg = 0;
// for (int i = 0; i < BEAT_BANDS; i++)
// {
// Serial.print(float(i), i > 9 ? 1 : 2);
// Serial.print(" ");
// }
// Serial.println("");
for (int i = 0; i < BEAT_BANDS; i++)
{
float v = fft.read(bandMap[i][0], bandMap[i][1]);
// if (v < 0.01)
// v = 0;
shorttermSamples[i][shortPos] = v;
// band scaling due to noise
// v = constrain(v - bandCorrection[i], 0, 2.0);
currentAvg += v;
longtermAvg[i] = 0;
for (int j = 0; j < LONGTERM_SAMPLES; j++)
{
longtermAvg[i] += longtermSamples[i][j];
}
band[i] = 0;
for (int j = 0; j < SHORTTERM_SAMPLES; j++)
{
band[i] += shorttermSamples[i][j];
}
band[i] = band[i] / float(SHORTTERM_SAMPLES);
longtermSamples[i][longPos] = v;
// if (band[i] >= 0.001)
// {
// Serial.print(band[i], 4);
// Serial.print(" ");
// }
// else
// {
// Serial.print(" - ");
// }
}
currentAvg = currentAvg / float(BEAT_BANDS);
// Serial.println("");
// return;
float con = fmap(potentiometer, 0, 65535, 1.0, 4.0);
float mul = fmap(potentiometer, 0, 65535, -10.0, -170.0);
con = con - 0.1;
// Serial.print(mul, 4);
// Serial.println(" ");
// Serial.println(con, 4);
// Serial.println("");
for (int i = 0; i < BEAT_BANDS; i++)
{
delta[i] = 0.0;
longtermAvg[i] = longtermAvg[i] / float(LONGTERM_SAMPLES);
// store a delta between the current value and the longterm avg per band
deltaSamples[i][deltaPos] = pow(longtermAvg[i] - band[i], 2);
// calculate the per band delta avg for all samples we have
for (int j = 0; j < DELTA_SAMPLES; j += 1)
{
delta[i] += deltaSamples[i][j];
}
// Serial.println();
delta[i] = delta[i] / float(DELTA_SAMPLES);
c[i] = (mul * delta[i]) + con;
// c[i] = (-100 * delta[i]) + 2.5;
// c[i] = (-60 * delta[i]) + 1.9;
// c[i] = (-60 * delta[i]) + 1.9;
// c[i] = (-50 * delta[i]) + 1.5;
// static float maxDelta = 0;
// per band delta avg : 0.00775
// float dx = fmap(constrain(delta[i], 0, 0.1), 0, 0.1, 0, .4);
// float dx = constrain(fmap(delta[i], 0, 1, 0, .4), 0, .4);
// lt avg ~ 0.3
// float lx = fmap(constrain(pow(longtermAvg[i], .5), 0, 6), 0, 20, .3, 0);
// float lx = 0;
// float count1 = fmap(constrain(count[i], 0, 15), 0, 15, 1.0, 0.0);
// float count2 = fmap(constrain(count[i], 30, 200), 30, 200, 0.0, .75);
// c[i] = 1.3 + dx + lx + count1 - count2;
// c[i] = 1.3 + dx + lx + count1 - count2;
// Serial.print(i);
// Serial.print(" count:");
// Serial.print(count[i]);
// Serial.print(" delta:");
// Serial.print(delta[i], 5);
// Serial.print(" dx:");
// Serial.print(dx, 5);
// Serial.print(" lx:");
// Serial.print(lx, 5);
// Serial.print(" c1:");
// Serial.print(count1, 5);
// Serial.print(" c2:");
// Serial.print(-count2, 5);
// Serial.print(" prepre:");
// Serial.print(c[i], 5);
// if (cyclePerBeatIntensity / standardDeviation > 3.5)
// {
// predictiveInfluence = predictiveInfluenceConstant * (1 - cos((float(nextBeatCounter) * TWO_PI) / float(cyclesPerBeat)));
// predictiveInfluence *= fmap(constrain(cyclePerBeatIntensity / standardDeviation, 3.5, 20), 3.5, 15, 1, 6);
// if (cyclesPerBeat > 10)
// c[i] = c[i] + predictiveInfluence;
// }
// Serial.print(" => ");
// Serial.print(c[i], 5);
// Serial.println();
// c[i] = 1.5;
}
// Serial.println("");
// return;
// avg over some frequency + calc global avg LONGTERM_SAMPLES
// one bin is 43 HZ -> 18275hz
avgSamples[longPos] = fft.read(0, 425) / 425.0;
float globalAvg = 0;
for (int j = 0; j < LONGTERM_SAMPLES; j += 1)
globalAvg += avgSamples[j];
globalAvg = globalAvg / float(LONGTERM_SAMPLES);
// Serial.print("global: ");
// Serial.println(globalAvg, 8);
if (globalAvg < 0.0005)
return;
// min 0.00042968
// max from laptop 0.00277068
// need to find real max
beat = 0;
for (int i = 0; i < BEAT_BANDS; i++)
{
// Serial.print(delta[i],4);
// Serial.print(delta[i]/globalAvg,4);
// Serial.print(" ");
}
// Serial.println();
// for (int i = 0; i < BEAT_BANDS; i++)
// {
// Serial.print(float(i), i > 9 ? 1 : 2);
// Serial.print(" ");
// }
// Serial.println("");
// find
for (int i = 0; i < BEAT_BANDS; i += 1)
{
// Serial.print(band[i],3);
// Serial.print(">");
// Serial.print(longtermAvg[i],3);
// Serial.print("=");
// Serial.print(c[i],4);
// Serial.print(" ");
//&& delta[i] > 0.0005
if (band[i] > longtermAvg[i] * c[i])
// if (band[i] > longtermAvg[i] * 1.5 && count[i] > 7)
{
if (false)
{
Serial.print("beat in ");
Serial.print(i);
Serial.print(" band:");
Serial.print(band[i], 6);
Serial.print(" avg:");
Serial.print(longtermAvg[i], 6);
Serial.print(" c:");
Serial.print(c[i], 6);
Serial.print(" avg*c: ");
Serial.print(longtermAvg[i] * c[i], 6);
Serial.print(" count:");
Serial.print(count[i]);
Serial.println();
}
// Serial.print(" x ");
// if (count[i] > 12 & count[i] < 200)
// {
// beatCounter[beatCounterPos % BEAT_COUNTER_SAMPLES] = count[i];
// beatCounterPos += 1;
// }
count[i] = 0;
}
else
{
// Serial.print(" - ");
}
}
// Serial.println("");
for (int i = 0; i < BEAT_BANDS; i += 1)
if (count[i] == 0)
beat += 1;
// beatsArray[beatPos] = beat;
// for (int i = 0; i < BEAT_SAMPLES; i += 1)
// beatsGlobalAvg += beatsArray[i];
// beatsGlobalAvg = beatsGlobalAvg / float(BEAT_SAMPLES);
// c[0] = 1.5 + fmap(constrain(nextBeatCounter, 0, 5), 0, 5, 5, 0);
// c[0] = 2.0 + map(constrain(nextBeatCounter, 0, 5), 0, 5, 5, 0);
// c[0] = 1.5; //+ map(constrain(nextBeatCounter, 0, 5), 0, 5, 5, 0);
// c[0] = 1.5 + map(constrain(nextBeatCounter, 0, 5), 0, 5, 5, 0);
// if (cyclesPerBeat > 10)
// c[0] = c[0] + .75 * (1 - cos((float(nextBeatCounter) * TWO_PI) / float(cyclesPerBeat)));
// global avg = 0.00277719
// threshold = constrain(c[0] * beatsGlobalAvg + fmap(constrain(globalAvg, 0, 2), 0, 2, 4, 0), 5, 1000);
// threshold = constrain(c[0] * beatsGlobalAvg, 5, 1000);
// if (false)
// {
// Serial.print("c0: ");
// Serial.print(c[0], 8);
// Serial.print(" cyclesPerBeat: ");
// Serial.print(cyclesPerBeat, 8);
// Serial.print(" nextBeatCounter: ");
// Serial.print(nextBeatCounter);
// Serial.print(" beatsGlobalAvg: ");
// Serial.print(beatsGlobalAvg, 8);
// Serial.print(" globalAvg: ");
// Serial.print(globalAvg, 8);
// Serial.print(" beats: ");
// Serial.print(beat);
// Serial.print(" threshold: ");
// Serial.print(threshold, 8);
// Serial.println("");
// }
threshold = 5;
// Serial.println(beat);
if (beat > threshold && nextBeatCounter > 5)
{
// float d = currentAvg - globalAvg;
// int p = constrain(d * 25500.0, 0, 255);
if (false)
{
Serial.print("BEAT c0: ");
Serial.print(c[0], 8);
Serial.print(" globalAvg: ");
Serial.print(globalAvg, 8);
Serial.print(" beats: ");
Serial.print(beat);
Serial.print(" threshold: ");
Serial.print(threshold, 8);
Serial.print(" nextBeat: ");
Serial.print(" total beat avg=");
Serial.print(beatsGlobalAvg, 8);
Serial.print(" currentAvg: ");
Serial.print(currentAvg, 8);
// Serial.print(" d=");
// Serial.print(d, 6);
// Serial.print(" P=");
// Serial.print(p);
Serial.println("");
}
int hue = beatsin8(15, 0, 255);
CRGB c = CHSV(hue, 255, 255);
fiberTail.setPixelColor(0, c.r, c.g, c.b);
eyes.setPixelColor(0, c.r, c.g, c.b);
fb = 255;
// fadeLightBy(leds, NUM_LEDS, 100);
// blur1d(leds, NUM_LEDS, 100);
// lwFrontInner.lerpTo(150, CHSV(HUE_RED, 230, 255));
// rwFrontInner.lerpTo(150, CHSV(HUE_RED, 230, 255));
// for (int i = BODY_FRONT_START + 1; i < BODY_FRONT_END - 9; i++)
// {
// leds[i].setHSV(0, 255, 255);
// }
nextBeatCounter = 0;
}
fb--;
fb--;
if (fb <= 0)
fb = 0;
fiberTail.setBrightness(fb);
fiberTail.show();
if (buttonState[EYE_STATE] == 1)
{
eyes.setBrightness(fb);
eyes.show();
}
for (int i = 0; i < BEAT_BANDS; i += 1)
if (count[i] == 0)
{
uint8_t h = beatsin8(15, 0, 255);
int hue = beatsin8(15, 0, 255) + i * 9;
int from = map(i, 0, BEAT_BANDS, 0, 255);
int to = map(i + 1, 0, BEAT_BANDS, 0, 255);
CRGB c = CHSV(hue, 255, 255);
leftWingLinearLerpFromTo(from, to, c);
rightWingLinearLerpFromTo(from, to, c);
bodyBack.lerpFromTo(from, to, c);
bodyFront.lerpFromTo(from, to, c);
headLeft.lerpFromTo(from, to, c);
headRight.lerpFromTo(from, to, c);
fiberLeft.lerpFromTo(from, to, c);
fiberRight.lerpFromTo(from, to, c);
// rwFront.lerpFromTo(map(i, 0, BEAT_BANDS, 0, 255), map(i + 1, 0, BEAT_BANDS, 0, 255), CHSV(hue, 255, 255));
// rwBackBottom.lerpFromTo(map(i, 0, BEAT_BANDS, 0, 255), map(i + 1, 0, BEAT_BANDS, 0, 255), CHSV(hue, 255, 255));
// rwBackTop.lerpFromTo(map(i, 0, BEAT_BANDS, 0, 255), map(i + 1, 0, BEAT_BANDS, 0, 255), CHSV(hue, 255, 255));
// rwMiddleTop.lerpFromTo(map(i, 0, BEAT_BANDS, 0, 255), map(i + 1, 0, BEAT_BANDS, 0, 255), CHSV(hue, 255, 255));
// rwMiddleBottom.lerpFromTo(map(i, 0, BEAT_BANDS, 0, 255), map(i + 1, 0, BEAT_BANDS, 0, 255), CHSV(hue, 255, 255));
// bodyBack.lerpFromTo(map(i, 0, BEAT_BANDS, 0, 255), map(i + 1, 0, BEAT_BANDS, 0, 255), CHSV(hue, 255, 255));
// bodyFront.lerpFromTo(map(i, 0, BEAT_BANDS, 0, 255), map(i + 1, 0, BEAT_BANDS, 0, 255), CHSV(hue, 255, 255));
// headLeft.lerpFromTo(map(i, 0, BEAT_BANDS, 0, 255), map(i + 1, 0, BEAT_BANDS, 0, 255), CHSV(hue, 255, 255));
// headRight.lerpFromTo(map(i, 0, BEAT_BANDS, 0, 255), map(i + 1, 0, BEAT_BANDS, 0, 255), CHSV(hue, 255, 255));
}
// for (int i = 0; i < MAX_TIME; i++)
// beatSpread[i] = 0;
// for (int i = 0; i < BEAT_COUNTER_SAMPLES; i++)
// {
// beatSpread[beatCounter[i]] += 1;
// }
// cyclesPerBeat = amode(beatCounter, BEAT_COUNTER_SAMPLES);
// if (cyclesPerBeat < 20)
// cyclesPerBeat *= 2;
// cyclePerBeatIntensity = amax(beatSpread, MAX_TIME);
// standardDeviation = 0;
// for (int i = 0; i < MAX_TIME; i++)
// standardDeviation += pow(BEAT_COUNTER_SAMPLES / MAX_TIME - beatSpread[i], 2);
// standardDeviation = pow(standardDeviation / MAX_TIME, .5);
for (int i = 0; i < BEAT_BANDS; i += 1)
count[i] += 1;
// deltaPos += 1;
nextBeatCounter += 1;
beatPos += 1;
// Serial.print(audioSamplingTimer);
// audioSamplingTimer = 0;
// Serial.print("|FFT: ");
// for (int i = 0; i < 20; i++)
// {
// float n = fft.read(i);
// if (n >= 0.01)
// {
// Serial.print(n);
// Serial.print(" ");
// }
// else
// {
// Serial.print(" - ");
// }
// }
// Serial.println();
}
// EVERY_N_MILLISECONDS(1000)
// {
// Serial.print("fft=");
// Serial.print(fft.processorUsage());
// Serial.print(",");
// Serial.print(fft.processorUsageMax());
// Serial.print(" Memory: ");
// Serial.print(AudioMemoryUsage());
// Serial.print(",");
// Serial.print(AudioMemoryUsageMax());
// Serial.println("");
// }
// // a sample is ready roughly every 3ms - lets test that assumption
// if (rms.available())
// {
// float peak = rms.read();
// Serial.println("peak " + String(peak) + " t=" + String(audioSamplingTimer));
// audioSamplingTimer = 0;
// sampleCount++;
// if(sampleCount >= AUDIO_SAMPLES) {
// }
// }
// a sample is ready roughly every 3ms - lets test that assumption
// if (audioSamplingTimer > 22)
// {
// if (audioPeak.available())
// {
// audioSamplingTimer = 0;
// float peak = audioPeak.read();
// }
// }
// if (audioShowTimer > 10)
// {
// audioShowTimer = 0;
// lwFrontInner.lerpTo(p, CHSV(HUE_BLUE, 230, p));
// }
// fadeToBlackBy(leds, NUM_LEDS, 5);
// fill(HEAD_LEFT_START, HEAD_LEFT_END, CRGB::Green);
// fill(HEAD_RIGHT_START, HEAD_RIGHT_END, CRGB::Blue);
// if (audioPeak.available())
// {
// float peak = audioPeak.read();
// audioUpdate(peak);
// if (peak < minAudioAvg)
// {
// peak = minAudioAvg;
// }
// int p = 128.0 * (peak - minAudioAvg) / (maxAudioAvg - minAudioAvg);
// lwFrontInner.lerpTo(p, CHSV(HUE_BLUE, 230, p));
// rightWingLinear(p, CHSV(HUE_BLUE + p, 230, p));
// }
}
void heartbeatSetup()
{
currentDelay = 10;
usePotentiometer = 0;
usePixies = 1;
shouldClear = false;
clear();
FastLED.show();
FastLED.setBrightness(255);
}
elapsedMillis timeElapsed;
void heartbeat()
{
static int fadeSpeed = 5;
fadeToBlackBy(leds, NUM_LEDS, fadeSpeed);
leds[fiberleft(0)] = CRGB(255, 0, 0);
leds[fiberleft(1)] = CRGB(255, 0, 0);
leds[fiberleft(2)] = CRGB(255, 0, 0);
leds[fiberleft(3)] = CRGB(255, 0, 0);
leds[fiberright(0)] = CRGB(255, 0, 0);
leds[fiberright(1)] = CRGB(255, 0, 0);
leds[fiberright(2)] = CRGB(255, 0, 0);
leds[fiberright(3)] = CRGB(255, 0, 0);
static int b = 0;
// uint8_t b = beat8(60);
// if (b < 40)
// {
// b = 40;
// }
// fill(BODY_FRONT_START, BODY_FRONT_END, CHSV(0, 230, 40));
if (timeElapsed > 1000)
{
timeElapsed = 0;
fadeSpeed = 15;
b = 1;
for (int i = BODY_FRONT_START + 1; i < BODY_FRONT_END - 9; i++)
{
leds[i].setHSV(0, 255, 255);
}
}
if (timeElapsed > 200 && b == 1)
{
// timeElapsed = 0;
fadeSpeed = 10;
b = 0;
for (int i = BODY_FRONT_START + 1; i < BODY_FRONT_END - 9; i++)
{
leds[i].setHSV(0, 255, 255);
}
}
int eyebrightness = map(potentiometer, 0, 65535, 0, 220);
eyes.setPixelColor(0, 255, 0, 0);
eyes.setBrightness(beatsin8(15, eyebrightness, 35 + eyebrightness));
eyes.show();
fiberHead.setPixelColor(0, 240, 10, 10);
fiberHead.setBrightness(150);
fiberHead.show();
fiberTail.setPixelColor(0, 255, 0, 0);
fiberTail.setBrightness(255);
fiberTail.show();
}
// the loop routine runs over and over again forever:
void loop()
{
if (shouldClear)
clear();
if (!usePixies)
basicPowerLedMode();
modes[currentMode][0]();
if (shouldShow)
FastLED.show();
EVERY_N_MILLISECONDS(250) { checkPotentiometer(); }
if (PAD_CONNECTED)
{
EVERY_N_MILLISECONDS(100) { checkButtons(); }
// EVERY_N_MILLISECONDS(30) { checkButtons(); }
}
EVERY_N_MILLISECONDS(500) { testled(); }
EVERY_N_MILLISECONDS(100) { checkSerial(); }
// EVERY_N_MILLISECONDS(250) { reportSensor(); }
if (currentDelay > 0)
delay(currentDelay);
}
|
/*******************************************************************************
* filename: C_PatternInitialiser.hpp
* description: Singleton class that initialises the ideal pattern
* author: Moritz Beber
* created: 2010-06-09
* copyright: Jacobs University Bremen. All rights reserved.
*******************************************************************************
*
******************************************************************************/
#ifndef _C_PATTERNINITIALISER_HPP
#define _C_PATTERNINITIALISER_HPP
/*******************************************************************************
* Includes
******************************************************************************/
// project
#include "common_definitions.hpp"
#include "M_Singleton.hpp"
#include "C_ParameterManager.hpp"
/*******************************************************************************
* Declarations
******************************************************************************/
namespace rfn {
class PatternInitialiser {
/* Singleton Pattern Declaration */
DECLARE_BASE_SINGLETON(PatternInitialiser)
public:
/* Member Functions */
// _instance retrieval method
static PatternInitialiser* instance(const PatternInitScheme scheme);
// pure virtual ideal pattern init method
virtual void init(ParameterManager* const parameters,
Matrix* const pattern) = 0;
protected:
/* Internal Functions */
double complexity(ParameterManager* const parameters,
Matrix* const pattern);
}; // class PatternInitialiser
} // namespace rfn
#endif // _C_PATTERNINITIALISER_HPP
|
#include <iostream>
#include <limits>
#include <ctime>
#include "database.h"
void help()
{
std::cout << "HELP:\n"
<< "\tinsert key v m\n"
<< "\t\tshort: i\n"
<< "\t\tif key exists updates record, otherwise adds record\n"
<< "\tget key\n"
<< "\t\tshort: g\n"
<< "\t\tgets record with given key\n"
<< "\tgetall\n"
<< "\t\tshort: ga\n"
<< "\t\tprints all records in order\n"
<< "\tdelete key\n"
<< "\t\tshort: d\n"
<< "\t\tdelete record with given key\n"
<< "\tprint\n"
<< "\t\tshort: p\n"
<< "\t\tprints DB\n"
<< "\treorganize\n"
<< "\t\tshort: re\n"
<< "\t\treorganizes DB\n"
<< "\trandom\n"
<< "\t\tshort: r\n"
<< "\t\tinserts record with random data\n"
<< "\tnew name\n"
<< "\t\tshort: n\n"
<< "\t\tcreates new db with given name\n"
<< "\topen name\n"
<< "\t\tshort: o\n"
<< "\t\topens existing db with given name\n"
<< "\tinfo\n"
<< "\t\tprints info about db\n"
<< "\texit\n"
<< "\t\texits program\n"
<< "\thelp\n"
<< "\t\tshort: h\n"
<< "\t\tprints help"
<< std::endl;
}
int main()
{
//INIT
std::string command, name;
int IOCounter = 0;
Record record;
DataBase db;
double m, v;
int key;
srand(static_cast<unsigned int>(std::time(nullptr)));
//MAIN LOOP
while (true)
{
if (db.file.fileName != "")
std::cout << "$" << db.file.fileName << " ";
std::cout << ">> ";
std::cin >> command;
if (command == "insert" || command == "i")
{
std::cin >> key;
std::cin >> v;
std::cin >> m;
record = { key, v, m };
std::cout << "\n" << record << std::endl;
db.Insert(record);
}
else if (command == "info")
db.Info();
else if (command == "get" || command == "g")
{
std::cin >> key;
record = db.Get(key);
if (record.key == key)
std::cout << "\n" << record << std::endl;
else
std::cout << "\nNo record with given key" << std::endl;
}
else if (command == "getall" || command == "ga")
{
std::cout << "\n";
do {
record = db.GetNext();
if (record.isInitialized() && record.key > 0)
std::cout << record << std::endl;
} while (record.isInitialized());
}
else if (command == "delete" || command == "d")
{
std::cin >> key;
if (db.Delete(key))
std::cout << "\nSuccess" << std::endl;
else
std::cout << "\nNo record with given key" << std::endl;
}
else if (command == "print" || command == "p")
db.Print();
else if (command == "reorganize" || command == "re")
db.Reorganize();
else if (command == "random" || command == "r")
{
std::cout << "\n";
key = rand() % 1000 + 1;
m = (rand() % 10000 + 1) / 100.0;
v = (rand() % 10000 + 1) / 100.0;
record = { key, v, m };
std::cout << "\n" << record << std::endl;
db.Insert(record);
}
else if (command == "new" || command == "n")
{
std::cin >> name;
db.Open(name + "_index", name + "_db", name + "_db_meta", true, &IOCounter);
}
else if (command == "open" || command == "o")
{
std::cin >> name;
db.Open(name + "_index", name + "_db", name + "_db_meta", false, &IOCounter);
}
else if (command == "exit")
break;
else if (command == "help" || command == "h")
help();
else
{
std::cout << "\nUNKNOWN COMMAND " << command << std::endl;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
std::cout << "\nIOCounter: " << IOCounter << std::endl;
IOCounter = 0;
std::cout << std::endl;
}
db.GenerateMetadata(db.file.fileName + "_meta");
return 0;
}
|
//
// Connection.h
// superasteroids
//
// Created by Cristian Marastoni on 03/06/14.
//
//
#include "NetTypes.h"
#include "NetTime.h"
#include "Reliability.h"
#include "../IpAddress.h"
class SocketLayer;
class BitStream;
class Channel;
class NetPacket;
class EndPoint;
class EndPointListener;
struct NetMessageHeader;
class Connection {
public:
enum State {
STATE_CONNECTED,
STATE_DISCONNECTED,
STATE_CONNECTING,
STATE_ACCEPTED,
STATE_DISCONNECTING,
STATE_ERROR
};
Connection();
~Connection();
void Init(EndPoint *endPoint);
void SetID(uint8 peerId);
void SetPeerListener(EndPointListener *listener);
void Disconnect();
void StartConnection(const IpAddress &address);
void ProduceMessage(BitStream &data, uint8 messageId, uint8 channelID);
void SendMessage(NetMessageHeader const &header, uint8 const *data);
void OnConnectionAttempt(const IpAddress &address, uint16 sessionID);
void OnConnectionAccepted(uint16 sessionID);
void OnConnectionAcknowledged();
void OnConnectionDenied(uint32 reason);
void OnPing(BitStream const &pingData);
void OnPong(BitStream const &pongData);
void OnAck(uint8 channelId, uint16 ackSeq);
void OnMessageReceived(NetMessageHeader const &header, BitStream const &data);
void OutputUserMessage(const NetMessageHeader &header, uint8 const *data);
State GetState() const {
return mState;
}
uint32 GetDisconnectReason() const {
return mDisconnectReason;
}
State Update(float dt);
NetID GetID() const {
return mNetID;
}
IpAddress const &GetAddress() const {
return mAddress;
}
Channel *GetChannel(uint8 channelId) const {
return mChannels[channelId];
}
public:
struct FindByAddress {
FindByAddress(IpAddress const &address) : mIP(address) { }
bool operator()(Connection const *connection) const {
return connection->GetAddress() == mIP;
}
IpAddress const &mIP;
};
struct FindById {
FindById(NetID peerID) : mID(peerID) { }
bool operator()(Connection const *connection) const {
return connection->GetID() == mID;
}
uint8 const mID;
};
private:
void ResetChannels();
void DestroyAllChannels();
void SendPing();
void SendPong(uint64 remoteTime);
void SendAck(uint8 channelId, uint16 messageSeq);
void SendConnectionAttempt();
void SendConnectionAccepted();
void SendConnectionAcknowledge();
void ConnectionTimeout();
void ConnectionError();
void ConnectionEstablished();
void UpdateMessageReceived();
private:
State mState;
uint8 mNumConnectionRetry;
uint16 mSessionID;
EndPoint *mEndPoint;
EndPointListener *mPeerListener;
Reliability mReliability;
Channel *mChannels[NetChannels::NUM_CHANNELS];
uint32 mNumChannels;
uint32 mDisconnectReason;
uint32 mNumMessageReceived;
uint32 mNumMessageSent;
float mKeepAliveTimeout;
float mConnectionTimeout;
float mConnectingTimer;
NetTime mNetTime;
NetID mNetID;
IpAddress mAddress;
};
|
#pragma once
#include <vector>
#include <string>
#include <random>
#include <ncurses.h>
using namespace std; //Boo hiss
class Map {
vector<vector<char>> map;
vector <pair<int,int>> m;
bool exit = false;
public:
static const char EXIT = 'E';
static const char HERO = 'H';
static const char MONSTER = 'M';
static const char VWALL = '|';
static const char HWALL = '_';
static const char WATER = '~';
static const char OPEN = '.';
static const char TREASURE = '$';
static const char HEALTH_UP = '^';
static const char TERRAIN = '@';
static const char BOSS = 'B';
static const size_t SIZE = 30; //World is a 100x100 map
static const size_t DISPLAY = 20; //Show a 20x20 area at a time
//Randomly generate map
void init_map() {
random_device rd; // only used once to initialise (seed) engine
mt19937 gen(rd()); // random-number engine used (Mersenne-Twister in this case)
uniform_int_distribution<int> d100(1,100);
map.clear();
map.resize(SIZE); //100 rows tall
for (auto &v : map) v.resize(SIZE,'.'); //100 columns wide
for (size_t i = 0; i < SIZE; i++) {
for (size_t j = 0; j < SIZE; j++) {
//Line the map with walls
if ((i ==0 and j==0) or (i==0 and j==SIZE-1))
map.at(i).at(j) =HWALL;
else if (j == 0 or j == SIZE-1)
map.at(i).at(j) = VWALL;
else if (i == 0 or i == SIZE-1)
map.at(i).at(j) = HWALL;
else if ( i==SIZE/2 and j==SIZE/2)
map.at(i).at(j)=BOSS;
else if (exit == false && (d100(gen)==1 or (i==28 and j==28))){
exit=true;
map.at(i).at(j)=EXIT;
}
else {
//5% chance of monster
if (d100(gen) <=2){
map.at(i).at(j) = HEALTH_UP;
}
else if (d100(gen) <= 5) {
map.at(i).at(j) = MONSTER;
m.push_back(make_pair(i,j));
}
else if (d100(gen) <= 3) {
map.at(i).at(j) = TREASURE;
}
/* else if (d100(gen) <=2)
map.at(i).at(j)= TERRAIN;
*/ else if (d100(gen) <= 3) { //3% each spot is water
map.at(i).at(j) = WATER;
}
else if (d100(gen) <= 50) { //20% chance of water near other water
if (map.at(i-1).at(j) == WATER or map.at(i+1).at(j) == WATER or map.at(i).at(j-1) == WATER or map.at(i).at(j+1) == WATER)
map.at(i).at(j) = WATER;
}
}
}
}
}
//Draw the DISPLAY tiles around coordinate (x,y)
void draw(int x, int y) {
int start_x = x - DISPLAY/2;
int end_x = x + DISPLAY/2;
int start_y = y - DISPLAY/2;
int end_y = y + DISPLAY/2;
//Bounds check to handle the edges
if (start_x < 0) {
end_x = end_x - start_x;
start_x = 0;
}
if (end_x > int(SIZE-1)) {
start_x = start_x - (end_x - (SIZE-1));
end_x = SIZE-1;
}
if (start_y < 0) {
end_y = end_y - start_y;
start_y = 0;
}
if (end_y > int(SIZE-1)) {
start_y = start_y - (end_y - (SIZE-1));
end_y = SIZE-1;
}
//Now draw the map using NCURSES
for (int i = start_y; i <= end_y; i++) {
for (int j = start_x; j <= end_x; j++) {
//if (i == cursor_x && j == cursor_y)
// attron(A_UNDERLINE | A_BOLD);
int color = 8;
if (map.at(i).at(j) == VWALL or map.at(i).at(j) ==HWALL)
color = 5;
else if (map.at(i).at(j) == WATER)
color = 2;
else if (map.at(i).at(j) == HERO)
color = 3;
else if (map.at(i).at(j) == TREASURE)
color = 4;
else if (map.at(i).at(j) == MONSTER)
color = 6;
else if (map.at(i).at(j) == TERRAIN)
color = 5;
else if (map.at(i).at(j) == HEALTH_UP)
color = 0;
else if (map.at(i).at(j) == BOSS)
color = 7;
else if (map.at(i).at(j) == EXIT)
color = 1;
attron(COLOR_PAIR(color));
mvaddch(i-start_y,j-start_x,map.at(i).at(j));
attroff(COLOR_PAIR(color));
//attroff(A_UNDERLINE | A_BOLD);
}
}
}
//dont need this function if doing JRPG game DONT DELETE JUST DONT USE
void monster_move(){
for (size_t i = 0; i < m.size(); i++){
int x = rand() %4;
if (x==0){
if (m.at(i).second<SIZE-2){
if (map.at(m.at(i).first).at(m.at(i).second) == VWALL);
else if (map.at(m.at(i).first).at(m.at(i).second+1) == HERO);
else if (map.at(m.at(i).first).at(m.at(i).second+1) == BOSS);
else if (map.at(m.at(i).first).at(m.at(i).second+1) == EXIT);
else if (map.at(m.at(i).first).at(m.at(i).second+1) == MONSTER);
else if (map.at(m.at(i).first).at(m.at(i).second+1) == HWALL);
else if (map.at(m.at(i).first).at(m.at(i).second+1) == WATER);
else if (map.at(m.at(i).first).at(m.at(i).second+1) == TREASURE);
else if (map.at(m.at(i).first).at(m.at(i).second+1) == HEALTH_UP);
else {
map.at(m.at(i).first).at(m.at(i).second)= OPEN;
m.at(i).second++;
map.at(m.at(i).first).at(m.at(i).second)= MONSTER;
}
}
}
else if(x==1){
if (m.at(i).first<SIZE-2){
if (map.at(m.at(i).first).at(m.at(i).second) == VWALL);
else if (map.at(m.at(i).first+1).at(m.at(i).second) == HERO);
else if (map.at(m.at(i).first+1).at(m.at(i).second) == BOSS);
else if (map.at(m.at(i).first+1).at(m.at(i).second) == EXIT);
else if (map.at(m.at(i).first+1).at(m.at(i).second) == MONSTER);
else if (map.at(m.at(i).first+1).at(m.at(i).second) == HWALL);
else if (map.at(m.at(i).first+1).at(m.at(i).second) == WATER);
else if (map.at(m.at(i).first+1).at(m.at(i).second) == TREASURE);
else if (map.at(m.at(i).first+1).at(m.at(i).second) == HEALTH_UP);
else {
map.at(m.at(i).first).at(m.at(i).second)= OPEN;
m.at(i).first++;
map.at(m.at(i).first).at(m.at(i).second)= MONSTER;
}
}
}
else if (x==2){
if (m.at(i).second>1){
if (map.at(m.at(i).first).at(m.at(i).second) == VWALL);
else if (map.at(m.at(i).first).at(m.at(i).second-1) == HERO);
else if (map.at(m.at(i).first).at(m.at(i).second-1) == BOSS);
else if (map.at(m.at(i).first).at(m.at(i).second-1) == EXIT);
else if (map.at(m.at(i).first).at(m.at(i).second-1) == MONSTER);
else if (map.at(m.at(i).first).at(m.at(i).second-1) == HWALL);
else if (map.at(m.at(i).first).at(m.at(i).second-1) == WATER);
else if (map.at(m.at(i).first).at(m.at(i).second-1) == TREASURE);
else if (map.at(m.at(i).first).at(m.at(i).second-1) == HEALTH_UP);
else {
map.at(m.at(i).first).at(m.at(i).second)= OPEN;
m.at(i).second--;
map.at(m.at(i).first).at(m.at(i).second)= MONSTER;
}
}
}
else if (x==3){
if (m.at(i).first>1){
if (map.at(m.at(i).first-1).at(m.at(i).second) == VWALL);
else if (map.at(m.at(i).first-1).at(m.at(i).second) == HERO);
else if (map.at(m.at(i).first-1).at(m.at(i).second) == BOSS);
else if (map.at(m.at(i).first-1).at(m.at(i).second) == EXIT);
else if (map.at(m.at(i).first-1).at(m.at(i).second) == MONSTER);
else if (map.at(m.at(i).first-1).at(m.at(i).second) == HWALL);
else if (map.at(m.at(i).first-1).at(m.at(i).second) == WATER);
else if (map.at(m.at(i).first-1).at(m.at(i).second) == TREASURE);
else if (map.at(m.at(i).first-1).at(m.at(i).second) == HEALTH_UP);
else {
map.at(m.at(i).first).at(m.at(i).second)= OPEN;
m.at(i).first--;
map.at(m.at(i).first).at(m.at(i).second)= MONSTER;
}
}
}
}
}
void remove_monster(int x , int y){
pair <int,int> k = make_pair(x,y);
for (size_t i=0; i <m.size();i++){
if (m.at(i).first==y && m.at(i).second==x){
m.at(i).first=m.at(m.size()-1).first;
m.at(i).second=m.at(m.size()-1).second;
m.pop_back();
}
}
}
void set(int x, int y, char c) {
for (unsigned int i =0; i < SIZE;i++){
for (unsigned int j =0; j < SIZE;j++){
if (map.at(i).at(j)=='H')
map.at(i).at(j)='.';
}
}
map.at(y).at(x) = c;
}
char get(int x, int y) {
return map.at(y).at(x);
}
Map() {
init_map();
}
};
|
#include<bits/stdc++.h>
using namespace std;
#define MOD 1000000007
#define pb push_back
#define mp make_pair
typedef long long ll;
map<int,int> m;
int ans;
int binary_search(int* a, vector<int> &b,int n,int x,int max,int min) {
int low, high, mid,f=0,g=0,l=0,e=0,o=0;
low = 1;
high = n;
ans=0;
vector< pair<int,int> > v;
while (low <= high) {
mid = (low + high) / 2;
if(x==max&&m[x]<mid) {
f=1;
break;
}
if(x==min&&m[x]>mid) {
f=1;
break;
}
if (a[mid] == x)
break;
else if (a[mid] < x) {
l++;
if(mid>m[x]) {
o++;
v.pb(mp(a[mid],0));
high = mid-1;
} else {
low = mid+1;
}
}
else if(a[mid]>x) {
g++;
if(mid<m[x]) {
e++;
v.pb(mp(a[mid],1));
low = mid+1;
} else {
high = mid-1;
}
}
}
//cout<<v.size()<<" ";
if(f==1||v.size()==0)
return mid;
else {
sort(v.begin(),v.end());
int it=upper_bound(b.begin(),b.end(),x)-b.begin();
int gi=n-it,li=n-gi-1,p=0;
gi-=g;
li-=l;
//cout<<gi<<" "<<li<<" "<<v.size()<<" ";
bool b[20]={false};
for(int i=0;i<v.size();i++) {
if(b[i]==false) {
int fi=v[i].second;
for(int j=i+1;j<v.size();j++) {
if(fi!=v[j].second&&b[j]==false) {
p++;
b[i]=true;
b[j]=true;
o--;
e--;
break;
}
}
}
}
// cout<<o<<" "<<e<<" ";
int r=v.size()-2*p;
if(r==0) {
ans=p;
return mid;
}
else {
if(e<=li&&o<=gi) {
ans=p+o+e;
return mid;
}
}
}
return -1;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin>>t;
while(t--) {
int n,q;
cin>>n>>q;
int a[n+1],max=0,min=INT_MAX;
vector<int> b(n);
b[0]=0;
for(int i=1;i<=n;i++) {
cin>>a[i];
m[a[i]]=i;
b[i-1]=a[i];
if(max<a[i])
max=a[i];
if(min>a[i])
min=a[i];
}
sort(b.begin(),b.end());
while(q--) {
int x;
cin>>x;
int mid=binary_search(a,b,n,x,max,min);
//cout<<mid<<" ";
if(m[x]==mid)
cout<<ans<<"\n";
else
cout<<-1<<"\n";
}
}
return 0;
}
|
#pragma once
#include "ServiceConfig.h"
#include "SimpleLogger.h"
#include "PageBaseUI.h"
#include "MsgTip.h"
#include "Stdafx.h"
#include <json/json.h>
#include <fstream>
#include <sstream>
#define FILE_NAME "\\..\\data\\etc\\vas-manager.conf"
class CServiceConfigUI :public CPageBaseUI
{
public:
CServiceConfigUI();
~CServiceConfigUI();
static string W2A(const wstring &wstrcode);
static wstring A2W(const string &AsciiStr);
void Notify(TNotifyUI &msg);
LRESULT HandleMessage(UINT uMsg, WPARAM wParam, LPARAM lParam);
virtual void InitUI(int nShowID = 0, LPVOID lpParam = NULL);
void Close(UINT nRet=1);
void SaveConfig();
private:
string GetEditContent();
void SetEditContent();
CEditUI*m_pService;
CEditUI*m_pPort;
CEditUI*m_pSql;
CEditUI*m_pUserName;
CEditUI*m_pPassWord;
string m_strFilePath;
string m_strService;
string m_strPort;
string m_strSql;
string m_strUserName;
string m_strPassWord;
};
|
#include <cstdio>
#include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <algorithm>
#define INT_MAX 0x7fffffff
#define INT_MIN 0x80000000
using namespace std;
bool helper(vector<vector<char>> &board, vector<vector<bool>> &sign,int cur, string word, int x,
int y){
if(cur == word.length()) return true;
int row = board.size();
int col = board[0].size();
if(x<0 || x>=row || y<0 || y>=col || sign[x][y] || board[x][y] != word[cur]) return false;
sign[x][y] = 1;
bool res = helper(board,sign,cur+1,word,x+1,y) ||
helper(board,sign,cur+1,word,x-1,y) ||
helper(board,sign,cur+1,word,x,y-1) ||
helper(board,sign,cur+1,word,x,y+1);
sign[x][y] = 0;
return res;
}
bool exist(vector<vector<char>> &board, string word){
int row = board.size();
int col = board[0].size();
vector<vector<bool>> sign(row,vector<bool>(col,0));
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
if(helper(board,sign,0,word,i,j)){
return true;
}
}
}
return false;
}
int main(){
string s,word;
cin >> word;
vector<vector<char>> board;
while(cin >> s){
vector<char> oneline;
for(int i=0;i<s.length();i++)
oneline.push_back(s[i]);
board.push_back(oneline);
}
cout<< "Word: " << word << endl;
cout << "Board: "<<endl;
for(vector<char> x : board){
for(char y : x)
cout << y <<" ";
cout << endl;
}
cout << "Res: " << exist(board,word) << endl;
}
|
#include "stdafx.h"
#include "LevelSerializer.h"
//#include "xml/WXXMLHandler.h"
//#include "xml/WXXMLAttributes.h"
/*!
\brief
Handler class used to parse the Scene XML files using SAX2
*/
class SceneXMLHandler : public WX::XMLHandler
{
public:
/*************************************************************************
Construction & Destruction
*************************************************************************/
/**
Constructor for SceneXMLHandler objects
*/
SceneXMLHandler();
/** Destructor for SceneXMLHandler objects */
~SceneXMLHandler();
/** Overridden from XMLHandler */
virtual void characters(const String& chars);
/** Overridden from XMLHandler */
virtual void startElement(const String& element, const WX::XMLAttributes& attributes);
/** Overridden from XMLHandler */
virtual void endElement(const String& element);
};
//////////////////////////////////////////////////////////////////////////
SceneXMLHandler::SceneXMLHandler()
{
}
SceneXMLHandler::~SceneXMLHandler()
{
}
//////////////////////////////////////////////////////////////////////////
void SceneXMLHandler::characters(const String& chars)
{
//if (mString)
//{
// mString->append(chars);
//}
}
//////////////////////////////////////////////////////////////////////////
void SceneXMLHandler::startElement(const String& element, const WX::XMLAttributes& attributes)
{
//if (element == "Property")
//{
// assert(mObject);
// const String* name = &attributes.getValue("name");
// const String& value = attributes.getValue("value");
// if (mPropertyNameMap)
// {
// NameMap::const_iterator it = mPropertyNameMap->find(*name);
// if (it != mPropertyNameMap->end())
// name = &it->second;
// }
// mObject->setPropertyAsString(*name, value);
//}
//else if (element == "Object")
//{
// assert(!mObject);
// const String& type = attributes.getValue("type");
// mObject = ObjectFactoryManager::getSingleton().createInstance(type);
// if (attributes.exists("name"))
// mObject->setName(attributes.getValue("name"));
// else
// mObject->setName(mScene->generateAutoName(mObject));
// mScene->addObject(mObject);
// NameCollectionMap::const_iterator it = mPropertyNameCollectionMap.find(type);
// if (it != mPropertyNameCollectionMap.end())
// {
// mPropertyNameMap = &it->second;
// }
//}
//else if (element == "Attribute")
//{
// assert(!mString);
// mAttributeName = attributes.getValue("name");
// mAttributeValue.clear();
// mString = &mAttributeValue;
//}
//else if (element == "Terrain")
//{
// mScene->mTerrainFilename = attributes.getValue("filename");
//}
//else if (element == "Scene")
//{
// String formatVersion = attributes.getValue("formatVersion");
// if (formatVersion != CURRENT_FORMAT_VERSION &&
// formatVersion != "0.1.0")
// {
// OGRE_EXCEPT(Ogre::Exception::ERR_INTERNAL_ERROR,
// "Unexpected format version was found while parsing the scene file."
// "\nformat version require: " + CURRENT_FORMAT_VERSION +
// "\nformat version in scene file: " + formatVersion,
// "SceneXMLHandler::startElement");
// }
// mScene->mName = attributes.getValueAs<String>("name", Ogre::StringUtil::BLANK);
// if (formatVersion == "0.1.0")
// {
// mPropertyNameCollectionMap.clear();
// NameMap& enviroment = mPropertyNameCollectionMap["Enviroment"];
// enviroment["fog mode"] = "fog.mode";
// enviroment["fog colour"] = "fog.colour";
// enviroment["fog exp density"] = "fog.exp density";
// enviroment["fog linear start"] = "fog.linear start";
// enviroment["fog linear end"] = "fog.linear end";
// }
//}
//else if (element == "Author")
//{
// assert(!mString);
// mString = &mScene->mAuthor;
//}
//else if (element == "Copyright")
//{
// assert(!mString);
// mString = &mScene->mCopyright;
//}
//else if (element == "Description")
//{
// assert(!mString);
// mString = &mScene->mDescription;
//}
//// anything else is an error which *should* have already been caught by XML validation
//else
//{
// OGRE_EXCEPT(Ogre::Exception::ERR_INTERNAL_ERROR,
// "Unexpected data was found while parsing the scene file: '" + element + "' is unknown.",
// "SceneXMLHandler::startElement");
//}
}
void SceneXMLHandler::endElement(const String& element)
{
//if (element == "Object")
//{
// assert(mObject);
// mObject.reset();
// mPropertyNameMap = NULL;
//}
//else if (element == "Attribute")
//{
// assert(mString);
// mString = NULL;
// mScene->setAttribute(mAttributeName, mAttributeValue);
//}
//else if (element == "Author")
//{
// assert(mString);
// mString = NULL;
//}
//else if (element == "Copyright")
//{
// assert(mString);
// mString = NULL;
//}
//else if (element == "Description")
//{
// assert(mString);
// mString = NULL;
//}
}
CLevelSerializer::CLevelSerializer()
{
}
CLevelSerializer::~CLevelSerializer()
{
}
void CLevelSerializer::Load()
{
}
void CLevelSerializer::Save()
{
}
|
#include "alistint_sol.h"
AListInt::AListInt() :
_size(0), _cap(10)
{
_data = new int[_cap];
}
AListInt::AListInt(int cap) :
_size(0), _cap(cap)
{
_data = new int[_cap];
}
AListInt::~AListInt()
{
delete [] _data;
}
bool AListInt::empty() const
{
return _size==0;
}
int AListInt::size() const
{
return _size;
}
void AListInt::insert (int position, const int& val)
{
if(_size+1 > _cap){
resize();
}
for(int i=_size-1; i >= position; --i){
_data[i+1] = _data[i];
}
_data[position] = val;
_size++;
}
void AListInt::remove (int position)
{
for(int i=position; i < _size; i++){
_data[i] = _data[i+1];
}
_size--;
}
void AListInt::set (int position, const int & val)
{
_data[position] = val;
}
int& AListInt::get (int position)
{
return _data[position];
}
int const & AListInt::get (int position) const
{
return _data[position];
}
void AListInt::resize()
{
int* temp = new int[2*_cap];
for(int i=0; i < _size; i++){
temp[i] = _data[i];
}
_cap *= 2;
delete [] _data;
_data = temp;
}
|
#include "config.h"
#include "base.h"
#include "boolean.h"
#include "mul.h"
#include "div.h"
#include "exceptions.h"
#include "barrett.h"
#include "modular.h"
void pow_mod(t_bint* a,
t_bint* b,
t_bint* n,
t_size sizeA,
t_size sizeB,
t_size sizeN) {
if (!sizeB || sizeB > sizeA) {
sizeB = sizeA;
}
if (!sizeN) {
sizeN = sizeA;
}
t_size mswN = msw(n,sizeN) + 1;
t_size sizeMu = mswN * 2 + 1;
t_bint* mu = new t_bint[sizeMu];
setNull(mu,sizeMu);
mu[sizeMu - 1] = 1;
barrettMu(mu, n, sizeMu, sizeN);
mod(a,n,sizeA,sizeN);
barrettMod(a, n, mu, sizeA, sizeN, sizeMu);
if (isNull(a,sizeA) && isNull(b,sizeB)) {
throw URException();
}
else if (isNull(a,sizeA) || cmp(a,1,sizeA) == CMP_EQUAL) {
}
else if (isNull(b,sizeB)) {
setNull(a,sizeA);
a[0] = 1;
return;
}
else {
t_size sizeT = sizeN * 2;
t_size sizeR = sizeN * 2;
t_bint* tmp = new t_bint[sizeT];
t_bint* result = new t_bint[sizeR];
t_size sizeP = sizeB;
t_bint* p = new t_bint[sizeP];
setNull(p,sizeP);
setNull(tmp,sizeT);
setNull(result,sizeR);
result[0] = 1;
mov(p,b,sizeP);
mov(tmp,a,sizeA);
t_bint i = 0;
while (!isNull(p,sizeP)) {
if (p[0] & 1) {
//mulMod(result,tmp,n,sizeR,sizeT,sizeN);
barrettMulMod(result,tmp,n,mu,sizeR,sizeT,sizeN,sizeMu);
}
sqrMod(tmp,n,sizeT,sizeN);
//barrettSqrMod(tmp, n, mu, sizeT, sizeN, sizeMu);
if (isNull(tmp,sizeT)) {
break;
}
else if(cmp(tmp,1,sizeT) == CMP_EQUAL) {
break;
}
shr(p,1,sizeP);
i++;
}
mov(a,result,sizeA);
mod(a,n,sizeA,sizeN);
//barrettMod(a, n, mu, sizeA, sizeN, sizeMu);
delete[] tmp;
delete[] result;
delete[] p;
delete[] mu;
}
}
void mulMod(t_bint* a,
t_bint* b,
t_bint* n,
t_size sizeA,
t_size sizeB,
t_size sizeN) {
mod(a,n,sizeA,sizeN);
mul(a,b,sizeA,sizeB);
mod(a,n,sizeA,sizeN);
}
void sqrMod(t_bint* a, t_bint* n, t_size sizeA, t_size sizeN) {
sqr(a,sizeA);
mod(a,n,sizeA,sizeN);
}
void barrettMulMod(t_bint* a,
t_bint* b,
t_bint* n,
t_bint* mu,
t_size sizeA,
t_size sizeB,
t_size sizeN,
t_size sizeMu) {
barrettMod(a,n,mu,sizeA,sizeN,sizeMu);
mul(a,b,sizeA,sizeB);
barrettMod(a,n,mu,sizeA,sizeN,sizeMu);
}
void barrettSqrMod(t_bint* a, t_bint* n, t_bint* mu, t_size sizeA,
t_size sizeN, t_size sizeMu) {
sqr(a,sizeA);
barrettMod(a, n, mu, sizeA, sizeN, sizeMu);
}
|
#include "pch.h"
#include "animation.h"
animation::animation(int x, int y, char s) {
this->x = x;
this->y = y;
end_char = s;
}
void animation::draw_animation(char field[10][10]) {
}
|
/*****************************************************************************************************************
* File Name : NthNodeFromEnd.h
* File Location : C:\Users\AVINASH\Desktop\CC++\Programming\src\sites\geeksforgeeks\linkedlist\page05\NthNodeFromEnd.h
* Created on : Dec 17, 2013 :: 11:39:02 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 NTHNODEFROMEND_H_
#define NTHNODEFROMEND_H_
llNode *getNthNodeFromEndIterative(llNode *ptr,unsigned int nValue){
if(ptr == NULL){
return NULL;
}
unsigned int length = 0;
llNode *traversalPtr = ptr;
while(traversalPtr != NULL){
length++;
traversalPtr = traversalPtr->next;
}
if(nValue > length){
return NULL;
}
length = length - nValue;
traversalPtr = ptr;
while(length--){
traversalPtr = traversalPtr->next;
}
return traversalPtr;
}
llNode *getNthNodeFromEndAuxspace(llNode *ptr,unsigned int nValue){
if(ptr == NULL){
return NULL;
}
stack<llNode *> auxSpace;
llNode *traversalPtr = ptr;
while(traversalPtr != NULL){
auxSpace.push(traversalPtr);
traversalPtr = traversalPtr->next;
}
while(!auxSpace.empty()){
if(nValue == 0){
return auxSpace.top();
}
nValue -= 1;
auxSpace.pop();
}
return NULL;
}
llNode *getNthNodeFromEnd(llNode *ptr,unsigned int &nValue){
if(ptr == NULL){
return NULL;
}
llNode *result = getNthNodeFromEnd(ptr->next,nValue);
if(result != NULL){
return result;
}
nValue -= 1;
return nValue == 0?ptr:NULL;
}
llNode *getNthNodeFromEndHashmap(llNode *ptr,unsigned int nValue){
if(ptr == NULL){
return NULL;
}
unsigned int index = 0;
hash_map<unsigned int,llNode *> indexNodeMap;
hash_map<unsigned int,llNode *>::iterator itToIndexNodeMap;
llNode *traversalPtr = ptr;
while(traversalPtr != NULL){
indexNodeMap.insert(pair<unsigned int,llNode *>(index,traversalPtr));
traversalPtr = traversalPtr->next;
index++;
}
index -= 1;
itToIndexNodeMap = indexNodeMap.find(nValue);
return itToIndexNodeMap == indexNodeMap.end()?NULL:itToIndexNodeMap->second;
}
#endif /* NTHNODEFROMEND_H_ */
/************************************************* End code *******************************************************/
|
#include <iostream>
#include <set>
#include <string>
using namespace std;
class SetStringer {
public:
void insert(double x) { m_set.insert(x); m_cached = false; }
const string & str() & {
if (m_cached) { return m_string; }
m_string.clear();
for (const auto & x : m_set) {
m_string += to_string(x) + "\n";
}
m_cached = true;
return m_string;
}
string && str() && {
this->str();
m_cached = false;
m_set.clear();
return move(m_string);
}
private:
set<double> m_set;
string m_string;
bool m_cached = false;
};
int main()
{
SetStringer foo;
// ... add stuff to foo
foo.insert(3.14);
foo.insert(2.36);
std::cout << foo.str() << std::endl << "============" << std::endl;
string s = move(foo).str(); // Stealing succeeds!
cerr << foo.str() << "============" << std::endl; // this probably prints empty
foo.insert(5.0);
cerr << foo.str(); // err, what?
return 0;
}
|
/***********************************************************************
qwertyScreen :
encapsulation of screen physical description/mesh descriptor
*************************************************************************/
#include "Screen.h"
qwerty::Screen::Screen()
{
//device related param must be queried via operating system
HDC hdc = ::GetDC(0);
//The width/height of the screen of the primary display monitor, in pixels
mPhysicalWidth= ::GetDeviceCaps(hdc, HORZSIZE);
mPhysicalHeight = ::GetDeviceCaps(hdc, VERTSIZE);
}
int qwerty::Screen::GetPhysicalWidth()
{
return mPhysicalWidth;
}
int qwerty::Screen::GetPhysicalHeight()
{
return mPhysicalHeight;
}
|
// Shortest path algorithm using stl
#include <bits/stdc++.h>
#define ASCII_CAP 65 //Capital letter A
#define COL_WIDTH 15
using namespace std;
enum Algorithm{SHP, SDP, STP, FTP, MGP};
// Convert capital letter to int
int ctoi(char a){
return (int)a - ASCII_CAP;
}
class Graph{
// number of vertices
int v;
// adjacency list
map< char, vector<int> > *adj;
public:
// Constructor
Graph(int v){
adj = new map< char, vector<int> >[v];
}
~Graph(){
delete[] adj;
}
// Print for debugging
void print(){
map<char, vector<int>>::iterator i;
for(i = adj.begin(); i != adj.end(); i++){
cout << i->first << endl;
for (int j = 0; j < 4; j++)
cout << i->second[j] << " ";
}
cout << endl;
}
// Add edge to adjacency list
void add_edge(char a, char b, vector<int> weights){
adj[ctoi(a)].insert(make_pair(a, weights));
adj[ctoi(b)].insert(make_pair(b, weights));
}
// Returns shortest path
vector<char> shortest_path(char bilbo, char dwarf, int algo){
// Initialize and set all distances to infinity
set< pair<char, int> > v_set;
vector<int> dist(v, INT_MAX);
vector<char> path(v);
// Add bilbo's position as 0
v_set.insert(make_pair(0, bilbo));
dist[ctoi(bilbo)] = 0;
//TODO: finish shortest path algorithm
}
};
int main(){
// Initialize input variables
list< pair<string, char> > addr;
pair <string, char> bilbo;
string algo_string, addr_file, map_file;
int algo = -1;
int vertices = 0;
// Temporary variables
string s1;
char c1, c2;
vector<int> iv(4);
// Get routing algorithm from user
while(algo < 0){
cout << "Enter routing algorithm (SHP, SDP, STP, FTP, MGP): ";
cin >> algo_string;
if(!algo_string.compare("SHP"))
algo = SHP;
else if(!algo_string.compare("SDP"))
algo = SDP;
else if(!algo_string.compare("STP"))
algo = STP;
else if(!algo_string.compare("FTP"))
algo = FTP;
else if(!algo_string.compare("MGP"))
algo = MGP;
else
cout << "Algorithm not valid. Try again.\n";
}
// Get addresses
cout << "Enter address file: ";
cin >> addr_file;
ifstream ifs;
ifs.open(addr_file, ifstream::in);
if(ifs.fail()){
cout << "Could not open file " << addr_file << ".\n";
return -1;
}
// Put addresses in list
while(ifs >> s1 >> c1){
addr.push_back(make_pair(s1,c1));
}
ifs.close();
// Get map
cout << "Enter map file: ";
cin >> map_file;
ifs.open(map_file);
if(ifs.fail()){
cout << "Could not open file " << map_file << ".\n";
return -1;
}
// Determine number of vertices
vertices = count(istreambuf_iterator<char>(ifs),
istreambuf_iterator<char>(), '\n') + 1;
// Create Graph
Graph dwarf_graph(vertices);
// Fill adjacency list
while(ifs >> c1 >> c2 >> iv[0] >> iv[1] >> iv[2] >> iv[3]){
dwarf_graph.add_edge(c1, c2, iv);
}
dwarf_graph.print();
ifs.close();
return 0;
}
|
/********************************************************************************
** Form generated from reading UI file 'SVP.ui'
**
** Created by: Qt User Interface Compiler version 5.8.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_SVP_H
#define UI_SVP_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QCheckBox>
#include <QtWidgets/QGroupBox>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QMenuBar>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QRadioButton>
#include <QtWidgets/QStatusBar>
#include <QtWidgets/QToolBar>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_SVPClass
{
public:
QWidget *centralWidget;
QHBoxLayout *horizontalLayout_2;
QHBoxLayout *horizontalLayout;
QLabel *drawLabel;
QWidget *widget_4;
QVBoxLayout *verticalLayout_6;
QWidget *widget_13;
QVBoxLayout *verticalLayout_19;
QGroupBox *groupBoxColour;
QVBoxLayout *verticalLayout_18;
QWidget *widget_23;
QVBoxLayout *verticalLayout_17;
QRadioButton *radioColourOne;
QWidget *widget_24;
QVBoxLayout *verticalLayout_16;
QRadioButton *radioColourTwo;
QWidget *widget_25;
QHBoxLayout *horizontalLayout_6;
QWidget *widgetColourOne;
QLabel *labelColourOne;
QWidget *widget_20;
QHBoxLayout *horizontalLayout_10;
QWidget *widgetColourTwo;
QLabel *labelColourTwo;
QWidget *widget_5;
QVBoxLayout *verticalLayout_7;
QCheckBox *checkArrows;
QWidget *widget_6;
QVBoxLayout *verticalLayout_8;
QWidget *widget_7;
QVBoxLayout *verticalLayout_9;
QPushButton *buttonVar;
QWidget *widget_21;
QWidget *widget_12;
QVBoxLayout *verticalLayout_11;
QPushButton *buttonRedraw;
QWidget *widget_27;
QMenuBar *menuBar;
QToolBar *mainToolBar;
QStatusBar *statusBar;
void setupUi(QMainWindow *SVPClass)
{
if (SVPClass->objectName().isEmpty())
SVPClass->setObjectName(QStringLiteral("SVPClass"));
SVPClass->resize(949, 711);
centralWidget = new QWidget(SVPClass);
centralWidget->setObjectName(QStringLiteral("centralWidget"));
horizontalLayout_2 = new QHBoxLayout(centralWidget);
horizontalLayout_2->setSpacing(6);
horizontalLayout_2->setContentsMargins(11, 11, 11, 11);
horizontalLayout_2->setObjectName(QStringLiteral("horizontalLayout_2"));
horizontalLayout = new QHBoxLayout();
horizontalLayout->setSpacing(6);
horizontalLayout->setObjectName(QStringLiteral("horizontalLayout"));
drawLabel = new QLabel(centralWidget);
drawLabel->setObjectName(QStringLiteral("drawLabel"));
horizontalLayout->addWidget(drawLabel);
widget_4 = new QWidget(centralWidget);
widget_4->setObjectName(QStringLiteral("widget_4"));
widget_4->setMaximumSize(QSize(200, 16777215));
verticalLayout_6 = new QVBoxLayout(widget_4);
verticalLayout_6->setSpacing(6);
verticalLayout_6->setContentsMargins(11, 11, 11, 11);
verticalLayout_6->setObjectName(QStringLiteral("verticalLayout_6"));
widget_13 = new QWidget(widget_4);
widget_13->setObjectName(QStringLiteral("widget_13"));
widget_13->setMaximumSize(QSize(16777215, 210));
verticalLayout_19 = new QVBoxLayout(widget_13);
verticalLayout_19->setSpacing(6);
verticalLayout_19->setContentsMargins(11, 11, 11, 11);
verticalLayout_19->setObjectName(QStringLiteral("verticalLayout_19"));
groupBoxColour = new QGroupBox(widget_13);
groupBoxColour->setObjectName(QStringLiteral("groupBoxColour"));
groupBoxColour->setCheckable(true);
verticalLayout_18 = new QVBoxLayout(groupBoxColour);
verticalLayout_18->setSpacing(6);
verticalLayout_18->setContentsMargins(11, 11, 11, 11);
verticalLayout_18->setObjectName(QStringLiteral("verticalLayout_18"));
widget_23 = new QWidget(groupBoxColour);
widget_23->setObjectName(QStringLiteral("widget_23"));
verticalLayout_17 = new QVBoxLayout(widget_23);
verticalLayout_17->setSpacing(6);
verticalLayout_17->setContentsMargins(11, 11, 11, 11);
verticalLayout_17->setObjectName(QStringLiteral("verticalLayout_17"));
radioColourOne = new QRadioButton(widget_23);
radioColourOne->setObjectName(QStringLiteral("radioColourOne"));
radioColourOne->setChecked(true);
verticalLayout_17->addWidget(radioColourOne);
verticalLayout_18->addWidget(widget_23);
widget_24 = new QWidget(groupBoxColour);
widget_24->setObjectName(QStringLiteral("widget_24"));
verticalLayout_16 = new QVBoxLayout(widget_24);
verticalLayout_16->setSpacing(6);
verticalLayout_16->setContentsMargins(11, 11, 11, 11);
verticalLayout_16->setObjectName(QStringLiteral("verticalLayout_16"));
radioColourTwo = new QRadioButton(widget_24);
radioColourTwo->setObjectName(QStringLiteral("radioColourTwo"));
verticalLayout_16->addWidget(radioColourTwo);
verticalLayout_18->addWidget(widget_24);
widget_25 = new QWidget(groupBoxColour);
widget_25->setObjectName(QStringLiteral("widget_25"));
horizontalLayout_6 = new QHBoxLayout(widget_25);
horizontalLayout_6->setSpacing(6);
horizontalLayout_6->setContentsMargins(11, 11, 11, 11);
horizontalLayout_6->setObjectName(QStringLiteral("horizontalLayout_6"));
widgetColourOne = new QWidget(widget_25);
widgetColourOne->setObjectName(QStringLiteral("widgetColourOne"));
widgetColourOne->setMaximumSize(QSize(20, 20));
QPalette palette;
QBrush brush(QColor(0, 0, 0, 255));
brush.setStyle(Qt::SolidPattern);
palette.setBrush(QPalette::Active, QPalette::WindowText, brush);
QBrush brush1(QColor(255, 0, 0, 255));
brush1.setStyle(Qt::SolidPattern);
palette.setBrush(QPalette::Active, QPalette::Button, brush1);
QBrush brush2(QColor(255, 127, 127, 255));
brush2.setStyle(Qt::SolidPattern);
palette.setBrush(QPalette::Active, QPalette::Light, brush2);
QBrush brush3(QColor(255, 63, 63, 255));
brush3.setStyle(Qt::SolidPattern);
palette.setBrush(QPalette::Active, QPalette::Midlight, brush3);
QBrush brush4(QColor(127, 0, 0, 255));
brush4.setStyle(Qt::SolidPattern);
palette.setBrush(QPalette::Active, QPalette::Dark, brush4);
QBrush brush5(QColor(170, 0, 0, 255));
brush5.setStyle(Qt::SolidPattern);
palette.setBrush(QPalette::Active, QPalette::Mid, brush5);
palette.setBrush(QPalette::Active, QPalette::Text, brush);
QBrush brush6(QColor(255, 255, 255, 255));
brush6.setStyle(Qt::SolidPattern);
palette.setBrush(QPalette::Active, QPalette::BrightText, brush6);
palette.setBrush(QPalette::Active, QPalette::ButtonText, brush);
palette.setBrush(QPalette::Active, QPalette::Base, brush6);
palette.setBrush(QPalette::Active, QPalette::Window, brush1);
palette.setBrush(QPalette::Active, QPalette::Shadow, brush);
palette.setBrush(QPalette::Active, QPalette::AlternateBase, brush2);
QBrush brush7(QColor(255, 255, 220, 255));
brush7.setStyle(Qt::SolidPattern);
palette.setBrush(QPalette::Active, QPalette::ToolTipBase, brush7);
palette.setBrush(QPalette::Active, QPalette::ToolTipText, brush);
palette.setBrush(QPalette::Inactive, QPalette::WindowText, brush);
palette.setBrush(QPalette::Inactive, QPalette::Button, brush1);
palette.setBrush(QPalette::Inactive, QPalette::Light, brush2);
palette.setBrush(QPalette::Inactive, QPalette::Midlight, brush3);
palette.setBrush(QPalette::Inactive, QPalette::Dark, brush4);
palette.setBrush(QPalette::Inactive, QPalette::Mid, brush5);
palette.setBrush(QPalette::Inactive, QPalette::Text, brush);
palette.setBrush(QPalette::Inactive, QPalette::BrightText, brush6);
palette.setBrush(QPalette::Inactive, QPalette::ButtonText, brush);
palette.setBrush(QPalette::Inactive, QPalette::Base, brush6);
palette.setBrush(QPalette::Inactive, QPalette::Window, brush1);
palette.setBrush(QPalette::Inactive, QPalette::Shadow, brush);
palette.setBrush(QPalette::Inactive, QPalette::AlternateBase, brush2);
palette.setBrush(QPalette::Inactive, QPalette::ToolTipBase, brush7);
palette.setBrush(QPalette::Inactive, QPalette::ToolTipText, brush);
palette.setBrush(QPalette::Disabled, QPalette::WindowText, brush4);
palette.setBrush(QPalette::Disabled, QPalette::Button, brush1);
palette.setBrush(QPalette::Disabled, QPalette::Light, brush2);
palette.setBrush(QPalette::Disabled, QPalette::Midlight, brush3);
palette.setBrush(QPalette::Disabled, QPalette::Dark, brush4);
palette.setBrush(QPalette::Disabled, QPalette::Mid, brush5);
palette.setBrush(QPalette::Disabled, QPalette::Text, brush4);
palette.setBrush(QPalette::Disabled, QPalette::BrightText, brush6);
palette.setBrush(QPalette::Disabled, QPalette::ButtonText, brush4);
palette.setBrush(QPalette::Disabled, QPalette::Base, brush1);
palette.setBrush(QPalette::Disabled, QPalette::Window, brush1);
palette.setBrush(QPalette::Disabled, QPalette::Shadow, brush);
palette.setBrush(QPalette::Disabled, QPalette::AlternateBase, brush1);
palette.setBrush(QPalette::Disabled, QPalette::ToolTipBase, brush7);
palette.setBrush(QPalette::Disabled, QPalette::ToolTipText, brush);
widgetColourOne->setPalette(palette);
widgetColourOne->setAutoFillBackground(true);
horizontalLayout_6->addWidget(widgetColourOne);
labelColourOne = new QLabel(widget_25);
labelColourOne->setObjectName(QStringLiteral("labelColourOne"));
horizontalLayout_6->addWidget(labelColourOne);
verticalLayout_18->addWidget(widget_25);
widget_20 = new QWidget(groupBoxColour);
widget_20->setObjectName(QStringLiteral("widget_20"));
horizontalLayout_10 = new QHBoxLayout(widget_20);
horizontalLayout_10->setSpacing(6);
horizontalLayout_10->setContentsMargins(11, 11, 11, 11);
horizontalLayout_10->setObjectName(QStringLiteral("horizontalLayout_10"));
widgetColourTwo = new QWidget(widget_20);
widgetColourTwo->setObjectName(QStringLiteral("widgetColourTwo"));
widgetColourTwo->setMaximumSize(QSize(20, 20));
QPalette palette1;
palette1.setBrush(QPalette::Active, QPalette::WindowText, brush);
QBrush brush8(QColor(0, 0, 255, 255));
brush8.setStyle(Qt::SolidPattern);
palette1.setBrush(QPalette::Active, QPalette::Button, brush8);
QBrush brush9(QColor(127, 127, 255, 255));
brush9.setStyle(Qt::SolidPattern);
palette1.setBrush(QPalette::Active, QPalette::Light, brush9);
QBrush brush10(QColor(63, 63, 255, 255));
brush10.setStyle(Qt::SolidPattern);
palette1.setBrush(QPalette::Active, QPalette::Midlight, brush10);
QBrush brush11(QColor(0, 0, 127, 255));
brush11.setStyle(Qt::SolidPattern);
palette1.setBrush(QPalette::Active, QPalette::Dark, brush11);
QBrush brush12(QColor(0, 0, 170, 255));
brush12.setStyle(Qt::SolidPattern);
palette1.setBrush(QPalette::Active, QPalette::Mid, brush12);
palette1.setBrush(QPalette::Active, QPalette::Text, brush);
palette1.setBrush(QPalette::Active, QPalette::BrightText, brush6);
palette1.setBrush(QPalette::Active, QPalette::ButtonText, brush);
palette1.setBrush(QPalette::Active, QPalette::Base, brush6);
palette1.setBrush(QPalette::Active, QPalette::Window, brush8);
palette1.setBrush(QPalette::Active, QPalette::Shadow, brush);
palette1.setBrush(QPalette::Active, QPalette::AlternateBase, brush9);
palette1.setBrush(QPalette::Active, QPalette::ToolTipBase, brush7);
palette1.setBrush(QPalette::Active, QPalette::ToolTipText, brush);
palette1.setBrush(QPalette::Inactive, QPalette::WindowText, brush);
palette1.setBrush(QPalette::Inactive, QPalette::Button, brush8);
palette1.setBrush(QPalette::Inactive, QPalette::Light, brush9);
palette1.setBrush(QPalette::Inactive, QPalette::Midlight, brush10);
palette1.setBrush(QPalette::Inactive, QPalette::Dark, brush11);
palette1.setBrush(QPalette::Inactive, QPalette::Mid, brush12);
palette1.setBrush(QPalette::Inactive, QPalette::Text, brush);
palette1.setBrush(QPalette::Inactive, QPalette::BrightText, brush6);
palette1.setBrush(QPalette::Inactive, QPalette::ButtonText, brush);
palette1.setBrush(QPalette::Inactive, QPalette::Base, brush6);
palette1.setBrush(QPalette::Inactive, QPalette::Window, brush8);
palette1.setBrush(QPalette::Inactive, QPalette::Shadow, brush);
palette1.setBrush(QPalette::Inactive, QPalette::AlternateBase, brush9);
palette1.setBrush(QPalette::Inactive, QPalette::ToolTipBase, brush7);
palette1.setBrush(QPalette::Inactive, QPalette::ToolTipText, brush);
palette1.setBrush(QPalette::Disabled, QPalette::WindowText, brush11);
palette1.setBrush(QPalette::Disabled, QPalette::Button, brush8);
palette1.setBrush(QPalette::Disabled, QPalette::Light, brush9);
palette1.setBrush(QPalette::Disabled, QPalette::Midlight, brush10);
palette1.setBrush(QPalette::Disabled, QPalette::Dark, brush11);
palette1.setBrush(QPalette::Disabled, QPalette::Mid, brush12);
palette1.setBrush(QPalette::Disabled, QPalette::Text, brush11);
palette1.setBrush(QPalette::Disabled, QPalette::BrightText, brush6);
palette1.setBrush(QPalette::Disabled, QPalette::ButtonText, brush11);
palette1.setBrush(QPalette::Disabled, QPalette::Base, brush8);
palette1.setBrush(QPalette::Disabled, QPalette::Window, brush8);
palette1.setBrush(QPalette::Disabled, QPalette::Shadow, brush);
palette1.setBrush(QPalette::Disabled, QPalette::AlternateBase, brush8);
palette1.setBrush(QPalette::Disabled, QPalette::ToolTipBase, brush7);
palette1.setBrush(QPalette::Disabled, QPalette::ToolTipText, brush);
widgetColourTwo->setPalette(palette1);
widgetColourTwo->setAutoFillBackground(true);
horizontalLayout_10->addWidget(widgetColourTwo);
labelColourTwo = new QLabel(widget_20);
labelColourTwo->setObjectName(QStringLiteral("labelColourTwo"));
horizontalLayout_10->addWidget(labelColourTwo);
verticalLayout_18->addWidget(widget_20);
verticalLayout_19->addWidget(groupBoxColour);
verticalLayout_6->addWidget(widget_13);
widget_5 = new QWidget(widget_4);
widget_5->setObjectName(QStringLiteral("widget_5"));
widget_5->setMaximumSize(QSize(16777215, 40));
verticalLayout_7 = new QVBoxLayout(widget_5);
verticalLayout_7->setSpacing(6);
verticalLayout_7->setContentsMargins(11, 11, 11, 11);
verticalLayout_7->setObjectName(QStringLiteral("verticalLayout_7"));
checkArrows = new QCheckBox(widget_5);
checkArrows->setObjectName(QStringLiteral("checkArrows"));
verticalLayout_7->addWidget(checkArrows);
verticalLayout_6->addWidget(widget_5);
widget_6 = new QWidget(widget_4);
widget_6->setObjectName(QStringLiteral("widget_6"));
widget_6->setMaximumSize(QSize(16777215, 40));
verticalLayout_8 = new QVBoxLayout(widget_6);
verticalLayout_8->setSpacing(6);
verticalLayout_8->setContentsMargins(11, 11, 11, 11);
verticalLayout_8->setObjectName(QStringLiteral("verticalLayout_8"));
verticalLayout_6->addWidget(widget_6);
widget_7 = new QWidget(widget_4);
widget_7->setObjectName(QStringLiteral("widget_7"));
widget_7->setMaximumSize(QSize(16777215, 40));
verticalLayout_9 = new QVBoxLayout(widget_7);
verticalLayout_9->setSpacing(6);
verticalLayout_9->setContentsMargins(11, 11, 11, 11);
verticalLayout_9->setObjectName(QStringLiteral("verticalLayout_9"));
buttonVar = new QPushButton(widget_7);
buttonVar->setObjectName(QStringLiteral("buttonVar"));
verticalLayout_9->addWidget(buttonVar);
verticalLayout_6->addWidget(widget_7);
widget_21 = new QWidget(widget_4);
widget_21->setObjectName(QStringLiteral("widget_21"));
widget_21->setMaximumSize(QSize(16777215, 40));
verticalLayout_6->addWidget(widget_21);
widget_12 = new QWidget(widget_4);
widget_12->setObjectName(QStringLiteral("widget_12"));
widget_12->setMaximumSize(QSize(16777215, 40));
verticalLayout_11 = new QVBoxLayout(widget_12);
verticalLayout_11->setSpacing(6);
verticalLayout_11->setContentsMargins(11, 11, 11, 11);
verticalLayout_11->setObjectName(QStringLiteral("verticalLayout_11"));
buttonRedraw = new QPushButton(widget_12);
buttonRedraw->setObjectName(QStringLiteral("buttonRedraw"));
verticalLayout_11->addWidget(buttonRedraw);
verticalLayout_6->addWidget(widget_12);
widget_27 = new QWidget(widget_4);
widget_27->setObjectName(QStringLiteral("widget_27"));
verticalLayout_6->addWidget(widget_27);
horizontalLayout->addWidget(widget_4);
horizontalLayout_2->addLayout(horizontalLayout);
SVPClass->setCentralWidget(centralWidget);
menuBar = new QMenuBar(SVPClass);
menuBar->setObjectName(QStringLiteral("menuBar"));
menuBar->setGeometry(QRect(0, 0, 949, 21));
SVPClass->setMenuBar(menuBar);
mainToolBar = new QToolBar(SVPClass);
mainToolBar->setObjectName(QStringLiteral("mainToolBar"));
SVPClass->addToolBar(Qt::TopToolBarArea, mainToolBar);
statusBar = new QStatusBar(SVPClass);
statusBar->setObjectName(QStringLiteral("statusBar"));
SVPClass->setStatusBar(statusBar);
retranslateUi(SVPClass);
buttonVar->setDefault(false);
QMetaObject::connectSlotsByName(SVPClass);
} // setupUi
void retranslateUi(QMainWindow *SVPClass)
{
SVPClass->setWindowTitle(QApplication::translate("SVPClass", "SVP", Q_NULLPTR));
drawLabel->setText(QString());
groupBoxColour->setTitle(QApplication::translate("SVPClass", "Farben", Q_NULLPTR));
radioColourOne->setText(QApplication::translate("SVPClass", "Fabrkanal 1", Q_NULLPTR));
radioColourTwo->setText(QApplication::translate("SVPClass", "Farbkanal 2", Q_NULLPTR));
labelColourOne->setText(QApplication::translate("SVPClass", "Farbe 1", Q_NULLPTR));
labelColourTwo->setText(QApplication::translate("SVPClass", "Farbe 2", Q_NULLPTR));
checkArrows->setText(QApplication::translate("SVPClass", "Pfeile", Q_NULLPTR));
buttonVar->setText(QApplication::translate("SVPClass", "Plot Variability", Q_NULLPTR));
buttonRedraw->setText(QApplication::translate("SVPClass", "Draw Lines", Q_NULLPTR));
} // retranslateUi
};
namespace Ui {
class SVPClass: public Ui_SVPClass {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_SVP_H
|
/*! @file SDPSDcrystal.cc
@brief Implements sensitive part (Crystals) of simulation.
@date March,2015
@author D. Flechas (dcflechasg@unal.edu.co)
*/
/* no-geant4 classes*/
#include "SDPSDcrystal.hh"
#include "PSDcrystalHit.hh"
/* geant4 classes*/
#include "G4VPhysicalVolume.hh"
#include "G4LogicalVolume.hh"
#include "G4Track.hh"
#include "G4Step.hh"
#include "G4ParticleDefinition.hh"
#include "G4VTouchable.hh"
#include "G4TouchableHistory.hh"
#include "G4ios.hh"
#include "G4VProcess.hh"
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
SDPSDcrystal::SDPSDcrystal(G4String name, G4int fNPixels)
: G4VSensitiveDetector(name),gammaID(-1),NPixels(fNPixels)
{
fPSDcrystalHitsCollection = NULL;
collectionName.insert("psdcrystalHCollection");
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
SDPSDcrystal::~SDPSDcrystal() {}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void SDPSDcrystal::Initialize(G4HCofThisEvent* hitsCE){
//G4cout<<"SDcrystal in"<<G4endl;
fPSDcrystalHitsCollection = new PSDcrystalHitsCollection
(SensitiveDetectorName,collectionName[0]);
//G4cout<<"SDcrystal out"<<G4endl;
//A way to keep all the hits of this event in one place if needed
static G4int hitsCID = -1;
if(hitsCID<0){
hitsCID = GetCollectionID(0);
}
hitsCE->AddHitsCollection( hitsCID, fPSDcrystalHitsCollection );
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
G4bool SDPSDcrystal::ProcessHits(G4Step* aStep,G4TouchableHistory* ){
G4double edep = aStep->GetTotalEnergyDeposit();
if(edep==0.) return false; //No edep so dont count as hit
G4StepPoint* thePrePoint = aStep->GetPreStepPoint();
G4TouchableHistory* theTouchable =
(G4TouchableHistory*)(aStep->GetPreStepPoint()->GetTouchable());
G4VPhysicalVolume* thePrePV = theTouchable->GetVolume();
G4StepPoint* thePostPoint = aStep->GetPostStepPoint();
// Particle name
G4String particleName = aStep->GetTrack()->GetDefinition()->GetParticleName();
// Creator process name
G4String CreatorProcessName = "NONE";
// Process name of the interaction, defined at the post estep point
G4String ProcessName = thePostPoint->GetProcessDefinedStep()->GetProcessName();
//check if step is due to primary particle: it has track ID 1 and parent 0
// The primary is the track with ID 1 and with no parent
G4bool isPrimary = ( aStep->GetTrack()->GetTrackID() == 1 && aStep->GetTrack()->GetParentID() == 0 ) ? true : false;
/// *** Gamma ID *** ///
gammaID=-1;
/// 0 : primary particle = gamma rays
/// 1 : origin = radiactive decay (example: 1275 keV (22Ne), 662 keV (137Cs))
/// 2 : origin = positron annihilation
/// 3 : other particles
if(isPrimary && particleName.contains("gamma"))
gammaID=0;
else
{
CreatorProcessName = aStep->GetTrack()->GetCreatorProcess()->GetProcessName();
//!* Gamma ray emitted due radioactive decay: In addition, an energy condition could be necessary
if( CreatorProcessName == "RadioactiveDecay" && particleName.contains("gamma") )
gammaID = 1;
//!* Gamma rays from positron annihilation
else if( CreatorProcessName =="annihil" && particleName.contains("gamma") )
gammaID = 2;
else
gammaID = 3;
}
/* detector ID */
G4int detector_ID=-1;
/// detector_ID = 0 -> BSDdetector
if(detector_ID==-1)
{
if(thePrePV->GetName().contains("PSD"))
{
G4int y = theTouchable->GetReplicaNumber(0); /* along +Y axis */
G4int x = theTouchable->GetReplicaNumber(1); /* along +X axis */
detector_ID = x + y*NPixels + 1; /// 1 and NPixels*NPixels are first one and last one
if( detector_ID<1 || detector_ID >= NPixels*NPixels+1)
{
G4cout<<"\nPOSITION: "<<"\tx = "<<x<<"\ty = "<<y<<G4endl;
G4cout<<"error with "<<thePrePV->GetName()<<"\t detector_ID = "<<detector_ID<<G4endl;
return false;
}
}
else
{
G4cout<<"SDPSDcrystal::ProcessHits: ERROR: Detector ID has not been assigned -> Detector not found"<<G4endl;
return false;
}
}
//Get the average position of the hit
G4ThreeVector pos = thePrePoint->GetPosition() + thePostPoint->GetPosition();
pos/=2.;
// store global and local time
G4double local_time = aStep->GetPostStepPoint()-> GetLocalTime();
G4double global_time = aStep->GetPostStepPoint()->GetGlobalTime();
PSDcrystalHit* crystalHit = new PSDcrystalHit(thePrePV,detector_ID,gammaID,isPrimary);
crystalHit->SetEdep(edep);
crystalHit->SetPos(pos);
crystalHit->SetLocalTime(local_time);
crystalHit->SetGlobalTime(global_time);
if(thePostPoint->GetProcessDefinedStep()->GetProcessName()=="phot")
crystalHit->SetFlagPhotoelectric(true);
//crystalHit->Print();
fPSDcrystalHitsCollection->insert(crystalHit);
return true;
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void SDPSDcrystal::EndOfEvent(G4HCofThisEvent* ) {}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void SDPSDcrystal::clear() {}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void SDPSDcrystal::DrawAll() {}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void SDPSDcrystal::PrintAll() {}
|
#include <cstdio>
#include <algorithm>
class Elephant{
private:
int index, Weight, Smart;
public:
Elephant();
Elephant(int, int, int);
//~Elephant();
int get_index();
int get_Weight();
int get_Smart();
bool operator < (Elephant X) const{
if(Weight != X.Weight) return Weight < X.Weight;
return Smart > X.Smart;
}
};
Elephant::Elephant() {}
Elephant::Elephant(int _index, int _Weight, int _Smart) {
index = _index;
Weight = _Weight;
Smart = _Smart;
}
int Elephant::get_index() {
return index;
}
int Elephant::get_Weight() {
return Weight;
}
int Elephant::get_Smart() {
return Smart;
}
int main(){
int n = 0, Weight, Smart;
Elephant elephants[1000];
while(scanf("%d %d", &Weight, &Smart) == 2) {
elephants[n] = Elephant(++n, Weight, Smart);
}
std::sort(elephants, elephants+n);
int dp[n], next[n], ans = 0, start;
for(int i = n-1; i >= 0; i--){
dp[i] = 1;
next[i] = -1;
for(int j = i + 1; j < n; j++){
if(elephants[i].get_Weight() < elephants[j].get_Weight() && elephants[i].get_Smart() > elephants[j].get_Smart() && 1+dp[j] > dp[i]){
dp[i] = 1 + dp[j];
next[i] = j;
}
}
if(dp[i] > ans){
ans = dp[i];
start = i;
}
}
printf("%d\n", ans);
for(int i = start; i != -1; i = next[i]) printf("%d\n", elephants[i].get_index());
return 0;
}
|
#ifndef _SPRITE_AI_ENGINE_H_
#define _SPRITE_AI_ENGINE_H_
class VertexInterface;
class CharacterInterface;
#include "observerlist.h"
#include "ailist.h"
namespace {
class SpriteAIengine
{
public:
SpriteAIengine();
~SpriteAIengine();
virtual bool movep(VertexInterface*);
virtual void move(VertexInterface*);
virtual bool strengthp(CharacterInterface*);
virtual void strength(CharacterInterface*);
virtual bool dexterityp(CharacterInterface*);
virtual void dexterity(CharacterInterface*);
virtual bool intelligencep(CharacterInterface*);
virtual void intelligence(CharacterInterface*);
private:
static AIlist _ailist;
};
AIlist SpriteAIengine::_ailist;
}
#endif
|
// [[Rcpp::depends(rstan)]]
// [[Rcpp::depends(RcppEigen)]]
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::plugins(cpp11)]]
#include <RcppArmadillo.h>
#include <stan/math.hpp>
#include <Eigen/Dense>
#include <RcppEigen.h>
#include <Rcpp.h>
using namespace arma;
using namespace std;
using Eigen::Matrix;
using Eigen::Dynamic;
using Eigen::MatrixXd;
using Eigen::Map;
struct scaleT {
const vec scale;
const vec df;
scaleT(const vec scIn, const vec dfIn) :
scale(scIn), df(dfIn) {}
template <typename T> //
T operator ()(const Matrix<T, Dynamic, 1>& theta)
const{
using std::log; using std::exp; using std::pow; using std::sqrt; using std::fabs; using std::lgamma;
int dim = theta.rows();
T logDens = 0;
for(int i = 0; i < dim; ++i){
logDens += - log(scale(i)) + lgamma((df(i) + 1)/2) - 0.5 * log(df(i) * 3.14159) - lgamma(df(i)/2) -
((df(i) + 1) / 2) * log(1 + pow(theta(i) / scale(i), 2) / df(i));
}
return logDens;
}
};
// [[Rcpp::export]]
Rcpp::List gradScaleT(vec scale, vec df, Rcpp::NumericMatrix thetaIn){
Map<MatrixXd> theta(Rcpp::as<Map<MatrixXd> >(thetaIn));
double eval;
int dim = theta.rows();
Matrix<double, Dynamic, 1> grad(dim);
scaleT logp(scale, df);
stan::math::set_zero_all_adjoints();
stan::math::gradient(logp, theta, eval, grad);
return Rcpp::List::create(Rcpp::Named("grad") = grad,
Rcpp::Named("val") = eval);
}
|
/*
Copyright (c) 2014 Mircea Daniel Ispas
This file is part of "Push Game Engine" released under zlib license
For conditions of distribution and use, see copyright notice in Push.hpp
*/
#pragma once
#include <cstdint>
namespace Push
{
namespace RenderConfig
{
inline constexpr size_t MaxTextures()
{
return 4;
}
}
}
|
#include <iostream>
#include <ctime>
using namespace std;
void speed(void);
int main()
{
clock_t time = clock();
speed();
time = clock()-time;
cout<<ends<<time<<endl;
return 0;//ยทยตยปร
}
|
#include "Util.h"
#include <BWAPI.h>
#include "BWAPI\Player.h"
using namespace System::IO;
using namespace System::Runtime::InteropServices;
extern BWAPI::GameWrapper BWAPI::Broodwar;
namespace BroodWar
{
double DoubleToDouble(double d)
{
return d;
}
int IntToInt(int i)
{
return i;
}
BWAPI::Unitset ToUnitset(IEnumerable<Unit^>^ collection, BWAPI::Unit(*converter)(Unit^))
{
BWAPI::Unitset result;
BWAPI::Unit outelement;
for each(Unit^ element in collection)
{
outelement = (BWAPI::Unit const)(converter(element));
result.insert(outelement);
}
return result;
}
void Util::Log(String^ string)
{
String^ fileName = Path::Combine(
Environment::GetFolderPath(Environment::SpecialFolder::Personal),
"text-from-lib.txt");
StreamWriter^ file = gcnew StreamWriter(fileName, true);
file->WriteLine(string);
file->Close();
IntPtr ptr = Marshal::StringToHGlobalAnsi(string);
BWAPI::Broodwar->sendText((char*)ptr.ToPointer());
Marshal::FreeHGlobal(ptr);
}
void Util::LogException(String^ module, Exception^ ex)
{
Log(String::Format("Unexpected error occured during {0}: {1}{2}{3}", module, ex->Message, Environment::NewLine, ex->StackTrace));
while((ex = ex->InnerException) != nullptr)
{
Log(String::Format("Internal error is: {0}{1}{2}", ex->Message, Environment::NewLine, ex->StackTrace));
}
}
Api::Player^ Util::ConvertPlayer(void *player)
{
return Api::ConvertPlayer(static_cast<BWAPI::Player>(player));
}
Api::Unit^ Util::ConvertUnit(void *unit)
{
return Api::ConvertUnit(static_cast<BWAPI::Unit>(unit));
}
Api::Position^ Util::ConvertPosition(void *position)
{
return Api::ConvertPosition(static_cast<BWAPI::Position*>(position));
}
void Util::LoadGameInstance(BWAPI::Game* game)
{
BWAPI::BroodwarPtr = game;
}
}
|
/*
-------------------------------------------
Student: Malik Sheharyaar Talhat talhat@sheridan.desire2learn.com
StudentID: 991435266
-------------------------------------------
*/
/*
* File: Node.h
* Author: Malik Sheharyaar Talhat talhat@sheridan.desire2learn.com
*
* Created on April 5, 2019, 5:08 PM
*/
#ifndef NODE_H
#define NODE_H
using namespace std;
struct Node {
string first_name;
string last_name;
int phone_number;
struct Node *prev;
struct Node *next;
};
#endif /* NODE_H */
|
// Question => Form the biggest number from the numeric string
// We will the sort the string in decreasing order and that will be the maximum number
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main(){
string str = "764535644223489";
sort(str.begin(), str.end(), greater<int>());
cout<<str<<endl;
return 0;
}
|
#include"Array.hpp"
#include<array>
#include<stdio.h>
using namespace std;
int main()
{
Array<int, 3> arr1;
Array<int, 3> arr2;
arr1.fill(3);
arr2.fill(1);
printf("%d %d %d\n", arr1[0], arr1[1], arr1[2]);
printf("%d %d %d\n", arr2[0], arr2[1], arr2[2]);
arr1.swap(arr2);
printf("%d %d %d\n", arr1[0], arr1[1], arr1[2]);
printf("%d %d %d\n", arr2[0], arr2[1], arr2[2]);
return 0;
}
|
//
// Entity.cpp
// Odin.MacOSX
//
// Created by Daniel on 15/10/15.
// Copyright (c) 2015 DG. All rights reserved.
//
#include "Entity.h"
#include "RenderLib.h"
namespace odin
{
Entity::Entity() :
m_drawable(nullptr)
{
}
Entity::Entity(render::Drawable& drawable, render::RenderStates& states) :
m_drawable(&drawable),
m_states(states)
{
}
void Entity::setDrawable(render::Drawable& drawable)
{
m_drawable = &drawable;
}
render::Drawable* Entity::getDrawable() const
{
return m_drawable;
}
void Entity::setRenderStates(const render::RenderStates& states)
{
m_states = states;
}
const render::RenderStates& Entity::getRenderStates() const
{
return m_states;
}
void Entity::draw() const
{
m_drawable->draw(m_states);
}
}
|
#include <conio.h>
#include <iostream.h>
void main () {
int a;
clrscr();
for(int i=1; i<=10; i++) {
for(int j=1; j<=10-i; j++)
cout <<" ";
for(int k=1; k<=i+i; k++)
cout <<"*";
cout <<"\n";
}
for(i=1; i<=10; i++) {
a=i*2;
for(int j=1; j<=22-a; j++)
cout <<"*";
cout <<"\n";
for(int k=1; k<=i; k++)
cout <<" ";
}
getche();
}
|
#include "NhanVienSanXuat.h"
#include "NhanVienVP.h"
int main(void)
{
cout << "Nhap so nhan vien can quan li: ";
int n;
cin >> n;
cin.ignore();
NhanVien **danhSachNhanVien = new NhanVien*[n];
for (int i = 0, ans; i < n; i++)
{
cout << "-->Nhap nhan vien thu " << i + 1 << endl;
cout << "Nhap 1 neu la nhan vien van phong, 0 neu la nhan vien san xuat: ";
cin >> ans;
cin.ignore();
if (ans)
danhSachNhanVien[i] = new NhanVienVP;
else
danhSachNhanVien[i] = new NhanVienSanXuat;
danhSachNhanVien[i]->nhap();
}
cout << "Cac nhan vien da nhap: " << endl;
for (int i = 0; i < n; i++)
{
cout << "\t#" << i + 1 << endl;
danhSachNhanVien[i]->xuat();
}
for (int i = 0; i < n; i++)
{
delete danhSachNhanVien[i];
}
delete[] danhSachNhanVien;
system("pause");
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.