text
stringlengths 8
6.88M
|
|---|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::Devices {
struct ILowLevelDevicesAggregateProvider;
struct ILowLevelDevicesAggregateProviderFactory;
struct ILowLevelDevicesController;
struct ILowLevelDevicesControllerStatics;
struct LowLevelDevicesAggregateProvider;
struct LowLevelDevicesController;
}
namespace Windows::Devices {
struct ILowLevelDevicesAggregateProvider;
struct ILowLevelDevicesAggregateProviderFactory;
struct ILowLevelDevicesController;
struct ILowLevelDevicesControllerStatics;
struct LowLevelDevicesAggregateProvider;
struct LowLevelDevicesController;
}
namespace Windows::Devices {
template <typename T> struct impl_ILowLevelDevicesAggregateProvider;
template <typename T> struct impl_ILowLevelDevicesAggregateProviderFactory;
template <typename T> struct impl_ILowLevelDevicesController;
template <typename T> struct impl_ILowLevelDevicesControllerStatics;
}
}
|
/***************************************************************************
Copyright (c) 2020 Philip Fortier
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.
***************************************************************************/
#include "stdafx.h"
#include "AppState.h"
#include "PicDrawManager.h"
#include "Pic.h"
#include "PicOperations.h"
#include "PaletteOperations.h"
#include "format.h"
#include "PicCommands.h"
#include "View.h"
using namespace Gdiplus;
PicScreenFlags PicScreenToFlags(PicScreen screen)
{
return (PicScreenFlags)(0x1 << (int)screen);
}
PicPositionFlags PicPositionToFlags(PicPosition pos)
{
return (PicPositionFlags)(0x1 << (int)pos);
}
PicDrawManager::PicDrawManager(const PicComponent *pPic, const PaletteComponent *pPalette, bool isEGAUndithered)
: _pPicWeak(pPic),
_paletteVGA{},
_isVGA(pPalette != nullptr),
_isContinuousPri(pPic && pPic->Traits->ContinuousPriority),
_isUndithered(isEGAUndithered),
_screenBuffers{}
{
_viewPorts = std::make_unique<ViewPort[]>(3);
_Reset();
_paletteVGA[255].rgbRed = 255;
_paletteVGA[255].rgbGreen = 255;
_paletteVGA[255].rgbBlue = 255;
_paletteVGA[255].rgbReserved = 0x1;
if (pPalette)
{
_ApplyVGAPalette(pPalette);
}
}
void PicDrawManager::_EnsureBufferPool(size16 size)
{
size_t byteSize = size.cx * size.cy;
if (!_bufferPool || (_bufferPool->GetSize() != byteSize))
{
_bufferPool = std::make_unique<BufferPool<12>>(byteSize);
Invalidate();
}
}
RGBQUAD *PicDrawManager::_GetPalette()
{
return (_isVGA ? _paletteVGA :
_isUndithered ? g_egaColorsMixed : nullptr);
}
void PicDrawManager::_ApplyVGAPalette(const PaletteComponent *pPalette)
{
for (int i = 1; i < 255; i++)
{
_paletteVGA[i] = pPalette->Colors[i];
}
}
void PicDrawManager::_Reset()
{
_fValidScreens = PicScreenFlags::None;
_iDrawPos = -1;
_fValidPalette = false;
_fValidState = false;
_bPaletteNumber = 0;
//_currentState.Reset(_bPaletteNumber);
_iInsertPos = -1;
}
void PicDrawManager::SetPic(const PicComponent *pPic, const PaletteComponent *pPalette, bool isEGAUndithered)
{
_isUndithered = isEGAUndithered;
_isVGA = (pPalette != nullptr);
_isContinuousPri = pPic && pPic->Traits->ContinuousPriority;
if (!IsSame(pPic, _pPicWeak))
{
_Reset();
}
_pPicWeak = pPic;
if (pPalette)
{
_ApplyVGAPalette(pPalette);
}
}
//
// Caller needs to free HBITMAP
//
HBITMAP PicDrawManager::CreateBitmap(PicScreen screen, PicPosition pos, size16 size, int cx, int cy, SCIBitmapInfo *pbmi, uint8_t **pBitsDest)
{
_EnsureBufferPool(size);
_RedrawBuffers(nullptr, PicScreenToFlags(screen), PicPositionToFlags(pos));
RGBQUAD *colors = _GetPalette();
int colorCount = 256;
if (screen == PicScreen::Visual)
{
colors = _GetPalette();
colorCount = 256;
}
else
{
if (_pPicWeak && _pPicWeak->Traits->ContinuousPriority)
{
colors = g_continuousPriorityColors;
colorCount = ARRAYSIZE(g_continuousPriorityColors);
}
else
{
colors = g_egaColors;
colorCount = ARRAYSIZE(g_egaColors);
}
}
return _CreateBitmap(GetScreenData(screen, pos), size, cx, cy, colors, colorCount, pbmi, pBitsDest);
}
const uint8_t *PicDrawManager::GetPicBits(PicScreen screen, PicPosition pos, size16 size, DrawPixelCallback drawPixelCallback)
{
_EnsureBufferPool(size);
_RedrawBuffers(nullptr, PicScreenToFlags(screen), PicPositionToFlags(pos), false, drawPixelCallback);
return GetScreenData(screen, pos);
}
void PicDrawManager::GetBitmapInfo(PicScreen screen, BITMAPINFO **ppbmi)
{
size16 size = _GetPicSize();
_EnsureBufferPool(size);
if (screen == PicScreen::Visual)
{
*ppbmi = new SCIBitmapInfo(size.cx, size.cy, _GetPalette(), 256);
}
else
{
if ((screen == PicScreen::Priority) && _pPicWeak && _pPicWeak->Traits->ContinuousPriority)
{
*ppbmi = new SCIBitmapInfo(size.cx, size.cy, g_continuousPriorityColors, ARRAYSIZE(g_continuousPriorityColors));
}
else
{
// These are always EGA bitmaps
*ppbmi = new SCIBitmapInfo(size.cx, size.cy);
}
}
}
//
// Copies one of our bitmaps (specified by dwDrawEnable) into pdataDisplay,
// and the aux bitmap into pdataAux. So callers can take what we have,
// and add things.
// Caller must delete the optional parameter *ppbmi
//
void PicDrawManager::CopyBitmap(PicScreen screen, PicPosition pos, size16 size, uint8_t *pdataDisplay, uint8_t *pdataAux, BITMAPINFO **ppbmi)
{
assert(size == _GetPicSize());
_EnsureBufferPool(size);
PicScreenFlags flags = PicScreenToFlags(screen);
_RedrawBuffers(nullptr, flags, PicPositionToFlags(pos));
assert(IsFlagSet(_fValidScreens, flags));
memcpy(pdataDisplay, GetScreenData(screen, pos), size.cx * size.cy);
if (ppbmi)
{
if (screen == PicScreen::Visual)
{
*ppbmi = new SCIBitmapInfo(size.cx, size.cy, _GetPalette(), 256);
}
else
{
// These are always EGA bitmaps
*ppbmi = new SCIBitmapInfo(size.cx, size.cy);
}
}
memcpy(pdataAux, GetScreenData(PicScreen::Aux, pos), size.cx * size.cy);
}
void PicDrawManager::SetPalette(uint8_t bPaletteNumber)
{
if (bPaletteNumber != _bPaletteNumber)
{
_bPaletteNumber = bPaletteNumber;
_fValidPalette = false; // Since the palette changed.
_fValidScreens = PicScreenFlags::None;
_fValidState = false;
}
}
uint8_t *PicDrawManager::GetScreenData(PicScreen screen, PicPosition pos)
{
return _screenBuffers[static_cast<int>(pos)][static_cast<int>(screen)];
}
void PicDrawManager::SetScreenData(PicScreen screen, PicPosition pos, uint8_t *data)
{
_screenBuffers[static_cast<int>(pos)][static_cast<int>(screen)] = data;
}
void PicDrawManager::_EnsureInitialBuffers(PicScreenFlags screenFlags)
{
for (int i = 0; i < 4; i++)
{
if (IsFlagSet(screenFlags, (PicScreenFlags)(0x1 << i)))
{
if (!_screenBuffers[0][i])
{
_screenBuffers[0][i] = _bufferPool->AllocateBuffer();
// REVIEW test -> indicate uninitlaize data.
*_screenBuffers[0][i] = 0xe;
}
}
else
{
// Return this and null out
_ReturnOldBufferIfNotUsedAnywhere((PicScreen)i, PicPosition::PrePlugin);
}
}
}
static int g_redrawDebug = 0;
void PicDrawManager::_RedrawBuffers(ViewPort *pState, PicScreenFlags screenFlags, PicPositionFlags picPositionFlags, bool assertIfCausedRedraw, DrawPixelCallback drawPixelCallback)
{
size16 size = _GetPicSize();
_EnsureBufferPool(size);
ViewPort state(_bPaletteNumber);
if (pState == nullptr)
{
pState = &state;
}
else
{
pState->Reset(_bPaletteNumber);
}
// If we know someone is going to want other screens, may as well include them now.
for (IPicDrawPlugin *plugin : _plugins)
{
screenFlags |= plugin->GetRequiredScreens();
picPositionFlags |= plugin->GetRequiredPicPosition();
}
// control and priority require visual for accurate fills, so add that in
if (IsFlagSet(screenFlags, PicScreenFlags::Control | PicScreenFlags::Priority))
{
screenFlags |= PicScreenFlags::Visual;
}
screenFlags |= PicScreenFlags::Aux; // Always
if (AreAllFlagsSet(_fValidScreens, screenFlags) && (AreAllFlagsSet(_validPositions, picPositionFlags)))
{
// Nothing to do
return;
}
// If we need some new screens, make it so that no positions are valid. We'll just redraw from scratch. Otherwise
// it's too complicated.
if (!AreAllFlagsSet(_fValidScreens, screenFlags))
{
_validPositions = PicPositionFlags::None;
}
// An important distinction:
// PicPositionFlags indicate which buffers people will be requesting. It doesn't mean we don't need
// to draw those to get to subsequent buffers, obviously.
// If anyone requests something earlier than we have, then we need to invalidate everything from then on.
// For instance, if someone needs PrePlugin, and that is not valid, we need to invalidate everything
// If someone needs PostPlugin, and we only have
PicPosition clearOutFromHereOn = PicPosition::PrePlugin;
if (IsFlagSet(_validPositions, PicPositionFlags::PrePlugin))
{
// We can re-use PrePlugin
clearOutFromHereOn = PicPosition::PostPlugin;
}
if (IsFlagSet(_validPositions, PicPositionFlags::PostPlugin))
{
clearOutFromHereOn = PicPosition::Final;
}
if (clearOutFromHereOn <= PicPosition::PrePlugin)
{
_ReturnOldBufferIfNotUsedAnywhere(PicPosition::PrePlugin);
}
if (clearOutFromHereOn <= PicPosition::PostPlugin)
{
_ReturnOldBufferIfNotUsedAnywhere(PicPosition::PostPlugin);
}
if (clearOutFromHereOn <= PicPosition::Final)
{
_ReturnOldBufferIfNotUsedAnywhere(PicPosition::Final);
}
_EnsureInitialBuffers(screenFlags);
bool atFinalPosition = (_iDrawPos == -1) || (_iDrawPos == _pPicWeak->commands.size());
// Can we re-use some of our per-position buffers? This optimization is essential, it will be used
// when we're drawing lines and such in the editor.
if (!IsFlagSet(_validPositions, PicPositionFlags::PrePlugin))
{
// Our initial viewport state.
_viewPorts[0] = *pState;
// Default states
if (IsFlagSet(screenFlags, PicScreenFlags::Priority))
{
memset(GetScreenData(PicScreen::Priority, PicPosition::PrePlugin), 0x00, _bufferPool->GetSize());
}
if (IsFlagSet(screenFlags, PicScreenFlags::Control))
{
memset(GetScreenData(PicScreen::Control, PicPosition::PrePlugin), 0x00, _bufferPool->GetSize());
}
if (IsFlagSet(screenFlags, PicScreenFlags::Visual))
{
memset(GetScreenData(PicScreen::Visual, PicPosition::PrePlugin), (_isVGA || _isUndithered) ? 0xff : 0x0f, _bufferPool->GetSize());
}
memset(GetScreenData(PicScreen::Aux, PicPosition::PrePlugin), 0x00, _bufferPool->GetSize());
PicData data =
{
screenFlags,
GetScreenData(PicScreen::Visual, PicPosition::PrePlugin), // Visual always needs to be provided (for fill)
GetScreenData(PicScreen::Priority, PicPosition::PrePlugin),
GetScreenData(PicScreen::Control, PicPosition::PrePlugin),
GetScreenData(PicScreen::Aux, PicPosition::PrePlugin),
_isVGA,
_isUndithered,
_GetPicSize(),
_isContinuousPri,
drawPixelCallback
};
// Now draw!
Draw(*_pPicWeak, data, _viewPorts[0], 0, _iDrawPos);
}
// Perf optimization: if no one is drawing on the pic, then we can "skip" this step
bool willDrawOnPic = false;
for (IPicDrawPlugin *plugin : _plugins)
{
willDrawOnPic = willDrawOnPic || plugin->WillDrawOnPic();
}
if (willDrawOnPic)
{
// Now do the plugins
_MoveToNextStep(picPositionFlags, PicPosition::PrePlugin);
// TODO: NEeds to be an if statement here
// Basically, if someone needs PostPlugin or Final, and PostPlugin is not valid
if (!IsFlagSet(_validPositions, PicPositionFlags::PostPlugin) &&
IsFlagSet(picPositionFlags, PicPositionFlags::PostPlugin | PicPositionFlags::Final))
{
PicData data =
{
screenFlags,
GetScreenData(PicScreen::Visual, PicPosition::PostPlugin), // Visual always needs to be provided (for fill)
GetScreenData(PicScreen::Priority, PicPosition::PostPlugin),
GetScreenData(PicScreen::Control, PicPosition::PostPlugin),
GetScreenData(PicScreen::Aux, PicPosition::PostPlugin),
_isVGA,
_isUndithered,
_GetPicSize(),
_isContinuousPri,
nullptr
};
// OutputDebugString("Drawing plguins\n");
for (IPicDrawPlugin *plugin : _plugins)
{
plugin->DrawOnPic(_viewPorts[1], data, screenFlags);
}
}
}
else
{
// Pretend no one needs "post plugin", and just use the previous buffers.
_MoveToNextStep(picPositionFlags & ~PicPositionFlags::PrePlugin, PicPosition::PrePlugin);
}
// Perf optimization: if the current position is the final, then "skip" this step and just re-use buffers.
if (atFinalPosition)
{
_MoveToNextStep(picPositionFlags & ~PicPositionFlags::PostPlugin, PicPosition::PostPlugin);
}
else
{
_MoveToNextStep(picPositionFlags, PicPosition::PostPlugin);
}
if (!IsFlagSet(_validPositions, PicPositionFlags::Final) &&
IsFlagSet(picPositionFlags, PicPositionFlags::Final))
{
if (!atFinalPosition && IsFlagSet(picPositionFlags, PicPositionFlags::Final))
{
// OutputDebugString("Drawing final\n");
PicData data =
{
screenFlags,
GetScreenData(PicScreen::Visual, PicPosition::Final), // Visual always needs to be provided (for fill)
GetScreenData(PicScreen::Priority, PicPosition::Final),
GetScreenData(PicScreen::Control, PicPosition::Final),
GetScreenData(PicScreen::Aux, PicPosition::Final),
_isVGA,
_isUndithered,
_GetPicSize(),
_isContinuousPri,
nullptr
};
// Now draw!
Draw(*_pPicWeak, data, _viewPorts[2], _iDrawPos, -1);
}
}
_validPositions = picPositionFlags;
_fValidScreens = screenFlags;
}
void PicDrawManager::_ReturnOldBufferIfNotUsedAnywhere(PicPosition pos)
{
for (int screenIndex = 0; screenIndex < 4; screenIndex++)
{
PicScreen screen = (PicScreen)screenIndex;
_ReturnOldBufferIfNotUsedAnywhere(screen, pos);
}
}
void PicDrawManager::_ReturnOldBufferIfNotUsedAnywhere(PicScreen screen, PicPosition pos)
{
uint8_t *buffer = GetScreenData(screen, pos);
bool usedElsewhere = false;
for (int posIndex = 0; !usedElsewhere && (posIndex < 3); posIndex++)
{
PicPosition cur = (PicPosition)posIndex;
usedElsewhere = (cur != pos) && (buffer == GetScreenData(screen, cur));
}
if (!usedElsewhere)
{
_bufferPool->FreeBuffer(buffer);
}
SetScreenData(screen, pos, nullptr);
}
void PicDrawManager::_MoveToNextStep(PicPositionFlags requestedFlags, PicPosition posCompleted)
{
bool debugFlag = false;
PicPositionFlags posFlagsCompleted = PicPositionToFlags(posCompleted);
PicPosition nextPos = (PicPosition)((int)posCompleted + 1);
_viewPorts[(int)nextPos] = _viewPorts[(int)posCompleted];
_ReturnOldBufferIfNotUsedAnywhere(nextPos);
// If the next position has different buffers, copy from the previous position.
for (int screenIndex = 0; screenIndex < 4; screenIndex++)
{
PicScreen screen = (PicScreen)screenIndex;
uint8_t *prev = GetScreenData(screen, posCompleted);
if (prev)
{
// If someone needs the position we just completed, we need to "branch" our buffers.
// Otherwise just assign pointers.
if (IsFlagSet(requestedFlags, posFlagsCompleted))
{
SetScreenData(screen, nextPos, _bufferPool->AllocateBuffer());
size16 size = _GetPicSize();
memcpy(GetScreenData(screen, nextPos), prev, size.cx * size.cy);
debugFlag = true;
}
else
{
// Just keep drawing on the same surface
SetScreenData(screen, nextPos, prev);
}
}
else
{
SetScreenData(screen, nextPos, nullptr);
}
}
if (debugFlag)
{
// OutputDebugString("memcpy'd\n");
}
}
HBITMAP _ScaleByHalf(uint8_t *pData, size16 sizeSource, int cx, int cy, const RGBQUAD *palette, int paletteCount)
{
HBITMAP hbm = nullptr;
SCIBitmapInfo bmiSCI(sizeSource.cx, sizeSource.cy, palette, paletteCount);
RGBQUAD *newData = nullptr;
HDC hDC = GetDC(nullptr);
BITMAPINFO bmi;
memset(&bmi, 0, sizeof(BITMAPINFO));
bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth = cx;
bmi.bmiHeader.biHeight = -cy; // top-down
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biCompression = BI_RGB;
hbm = CreateDIBSection(hDC, &bmi, DIB_RGB_COLORS, (void**)&newData, nullptr, 0);
ReleaseDC(nullptr, hDC);
for (int y = 0; y < cy; y++)
{
uint8_t *source = pData + (y * 2 * sizeSource.cx);
uint8_t *sourceNext = pData + ((y * 2 + 1) * sizeSource.cx);
RGBQUAD *dest = newData + ((cy - (y + 1)) * cx);
for (int x = 0; x < cx; x++)
{
RGBQUAD a = bmiSCI.bmiColors[*source];
RGBQUAD b = bmiSCI.bmiColors[*(source + 1)];
RGBQUAD c = bmiSCI.bmiColors[*(sourceNext)];
RGBQUAD d = bmiSCI.bmiColors[*(sourceNext + 1)];
int blue = (a.rgbBlue + b.rgbBlue + c.rgbBlue + d.rgbBlue) >> 2;
int red = (a.rgbRed + b.rgbRed + c.rgbRed + d.rgbRed) >> 2;
int green = (a.rgbGreen + b.rgbGreen + c.rgbGreen + d.rgbGreen) >> 2;
RGBQUAD final = {
(BYTE)blue, (BYTE)green, (BYTE)red, 0
};
*dest = final;
dest++;
source += 2;
sourceNext += 2;
}
}
return hbm;
}
HBITMAP PicDrawManager::_GetBitmapGDIP(uint8_t *pData, int cx, int cy, const RGBQUAD *palette, int paletteCount) const
{
size16 size = _GetPicSize();
HBITMAP hbm = nullptr;
SCIBitmapInfo bmi(size.cx, size.cy, palette, paletteCount);
std::unique_ptr<Gdiplus::Bitmap> pimgVisual(Gdiplus::Bitmap::FromBITMAPINFO(&bmi, pData));
if (pimgVisual)
{
if ((cx == size.cx) && (cy == size.cy))
{
// Exact size.
pimgVisual->GetHBITMAP(Color::Black, &hbm);
}
else
{
if ((cx == size.cx / 2) && (cy == size.cy / 2))
{
hbm = _ScaleByHalf(pData, size, cx, cy, palette, paletteCount);
}
else
{
std::unique_ptr<Bitmap> newBitmap = std::make_unique<Bitmap>(cx, cy, PixelFormat24bppRGB);
Graphics graphics(newBitmap.get());
graphics.SetCompositingMode(CompositingModeSourceCopy);
graphics.SetPixelOffsetMode(PixelOffsetModeHighSpeed);
graphics.SetSmoothingMode(SmoothingModeHighSpeed);
graphics.SetInterpolationMode(InterpolationModeHighQualityBilinear);
graphics.DrawImage(pimgVisual.get(), 0, 0, cx, cy);
newBitmap->GetHBITMAP(Color::Black, &hbm);
}
}
}
return hbm;
}
std::unique_ptr<Cel> PicDrawManager::MakeCelFromPic(PicScreen screen, PicPosition position)
{
_EnsureBufferPool(_pPicWeak->Size);
_RedrawBuffers(nullptr, PicScreenToFlags(screen), PicPositionToFlags(position));
std::unique_ptr<Cel> cel = std::make_unique<Cel>();
cel->size = _pPicWeak->Size;
cel->Stride32 = true;
const uint8_t *data = GetScreenData(screen, position);
cel->Data.allocate(cel->GetStride() * cel->size.cy);
cel->Data.assign(data, data + cel->Data.size());
return cel;
}
HBITMAP PicDrawManager::_CreateBitmap(uint8_t *pData, size16 size, int cxRequested, int cyRequested, const RGBQUAD *palette, int paletteCount, SCIBitmapInfo *pbmi, uint8_t **ppBitsDest) const
{
HBITMAP hbm = nullptr;
if (!appState->_fNoGdiPlus && (!pbmi || !ppBitsDest))
{
// Use GDI+ if we can - the images are much better.
hbm = _GetBitmapGDIP(pData, cxRequested, cyRequested, palette, paletteCount);
}
else
{
// Here we'll use some ugly GDI scaling.
CDC dc;
if (dc.CreateCompatibleDC(nullptr))
{
int cxBmp = size.cx;
int cyBmp = size.cy;
SCIBitmapInfo bmi;
uint8_t *pBitsDest;
if (!pbmi)
{
ppBitsDest = &pBitsDest;
pbmi = &bmi;
}
*pbmi = SCIBitmapInfo(cxRequested, cyRequested, palette, paletteCount);
CBitmap bitmap;
if (bitmap.Attach(CreateDIBSection(dc, pbmi, DIB_RGB_COLORS, (void**)ppBitsDest, nullptr, 0)))
{
SCIBitmapInfo bmiSrc(cxBmp, cyBmp, palette, paletteCount);
HGDIOBJ hObjOld = dc.SelectObject((HBITMAP)bitmap);
if ((cxRequested != cxBmp) || (cyRequested != cyBmp))
{
// NOTE: HALFTONE is not supported on Win 98/Me
// As a result, the images will be resized poorly for dithered colours.
SetStretchBltMode(dc, HALFTONE);
SetBrushOrgEx(dc, 0, 0, nullptr);
StretchDIBits(dc, 0, 0, cxRequested, cyRequested,
0, 0, cxBmp, cyBmp, pData, &bmiSrc, DIB_RGB_COLORS, SRCCOPY);
}
else
{
SetStretchBltMode(dc, COLORONCOLOR);
SetBrushOrgEx(dc, 0, 0, nullptr);
StretchDIBits(dc, 0, 0, cxRequested, cyRequested,
0, 0, cxBmp, cyBmp, pData, &bmiSrc, DIB_RGB_COLORS, SRCCOPY);
}
dc.SelectObject(hObjOld);
hbm = (HBITMAP)bitmap.Detach();
}
}
}
return hbm;
}
void PicDrawManager::RefreshAllScreens(PicScreenFlags picScreenFlags, PicPositionFlags picPositionFlags)
{
_RedrawBuffers(nullptr, picScreenFlags, picPositionFlags);
}
const ViewPort *PicDrawManager::GetViewPort(PicPosition pos)
{
_RedrawBuffers(nullptr, _fValidScreens, PicPositionToFlags(pos), true);
return &_viewPorts[(int)pos];
}
//
// Given a point, determines the position in the pic, before iState (-1 = end)
// where that position changed.
// Returns -1 if that point was never changed.
// Currently only works for visual screen.
//
ptrdiff_t PicDrawManager::PosFromPoint(int x, int y, ptrdiff_t iStart)
{
ViewPort state(0);
size16 size = _GetPicSize();
size_t byteSize = size.cx * size.cy;
// Clear out our cached bitmaps.
PicScreenFlags dwMapsToRedraw = PicScreenFlags::None;
std::vector<uint8_t> pdataVisual(byteSize, 0x0f);
std::vector<uint8_t> pdataAux(byteSize, 0x00);
dwMapsToRedraw |= PicScreenFlags::Visual;
PicData data =
{
dwMapsToRedraw,
&pdataVisual[0], // Visual always needs to be provided (for fill)
nullptr,
nullptr,
&pdataAux[0], // Aux always needs to be provided (for fill)
_isVGA,
_isUndithered,
_GetPicSize(),
_isContinuousPri,
nullptr
};
return GetLastChangedSpot(*_pPicWeak, data, state, x, y);
}
//
// Seek to a particular position.
// The picture is drawn up to and including that position.
//
//
bool PicDrawManager::SeekToPos(ptrdiff_t iPos)
{
bool fChanged = ((iPos != _iInsertPos) || (iPos != _iDrawPos));
if (fChanged)
{
_iInsertPos = iPos;
_iDrawPos = iPos;
_OnPosChanged();
}
return fChanged;
}
void PicDrawManager::AddPicPlugin(IPicDrawPlugin *plugin)
{
_plugins.push_back(plugin);
}
void PicDrawManager::Invalidate()
{
_fValidScreens = PicScreenFlags::None;
_fValidState = false;
}
void PicDrawManager::_OnPosChanged(bool fNotify)
{
Invalidate();
}
void PicDrawManager::InvalidatePlugins()
{
_validPositions &= ~(PicPositionFlags::Final | PicPositionFlags::PostPlugin);
}
size16 PicDrawManager::_GetPicSize() const
{
size16 size(DEFAULT_PIC_WIDTH, DEFAULT_PIC_HEIGHT);
if (_pPicWeak)
{
size = _pPicWeak->Size;
}
return size;
}
|
#ifdef __cplusplus
#include <cstdlib>
#else
#include <stdlib.h>
#endif
#ifdef __APPLE__
#include <SDL/SDL.h>
#else
#include <SDL.h>
#include <SDL_image.h>
#endif
int main ( int argc, char** argv )
{
if ( SDL_Init( SDL_INIT_VIDEO ) < 0 )
{
printf( "Unable to init SDL: %s\n", SDL_GetError() );
return 1;
}
atexit(SDL_Quit);
SDL_Surface* screen = SDL_SetVideoMode(640, 480, 16,
SDL_HWSURFACE|SDL_DOUBLEBUF);
if ( !screen )
{
printf("Unable to set 640x480 video: %s\n", SDL_GetError());
return 1;
}
SDL_Surface *png;
png = IMG_Load("obj/pc.png");
if (!png)
{
printf("Unable to load bitmap: %s\n", SDL_GetError());
return 1;
}
SDL_Rect dstrect;
dstrect.x = (screen->w - png->w) / 2;
dstrect.y = (screen->h - png->h) / 2;
bool done = false;
while (!done)
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_QUIT:
done = true;
break;
case SDL_KEYDOWN:
{
if (event.key.keysym.sym == SDLK_ESCAPE)
done = true;
break;
}
}
}
SDL_FillRect(screen, 0, SDL_MapRGB(screen->format, 255, 255, 255));
SDL_BlitSurface(png, 0, screen, &dstrect);
SDL_Flip(screen);
}
SDL_FreeSurface(png);
printf("Exited cleanly\n");
return 0;
}
|
#include<iostream.h>
void destinations()
{
clrscr();
gotoxy(30,7);
cout<<"Domestic destinations";
gotoxy(33,9);
cout<<"1. New Delhi";
gotoxy(33,10);
cout<<"2. Mumbai";
gotoxy(33,11);
cout<<"3. Chennai";
gotoxy(33,12);
cout<<"4. Kolkata";
gotoxy(33,13);
cout<<"5. Hyderabad";
gotoxy(27,16);
cout<<"Press any key to proceed...";
getch();
clrscr();
gotoxy(27,7);
cout<<"International Destinations";
gotoxy(33,9);
cout<<"1. London";
gotoxy(33,10);
cout<<"2. Paris";
gotoxy(33,11);
cout<<"3. Dubai";
gotoxy(33,12);
cout<<"4. Singapore ";
gotoxy(33,13);
cout<<"5. Hong Kong";
gotoxy(27,16);
cout<<"Press any key to continue ";
getch();
clrscr();
}
|
//
// Copyright Jason Rice 2017
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef NBDL_CONCEPT_BUFFER_HPP
#define NBDL_CONCEPT_BUFFER_HPP
#include <nbdl/concept/Container.hpp>
#include <type_traits>
#include <utility>
namespace nbdl {
template<typename T>
concept Buffer = nbdl::ContiguousByteContainer<T> &&
nbdl::FixedSizeContainer<T>;
}
#endif
|
/// @file CutHash.cc
/// @brief CutHash の実装ファイル
/// @author Yusuke Matsunaga (松永 裕介)
///
/// Copyright (C) 2005-2012 Yusuke Matsunaga
/// All rights reserved.
#include "CutHash.h"
#include "Cut.h"
BEGIN_NAMESPACE_YM
//////////////////////////////////////////////////////////////////////
// クラス CutHash
//////////////////////////////////////////////////////////////////////
// @brief コンストラクタ
CutHash::CutHash() :
mTableSize(0)
{
alloc_table(1024);
mNum = 0;
}
// @brief デストラクタ
CutHash::~CutHash()
{
clear();
delete [] mTable;
}
// @brief 内容をクリアする.
void
CutHash::clear()
{
for (ymuint32 i = 0; i < mTableSize; ++ i) {
mTable[i] = NULL;
}
mNum = 0;
}
// @brief 関数に対応するカットを返す.
Cut*
CutHash::find(TvFunc f)
{
ymuint32 pos = f.hash() % mTableSize;
for (Cut* cut = mTable[pos]; cut; cut = cut->mLink) {
if ( cut->mFunc == f ) {
return cut;
}
}
return NULL;
}
// @brief カットを登録する.
void
CutHash::put(Cut* cut)
{
if ( mNum >= mNextLimit ) {
// テーブルを拡張する.
Cut** old_table = mTable;
ymuint32 old_size = mTableSize;
alloc_table(old_size * 2);
for (ymuint32 i = 0; i < old_size; ++ i) {
for (Cut* cut = old_table[i]; cut; ) {
Cut* next = cut->mLink;
ymuint32 pos1 = cut->mFunc.hash() % mTableSize;
cut->mLink = mTable[pos1];
mTable[pos1] = cut;
cut = next;
}
}
}
// テーブルに追加する.
ymuint pos = cut->mFunc.hash() % mTableSize;
cut->mLink = mTable[pos];
mTable[pos] = cut;
}
// ハッシュ表を拡大する.
void
CutHash::alloc_table(ymuint32 new_size)
{
mTable = new Cut*[new_size];
mTableSize = new_size;
mNextLimit = static_cast<ymuint32>(mTableSize * 1.8);
for (ymuint32 i = 0; i < new_size; ++ i) {
mTable[i] = NULL;
}
}
END_NAMESPACE_YM
|
#ifndef VECTOR2_H
#define VECTOR2_H
#include <math.h>
#include "pacman-main.h"
#ifdef near
#undef near
#endif // near
// Conflict between WinDef.h archaic
// "near" and our Vector2.near()
// If two vectors v1 and v2
// are within EPS of each other
// in both x and y,
// then v1.near(v2)
// is true
#define EPS 0.0001f
class Vector2
{
public:
float x,y;
Vector2() ;
Vector2(float ix, float iy) ;
Vector2(const Vector2& other) ;
// Almost equal
bool near( const Vector2& other ) ;
float mag() ;
float magSquared() ;
/// Makes this vector
/// a unit vector, while
/// retaining its direction
Vector2& normalize() ;
Vector2& setMag( float newMagnitude ) ;
Vector2& print() ;
} ;
// Operator overloading outside
bool operator==(const Vector2& a, const Vector2& b ) ;
Vector2 operator+(const Vector2& a, const Vector2& b) ;
Vector2 operator-(const Vector2& a, const Vector2& b) ;
Vector2 operator*(const Vector2& a, float c) ;
// and support for (scalar*vector) [2.5f*v1]
Vector2 operator*(float c, const Vector2& a) ;
float dot(const Vector2& a, const Vector2& b) ;
Vector2& operator+=( Vector2& a, Vector2& b ) ;
Vector2& operator*=( Vector2& a, float c ) ;
Vector2& operator/=( Vector2& a, float c ) ;
#endif // VECTOR2_H
|
#ifndef EXAMPLE_HPP
#define EXAMPLE_HPP
#include <vector>
int fact(int n);
void print_vector();
std::vector<int> ret_vector();
void pass_print_vector(std::vector<int> array);
class Shape{
public:
Shape();
Shape(int x, int y);
~Shape();
double x, y;
void move(double dx, double dy);
double area();
double perimeter();
void print_shape();
static void print_shape_vector(std::vector<Shape> shape_array);
};
#endif
|
/*****************************************************************************************************
* 剑指offer第42-2题
* 题目描述
* 用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,
字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”
*
* Input: 字符串和翻转的位置
* Output: 翻转后的字符串
*
* Note: (着重掌握翻转字符串的操作,是各种字符串操作的基石)
* 首先将前N个字符串进行翻转,再将后len-N+1的字符串进行翻转,最后将所有的字符进行翻转。
解释数学:YX=(XTYT)T ,其中T为转置
* author: lcxanhui@163.com
* time: 2019.5.30
******************************************************************************************************/
#include<iostream>
#include<string>
using namespace std;
// 翻转字符串的经典代码,掌握
void Reverse(string& str, int begin, int end)
{
if (begin < 0 || end < 0)
return;
while (begin < end) // 判断条件
{
char temp;
temp = str[begin];
str[begin] = str[end];
str[end] = temp;
begin++;
end--;
}
}
string LeftRotateString(string str,int n)
{
int len = str.size();
if (len <= 0 || n<=0)
return str;
if (n > len)
n = n % len; //如果位置N大于len,比如12>9,则求余运算后为3,在字符串的第3个位置进行翻转
string& temp = str;
Reverse(temp, 0, n - 1);
Reverse(temp, n, len - 1);
Reverse(temp, 0, len - 1);
return str;
}
int main()
{
string str = "I am a student.";
int n;
cin >> n;
string res = LeftRotateString(str, n);
cout << res;
return 0;
}
|
//
// Student.cpp
// Homework7
//
// Created by HeeCheol Kim on 01/11/2018.
// Copyright © 2018 HeeCheol Kim. All rights reserved.
//
#include "Student.h"
Student::Student() {
this->id = 0;
this->name = "";
this->school = "";
this->score = 0;
}
void Student::showInfo() {
cout << "학번 : " << this->id << endl;
cout << "이름 : " << this->name << endl;
cout << "출신학교 : " << this->school << endl;
cout << "점수 : " << this->score << endl;
}
|
//Problem link:- https://www.hackerrank.com/challenges/array-splitting/
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll solve(int s,int e,ll arr[],ll sum[]){
if(s>=e)return 0;
ll x=sum[e]-(s>0?sum[s-1]:0);
int f=0;ll xx=0;ll idx;
for(int i=s;i<=e;i++){
xx+=arr[i];
if(2*xx==x){idx=i;f=1;break;}
}
if(f==0)return 0;
else return 1+max(solve(s,idx,arr,sum),solve(idx+1,e,arr,sum));
}
int main(){
int t;
cin >> t;
while(t--){
ll n;
ll arr[35000];
ll sum[35000];
cin >> n;
for(int i=0;i<n;i++)
cin >> arr[i];
sum[0]=arr[0];
for(int i=1;i<n;i++)
sum[i]=arr[i]+sum[i-1];
ll ans=solve(0,n-1,arr,sum);
cout << ans << endl;
}
return 0;
}
|
// -*- C++ -*-
//
// Copyright (C) 1998, 1999, 2000, 2002 Los Alamos National Laboratory,
// Copyright (C) 1998, 1999, 2000, 2002 CodeSourcery, LLC
//
// This file is part of FreePOOMA.
//
// FreePOOMA is free software; you can redistribute it and/or modify it
// under the terms of the Expat license.
//
// 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 Expat
// license for more details.
//
// You should have received a copy of the Expat license along with
// FreePOOMA; see the file LICENSE.
//
//-----------------------------------------------------------------------------
// evaluatorTest3 - a simple patch function
//-----------------------------------------------------------------------------
#include "Pooma/Pooma.h"
#include "Pooma/Arrays.h"
#include "Evaluator/PatchFunction.h"
#include "Utilities/Tester.h"
#include <iostream>
// This really simple example doesn't do anything a stencil couldn't do,
// but you could imagine writing something more complicated.
struct MyFunction
{
template<class ArrayPatch>
void apply(const ArrayPatch &a) const
{
int i;
int from = a.domain()[0].first();
int to = a.domain()[0].last();
for (i = from; i <= to; ++i)
{
if (a(i)>5.0)
{
a(i) /= 4.0;
}
}
}
};
// version that takes two arguments. You are writing to the
// first argument and reading from the second.
struct MyFunction2
{
MyFunction2(double v1,double v2) : v1_m(v1),v2_m(v2) { }
template<class ArrayPatch1, class ArrayPatch2>
void apply(const ArrayPatch1 &a1, const ArrayPatch2 &a2) const
{
int i;
int from = a1.domain()[0].first();
int to = a1.domain()[0].last();
for (i = from; i <= to; ++i)
{
if (a2(i)>v1_m)
{
a1(i) /= v2_m;
}
}
}
double v1_m,v2_m;
};
struct MyFunction3
{
MyFunction3(double v1,double v2) : v1_m(v1),v2_m(v2) { }
template<class ArrayPatch1, class ArrayPatch2, class ArrayPatch3>
void apply(const ArrayPatch1 &a1, const ArrayPatch2 &a2,
const ArrayPatch3 &a3) const
{
int i;
int from = a1.domain()[0].first();
int to = a1.domain()[0].last();
for (i = from; i <= to; ++i)
{
if (a2(i)>v1_m)
{
a1(i) /= v2_m;
}
else
{
a1(i) += a3(i);
}
}
}
double v1_m,v2_m;
};
struct TestFunction
{
TestFunction(Inform &inform) : inform_m(&inform) { }
TestFunction(const TestFunction &tf) : inform_m(tf.inform_m) { }
template<class Patch>
void apply(const Patch &a)
{
(*inform_m) << "test:" << a << std::endl;
}
template<class Patch>
void apply(const Patch &a, int node)
{
(*inform_m) << node << ":" << a << std::endl;
}
template<class P1, class P2>
void apply(const P1 &a, const P2 &b, int node)
{
(*inform_m) << "a:" << node << ":" << a << std::endl;
(*inform_m) << "b:" << ":" << b << std::endl;
}
template<class P1, class P2, class P3>
void apply(const P1 &a, const P2 &b, const P3 &c, int node)
{
(*inform_m) << "a:" << node << ":" << a << std::endl;
(*inform_m) << "b:" << ":" << b << std::endl;
(*inform_m) << "c:" << ":" << c << std::endl;
}
mutable Inform *inform_m;
};
int main(int argc, char *argv[])
{
// Initialize POOMA and output stream, using Tester class
Pooma::initialize(argc, argv);
Pooma::Tester tester(argc, argv);
tester.out() << argv[0] << ": Patch function test." << std::endl;
tester.out() << "------------------------------------------------" << std::endl;
int size = 120;
Interval<1> domain(size);
UniformGridPartition<1> partition(Loc<1>(10));
UniformGridLayout<1> layout(domain, partition, ReplicatedTag());
Array<1,double,MultiPatch<UniformTag,Brick> > a(layout),b(layout);
int i;
for (i = 0; i < size; ++i )
{
a(i) = i;
}
b = where(a>5.0,a/4.0,a);
PatchFunction<MyFunction,PatchTag1>()(a);
tester.out() << a << std::endl;
tester.out() << b << std::endl;
tester.check(sum((a-b)*(a-b))<0.001);
UniformGridPartition<1> partition2(Loc<1>(12));
UniformGridLayout<1> layout2(domain, partition2, ReplicatedTag());
Array<1,double,MultiPatch<UniformTag,Brick> > a2(layout2),b2(layout2);
for (i = 0; i < size; ++i )
{
a(i) = i;
a2(i) = 3+i;
b2(i) = 3+i;
}
PatchFunction<MyFunction2,PatchTag2>(5.0,4.0)(a2,a);
b2 = where(a>5.0,b2/4.0,b2);
tester.check(sum((a2-b2)*(a2-b2))<0.001);
for (i = 0; i < size; ++i )
{
a(i) = i;
a2(i) = 3+i;
b2(i) = 3+i;
}
PatchFunction<MyFunction3,PatchTag3>(5.0,4.0)(a2,a,a);
b2 = where(a>5.0,b2/4.0,b2+a);
tester.out() << a << std::endl;
tester.out() << a2 << std::endl;
tester.out() << b2 << std::endl;
tester.check(sum((a2-b2)*(a2-b2))<0.001);
TestFunction tf(tester.out());
PatchFunction<TestFunction, PatchParticle1<true> > test(tf);
test(b2);
PatchFunction<TestFunction, PatchParticle2<false, false> > test2(tf);
test2(b2,a2);
PatchFunction<TestFunction, PatchParticle3<false, false, false> > test3(tf);
test3(b2,a2,a2);
PatchFunction<TestFunction, PatchReadTag1> test4(tf);
test4(b2*2+a);
PatchFunction<TestFunction, PatchParticle1<false> > test5(tf);
test5(b2*2+a2);
tester.out() << "------------------------------------------------" << std::endl;
int retval = tester.results("evaluatorTest3");
Pooma::finalize();
return retval;
}
// ACL:rcsinfo
// ----------------------------------------------------------------------
// $RCSfile: evaluatorTest3.cpp,v $ $Author: richard $
// $Revision: 1.14 $ $Date: 2004/11/01 18:16:41 $
// ----------------------------------------------------------------------
// ACL:rcsinfo
|
#include<bits/stdc++.h>
using namespace std;
int main(){
int a, b; scanf("%d %d", &a, &b);
if ( a <= b && b <= a*6 ){
printf("Yes\n");
}
else printf("No\n");
}
|
#ifndef FOGDELETEEXPR_HXX
#define FOGDELETEEXPR_HXX
class FogDeleteExpr : public FogDecoratedExpr
{
typedef FogDecoratedExpr Super;
typedef FogDeleteExpr This;
TYPEDECL_SINGLE(This, Super)
FOGTOKEN_MEMBER_DECLS
FOGTOKEN_LEAF_DECLS
private:
IsGlobalDelete _is_global;
const IsArrayDelete _is_array;
private:
FogDeleteExpr(const This& anExpr);
public:
FogDeleteExpr(FogExpr& anExpr, IsArrayDelete isArray) : Super(anExpr), _is_global(SCOPED_DELETE), _is_array(isArray) {}
virtual size_t executable_tokens() const;
virtual std::ostream& print_viz(std::ostream& s) const;
virtual bool resolve_semantics(FogSemanticsContext& theSemantics) const;
void set_global() { _is_global = GLOBAL_DELETE; }
};
#endif
|
// Copyright 2013 Daniel Parker
// Distributed under Boost license
#include <boost/test/unit_test.hpp>
#include <jsoncons/json.hpp>
#include <jsoncons/json_serializer.hpp>
#include <jsoncons/json_parser.hpp>
#include <jsoncons/json_decoder.hpp>
#include <sstream>
#include <vector>
#include <utility>
#include <ctime>
using namespace jsoncons;
BOOST_AUTO_TEST_SUITE(json_parser_tests)
BOOST_AUTO_TEST_CASE(test_object)
{
jsoncons::json_decoder<json> decoder;
json_parser parser(decoder);
parser.reset();
static std::string s("{}");
parser.set_source(s.data(),s.length());
parser.parse();
BOOST_CHECK(parser.done());
parser.end_parse();
json j = decoder.get_result();
}
BOOST_AUTO_TEST_CASE(test_array)
{
jsoncons::json_decoder<json> decoder;
json_parser parser(decoder);
parser.reset();
static std::string s("[]");
parser.set_source(s.data(),s.length());
parser.parse();
BOOST_CHECK(parser.done());
parser.end_parse();
json j = decoder.get_result();
}
BOOST_AUTO_TEST_CASE(test_string)
{
jsoncons::json_decoder<json> decoder;
json_parser parser(decoder);
parser.reset();
static std::string s("\"\"");
parser.set_source(s.data(),s.length());
parser.parse();
BOOST_CHECK(parser.done());
parser.end_parse();
json j = decoder.get_result();
}
BOOST_AUTO_TEST_CASE(test_integer)
{
jsoncons::json_decoder<json> decoder;
json_parser parser(decoder);
parser.reset();
static std::string s("10");
parser.set_source(s.data(),s.length());
parser.parse();
BOOST_CHECK(!parser.done());
parser.end_parse();
BOOST_CHECK(parser.done());
json j = decoder.get_result();
}
BOOST_AUTO_TEST_CASE(test_integer_space)
{
jsoncons::json_decoder<json> decoder;
json_parser parser(decoder);
parser.reset();
static std::string s("10 ");
parser.set_source(s.data(),s.length());
parser.parse();
BOOST_CHECK(parser.done());
parser.end_parse();
json j = decoder.get_result();
}
BOOST_AUTO_TEST_CASE(test_double_space)
{
jsoncons::json_decoder<json> decoder;
json_parser parser(decoder);
parser.reset();
static std::string s("10.0 ");
parser.set_source(s.data(),s.length());
parser.parse();
BOOST_CHECK(parser.done());
parser.end_parse();
json j = decoder.get_result();
}
BOOST_AUTO_TEST_CASE(test_false)
{
jsoncons::json_decoder<json> decoder;
json_parser parser(decoder);
parser.reset();
static std::string s("false");
parser.set_source(s.data(),s.length());
parser.parse();
BOOST_CHECK(parser.done());
parser.end_parse();
json j = decoder.get_result();
}
BOOST_AUTO_TEST_CASE(test_true)
{
jsoncons::json_decoder<json> decoder;
json_parser parser(decoder);
parser.reset();
static std::string s("true");
parser.set_source(s.data(),s.length());
parser.parse();
BOOST_CHECK(parser.done());
parser.end_parse();
json j = decoder.get_result();
}
BOOST_AUTO_TEST_CASE(test_null)
{
jsoncons::json_decoder<json> decoder;
json_parser parser(decoder);
parser.reset();
static std::string s("null");
parser.set_source(s.data(),s.length());
parser.parse();
BOOST_CHECK(parser.done());
parser.end_parse();
json j = decoder.get_result();
}
BOOST_AUTO_TEST_CASE(test_array_string)
{
jsoncons::json_decoder<json> decoder;
json_parser parser(decoder);
parser.reset();
static std::string s1("[\"\"");
parser.set_source(s1.data(),s1.length());
parser.parse();
BOOST_CHECK(!parser.done());
static std::string s2("]");
parser.set_source(s2.data(), s2.length());
parser.parse();
BOOST_CHECK(parser.done());
parser.end_parse();
json j = decoder.get_result();
}
BOOST_AUTO_TEST_SUITE_END()
|
/*
HOW TO USE:
spritemanager is basic class to manage load and release sprite and texture.
It load all image you have, if you want to use sprite any where, just getSprite from SpriteManager.
if you dont want you use this image any more, you can call release.
everytime use this, you have to call SpriteManager::getInstance() first.
this is Singleton format.
Seemore about Singleton: http://www.stdio.vn/articles/read/224/singleton-pattern
you can call directly: SpriteManager::getInstance()->DOSOMETHING()
or reference it:
SpriteManager* _spritemanager;
...
_spritemanager = SpriteManager::getInstance();
...
_spritemanager->DOSOMETHING()
Next, you should call loadresource(LPD3DXSPRITE spriteHandle) in Game::loadresource().
It will load all your image from file to memory.
Remember: Insert your code to loadresource to load image from file.
If you want object reference to Sprite. call:
SpriteManager::getInstance()->getSprite(eID::OBJECT_ID)
what is eID::OBJECT_ID ?
in define.h you can insert element to eID.
OK. Now you have sprite to draw.
If you dont want to use this sprite any more, call releaseSprite or releaseTexture
they often are called in object::release
Call SpriteManager::release() in game:release() to clean all memory.
*/
#include "SpriteManager.h"
US_FRAMEWORK
SpriteManager* SpriteManager::_instance = nullptr;
SpriteManager::SpriteManager(void)
{
// do nothing.
}
SpriteManager::~SpriteManager(void)
{
for (auto spr = _listSprite.begin(); spr != _listSprite.end(); ++spr)
{
spr->second->release(); // release image
delete spr->second; // delete sprite
}
if (_listSprite.empty() == false)
_listSprite.clear(); // remove all from MAP
}
void SpriteManager::loadResource(LPD3DXSPRITE spriteHandle)
{
/* if you have any image, load them with this format */
// [psedue code]
// sp = new SPRITE(...)
// this->_listSprite.insert(pair<eID, Sprite*>(eID::ENUMOBJECT, sp));
Sprite* sp = NULL;
sp = new Sprite(spriteHandle, L"Resource//Images//Soldier.png",10,10);
this->_listSprite.insert(pair<eID, Sprite*>(eID::SOLDIER, sp));
this->loadSpriteInfo(eID::SOLDIER, "Resource//Images//soldier_animation.txt");
sp = new Sprite(spriteHandle, L"Resource//Images//rifleman.png", 10, 10);
this->_listSprite.insert(pair<eID, Sprite*>(eID::RIFLEMAN, sp));
this->loadSpriteInfo(eID::RIFLEMAN, "Resource//Images//rifleman_animation.txt");
Sprite* bill = new Sprite(spriteHandle, L"Resource//Images//bill_animation.png");
this->_listSprite[eID::BILL] = bill;
this->loadSpriteInfo(eID::BILL, "Resource//Images//bill_animation.txt");
sp = new Sprite(spriteHandle, L"Resource//Images//Falcon.png");
this->_listSprite.insert(pair<eID, Sprite*>(eID::FALCON, sp));
this->loadSpriteInfo(eID::FALCON, "Resource//Images//falcon_animation.txt");
sp = new Sprite(spriteHandle, L"Resource//Images//Cannon_all.png", 15, 5);
this->_listSprite[eID::REDCANNON] = sp;
this->loadSpriteInfo(eID::REDCANNON, "Resource//Images//cannon_animation.txt");
sp = new Sprite(spriteHandle, L"Resource//Images//wall_turret_all.png", 42, 9);
this->_listSprite[eID::WALL_TURRET] = sp;
this->loadSpriteInfo(eID::WALL_TURRET, "Resource//Images//Wall_turret_animation.txt");
sp = new Sprite(spriteHandle, L"Resource//Images//effect_waterfall.png", 2, 2);
this->_listSprite[eID::WATERFALLEFFECT] = sp;
this->loadSpriteInfo(eID::WATERFALLEFFECT, "Resource//Images//effect_waterfall.txt");
sp = new Sprite(spriteHandle, L"Resource//Images//effect_water.png", 2, 2);
this->_listSprite[eID::WATEREFFECT] = sp;
this->loadSpriteInfo(eID::WATEREFFECT, "Resource//Images//effect_water.txt");
//
sp = new Sprite(spriteHandle, L"Resource//Images//aircraft.png", 10, 10);
this->_listSprite[eID::AIRCRAFT] = sp;
this->loadSpriteInfo(eID::AIRCRAFT, "Resource//Images//aircraft_animation.txt");
sp = new Sprite(spriteHandle, L"Resource//Images//falcon.png", 7, 7);
this->_listSprite[eID::FALCON] = sp;
this->loadSpriteInfo(eID::FALCON, "Resource//Images//falcon_animation.txt");
sp = new Sprite(spriteHandle, L"Resource//Images//explosion.png");
this->_listSprite[eID::EXPLOSION] = sp;
this->loadSpriteInfo(eID::EXPLOSION, "Resource//Images//explosion_animation.txt");
sp = new Sprite(spriteHandle, L"Resource//Images//boss_stage1.png");
this->_listSprite[eID::BOSS_STAGE1] = sp;
this->loadSpriteInfo(eID::BOSS_STAGE1, "Resource//Images//boss_stage1_animation.txt");
sp = new Sprite(spriteHandle, L"Resource//Images//bridge.png", 6, 3);
this->_listSprite[eID::BRIDGE] = sp;
auto bl = new Sprite(spriteHandle, L"Resource//Images//Bullets.png");
this->_listSprite[eID::BULLET] = bl;
this->loadSpriteInfo(eID::BULLET, "Resource//Images//bullets_type.txt");
sp = new Sprite(spriteHandle, L"Resource//Map//stage1.png", 120, 10);
sp->setOrigin(VECTOR2ZERO);
this->_listSprite[eID::MAP1] = sp;
sp = new Sprite(spriteHandle, L"Resource//Map//stage3.png", 140, 10);
sp->setOrigin(VECTOR2ZERO);
this->_listSprite[eID::MAP3] = sp;
sp = new Sprite(spriteHandle, L"Resource//Images//stage3_elements.png", 5, 5);
this->_listSprite[eID::ROCKFLY] = sp;
this->loadSpriteInfo(eID::ROCKFLY, "Resource//Images//rockfly_animation.txt");
this->_listSprite[eID::SHADOW_ARM] = sp;
this->loadSpriteInfo(eID::SHADOW_ARM, "Resource//Images//shadowarm_animation.txt");
sp = new Sprite(spriteHandle, L"Resource//Images//ScubaSoldier.png");
this->_listSprite[eID::SCUBASOLDIER] = sp;
this->loadSpriteInfo(eID::SCUBASOLDIER, "Resource//Images//scubasoldier_animation.txt");
sp = new Sprite(spriteHandle, L"Resource//Images//Life.png");
this->_listSprite[eID::LIFE_ICON] = sp;
this->loadSpriteInfo(eID::LIFE_ICON, "Resource//Images//life_info.txt");
sp = new Sprite(spriteHandle, L"Resource//Images//intro.png");
this->_listSprite[eID::MENU] = sp;
sp = new Sprite(spriteHandle, L"Resource//Images//yellowfalcon.png");
this->_listSprite[eID::YELLOWFALCON] = sp;
sp = new Sprite(spriteHandle, L"Resource/Images//BeginState3.png");
this->_listSprite[eID::BEGIN_STAGE3] = sp;
sp = new Sprite(spriteHandle, L"Resource//Images//GameOver.png");
this->_listSprite[eID::GAME_OVER_SCENE] = sp;
sp = new Sprite(spriteHandle, L"Resource//Images//boss_stage3.png");
this->_listSprite[eID::SHADOW_MOUTH] = sp;
this->loadSpriteInfo(eID::SHADOW_MOUTH, "Resource//Images//shadowbeast_animation.txt");
sp = new Sprite(spriteHandle, L"Resource//Images//fire.png");
this->_listSprite[eID::FIRE] = sp;
this->loadSpriteInfo(eID::FIRE, "Resource//Images//fire_animation.txt");
sp = new Sprite(spriteHandle, L"Resource//Images//rockfall.png", 4, 4);
this->_listSprite[eID::ROCKFALL] = sp;
this->loadSpriteInfo(eID::ROCKFALL, "Resource//Images//rockfall_animation.txt");
sp = new Sprite(spriteHandle, L"Resource//Images//fontEx.png", 30, 10);
this->_listSprite[eID::FONTEX] = sp;
sp = new Sprite(spriteHandle, L"Resource//Images//fontFull.png", 54, 6);
this->_listSprite[eID::FONTFULL] = sp;
}
Sprite* SpriteManager::getSprite(eID id)
{
Sprite *it = this->_listSprite.find(id)->second;
return new Sprite(*it); // get the copy version of Sprite
}
RECT SpriteManager::getSourceRect(eID id, string name)
{
//return _sourceRectList[id].at(name);
return _sourceRectList[id][name];
}
void SpriteManager::releaseSprite(eID id)
{
Sprite *it = this->_listSprite.find(id)->second;
delete it; // delete the sprite only, dont relase image
this->_listSprite.erase(id); // erase funciotn only remove the pointer from MAP, dont delete it.
}
void SpriteManager::releaseTexture(eID id)
{
Sprite *spr = this->_listSprite.find(id)->second;
spr->release(); // release image
delete spr;
this->_listSprite.erase(id); // erase funciotn only remove the pointer from MAP, dont delete it.
}
SpriteManager* SpriteManager::getInstance()
{
if (_instance == nullptr)
_instance = new SpriteManager();
return _instance;
}
void SpriteManager::release()
{
delete _instance; // _instance is static attribute, only static function can delete it.
_instance = nullptr;
}
void SpriteManager::loadSpriteInfo(eID id, const char* fileInfoPath)
{
FILE* file;
file = fopen(fileInfoPath, "r");
if (file)
{
while (!feof(file))
{
RECT rect;
char name[100];
fgets(name, 100, file);
fscanf(file, "%s %d %d %d %d", &name, &rect.left, &rect.top, &rect.right, &rect.bottom);
_sourceRectList[id][string(name)] = rect;
}
}
fclose(file);
}
|
#ifndef __CONCRETE_STATE_H__
#define __CONCRETE_STATE_H__
#include "State.h"
class Order : public State
{
public:
virtual void process() override;
};
class Pay : public State
{
public:
virtual void process() override;
};
class Ordered : public State
{
public:
virtual void process() override;
};
class Finish : public State
{
public:
virtual void process() override;
};
#endif // __CONCRETE_STATE_H__
|
///////////////////////////////////////////////////////////////////
//Copyright 2019-2020 Perekupenko Stanislav. All Rights Reserved.//
//@Author Perekupenko Stanislav (stanislavperekupenko@gmail.com) //
///////////////////////////////////////////////////////////////////
#include "CPP_PlayerController.h"
ACPP_PlayerController::ACPP_PlayerController() {
bEnableClickEvents = true;
bShowMouseCursor = true;
DefaultClickTraceChannel = ECollisionChannel::ECC_GameTraceChannel2;
}
|
#if (defined HAS_VTK)
#include <irtkImage.h>
//#include <nr.h>
//#include <time.h>
//#include <unistd.h>
#include <gsl/gsl_rng.h>
#include <sys/time.h>
#include <vtkMath.h>
#include <vtkPointData.h>
#include <vtkCell.h>
#include <vtkFloatArray.h>
#include <vtkIdList.h>
#include <vtkPolyData.h>
#include <vtkPolyDataReader.h>
#include <vtkPolyDataWriter.h>
char *input_name = NULL;
char *output_name = NULL;
char *scalar_name = NULL;
void usage()
{
cerr << " " << endl;
cerr << " Usage: polydatarandomscalars [input] [output] <options>" << endl;
cerr << " " << endl;
cerr << " Random scalars given to input surface. Uniform distribution in [0,1]." << endl;
cerr << " " << endl;
cerr << " " << endl;
cerr << " Options:" << endl;
cerr << " -name name : Give the output scalars the name 'name'" << endl;
cerr << " -seed M : Seed for random number generator." << endl;
cerr << " " << endl;
cerr << " " << endl;
exit(1);
}
int main(int argc, char **argv)
{
long i;
int noOfPoints;
bool ok;
if (argc < 3){
usage();
}
// Prepare for random stuff.
gsl_rng * ranGen;
// const gsl_rng_type * ranGenType;
gsl_rng_env_setup();
// ranGenType = gsl_rng_default;
ranGen = gsl_rng_alloc (gsl_rng_mt19937);
timeval tv;
gettimeofday(&tv, NULL);
unsigned long init = tv.tv_usec;
// Parse arguments.
input_name = argv[1];
argv++;
argc--;
output_name = argv[1];
argv++;
argc--;
while (argc > 1){
ok = false;
if ((ok == false) && (strcmp(argv[1], "-name") == 0)){
argc--;
argv++;
scalar_name = argv[1];
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-seed") == 0)) {
argc--;
argv++;
init = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if (!ok){
cerr << "Cannot parse argument " << argv[1] << endl;
usage();
}
}
gsl_rng_set(ranGen, init);
cerr << "Input : " << input_name << endl;
cerr << "Output : " << output_name << endl;
// Read the polydata file
vtkPolyDataReader* reader = vtkPolyDataReader::New();
reader->SetFileName(input_name);
reader->Update();
vtkPolyData* input = reader->GetOutput();
noOfPoints = input->GetNumberOfPoints();
vtkFloatArray *scalars = vtkFloatArray::New();
scalars->SetNumberOfComponents(1);
scalars->SetNumberOfTuples(noOfPoints);
for (i = 0; i < noOfPoints; ++i){
// scalars->SetTuple1(i, ran2(&ran2Seed));
scalars->SetTuple1(i, gsl_rng_uniform(ranGen));
}
if (scalar_name == NULL){
scalars->SetName("Random");
} else {
scalars->SetName(scalar_name);
}
input->GetPointData()->AddArray(scalars);
// Write the result.
vtkPolyDataWriter *writer = vtkPolyDataWriter::New();
writer->SetInputData(input);
writer->SetFileName(output_name);
writer->SetFileTypeToBinary();
writer->Update();
writer->Write();
}
#else
#include <irtkImage.h>
int main( int argc, char *argv[] ){
cerr << argv[0] << " needs to be compiled with the VTK library " << endl;
}
#endif
|
/*
Copyright (c) 2011 Andrew Wall
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "SuccessLogger.h"
#include "ProjectDescription.h"
namespace gppUnit {
using std::endl;
void LoggerAlgorithm::LogToFile(const std::string& fileName, const ProjectDescription* project) {
if(allowedToProceed(project)) {
if(fileExists(fileName)) {
openFileForAppend(fileName);
} else {
openFileForWriting(fileName);
writeHeader(fileName, project);
}
writeLog(project);
closeFile();
}
}
bool FileLogger::fileExists(const std::string& fileName) const {
std::ifstream ifile;
ifile.open(fileName.c_str(), std::ios::in);
bool ret = ifile.is_open();
ifile.close();
return ret;
}
void FileLogger::openFileForAppend(const std::string& fileName) {
openFile(fileName, std::ios::out | std::ios::app);
}
void FileLogger::openFileForWriting(const std::string& fileName) {
openFile(fileName, std::ios::out);
}
void FileLogger::openFile(const std::string& fileName, std::ios_base::openmode mode) {
file.open(fileName.c_str(), mode);
}
void FileLogger::closeFile() {
file.close();
}
bool SuccessLoggerImplementation::allowedToProceed(const ProjectDescription* project) const {
return project->hasPassed();
}
void SuccessLoggerImplementation::writeHeader(const std::string& fileName, const ProjectDescription* project) {
getFile() << "'table=1.1" << endl
<< "'" << fileName << " - Automatically created by gppUnit1.5" << endl
<< "unittests,name=" << project->name() << endl
<< "tests,units,date,time,runtime" << endl
;
}
void SuccessLoggerImplementation::writeLog(const ProjectDescription* project) {
getFile() << project->results() << ','
<< project->classes() << ','
<< getNow() << ','
<< project->run_time()
<< endl;
}
bool AllRunsLoggerImplementation::allowedToProceed(const ProjectDescription*) const {
return true;
}
void AllRunsLoggerImplementation::writeHeader(const std::string& fileName, const ProjectDescription* project) {
getFile() << "'table=1.1" << endl
<< "'" << fileName << " - Automatically created by gppUnit1.5" << endl
<< "unittests,name=" << project->name() << endl
<< "passed,tests,units,date,time,runtime" << endl
;
}
void AllRunsLoggerImplementation::writeLog(const ProjectDescription* project) {
getFile() << project->hasPassed() << ','
<< project->results() << ','
<< project->classes() << ','
<< getNow() << ','
<< project->run_time()
<< endl;
}
}
|
#include "Dish.h"
#include <iostream>
Dish::Dish()
{
}
Dish::Dish(const std::string& v_type)
{
this->type = v_type;
}
|
//
// Created by Vesper on 6/8/18.
//
// code note for modern c++ metaprogramming
// https://www.youtube.com/watch?v=JSR8YBhW_uM&t=5077s
#include <iostream>
#include <type_traits>
using namespace std;
struct HasX {int x;};
struct HasY {int y;};
template <typename T, typename=void >
constexpr bool has_x = false;
template <typename T>
constexpr bool has_x <T, void_t< decltype(T::x)>> =true;
template <typename T, typename = void>
constexpr bool has_x_of = false;
template<typename T>
constexpr bool has_x_of <T, decltype(T::x)> = true;
//Typelist
template <typename T, typename ...Types>
constexpr bool ContainsType = false;
// https://en.cppreference.com/w/cpp/language/parameter_pack
// A pattern followed by an ellipsis, in which the name of at least one parameter pack appears at least once,
// is expanded into zero or more comma-separated instantiations of the pattern, where the name of the parameter
// pack is replaced by each of the elements from the pack, in order.
template<typename T, typename ...Rest>
constexpr bool ContainsType<T,T,Rest...> = true;
// recursively calling itself
template<typename T, typename J, typename ...Rest>
constexpr bool ContainsType<T,J,Rest...> = ContainsType<T,Rest...>;
int main(){
static_assert(has_x<HasX>);
static_assert(!has_x<HasY>);
static_assert(has_x_of<HasX,int>);
static_assert(!has_x_of<HasY,int>);
static_assert(!has_x_of<HasX,float>);
static_assert(ContainsType<int, float, double, int, void>);
static_assert(!ContainsType<char, float, double, int, void>);
return 0;
}
|
// vesamode.h - VESA graphics mode
// (c) 1997, 2020 Michael Fink
// https://github.com/vividos/OldStuff/
#pragma once
#ifndef __vesa_mode_h_
#define __vesa_mode_h_
#include "defs.h"
#include "graphic.h"
struct vesa_vbe_info_block;
struct vesa_mode_info_block;
// base class for VESA graphics modes
// http://www.phatcode.net/res/221/files/vbe20.pdf
class vesa_mode : public graphics
{
public:
// returns if VESA bios extensions are available at all
static bool is_avail();
// prints out all available modes using printf
static void show_modes();
// finds a suitable graphics mode, with given parameters
static vesa_mode* find_mode(word xres, word yres,
byte bits_per_pixel, bool exact_match);
// ctor common for all vesa modes
vesa_mode(vesa_mode_info_block* mib, word mode);
// dtor
virtual ~vesa_mode();
// override some virtual methods that are common to all vesa modes
virtual void on();
virtual void off();
virtual byte far* get_framebuffer_ptr(word x, word y);
virtual void getpix(word x, word y, byte* pixel);
virtual void set_palette(const palette256 palette);
virtual void setpix(word x, word y, const byte* pixel);
virtual void setline(word x, word y, word
length_in_bytes, const byte* line);
// saves state of the video mode, e.g. to change to text mode
void save_mode();
// restores video mode state
void restore_mode();
private:
// retrieves vesa vbe info block
static bool get_vbe_info_block(vesa_vbe_info_block far* vib);
// returns currently used vesa mode, if any
static word get_current_vesa_mode();
// retrieves vesa mode info block for given mode
static bool get_mode_info_block(
vesa_mode_info_block far* mib, word mode);
// creates a graphics mode object from given vesa mode
static vesa_mode* create_mode(
vesa_mode_info_block far* mib, word mode);
protected:
// calculates buffer position in window or linear framebuffer
byte far* get_buffer_pos(word x, word y);
// sets new page
void set_page(word page);
protected:
// segment of frame buffer
word segment;
private:
// indicates if video mode has a linear framebuffer
bool has_linear_framebuffer;
// start of framebuffer, either the window, or the linear framebuffer
byte far* start;
// last page that was set
word last_page;
// mode word
word mode;
// bytes pre scanline
word bytes_per_line;
// window granularity, in kb
word granularity_kb;
// number of bits per pixel
byte bits_per_pixel;
// function to set frame in windowed mode
void (far* setframe)();
// saved video state; used in save_mode()/restore_mode()
byte far* saved_state_buffer;
};
// vesa mode implementation for 8-bit pixel formats
// these modes use a palette
class vesa_mode_8bit : public vesa_mode
{
public:
vesa_mode_8bit(vesa_mode_info_block* mib, word mode)
:vesa_mode(mib, mode)
{
}
virtual void set_palette(const palette256 palette);
};
// vesa mode implementation for 24-bit pixel formats
// these are true-color modes not using a palette
// pixels are stored as RR GG BB values
class vesa_mode_24bit : public vesa_mode
{
public:
vesa_mode_24bit(vesa_mode_info_block* mib, word mode)
: vesa_mode(mib, mode)
{
}
};
// vesa mode implementation for 15 and 16-bit pixel formats
// the pixel and line pointers point to word sized values, and color values
// are stored using 555 (15-bit) or 565 (16-bit) bit patterns
class vesa_mode_16bit : public vesa_mode
{
public:
vesa_mode_16bit(vesa_mode_info_block* mib, word mode)
: vesa_mode(mib, mode)
{
}
};
// vesa mode implementation for 4-bit pixel formats
// the pixel and line parameters still contain pointer to bytes
class vesa_mode_4bit : public vesa_mode
{
public:
vesa_mode_4bit(vesa_mode_info_block* mib, word mode)
: vesa_mode(mib, mode)
{
}
virtual void setpix(word x, word y, const byte* pixel);
virtual void setline(word x, word y, word length, const byte* line);
virtual void set_palette(const palette256 palette);
};
#endif
|
/*
Copyright (c) 2005-2023, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef QUADRATICMESHHELPER_HPP_
#define QUADRATICMESHHELPER_HPP_
#include "AbstractTetrahedralMesh.hpp"
#include "TrianglesMeshReader.hpp"
/**
* A helper class for QuadraticMesh and DistributedQuadratic mesh, containing utility methods
* that are common to both classes (and only require public access).
*/
template<unsigned DIM>
class QuadraticMeshHelper
{
public:
/**
* Top level method for adding internal nodes to the mesh's elements.
*
* Note that the internal nodes must already exist in the mesh; this method just associates them with
* the relevant elements.
*
* @param pMesh the mesh to modify
* @param pMeshReader pointer to the reader for accessing the on-disk mesh data
*/
static void AddInternalNodesToElements(AbstractTetrahedralMesh<DIM, DIM>* pMesh,
AbstractMeshReader<DIM,DIM>* pMeshReader);
/**
* Top level method for adding internal nodes to the mesh's boundary elements.
*
* Note that the internal nodes must already exist in the mesh; this method just associates them with
* the relevant boundary elements. If the mesh on disk has internal node indices in the boundary
* elements file, then we just look them up. Otherwise we figure out which normal element has each
* boundary element as a face, and extract the internal nodes from that.
*
* @param pMesh the mesh to modify
* @param pMeshReader pointer to the reader for accessing the on-disk mesh data
*/
static void AddInternalNodesToBoundaryElements(AbstractTetrahedralMesh<DIM, DIM>* pMesh,
AbstractMeshReader<DIM,DIM>* pMeshReader);
/**
* Used by AddInternalNodesToBoundaryElements in the case where the on-disk mesh doesn't have
* the associations already, and by the linear -> quadratic mesh conversion routines.
*
* If there is an on-mesh disk that has containing element information in its edge/face file,
* then this can be supplied to speed up finding the full element containing each boundary element.
*
* @param pMesh the mesh to modify
* @param pMeshReader pointer to the reader for accessing the on-disk mesh data, if any; NULL otherwise
*/
static void AddNodesToBoundaryElements(AbstractTetrahedralMesh<DIM, DIM>* pMesh,
AbstractMeshReader<DIM,DIM>* pMeshReader);
/**
* Check whether all the boundary elements in the given mesh have the expected number of nodes.
*
* @param pMesh the mesh to check
*/
static void CheckBoundaryElements(AbstractTetrahedralMesh<DIM, DIM>* pMesh);
/**
* This method adds the given node (defined by an element and a node index)
* to the given boundary element, and also sets the node as a boundary
* node and adds it to the mesh's boundary nodes.
*
* @param pMesh the (quadratic) mesh to modify
* @param pBoundaryElement pointer to a boundary element in the mesh
* @param pElement pointer to an element in the mesh
* @param internalNode index of a node in the mesh
*/
static void AddNodeToBoundaryElement(AbstractTetrahedralMesh<DIM, DIM>* pMesh,
BoundaryElement<DIM-1,DIM>* pBoundaryElement,
Element<DIM,DIM>* pElement,
unsigned internalNode);
/**
* This method adds the given node to the given boundary element, and also sets
* the node as a boundary node and adds it to the mesh's boundary nodes.
*
* @param pMesh the (quadratic) mesh to modify
* @param pBoundaryElement pointer to a boundary element in the mesh
* @param pNode pointer to a node in the mesh
*/
static void AddNodeToBoundaryElement(AbstractTetrahedralMesh<DIM, DIM>* pMesh,
BoundaryElement<DIM-1,DIM>* pBoundaryElement,
Node<DIM>* pNode);
/**
* Given a face in an element (defined by giving an element and the opposite
* node number to the face) that corresponds to a given boundary element,
* this method adds in the face's internal nodes to the boundary element
* (in the correct order).
*
* @param pMesh the (quadratic) mesh to modify
* @param pBoundaryElement pointer to a boundary element in the mesh
* @param pElement pointer to an element in the mesh
* @param nodeIndexOppositeToFace index of a node in the mesh
*/
static void AddExtraBoundaryNodes(AbstractTetrahedralMesh<DIM, DIM>* pMesh,
BoundaryElement<DIM-1,DIM>* pBoundaryElement,
Element<DIM,DIM>* pElement,
unsigned nodeIndexOppositeToFace);
/**
* Nasty helper method for AddNodeToBoundaryElement() in 3D.
*
* This method takes in the three vertices of a face which match the given boundary
* element, and figure out if the order of the nodes in the face is reversed in
* the boundary element (returned in the bool 'rReverse'). Also, the offset between
* the first node in the face (as given to this method) and the first node in
* the boundary element is computed (returned in the variable 'rOffset'). Offset
* should then be applied before reverse to match the face nodes to the boundary
* element nodes.
*
* \todo document these parameters
*
* @param boundaryElemNode0
* @param boundaryElemNode1
* @param pElement
* @param node0
* @param node1
* @param node2
* @param rOffset
* @param rReverse
*/
static void HelperMethod1(unsigned boundaryElemNode0, unsigned boundaryElemNode1,
Element<DIM,DIM>* pElement,
unsigned node0, unsigned node1, unsigned node2,
unsigned& rOffset,
bool& rReverse);
/**
* Nasty helper method for AddNodeToBoundaryElement() in 3D.
*
* This method takes the three internal nodes for some face in some element,
* applies the given offset and reverse (see HelperMethod1) to them, to get
* the ordered internal nodes which should given to the boundary element.
* It then calls AddNodeToBoundaryElement with each of the three internal nodes.
*
* \todo document these parameters
*
* @param pMesh
* @param pBoundaryElement
* @param pElement
* @param internalNode0
* @param internalNode1
* @param internalNode2
* @param offset
* @param reverse
*/
static void HelperMethod2(AbstractTetrahedralMesh<DIM, DIM>* pMesh,
BoundaryElement<DIM-1,DIM>* pBoundaryElement,
Element<DIM,DIM>* pElement,
unsigned internalNode0, unsigned internalNode1, unsigned internalNode2,
unsigned offset,
bool reverse);
};
#endif // QUADRATICMESHHELPER_HPP_
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
int a[10000];
for (int i=0; i<n; i++) cin >> a[i];
sort(a, a+n);
for (int i=0; i<n-1; i++)
for (int j=i+1; j<n; j++)
if (!(a[i]+a[j]))
{
cout << a[i] << ' ' << a[j] << endl;
}
return 0;
}
|
/***********************************************************************
created: 24/9/2004
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#ifndef _CEGuiBaseApplication_h_
#define _CEGuiBaseApplication_h_
#include <vector>
#include "CEGUI/String.h"
#include "CEGUI/text/RenderedText.h"
// If this looks wanky, it's becase it is! Behold that this is not as fullblown
// as it could be though.
#ifndef PATH_MAX
# include <stdlib.h>
# ifndef PATH_MAX
# include <limits.h>
# endif
# ifndef PATH_MAX
# ifdef _MAX_PATH
# define PATH_MAX _MAX_PATH
# else
# define PATH_MAX 260
# endif
# endif
#endif
/*************************************************************************
Forward refs
*************************************************************************/
class SampleBrowserBase;
namespace CEGUI
{
class Renderer;
class ImageCodec;
class ResourceProvider;
class GeometryBuffer;
class EventArgs;
class GUIContext;
}
/*!
\brief
Base application abstract base class.
The "BaseApplication" family of classes are used to start up and run a
host application for CeGui samples in a consistent manner.
*/
class CEGuiBaseApplication
{
public:
//! Constructor.
CEGuiBaseApplication();
//! Destructor
virtual ~CEGuiBaseApplication();
/*!
\brief
Initialise the base application.
This will fully initialise the application, finish initialisation of the
demo via calls to 'sampleApp', and finally control execution of the
sample. This calls calls the virtual run function.
Classes that override this method must first call the implementation of
the superclass!
\param sampleApp
Pointer to the CEGuiSample object that the CEGuiBaseApplication is being
invoked for.
\return
- true if the application initialised okay (cleanup function will be
called).
*/
virtual bool init(SampleBrowserBase* sampleApp,
const CEGUI::String& logFile,
const CEGUI::String& dataPathPrefixOverride);
/*!
\brief
Performs any required cleanup of the base application system.
Classes that override this method must, lastly, call the implementation
of the superclass!
*/
virtual void cleanup();
virtual void destroyRenderer();
/*!
\brief
Render a single display frame. This should be called by subclasses to
perform rendering.
This function handles all per-frame updates, calls beginRendering, then
renders the CEGUI output, and finally calls endRendering.
\param elapsed
Number of seconds elapsed since last frame.
*/
void renderSingleFrame(const float elapsed);
/*!
\brief
Return the path prefix to use for datafiles. The value returned
is obtained via a environment variable named 'CEGUI_SAMPLE_DATAPATH'
if the variable is not set, a default will be used depending on the
build system in use.
*/
CEGUI::String getDataPathPrefix() const { return d_dataPathPrefix; }
void initDataPathPrefix(const CEGUI::String &override);
/*!
\brief
Registers the overlay handler for rendering the FPS for a specified GUIContext.
This will be used to render the overlay for the specific samples.
/param gui_context
The sample's GUIContext for which we will register the overlay rendering.
*/
void registerSampleOverlayHandler(CEGUI::GUIContext* gui_context);
/*!
\brief
Return the main window GUI context
*/
CEGUI::GUIContext* getMainWindowGUIContext() const { return d_context; }
//! The abstract function for running the application.
virtual void run() {}
protected:
//! name of env var that holds the path prefix to the data files.
static const char DATAPATH_VAR_NAME[];
//! The abstract function for destroying the renderer and the window.
virtual void destroyWindow() = 0;
//! Implementation function to perform required pre-render operations.
virtual void beginRendering(const float elapsed) = 0;
//! Implementation function to perform required post-render operations.
virtual void endRendering() = 0;
/*!
\brief
Setup standard sample resource group directory locations. Default uses
the CEGUI::DefaultResourceProvider - override if the sample base app
being implemented uses something else!
*/
virtual void initialiseResourceGroupDirectories();
//! initialise the standard default resource groups used by the samples.
virtual void initialiseDefaultResourceGroups();
//! function that updates the FPS rendering as needed.
void updateFPS(const float elapsed);
//! function that updates the logo rotation as needed.
void updateLogo(const float elapsed);
//! function that positions the logo GeometryBuffer at the correct place.
void updateLogoGeometry();
//! function that positions the FPS GeometryBuffer at the correct place.
void updateFPSGeometry();
//! function that updates the rotation of the logo.
void updateLogoGeometryRotation();
//! event handler function that draws the logo and FPS overlay elements.
bool sampleBrowserOverlayHandler(const CEGUI::EventArgs& args);
//! event handler function called when main view is resized
bool resizeHandler(const CEGUI::EventArgs& args);
//! SampleFramework base used in the application
static SampleBrowserBase* d_sampleApp;
//! The window width the application should get created with at start
static const int s_defaultWindowWidth = 1280;
//! The window height the application should get created with at start
static const int s_defaultWindowHeight = 720;
//! true when the base app should cleanup and exit.
bool d_quitting;
//! Renderer to use. This MUST be set in the subclass constructor.
CEGUI::Renderer* d_renderer;
//! ImageCodec to use. Set in subclass constructor, may be 0.
CEGUI::ImageCodec* d_imageCodec;
//! ResourceProvider to use. Set in subclass constructor, may be 0.
CEGUI::ResourceProvider* d_resourceProvider;
//! GUI context of the main window
CEGUI::GUIContext* d_context;
//! GeometryBuffer used for drawing the spinning CEGUI logo
std::vector<CEGUI::GeometryBuffer*> d_logoGeometry;
//! GeometryBuffers used for drawing the FPS value.
std::vector<CEGUI::GeometryBuffer*> d_FPSGeometry;
//! Fraction of second elapsed (used for counting frames per second).
float d_FPSElapsed;
//! Number of frames drawn so far.
int d_FPSFrames;
//! Last changed FPS value.
int d_FPSValue;
//! whether to spin the logo
bool d_spinLogo;
CEGUI::RenderedText d_fpsRenderedText;
private:
CEGUI::String d_dataPathPrefix;
};
#endif // end of guard _CEGuiBaseApplication_h_
|
#ifndef DOWNLOAD_LISTENER_H
#define DOWNLOAD_LISTENER_H
#include <megaapi.h>
class file_cache_item;
class download_listener : public mega::MegaTransferListener
{
file_cache_item &cache_item;
std::string id;
public:
download_listener(file_cache_item &cache_item);
virtual void onTransferStart(mega::MegaApi *, mega::MegaTransfer *);
virtual void onTransferUpdate(mega::MegaApi *, mega::MegaTransfer *);
virtual void onTransferFinish(mega::MegaApi *,
mega::MegaTransfer *,
mega::MegaError *);
};
#endif // DOWNLOAD_LISTENER_H
|
//**************************************************************************
//**
//** See jlquake.txt for copyright info.
//**
//** This program is free software; you can redistribute it and/or
//** modify it under the terms of the GNU General Public License
//** as published by the Free Software Foundation; either version 3
//** of the License, or (at your option) any later version.
//**
//** This program is distributed in the hope that it will be useful,
//** but WITHOUT ANY WARRANTY; without even the implied warranty of
//** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//** included (gnu.txt) GNU General Public License for more details.
//**
//**************************************************************************
#include "local.h"
#include "../../client_main.h"
#include "../particles.h"
#include "../dynamic_lights.h"
#include "../../../common/Common.h"
#include "../../../common/common_defs.h"
static sfxHandle_t clh2_sfx_tink1;
static sfxHandle_t clh2_sfx_ric1;
static sfxHandle_t clh2_sfx_ric2;
static sfxHandle_t clh2_sfx_ric3;
static sfxHandle_t clh2_sfx_r_exp3;
sfxHandle_t clh2_sfx_icestorm;
static sfxHandle_t clh2_sfx_lightning1;
static sfxHandle_t clh2_sfx_lightning2;
static sfxHandle_t clh2_sfx_sunstaff;
static sfxHandle_t clh2_sfx_sunhit;
static sfxHandle_t clh2_sfx_hammersound;
static sfxHandle_t clh2_sfx_buzzbee;
void CLH2_InitTEnts() {
clh2_sfx_tink1 = S_RegisterSound( "weapons/tink1.wav" );
clh2_sfx_ric1 = S_RegisterSound( "weapons/ric1.wav" );
clh2_sfx_ric2 = S_RegisterSound( "weapons/ric2.wav" );
clh2_sfx_ric3 = S_RegisterSound( "weapons/ric3.wav" );
if ( GGameType & GAME_HexenWorld ) {
clh2_sfx_r_exp3 = S_RegisterSound( "weapons/r_exp3.wav" );
clh2_sfx_icestorm = S_RegisterSound( "crusader/blizzard.wav" );
clh2_sfx_lightning1 = S_RegisterSound( "crusader/lghtn1.wav" );
clh2_sfx_lightning2 = S_RegisterSound( "crusader/lghtn2.wav" );
clh2_sfx_sunstaff = S_RegisterSound( "crusader/sunhum.wav" );
clh2_sfx_sunhit = S_RegisterSound( "crusader/sunhit.wav" );
clh2_sfx_hammersound = S_RegisterSound( "paladin/axblade.wav" );
clh2_sfx_buzzbee = S_RegisterSound( "assassin/scrbfly.wav" );
CLHW_InitExplosionSounds();
}
}
void CLH2_ClearTEnts() {
CLH2_ClearExplosions();
CLH2_ClearStreams();
}
int CLH2_TempSoundChannel() {
static int last = -1;
if ( !( GGameType & GAME_HexenWorld ) ) {
return -1;
}
last--;
if ( last < -20 ) {
last = -1;
}
return last;
}
h2entity_state_t* CLH2_FindState( int entityNumber ) {
static h2entity_state_t pretend_player;
if ( !( GGameType & GAME_HexenWorld ) ) {
return &h2cl_entities[ entityNumber ].state;
}
if ( entityNumber >= 1 && entityNumber <= MAX_CLIENTS_QHW ) {
if ( entityNumber == cl.viewentity ) {
VectorCopy( cl.qh_simorg, pretend_player.origin );
} else {
VectorCopy( cl.hw_frames[ clc.netchan.incomingSequence & UPDATE_MASK_HW ].playerstate[ entityNumber - 1 ].origin, pretend_player.origin );
}
return &pretend_player;
}
hwpacket_entities_t* pack = &cl.hw_frames[ clc.netchan.incomingSequence & UPDATE_MASK_HW ].packet_entities;
for ( int pnum = 0; pnum < pack->num_entities; pnum++ ) {
if ( pack->entities[ pnum ].number == entityNumber ) {
return &pack->entities[ pnum ];
}
}
return NULL;
}
static void CLH2_ParseWizSpike( QMsg& message ) {
vec3_t pos;
message.ReadPos( pos );
CLH2_RunParticleEffect( pos, oldvec3_origin, 30 );
}
static void CLH2_ParseKnightSpike( QMsg& message ) {
vec3_t pos;
message.ReadPos( pos );
CLH2_RunParticleEffect( pos, oldvec3_origin, 20 );
}
static void CLH2_ParseSpikeCommon( QMsg& message, int count ) {
vec3_t pos;
message.ReadPos( pos );
CLH2_RunParticleEffect( pos, oldvec3_origin, count );
if ( rand() % 5 ) {
S_StartSound( pos, CLH2_TempSoundChannel(), 0, clh2_sfx_tink1, 1, 1 );
} else {
int rnd = rand() & 3;
if ( rnd == 1 ) {
S_StartSound( pos, CLH2_TempSoundChannel(), 0, clh2_sfx_ric1, 1, 1 );
} else if ( rnd == 2 ) {
S_StartSound( pos, CLH2_TempSoundChannel(), 0, clh2_sfx_ric2, 1, 1 );
} else {
S_StartSound( pos, CLH2_TempSoundChannel(), 0, clh2_sfx_ric3, 1, 1 );
}
}
}
static void CLH2_ParseSpike( QMsg& message ) {
CLH2_ParseSpikeCommon( message, 10 );
}
static void CLH2_ParseSuperSpike( QMsg& message ) {
CLH2_ParseSpikeCommon( message, 20 );
}
static void CLH2_ParseExplosion( QMsg& message ) {
vec3_t pos;
message.ReadPos( pos );
CLH2_ParticleExplosion( pos );
}
static void CLHW_ParseExplosion( QMsg& message ) {
// particles
vec3_t pos;
message.ReadPos( pos );
CLH2_ParticleExplosion( pos );
// light
CLH2_ExplosionLight( pos );
// sound
S_StartSound( pos, CLH2_TempSoundChannel(), 0, clh2_sfx_r_exp3, 1, 1 );
}
static void CLH2_ParseBeam( QMsg& message ) {
message.ReadShort();
message.ReadCoord();
message.ReadCoord();
message.ReadCoord();
message.ReadCoord();
message.ReadCoord();
message.ReadCoord();
}
static void CLHW_ParseTarExplosion( QMsg& message ) {
vec3_t pos;
message.ReadPos( pos );
CLH2_BlobExplosion( pos );
S_StartSound( pos, CLH2_TempSoundChannel(), 0, clh2_sfx_r_exp3, 1, 1 );
}
static void CLH2_ParseLavaSplash( QMsg& message ) {
vec3_t pos;
message.ReadPos( pos );
CLH2_LavaSplash( pos );
}
static void CLH2_ParseTeleport( QMsg& message ) {
vec3_t pos;
message.ReadPos( pos );
CLH2_TeleportSplash( pos );
}
static void CLHW_ParseGunShot( QMsg& message ) {
int cnt = message.ReadByte();
vec3_t pos;
message.ReadPos( pos );
CLH2_RunParticleEffect( pos, oldvec3_origin, 20 * cnt );
}
static void CLHW_ParseLightningBlood( QMsg& message ) {
vec3_t pos;
message.ReadPos( pos );
CLH2_RunParticleEffect( pos, oldvec3_origin, 50 );
}
static void CLHW_ParseBoneRic( QMsg& message ) {
vec3_t pos;
message.ReadPos( pos );
int cnt = message.ReadByte();
CLH2_RunParticleEffect4( pos, 3, 368 + rand() % 16, pt_h2grav, cnt );
int rnd = rand() % 100;
if ( rnd > 95 ) {
S_StartSound( pos, CLH2_TempSoundChannel(), 0, clh2_sfx_ric1, 1, 1 );
} else if ( rnd > 91 ) {
S_StartSound( pos, CLH2_TempSoundChannel(), 0, clh2_sfx_ric2, 1, 1 );
} else if ( rnd > 87 ) {
S_StartSound( pos, CLH2_TempSoundChannel(), 0, clh2_sfx_ric3, 1, 1 );
}
}
static void CLHW_ParseIceStorm( QMsg& message ) {
static int playIceSound = 600;
int ent = message.ReadShort();
h2entity_state_t* state = CLH2_FindState( ent );
if ( !state ) {
return;
}
vec3_t center;
VectorCopy( state->origin, center );
playIceSound += cls.frametime;
if ( playIceSound >= 600 ) {
S_StartSound( center, CLH2_TempSoundChannel(), 0, clh2_sfx_icestorm, 1, 1 );
playIceSound -= 600;
}
for ( int i = 0; i < 5; i++ ) {
// make some ice beams...
vec3_t source;
VectorCopy( center, source );
source[ 0 ] += rand() % 100 - 50;
source[ 1 ] += rand() % 100 - 50;
vec3_t dest;
VectorCopy( source, dest );
dest[ 2 ] += 128;
CLH2_CreateStreamIceChunks( ent, i, i + H2STREAM_ATTACHED, 0, 300, source, dest );
}
}
static void CLHW_ParseSunstuffCheap( QMsg& message ) {
int ent = message.ReadShort();
int reflect_count = message.ReadByte();
// read in up to 4 points for up to 3 beams
vec3_t points[ 4 ];
for ( int i = 0; i < 2 + reflect_count; i++ ) {
message.ReadPos( points[ i ] );
}
h2entity_state_t* state = CLH2_FindState( ent );
if ( !state ) {
return;
}
// actually create the sun model pieces
for ( int i = 0; i < reflect_count + 1; i++ ) {
CLH2_CreateStreamSunstaff1( ent, i, !i ? i + H2STREAM_ATTACHED : i, 0, 500, points[ i ], points[ i + 1 ] );
}
}
static void CLHW_ParseLightningHammer( QMsg& message ) {
int ent = message.ReadShort();
h2entity_state_t* state = CLH2_FindState( ent );
if ( state ) {
if ( rand() & 1 ) {
S_StartSound( state->origin, CLH2_TempSoundChannel(), 0, clh2_sfx_lightning1, 1, 1 );
} else {
S_StartSound( state->origin, CLH2_TempSoundChannel(), 0, clh2_sfx_lightning2, 1, 1 );
}
for ( int i = 0; i < 5; i++ ) {
// make some lightning
vec3_t source;
VectorCopy( state->origin, source );
source[ 0 ] += rand() % 30 - 15;
source[ 1 ] += rand() % 30 - 15;
vec3_t dest;
VectorCopy( source, dest );
dest[ 0 ] += rand() % 80 - 40;
dest[ 1 ] += rand() % 80 - 40;
dest[ 2 ] += 64 + ( rand() % 48 );
CLH2_CreateStreamLightning( ent, i, i, 0, 500, source, dest );
}
}
}
static void CLHW_ParseSwordExplosion( QMsg& message ) {
vec3_t pos;
message.ReadPos( pos );
int ent = message.ReadShort();
h2entity_state_t* state = CLH2_FindState( ent );
if ( state ) {
if ( rand() & 1 ) {
S_StartSound( pos, CLH2_TempSoundChannel(), 0, clh2_sfx_lightning1, 1, 1 );
} else {
S_StartSound( pos, CLH2_TempSoundChannel(), 0, clh2_sfx_lightning2, 1, 1 );
}
for ( int i = 0; i < 5; i++ ) {
// make some lightning
vec3_t source;
VectorCopy( pos, source );
source[ 0 ] += rand() % 30 - 15;
source[ 1 ] += rand() % 30 - 15;
vec3_t dest;
VectorCopy( source, dest );
dest[ 0 ] += rand() % 80 - 40;
dest[ 1 ] += rand() % 80 - 40;
dest[ 2 ] += 64 + ( rand() % 48 );
CLH2_CreateStreamLightning( ent, i, i, 0, 500, source, dest );
}
}
CLHW_SwordExplosion( pos );
}
static void CLHW_ParseSunstaffPower( QMsg& message ) {
int ent = message.ReadShort();
vec3_t source;
message.ReadPos( source );
vec3_t dest;
message.ReadPos( dest );
CLHW_SunStaffExplosions( dest );
h2entity_state_t* state = CLH2_FindState( ent );
if ( !state ) {
return;
}
S_StartSound( state->origin, CLH2_TempSoundChannel(), 0, clh2_sfx_sunstaff, 1, 1 );
CLH2_CreateStreamSunstaffPower( ent, source, dest );
}
static void CLHW_ParseCubeBeam( QMsg& message ) {
int ent = message.ReadShort();
int ent2 = message.ReadShort();
h2entity_state_t* state = CLH2_FindState( ent );
h2entity_state_t* state2 = CLH2_FindState( ent2 );
if ( state || state2 ) {
vec3_t source;
if ( state ) {
VectorCopy( state->origin, source );
} else { //don't know where the damn cube is--prolly won't see beam anyway then, so put it all at the target
VectorCopy( state2->origin, source );
source[ 2 ] += 10;
}
vec3_t dest;
if ( state2 ) {
VectorCopy( state2->origin, dest ); //in case they're both valid, copy me again
dest[ 2 ] += 30;
} else { //don't know where the damn victim is--prolly won't see beam anyway then, so put it all at the cube
VectorCopy( source, dest );
dest[ 2 ] += 10;
}
S_StartSound( source, CLH2_TempSoundChannel(), 0, clh2_sfx_sunstaff, 1, 1 );
S_StartSound( dest, CLH2_TempSoundChannel(), 0, clh2_sfx_sunhit, 1, 1 );
CLH2_SunStaffTrail( dest, source );
int skin = rand() % 5;
CLH2_CreateStreamColourBeam( ent, 0, 0, skin, 100, source, dest );
}
}
static void CLHW_ParseLightningExplode( QMsg& message ) {
int ent = message.ReadShort();
vec3_t pos;
message.ReadPos( pos );
if ( rand() & 1 ) {
S_StartSound( pos, CLH2_TempSoundChannel(), 0, clh2_sfx_lightning1, 1, 1 );
} else {
S_StartSound( pos, CLH2_TempSoundChannel(), 0, clh2_sfx_lightning2, 1, 1 );
}
for ( int i = 0; i < 10; i++ ) {
// make some lightning
float tempAng = ( rand() % 628 ) / 100.0;
float tempPitch = ( rand() % 628 ) / 100.0;
vec3_t dest;
VectorCopy( pos, dest );
dest[ 0 ] += 75.0 * cos( tempAng ) * cos( tempPitch );
dest[ 1 ] += 75.0 * sin( tempAng ) * cos( tempPitch );
dest[ 2 ] += 75.0 * sin( tempPitch );
CLH2_CreateStreamLightning( ent, i, i, 0, 500, pos, dest );
}
}
static void CLHW_ParseChainLightning( QMsg& message ) {
int ent = message.ReadShort();
int numTargs = 0;
int oldNum;
vec3_t points[ 12 ];
do {
message.ReadPos( points[ numTargs ] );
oldNum = numTargs;
if ( points[ numTargs ][ 0 ] || points[ numTargs ][ 1 ] || points[ numTargs ][ 2 ] ) {
if ( numTargs < 9 ) {
numTargs++;
}
}
} while ( points[ oldNum ][ 0 ] || points[ oldNum ][ 1 ] || points[ oldNum ][ 2 ] );
if ( numTargs == 0 ) {
return;
}
for ( int temp = 0; temp < numTargs - 1; temp++ ) {
// make the connecting lightning...
CLH2_CreateStreamLightning( ent, temp, temp, 0, 300, points[ temp ], points[ temp + 1 ] );
CLHW_ChainLightningExplosion( points[ temp + 1 ] );
}
}
void CLH2_ParseTEnt( QMsg& message ) {
int type = message.ReadByte();
switch ( type ) {
case H2TE_WIZSPIKE: // spike hitting wall
CLH2_ParseWizSpike( message );
break;
case H2TE_KNIGHTSPIKE: // spike hitting wall
case H2TE_GUNSHOT: // bullet hitting wall
CLH2_ParseKnightSpike( message );
break;
case H2TE_SPIKE: // spike hitting wall
CLH2_ParseSpike( message );
break;
case H2TE_SUPERSPIKE: // super spike hitting wall
CLH2_ParseSuperSpike( message );
break;
case H2TE_EXPLOSION: // rocket explosion
CLH2_ParseExplosion( message );
break;
case H2TE_LIGHTNING1:
case H2TE_LIGHTNING2:
case H2TE_LIGHTNING3:
CLH2_ParseBeam( message );
break;
case H2TE_LAVASPLASH:
CLH2_ParseLavaSplash( message );
break;
case H2TE_TELEPORT:
CLH2_ParseTeleport( message );
break;
case H2TE_STREAM_CHAIN:
case H2TE_STREAM_SUNSTAFF1:
case H2TE_STREAM_SUNSTAFF2:
case H2TE_STREAM_LIGHTNING:
case H2TE_STREAM_LIGHTNING_SMALL:
case H2TE_STREAM_COLORBEAM:
case H2TE_STREAM_ICECHUNKS:
case H2TE_STREAM_GAZE:
case H2TE_STREAM_FAMINE:
CLH2_ParseStream( message, type );
break;
default:
common->FatalError( "CL_ParseTEnt: bad type" );
}
}
void CLHW_ParseTEnt( QMsg& message ) {
int type = message.ReadByte();
switch ( type ) {
case H2TE_WIZSPIKE: // spike hitting wall
CLH2_ParseWizSpike( message );
break;
case H2TE_KNIGHTSPIKE: // spike hitting wall
CLH2_ParseKnightSpike( message );
break;
case H2TE_SPIKE: // spike hitting wall
CLH2_ParseSpike( message );
break;
case H2TE_SUPERSPIKE: // super spike hitting wall
CLH2_ParseSuperSpike( message );
break;
case HWTE_DRILLA_EXPLODE:
CLHW_ParseDrillaExplode( message );
break;
case H2TE_EXPLOSION: // rocket explosion
CLHW_ParseExplosion( message );
break;
case HWTE_TAREXPLOSION: // tarbaby explosion
CLHW_ParseTarExplosion( message );
break;
case H2TE_LIGHTNING1: // lightning bolts
case H2TE_LIGHTNING2:
case H2TE_LIGHTNING3:
CLH2_ParseBeam( message );
break;
case H2TE_LAVASPLASH:
CLH2_ParseLavaSplash( message );
break;
case H2TE_TELEPORT:
CLH2_ParseTeleport( message );
break;
case H2TE_GUNSHOT: // bullet hitting wall
case HWTE_BLOOD: // bullets hitting body
CLHW_ParseGunShot( message );
break;
case HWTE_LIGHTNINGBLOOD: // lightning hitting body
CLHW_ParseLightningBlood( message );
break;
case H2TE_STREAM_CHAIN:
case H2TE_STREAM_SUNSTAFF1:
case H2TE_STREAM_SUNSTAFF2:
case H2TE_STREAM_LIGHTNING:
case HWTE_STREAM_LIGHTNING_SMALL:
case H2TE_STREAM_COLORBEAM:
case H2TE_STREAM_ICECHUNKS:
case H2TE_STREAM_GAZE:
case H2TE_STREAM_FAMINE:
CLH2_ParseStream( message, type );
break;
case HWTE_BIGGRENADE:
CLHW_ParseBigGrenade( message );
break;
case HWTE_CHUNK:
CLHW_ParseChunk( message );
break;
case HWTE_CHUNK2:
CLHW_ParseChunk2( message );
break;
case HWTE_XBOWHIT:
CLHW_ParseXBowHit( message );
break;
case HWTE_METEORHIT:
CLHW_ParseMeteorHit( message );
break;
case HWTE_HWBONEPOWER:
CLHW_ParseBonePower( message );
break;
case HWTE_HWBONEPOWER2:
CLHW_ParseBonePower2( message );
break;
case HWTE_HWRAVENDIE:
CLHW_ParseRavenDie( message );
break;
case HWTE_HWRAVENEXPLODE:
CLHW_ParseRavenExplode( message );
break;
case HWTE_ICEHIT:
CLHW_ParseIceHit( message );
break;
case HWTE_ICESTORM:
CLHW_ParseIceStorm( message );
break;
case HWTE_HWMISSILEFLASH:
CLHW_ParseMissileFlash( message );
break;
case HWTE_SUNSTAFF_CHEAP:
CLHW_ParseSunstuffCheap( message );
break;
case HWTE_LIGHTNING_HAMMER:
CLHW_ParseLightningHammer( message );
break;
case HWTE_HWTELEPORT:
CLHW_ParseTeleport( message );
break;
case HWTE_SWORD_EXPLOSION:
CLHW_ParseSwordExplosion( message );
break;
case HWTE_AXE_BOUNCE:
CLHW_ParseAxeBounce( message );
break;
case HWTE_AXE_EXPLODE:
CLHW_ParseAxeExplode( message );
break;
case HWTE_TIME_BOMB:
CLHW_ParseTimeBomb( message );
break;
case HWTE_FIREBALL:
CLHW_ParseFireBall( message );
break;
case HWTE_SUNSTAFF_POWER:
CLHW_ParseSunstaffPower( message );
break;
case HWTE_PURIFY2_EXPLODE:
CLHW_ParsePurify2Explode( message );
break;
case HWTE_PLAYER_DEATH:
CLHW_ParsePlayerDeath( message );
break;
case HWTE_PURIFY1_EFFECT:
CLHW_ParsePurify1Effect( message );
break;
case HWTE_TELEPORT_LINGER:
CLHW_ParseTeleportLinger( message );
break;
case HWTE_LINE_EXPLOSION:
CLHW_ParseLineExplosion( message );
break;
case HWTE_METEOR_CRUSH:
CLHW_ParseMeteorCrush( message );
break;
case HWTE_ACIDBALL:
CLHW_ParseAcidBall( message );
break;
case HWTE_ACIDBLOB:
CLHW_ParseAcidBlob( message );
break;
case HWTE_FIREWALL:
CLHW_ParseFireWall( message );
break;
case HWTE_FIREWALL_IMPACT:
CLHW_ParseFireWallImpact( message );
break;
case HWTE_HWBONERIC:
CLHW_ParseBoneRic( message );
break;
case HWTE_POWERFLAME:
CLHW_ParsePowerFlame( message );
break;
case HWTE_BLOODRAIN:
CLHW_ParseBloodRain( message );
break;
case HWTE_AXE:
CLHW_ParseAxe( message );
break;
case HWTE_PURIFY2_MISSILE:
CLHW_ParsePurify2Missile( message );
break;
case HWTE_SWORD_SHOT:
CLHW_ParseSwordShot( message );
break;
case HWTE_ICESHOT:
CLHW_ParseIceShot( message );
break;
case HWTE_METEOR:
CLHW_ParseMeteor( message );
break;
case HWTE_LIGHTNINGBALL:
CLHW_ParseLightningBall( message );
break;
case HWTE_MEGAMETEOR:
CLHW_ParseMegaMeteor( message );
break;
case HWTE_CUBEBEAM:
CLHW_ParseCubeBeam( message );
break;
case HWTE_LIGHTNINGEXPLODE:
CLHW_ParseLightningExplode( message );
break;
case HWTE_ACID_BALL_FLY:
CLHW_ParseAcidBallFly( message );
break;
case HWTE_ACID_BLOB_FLY:
CLHW_ParseAcidBlobFly( message );
break;
case HWTE_CHAINLIGHTNING:
CLHW_ParseChainLightning( message );
break;
default:
common->FatalError( "CL_ParseTEnt: bad type" );
}
}
void CLHW_UpdateHammer( refEntity_t* ent, int edict_num ) {
// do this every .3 seconds
int testVal = cl.serverTime / 100;
int testVal2 = ( cl.serverTime - cls.frametime ) / 100;
if ( testVal != testVal2 ) {
if ( !( testVal % 3 ) ) {
S_StartSound( ent->origin, edict_num, 2, clh2_sfx_hammersound, 1, 1 );
}
}
}
void CLHW_UpdateBug( refEntity_t* ent ) {
int testVal = cl.serverTime / 100;
int testVal2 = ( cl.serverTime - cls.frametime ) / 100;
if ( testVal != testVal2 ) {
S_StartSound( ent->origin, CLH2_TempSoundChannel(), 1, clh2_sfx_buzzbee, 1, 1 );
}
}
void CLH2_UpdateTEnts() {
CLH2_UpdateExplosions();
CLH2_UpdateStreams();
CLHW_UpdateTargetBall();
}
|
//
// Recorder - a GPS logger app for Windows Mobile
// Copyright (C) 2006-2019 Michael Fink
//
/// \file WaitEventThread.hpp WaitEvent() thread
//
#pragma once
#include "WorkerThread.hpp"
#include <boost/bind.hpp>
/// \brief class that implements a worker thread that waits on a serial port for read/write events
/// the class is mainly written for Windows CE when no overlapped support is available; waiting
/// for events is simulated using calling WaitCommEvent() in another thread waiting for an event
/// that gets set when the call returns.
class CWaitEventThread
{
public:
/// ctor
CWaitEventThread(HANDLE hPort)
:m_hPort(hPort),
m_hEventReady(::CreateEvent(NULL, TRUE, FALSE, NULL)), // manual-reset
m_hEventWait(::CreateEvent(NULL, TRUE, FALSE, NULL)), // manual-reset
m_hEventContinue(::CreateEvent(NULL, TRUE, FALSE, NULL)), // manual-reset
m_hEventStop(::CreateEvent(NULL, TRUE, FALSE, NULL)), // manual-reset
m_workerThread(boost::bind(&CWaitEventThread::Run, this))
{
}
~CWaitEventThread()
{
// stop background thread
StopThread();
m_workerThread.Join();
CloseHandle(m_hEventReady);
CloseHandle(m_hEventWait);
CloseHandle(m_hEventContinue);
CloseHandle(m_hEventStop);
}
/// \todo only in ready state?
void SetPort(HANDLE hPort)
{
// TODO only in "ready" state?
m_hPort = hPort;
}
/// \todo thread-safe exchange?
void SetMask(DWORD dwEventMask)
{
//ATLTRACE(_T("T1: setting new mask, %08x\n"), dwEventMask);
// TODO thread-safe exchange? only do in "ready" thread state?
m_dwEventMask = dwEventMask;
}
/// waits for thead to be ready to wait for comm event
void WaitForThreadReady()
{
WaitForSingleObject(m_hEventReady, INFINITE);
ResetEvent(m_hEventReady);
}
/// tells thread to continue waiting
void ContinueWait()
{
SetEvent(m_hEventContinue);
}
/// \todo wait for ready thread state
void StopThread()
{
// TODO wait for "ready" thread state
//ATLTRACE(_T("T1: stopping worker thread\n"));
::SetEvent(m_hEventStop);
if (FALSE == ::SetCommMask(m_hPort, 0))
{
DWORD dw = GetLastError();
dw++;
}
//ATLTRACE(_T("T1: stopped worker thread\n"));
}
bool WaitComm();
int Run();
/// returns wait event handle
HANDLE GetWaitEventHandle() const { return m_hEventWait; }
/// returns event result mask
DWORD GetEventResult()
{
// wait event must be set
//ATLTRACE(_T("T2: testing wait event\n"));
DWORD dwTest = ::WaitForSingleObject(m_hEventWait, 0);
//ATLASSERT(WAIT_OBJECT_0 == dwTest);
// note: m_dwEventResult can be accessed without protection from the worker
// thread because it is set when WaitCommEvent() returned.
return m_dwEventResult;
}
private:
DWORD m_dwEventMask;
DWORD m_dwEventResult;
HANDLE m_hPort;
/// when event is set, the wait thread is ready to do a next "wait" task
HANDLE m_hEventReady;
/// when event is set, the WaitCommEvent call returned successfully
HANDLE m_hEventWait;
/// when event is set, the wait thread is allowed to continue with a WaitCommEvent call
HANDLE m_hEventContinue;
/// when event is set, the wait thread should exit
HANDLE m_hEventStop;
/// worker thread
WorkerThread m_workerThread;
};
|
/********************************************************************************
Copyright (c) 2012, Francisco Claude.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of libcds nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
********************************************************************************/
#include <libcds/array.h>
#include <libcds/libcds.h>
#include <fstream>
#include <algorithm>
namespace cds {
namespace basic {
using std::istream;
using std::ostream;
using cds::basic::Array;
using cds::basic::ArrayTpl;
Array *Array::Create(cds_word *A, cds_word i, cds_word j, cds_word bpe) {
cds_word max_value = 0;
for (cds_word k = i; k <= j; k++) {
max_value = max(max_value, A[k]);
}
Array *ret = Create(j - i + 1, max(msb(max_value), bpe));
for (cds_word k = i; k <= j; k++) {
assert(A[k] <= max_value);
ret->SetField(k - i, A[k]);
}
return ret;
}
Array *Array::Create(const vector<cds_word> &values) {
cds_word max_value = 0;
for (cds_word k = 0; k < values.size(); k++) {
max_value = max(max_value, values[k]);
}
Array *ret = Create(values.size(), msb(max_value));
for (cds_word k = 0; k < values.size(); k++) {
assert(values[k] <= max_value);
ret->SetField(k, values[k]);
}
return ret;
}
template <cds_word bpe> void ArrayTpl<bpe>::Save(ostream &out) const {
SaveValue(out, bpe);
SaveValue(out, length_);
cds_word uint_length = WordsLength(length_, bpe);
SaveValue(out, data_, uint_length);
}
template <cds_word bpe> ArrayTpl<bpe>::ArrayTpl(istream &input) {
length_ = LoadValue<cds_word>(input);
cds_word uint_length = WordsLength(length_, bpe);
data_ = LoadValue<cds_word>(input, uint_length);
}
template <cds_word bpe> ArrayTpl<bpe> *ArrayTpl<bpe>::Load(istream &input) {
cds_word id = LoadValue<cds_word>(input);
if (id != bpe) {
return NULL;
}
return new ArrayTpl<bpe>(input);
}
template <cds_word bpe> ArrayTpl<bpe>::ArrayTpl(cds_word n) {
length_ = n;
InitData();
}
template <cds_word bpe> ArrayTpl<bpe>::ArrayTpl(cds_word *A, cds_word i, cds_word j) {
length_ = j - i + 1;
InitData();
for (cds_word k = i; k <= j; k++) {
SetField(k - i, A[k]);
}
}
template <cds_word bpe> cds_word ArrayTpl<bpe>::GetSize() const {
return sizeof(cds_word) * WordsLength(length_, bpe)
+ sizeof(*this);
}
template <cds_word bpe> cds_word ArrayTpl<bpe>::GetLength() const {
return length_;
}
template <cds_word bpe> ArrayTpl<bpe>::~ArrayTpl() {
delete [] data_;
}
template <cds_word bpe> cds_word ArrayTpl<bpe>::GetMax() const {
cds_word max_value = 0; // default max
for (cds_word i = 0; i < length_; i++) {
max_value = max(max_value, GetField(i));
}
return max_value;
}
// Implementation based on the STL lower_bound implementation.
template <cds_word bpe> cds_word ArrayTpl<bpe>::LowerBound(cds_word value, cds_word ini, cds_word fin) const {
assert(ini <= fin);
assert(fin <= length_);
cds_word count, step;
count = fin - ini;
while (count > 0) {
step = count / 2;
cds_word pos = ini + step;
if (GetField(pos) < value) {
ini = pos + 1;
count -= step + 1;
} else {
count = step;
}
}
return ini;
}
template <cds_word bpe> cds_word ArrayTpl<bpe>::LowerBound(cds_word value) const {
return LowerBound(value, 0, length_);
}
template <cds_word bpe> cds_word ArrayTpl<bpe>::LowerBoundExp(cds_word value, cds_word ini, cds_word fin) const {
cds_word sum = 1;
while (ini + sum < fin) {
if (GetField(ini + sum) >= value) {
return LowerBound(value, ini, ini + sum);
}
ini += sum;
sum *= 2;
}
return LowerBound(value, ini, fin);
}
template <cds_word bpe> cds_word ArrayTpl<bpe>::LowerBoundExp(cds_word value) const {
return LowerBoundExp(value, 0, length_);
}
// Also based on the STL version.
template <cds_word bpe> cds_word ArrayTpl<bpe>::UpperBound(cds_word value, cds_word ini, cds_word fin) const {
assert(ini <= fin);
assert(fin <= length_);
cds_word count, step;
count = fin - ini;
while (count > 0) {
step = count / 2;
cds_word pos = ini + step;
if (!(value < GetField(pos))) {
ini = pos + 1;
count -= step + 1;
} else {
count = step;
}
}
return ini;
}
template <cds_word bpe> cds_word ArrayTpl<bpe>::UpperBound(cds_word value) const {
return UpperBound(value, 0, length_);
}
template <cds_word bpe> cds_word ArrayTpl<bpe>::BinarySearch(cds_word value, cds_word ini, cds_word fin) const {
assert(ini <= fin);
assert(fin <= length_);
cds_word pos = LowerBound(value, ini, fin);
if (pos != fin && !(value < GetField(pos))) {
return pos;
} else {
return fin;
}
}
template <cds_word bpe> cds_word ArrayTpl<bpe>::BinarySearch(cds_word value) const {
return BinarySearch(value, 0, length_);
}
template <cds_word bpe> void ArrayTpl<bpe>::InitData() {
cds_word uint_length = WordsLength(length_, bpe);
data_ = new cds_word[uint_length];
for (cds_word i = 0; i < uint_length; i++) {
data_[i] = 0;
}
}
template <> cds_word ArrayTpl<32>::GetField(const cds_word position) const {
assert(position < length_);
return reinterpret_cast<uint32_t *>(data_)[position];
}
template <> cds_word ArrayTpl<16>::GetField(const cds_word position) const {
assert(position < length_);
return reinterpret_cast<uint16_t *>(data_)[position];
}
template <> cds_word ArrayTpl<8>::GetField(const cds_word position) const {
assert(position < length_);
return reinterpret_cast<uint8_t *>(data_)[position];
}
template <> cds_word ArrayTpl<4>::GetField(const cds_word position) const {
assert(position < length_);
return cds::basic::GetField4(data_, position);
}
template <> cds_word ArrayTpl<2>::GetField(const cds_word position) const {
assert(position < length_);
return cds::basic::GetField2(data_, position);
}
template <> cds_word ArrayTpl<1>::GetField(const cds_word position) const {
assert(position < length_);
if (cds::basic::BitGet(data_, position)) {
return 1;
}
return 0;
}
template <cds_word bpe> cds_word ArrayTpl<bpe>::GetField(const cds_word position) const {
assert(position < length_);
return cds::basic::GetField(data_, bpe, position);
}
template <cds_word bpe> cds_word ArrayTpl<bpe>::SetField(const cds_word position, const cds_word v) {
assert(position < length_);
cds::basic::SetField(data_, bpe, position, v);
return v;
}
Array *Array::Load(istream &input) {
cds_word id = LoadValue<cds_word>(input);
size_t pos = input.tellg();
input.seekg(pos - sizeof(cds_word));
switch (id) {
case 0:
return ArrayTpl<0>::Load(input);
case 1:
return ArrayTpl<1>::Load(input);
case 2:
return ArrayTpl<2>::Load(input);
case 3:
return ArrayTpl<3>::Load(input);
case 4:
return ArrayTpl<4>::Load(input);
case 5:
return ArrayTpl<5>::Load(input);
case 6:
return ArrayTpl<6>::Load(input);
case 7:
return ArrayTpl<7>::Load(input);
case 8:
return ArrayTpl<8>::Load(input);
case 9:
return ArrayTpl<9>::Load(input);
case 10:
return ArrayTpl<10>::Load(input);
case 11:
return ArrayTpl<11>::Load(input);
case 12:
return ArrayTpl<12>::Load(input);
case 13:
return ArrayTpl<13>::Load(input);
case 14:
return ArrayTpl<14>::Load(input);
case 15:
return ArrayTpl<15>::Load(input);
case 16:
return ArrayTpl<16>::Load(input);
case 17:
return ArrayTpl<17>::Load(input);
case 18:
return ArrayTpl<18>::Load(input);
case 19:
return ArrayTpl<19>::Load(input);
case 20:
return ArrayTpl<20>::Load(input);
case 21:
return ArrayTpl<21>::Load(input);
case 22:
return ArrayTpl<22>::Load(input);
case 23:
return ArrayTpl<23>::Load(input);
case 24:
return ArrayTpl<24>::Load(input);
case 25:
return ArrayTpl<25>::Load(input);
case 26:
return ArrayTpl<26>::Load(input);
case 27:
return ArrayTpl<27>::Load(input);
case 28:
return ArrayTpl<28>::Load(input);
case 29:
return ArrayTpl<29>::Load(input);
case 30:
return ArrayTpl<30>::Load(input);
case 31:
return ArrayTpl<31>::Load(input);
case 32:
return ArrayTpl<32>::Load(input);
case 33:
return ArrayTpl<33>::Load(input);
case 34:
return ArrayTpl<34>::Load(input);
case 35:
return ArrayTpl<35>::Load(input);
case 36:
return ArrayTpl<36>::Load(input);
case 37:
return ArrayTpl<37>::Load(input);
case 38:
return ArrayTpl<38>::Load(input);
case 39:
return ArrayTpl<39>::Load(input);
case 40:
return ArrayTpl<40>::Load(input);
case 41:
return ArrayTpl<41>::Load(input);
case 42:
return ArrayTpl<42>::Load(input);
case 43:
return ArrayTpl<43>::Load(input);
case 44:
return ArrayTpl<44>::Load(input);
case 45:
return ArrayTpl<45>::Load(input);
case 46:
return ArrayTpl<46>::Load(input);
case 47:
return ArrayTpl<47>::Load(input);
case 48:
return ArrayTpl<48>::Load(input);
case 49:
return ArrayTpl<49>::Load(input);
case 50:
return ArrayTpl<50>::Load(input);
case 51:
return ArrayTpl<51>::Load(input);
case 52:
return ArrayTpl<52>::Load(input);
case 53:
return ArrayTpl<53>::Load(input);
case 54:
return ArrayTpl<54>::Load(input);
case 55:
return ArrayTpl<55>::Load(input);
case 56:
return ArrayTpl<56>::Load(input);
case 57:
return ArrayTpl<57>::Load(input);
}
return NULL;
}
Array *Array::Create(cds_word n, cds_word bpe) {
switch (bpe) {
case 0:
return new ArrayTpl<0>(n);
case 1:
return new ArrayTpl<1>(n);
case 2:
return new ArrayTpl<2>(n);
case 3:
return new ArrayTpl<3>(n);
case 4:
return new ArrayTpl<4>(n);
case 5:
return new ArrayTpl<5>(n);
case 6:
return new ArrayTpl<6>(n);
case 7:
return new ArrayTpl<7>(n);
case 8:
return new ArrayTpl<8>(n);
case 9:
return new ArrayTpl<9>(n);
case 10:
return new ArrayTpl<10>(n);
case 11:
return new ArrayTpl<11>(n);
case 12:
return new ArrayTpl<12>(n);
case 13:
return new ArrayTpl<13>(n);
case 14:
return new ArrayTpl<14>(n);
case 15:
return new ArrayTpl<15>(n);
case 16:
return new ArrayTpl<16>(n);
case 17:
return new ArrayTpl<17>(n);
case 18:
return new ArrayTpl<18>(n);
case 19:
return new ArrayTpl<19>(n);
case 20:
return new ArrayTpl<20>(n);
case 21:
return new ArrayTpl<21>(n);
case 22:
return new ArrayTpl<22>(n);
case 23:
return new ArrayTpl<23>(n);
case 24:
return new ArrayTpl<24>(n);
case 25:
return new ArrayTpl<25>(n);
case 26:
return new ArrayTpl<26>(n);
case 27:
return new ArrayTpl<27>(n);
case 28:
return new ArrayTpl<28>(n);
case 29:
return new ArrayTpl<29>(n);
case 30:
return new ArrayTpl<30>(n);
case 31:
return new ArrayTpl<31>(n);
case 32:
return new ArrayTpl<32>(n);
case 33:
return new ArrayTpl<33>(n);
case 34:
return new ArrayTpl<34>(n);
case 35:
return new ArrayTpl<35>(n);
case 36:
return new ArrayTpl<36>(n);
case 37:
return new ArrayTpl<37>(n);
case 38:
return new ArrayTpl<38>(n);
case 39:
return new ArrayTpl<39>(n);
case 40:
return new ArrayTpl<40>(n);
case 41:
return new ArrayTpl<41>(n);
case 42:
return new ArrayTpl<42>(n);
case 43:
return new ArrayTpl<43>(n);
case 44:
return new ArrayTpl<44>(n);
case 45:
return new ArrayTpl<45>(n);
case 46:
return new ArrayTpl<46>(n);
case 47:
return new ArrayTpl<47>(n);
case 48:
return new ArrayTpl<48>(n);
case 49:
return new ArrayTpl<49>(n);
case 50:
return new ArrayTpl<50>(n);
case 51:
return new ArrayTpl<51>(n);
case 52:
return new ArrayTpl<52>(n);
case 53:
return new ArrayTpl<53>(n);
case 54:
return new ArrayTpl<54>(n);
case 55:
return new ArrayTpl<55>(n);
case 56:
return new ArrayTpl<56>(n);
case 57:
return new ArrayTpl<57>(n);
case 58:
return new ArrayTpl<58>(n);
}
return NULL;
}
};
};
|
#pragma once
#define _USE_MATH_DEFINES
#include "math.h"
#include "iostream"
using namespace std;
class CIR
{
private:
double a,b;
double p;
int n;
double f(double x) {
return pow(M_E,x)*cos(x);
}
public:
double f1() {
double h = b - a;
double t = ((b - a) / 2) * (f(a) + f(b));
double tt = 1;
int n=0;
double tempout = t;
for (int m = 1; abs((tt - t)) > p; m++)
{
t = tempout;
h = 0.5 * h;
double temp = 0;
for (int i = 1; i <= pow(2.0, (m - 1)); i++)
{
temp = temp + f(a + (2.0 * i - 1) * h);
}
n++;
tt = 0.5 * t + h * temp;
tempout = tt;
}
cout << n << endl;
return tt;
}
CIR(double a, double b,double p) {
this->a = a;
this->b = b;
this->p = p;
}
};
|
#include "custom_glog_sink.h"
#include <iostream>
#include <sstream>
void CustomGlogSink::send(google::LogSeverity severity, const char* full_filename,
const char* base_filename, int line, const struct ::tm* tm_time,
const char* message, size_t message_len) {
auto padding_zero = [](uint32_t a) { return (a < 10 ? "0" : ""); };
std::string time = std::to_string(tm_time->tm_year + 1900) + "-" +
padding_zero(tm_time->tm_mon + 1) + std::to_string(tm_time->tm_mon + 1) + "-" +
padding_zero(tm_time->tm_mday) + std::to_string(tm_time->tm_mday) + " " +
padding_zero(tm_time->tm_hour) + std::to_string(tm_time->tm_hour) + ":" +
padding_zero(tm_time->tm_min) + std::to_string(tm_time->tm_min) + ":" +
padding_zero(tm_time->tm_sec) + std::to_string(tm_time->tm_sec);
std::stringstream ss;
ss << kSeverityMap[severity] + " " + time << " " << base_filename << ":" << line << ": "
<< message;
std::cout << ss.str();
// std::cout << "CustomGlogSink:"
// << google::LogSink::ToString(severity, full_filename, line, tm_time, message,
// message_len)
// << std::endl;
}
void CustomGlogSink::WaitTillSent() {
// std::cout << "CustomGlogSink::WaitTillSent" << std::endl;
}
|
#ifndef _SERVICIOPAGINAERROR_H
#define _SERVICIOPAGINAERROR_H
#include "servicio.h"
#include "dominio.h"
class cServicioPaginaError:public cServicio {
public:
//Constructor e iniciador
cServicioPaginaError(cDominio *dominio);
bool iniciar();
//Agrega la pagina de error a la configuracion del apache
int agregarFileHttpdConf(const std::string &, cDominio &);
//Agrega un archivo con la pagina de error en el sistema
int agregarFilePagina(const std::string &, cDominio &);
//Agrega una pagina de error en el sistema
int agregarPaginaError(const std::string &, cDominio &);
//Agrega un pagina de error en la base de datos
int agregarPaginaErrorDB(const std::string &, cDominio &);
//Quita una pagina de error de la configuracion del apache
int quitarFileHttpdConf(const std::string &, cDominio &);
//Quita una pagina de error del sistema
int quitarPaginaError(const std::string &, cDominio &);
//Quita una pagina de error de la base de datos
int quitarPaginaErrorDB(const std::string &, cDominio &);
//Trae la cantidad del servicio
std::string traerCantidad();
//Verifica la existencia de un codigo de error en la base de datos
int verificarExisteCodigoErrorDB(const std::string &, cDominio &dominio);
//Verifica la existencia de una pagina de error en la base de datos
int verificarExistePaginaErrorDB(const std::string &, cDominio &dominio);
//Verifica la existencia de las paginas de error
int verificarExistenPaginaErrorDB(cDominio &dominio);
};
#endif // _SERVICIOPAGINAERROR_H
|
#include<iostream>
#include<list>
using namespace std;
// //list 链表
// 将数据进行链式存储,物理存储单元上非连续的存储结构
// 数据元素的逻辑顺序是通过链表的指针链接实现的
// 链表是由一系列结点组成
// 结点的组成:存储数据元素的数据域 和 存储下一个结点地址的指针域
// 优点,可以对任意位置进行快速插入或删除元素
//缺点,遍历速度没有数组快;占用的空间大
// STL中的链表是一个双向循环链表
// 指针域中存两个指针,指向前一个结点和指向下一个结点
// list迭代器,只支持迁移和后移,属于双向迭代器
// list和vector是最常用的的两个容易,各有优缺点
int main()
{
return 0;
}
|
// This is an independent project of an individual developer. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
#include <boost/test/unit_test.hpp>
#include "complex.hpp"
using std::complex;
using std::string;
using std::exception;
BOOST_AUTO_TEST_CASE (complex_toString1)
{
const complex<double> a (1.0, 0.0);
const string expected ("1");
const string actual = to_string (a);
BOOST_CHECK_EQUAL (expected, actual);
}
BOOST_AUTO_TEST_CASE (complex_toString2)
{
const complex<double> a (0.0, 1.0);
const string expected ("1i");
const string actual = to_string (a);
BOOST_CHECK_EQUAL (expected, actual);
}
BOOST_AUTO_TEST_CASE (complex_toString3)
{
const complex<double> a (-2.4, 1.5);
const string expected ("-2.4+1.5i");
const string actual = to_string (a);
BOOST_CHECK_EQUAL (expected, actual);
}
BOOST_AUTO_TEST_CASE (complex_toString4)
{
const complex<double> a (2.4, -1.5);
const string expected ("2.4-1.5i");
const string actual = to_string (a);
BOOST_CHECK_EQUAL (expected, actual);
}
BOOST_AUTO_TEST_CASE (complex_toString5)
{
const complex<double> a (0.0, 0.0);
const string expected ("0");
const string actual = to_string (a);
BOOST_CHECK_EQUAL (expected, actual);
}
BOOST_AUTO_TEST_CASE (complex_equals1)
{
const complex<double> a (1.0, 2.0);
const complex<double> b (1.0, 2.0);
BOOST_CHECK (equals (a, b));
}
BOOST_AUTO_TEST_CASE (complex_equals2)
{
const complex<double> a (1.0, 2.0);
const complex<double> b (1.1, 2.0);
BOOST_CHECK (!equals (a, b));
}
BOOST_AUTO_TEST_CASE (complex_equals3)
{
const complex<double> a (1.0, 2.1);
const complex<double> b (1.0, 2.0);
BOOST_CHECK (!equals (a, b));
}
BOOST_AUTO_TEST_CASE (complex_parse1)
{
try
{
const complex<double>a = parse_complex ("gbc");
(void)a;
}
catch (const exception&)
{
return;
}
BOOST_FAIL ("no throw exception");
}
BOOST_AUTO_TEST_CASE (complex_parse2)
{
const complex<double> actual = parse_complex ("-1.3");
const complex<double> expected (-1.3, 0.0);
BOOST_CHECK (equals (actual, expected));
}
BOOST_AUTO_TEST_CASE (complex_parse3)
{
const complex<double> actual = parse_complex ("2.5i");
const complex<double> expected (0.0, 2.5);
BOOST_CHECK (equals (actual, expected));
}
BOOST_AUTO_TEST_CASE (complex_parse4)
{
const complex<double> actual = parse_complex ("1.3-2.5i");
const complex<double> expected (1.3, -2.5);
BOOST_CHECK (equals (actual, expected));
}
BOOST_AUTO_TEST_CASE (complex_parse5)
{
const complex<double> actual = parse_complex ("1");
const complex<double> expected (1.0, 0.0);
BOOST_CHECK (equals (actual, expected));
}
BOOST_AUTO_TEST_CASE (complex_parse6)
{
try
{
const complex<double>a = parse_complex ("1.3-2.5");
(void)a;
}
catch (const exception&)
{
return;
}
BOOST_FAIL ("no throw exception");
}
BOOST_AUTO_TEST_CASE (complex_parse7)
{
try
{
const complex<double>a = parse_complex ("1.3i-2.5");
(void)a;
}
catch (const exception&)
{
return;
}
BOOST_FAIL ("no throw exception");
}
BOOST_AUTO_TEST_CASE (complex_parse8)
{
try
{
const complex<double>a = parse_complex ("1.3ij");
(void)a;
}
catch (const exception&)
{
return;
}
BOOST_FAIL ("no throw exception");
}
BOOST_AUTO_TEST_CASE (complex_parse9)
{
try
{
const complex<double>a = parse_complex ("1.3+3.5546ij");
(void)a;
}
catch (const exception&)
{
return;
}
BOOST_FAIL ("no throw exception");
}
BOOST_AUTO_TEST_CASE (complex_parse10)
{
try
{
const complex<double>a = parse_complex ("1.3ji");
(void)a;
}
catch (const exception&)
{
return;
}
BOOST_FAIL ("no throw exception");
}
BOOST_AUTO_TEST_CASE (complex_parse11)
{
try
{
const complex<double>a = parse_complex ("1.3+3.5546ji");
(void)a;
}
catch (const exception&)
{
return;
}
BOOST_FAIL ("no throw exception");
}
BOOST_AUTO_TEST_CASE (complex_parse12)
{
const complex<double> actual = parse_complex ("i");
const complex<double> expected (0.0, 1.0);
BOOST_CHECK (equals (actual, expected));
}
BOOST_AUTO_TEST_CASE (complex_parse13)
{
const complex<double> actual = parse_complex ("-i");
const complex<double> expected (0.0, -1.0);
BOOST_CHECK (equals (actual, expected));
}
BOOST_AUTO_TEST_CASE (complex_parse14)
{
const complex<double> actual = parse_complex ("0.5+i");
const complex<double> expected (0.5, 1.0);
BOOST_CHECK (equals (actual, expected));
}
BOOST_AUTO_TEST_CASE (complex_parse15)
{
const complex<double> actual = parse_complex ("0.5-i");
const complex<double> expected (0.5, -1.0);
BOOST_CHECK (equals (actual, expected));
}
BOOST_AUTO_TEST_CASE (complex_parse16)
{
const complex<double> actual = parse_complex ("+i");
const complex<double> expected (0.0, 1.0);
BOOST_CHECK (equals (actual, expected));
}
|
#include "enemigo_tanque.h"
using namespace App_Juego_ObjetoJuego;
const float Enemigo_tanque::SALUD_DEFECTO=30.0f;
const float Enemigo_tanque::TIEMPO_PROXIMO_DISPARO_DEFECTO=3.0f;
Enemigo_tanque::Enemigo_tanque(float px, float py, int w, int h, float s)
:
Objeto_juego_I(),
Actor(px, py, w, h),
salud(0.0f, s, s),
tiempo_proximo_disparo(TIEMPO_PROXIMO_DISPARO_DEFECTO),
angulo(0.0f)
{
}
Enemigo_tanque_abajo::Enemigo_tanque_abajo(float px, float py, float s)
:Enemigo_tanque(px, py, W, H, s)
{
}
void Enemigo_tanque_abajo::transformar_cuerpo(App_Graficos::Bloque_transformacion_representable &b)const
{
using namespace App_Definiciones;
const auto f=b.obtener_frame(animaciones::sprites, animaciones_sprites::enemigo_tanque, 0);
b.establecer_posicion(acc_espaciable_x(), acc_espaciable_y(), f.w, f.h);
b.establecer_recorte(f.x, f.y, f.w, f.h);
}
float Enemigo_tanque_abajo::transformar_angulo_disparo(float a) const
{
if(a > 180.0f) a=180.0f;
else if(a < 0.f) a=0.f;
return a;
}
bool Enemigo_tanque_abajo::validar_angulo_disparo(float a) const
{
return a >= 0.f && a <= 180.0f;
}
Enemigo_tanque_arriba::Enemigo_tanque_arriba(float px, float py, float s)
:Enemigo_tanque(px, py, W, H, s)
{
}
void Enemigo_tanque_arriba::transformar_cuerpo(App_Graficos::Bloque_transformacion_representable &b)const
{
using namespace App_Definiciones;
const auto f=b.obtener_frame(animaciones::sprites, animaciones_sprites::enemigo_tanque, 0);
b.establecer_posicion(acc_espaciable_x(), acc_espaciable_y(), f.w, f.h);
b.invertir_vertical(true);
b.establecer_recorte(f.x, f.y, f.w, f.h);
}
float Enemigo_tanque_arriba::transformar_angulo_disparo(float a) const
{
if(a > 360.0f) a=360.0f;
else if(a < 180.f) a=180.f;
return a;
}
bool Enemigo_tanque_arriba::validar_angulo_disparo(float a) const
{
return a >= 180.f && a <= 360.0f;
}
Enemigo_tanque_derecha::Enemigo_tanque_derecha(float px, float py, float s)
:Enemigo_tanque(px, py, W, H, s)
{
}
void Enemigo_tanque_derecha::transformar_cuerpo(App_Graficos::Bloque_transformacion_representable &b)const
{
using namespace App_Definiciones;
const auto f=b.obtener_frame(animaciones::sprites, animaciones_sprites::enemigo_tanque, 0);
b.establecer_posicion(acc_espaciable_x(), acc_espaciable_y(), f.w, f.h);
b.especificar_centro_rotacion(W / 2, W / 2);
b.rotar(90);
b.invertir_vertical(true); //En realidad estamos invirtiendo el vertical, y rotando.
b.establecer_recorte(f.x, f.y, f.w, f.h);
}
float Enemigo_tanque_derecha::transformar_angulo_disparo(float a) const
{
if(a > 270.0f) a=270.0f;
else if(a < 90.f) a=90.f;
return a;
}
bool Enemigo_tanque_derecha::validar_angulo_disparo(float a) const
{
return a >= 90.f && a <= 270.0f;
}
Enemigo_tanque_izquierda::Enemigo_tanque_izquierda(float px, float py, float s)
:Enemigo_tanque(px, py, W, H, s)
{
}
void Enemigo_tanque_izquierda::transformar_cuerpo(App_Graficos::Bloque_transformacion_representable &b)const
{
using namespace App_Definiciones;
const auto f=b.obtener_frame(animaciones::sprites, animaciones_sprites::enemigo_tanque, 0);
b.establecer_posicion(acc_espaciable_x(), acc_espaciable_y(), f.w, f.h);
b.especificar_centro_rotacion(W / 2, W / 2);
b.rotar(90);
b.establecer_recorte(f.x, f.y, f.w, f.h);
}
float Enemigo_tanque_izquierda::transformar_angulo_disparo(float a) const
{
if(a > 90.f && a < 270.f) a=270.f;
return a;
}
bool Enemigo_tanque_izquierda::validar_angulo_disparo(float a) const
{
return (a >= 0.f && a <= 90.0f) || (a >= 270.f && a <=360.f);
}
/**************************************************/
unsigned short int Enemigo_tanque::obtener_profundidad_ordenacion()const
{
return 10;
}
unsigned int Enemigo_tanque::obtener_ciclos_representable()const
{
return 2;
}
void Enemigo_tanque::transformar_bloque(App_Graficos::Bloque_transformacion_representable &b) const
{
using namespace App_Graficos;
b.establecer_tipo(Bloque_transformacion_representable::tipos::tr_bitmap);
b.establecer_alpha(255);
b.establecer_recurso(App::Recursos_graficos::rt_juego);
switch(b.acc_ciclo())
{
case 1: transformar_cuerpo(b); break;
case 2:
{
using namespace App_Definiciones;
const auto f=b.obtener_frame(animaciones::sprites, animaciones_sprites::enemigo_tanque_canon, 0);
b.especificar_centro_rotacion(2,2);
b.rotar(-angulo);
b.establecer_recorte(f.x, f.y, f.w, f.h);
b.establecer_posicion(acc_espaciable_x()+(acc_espaciable_w()/2)-2,
acc_espaciable_y()+(acc_espaciable_h()/2)-(f.h/2),
f.w, f.h);
}
break;
}
}
void Enemigo_tanque::turno(App_Interfaces::Contexto_turno_I& ct)
{
float delta=ct.acc_delta();
tiempo_proximo_disparo-=delta;
auto v=obtener_vector_cartesiano_para(ct.acc_blanco());
angulo=transformar_angulo_disparo(DLibH::Herramientas::angulo_360(v.angulo_grados()));
}
void Enemigo_tanque::recibir_disparo(float potencia, App_Interfaces::Disparable_contexto_I& contexto)
{
int id_sonido=App::Recursos_audio::rs_explosion;
salud-=potencia;
contexto.insertar_marcador(potencia, acc_espaciable_cx(), acc_espaciable_y());
contexto.asignar_barra(salud.max(), salud.actual(), "SENTRY");
if(salud <= 0.0f)
{
mut_borrar(true);
}
else
{
id_sonido=App::Recursos_audio::rs_golpe;
}
insertar_reproducir(App_Audio::Info_audio_reproducir(
App_Audio::Info_audio_reproducir::t_reproduccion::simple,
App_Audio::Info_audio_reproducir::t_sonido::repetible,
id_sonido, 127, 127));
}
void Enemigo_tanque::generar_objetos(App_Interfaces::Factoria_objetos_juego_I& f)
{
//TODO: Esto se repite a saco...
if(es_borrar())
{
const auto& v=DLibH::Vector_2d(0.f, 0.f);
float x=acc_espaciable_x()+(acc_espaciable_w()/2);
float y=acc_espaciable_y()+(acc_espaciable_w()/2);
auto g=Herramientas_proyecto::Generador_int(10, 30);
auto gvel=Herramientas_proyecto::Generador_int(150, 300);
int i=0, mp=g();
while(i < mp)
{
auto g=Herramientas_proyecto::Generador_int(0, 359);
auto v=Vector_2d::vector_unidad_para_angulo(g())*gvel();
f.fabricar_chatarra(x, y, 3.0f, v);
++i;
}
auto gtraza=Herramientas_proyecto::Generador_int(3, 5);
auto gveltraza=Herramientas_proyecto::Generador_int(160, 200);
auto gduracion=Herramientas_proyecto::Generador_int(40, 100);
i=0;
while(i < gtraza())
{
auto g=Herramientas_proyecto::Generador_int(0, 359);
auto v=Vector_2d::vector_unidad_para_angulo(g())*gveltraza();
float dur=(float)gduracion() / 100.0;
f.fabricar_trazador_humo(x, y, dur, v);
++i;
}
f.fabricar_explosion(x, y, 1.0f, v);
}
else
{
if(tiempo_proximo_disparo < 0.0f)
{
tiempo_proximo_disparo=TIEMPO_PROXIMO_DISPARO_DEFECTO;
//Calculamos el vector hasta el blanco.
const auto v=obtener_vector_cartesiano_para(f.acc_blanco_disparo()) * 200.0f;
float angulo_vector=DLibH::Herramientas::angulo_360(v.angulo_grados());
if(validar_angulo_disparo(angulo_vector))
{
const auto dp=desplazamiento_origen_proyectil();
float rad=DLibH::Herramientas::grados_a_radianes(angulo_vector);
float canx=cos(rad)*8.f+dp.x;
float cany=-(sin(rad)*8.f)+dp.y; //Negamos para convertir de cartesiano a pantalla...
f.fabricar_proyectil_normal_enemigo(acc_espaciable_cx()+canx, acc_espaciable_cy()+cany, 8, 8, v.a_pantalla(), 25.0);
//TODO: Los concerns de audio están mezlados con el resto :(.
insertar_reproducir(App_Audio::Info_audio_reproducir(
App_Audio::Info_audio_reproducir::t_reproduccion::simple,
App_Audio::Info_audio_reproducir::t_sonido::repetible,
App::Recursos_audio::rs_disparo, 127, 127));
}
}
}
}
void Enemigo_tanque::efecto_colision(App_Interfaces::Efecto_colision_recogedor_I& er)
{
er.recibir_impacto(2.5f);
}
|
#ifndef BACKSTROKE_TESTCODEBUILDER_H
#define BACKSTROKE_TESTCODEBUILDER_H
#include "builderTypes.h"
class BasicExpressionTest : public TestCodeBuilder
{
public:
BasicExpressionTest(const std::string& name, bool is_cxx_style = false)
: TestCodeBuilder(name, is_cxx_style) {}
protected:
virtual void build();
};
class ComplexExpressionTest : public TestCodeBuilder
{
public:
ComplexExpressionTest(const std::string& name, bool is_cxx_style = false)
: TestCodeBuilder(name, is_cxx_style) {}
protected:
virtual void build();
};
#endif /* BACKSTROKE_TESTCODEBUILDER_H */
|
#include <wx/msgdlg.h>
#include <iostream>
#include <wx/timer.h>
#include <wx/vector.h>
#include <fstream>
#include <bits/stdc++.h>
#include "PacManDesktopAppMain.h"
using namespace std;
// Class MAP
class c_map
{
private:
const unsigned int POINT_2=5;
const unsigned int POINT_1=1;
int i_poziom = 0;
int i_points = 0;
int i_allTime = 0;
string MapData[20][20];
string PrimaryMap[20][20];
int i_RozmiarMapyX = 20;
int i_RozmiarMapyY = 20;
int i_pozostale_punkty =1;
public:
wxStaticBitmap* Mapa[20][20];
// LOADING FILE INTO MAP
void wczytajPlikMapy(string NazwaPliku){
string singleLine[20],line,text;
short loop=0;
ifstream myfile (NazwaPliku);
int x;
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
singleLine[loop] = line;
istringstream streamedString(singleLine[loop]);
x = 0;
while(streamedString >> text){
MapData[x][loop]=text;
PrimaryMap[x][loop]=text;
cout<<MapData[x][loop];
++x;
};
cout<<"\n";
loop++;
}
myfile.close();
}
else cout << "Brak pliku";
};
// SAVING THE FILE TO THE MAP
void zapiszPlikMapy(char* NazwaPliku){
fstream plik;
// Otwieranie wyznaczonego pliku
plik.open( NazwaPliku, ios::out);
//Jezeli plik istnieje, zapisuje plik
if(plik.good())
{
plik << i_RozmiarMapyX<<" "<<endl;
plik << i_RozmiarMapyY<<" "<<endl;
for (int i=0; i<i_RozmiarMapyY;i++){
for(int j=0; j<i_RozmiarMapyX; j++){
plik<<Mapa[i][j]<<" ";
}
plik<<endl;
}
plik.close();
}
//Jezeli plik nie istnieje
else{
cout<<"Brak pliku";
}
}
// Loading a map based on data
string loadMapData(int playerX, int playerY,int fastBotX, int fastBotY ,int slowBotX ,int slowBotY, int i, int j){
if(i==playerX && j==playerY){
return "pacman.png";
}
if(i==fastBotX && j==fastBotY){
return "capman.png";
}
if(i==slowBotX && j==slowBotY){
return "capman.png";
}
else if(MapData[i][j]=="WOL"){
return "free.bmp";
}
else if(MapData[i][j]=="PK1"){
return "pk1.bmp";
}
else if(MapData[i][j]=="PEF"){
return "pef.bmp";
}
else if(MapData[i][j]=="PES"){
return "pes.bmp";
}
else{
return "wall.png";
}
}
// Get Map Data
string** getMapData(){
string** table = new string*[20];
for(int i = 0; i < 20; i++) {
table[i] = new string[20];
for(int j = 0; j < 20; j++){table[i][j] = MapData[i][j];}
}
return table;
}
void countPoints(){
i_points=0;
// Downloading wall informations
for (int i = 0;i<20;i+=1){
for(int j = 0;j<20;j+=1){
if(MapData[i][j]=="PK1"){i_points+=1;}
}
}
}
// Simple sets / gets
string getPrimData(int X, int Y){return PrimaryMap[X][Y];}
void setLevel(int value){i_poziom=value;}
int getLevel(){return i_poziom;}
int getTime(){return i_allTime;}
void setTime(int value){i_allTime=value;}
int geti_RozmiarMapyX(){return i_allTime;}
void seti_RozmiarMapyX(int value){i_allTime=value;}
int getMapPoints(){return i_points;}
void setMapPoints(int value){i_points = value;}
void setMapData(string value, int x, int y){MapData[x][y]=value;}
};
|
#include "RendererConsole.hpp"
void RendererConsole::render(const LifeSimulator& simulation)
{
rlutil::cls();
rlutil::hidecursor();
for (int i = 0; i < simulation.getSizeY(); i++)
{
for (int j = 0; j < simulation.getSizeX(); j++)
{
if (simulation.getCell(j, i))
{
rlutil::locate(j+1, i+1);
rlutil::setChar('*');
}
}
}
rlutil::locate(simulation.getSizeX()+1, simulation.getSizeY()+1);
rlutil::showcursor();
}
|
//
// Created by twome on 08/05/2020.
//
#include <iostream>
#include <nfd.h>
#include "MenuScreen.h"
#include "../components/Button.h"
#include "../../io/XmlGuiLoader.h"
#include "../../render/GameWindow.h"
#include "NewGameScreen.h"
#include "../../io/FieldIO.h"
MenuScreen::MenuScreen() : Screen("menuScreen") {
XmlGuiLoader::load(this, "main_menu.xml");
auto btnNewGame = find_component<Button>("btnNewGame");
auto btnLoadGame = find_component<Button>("btnLoadGame");
auto btnExitGame = find_component<Button>("btnExitGame");
btnNewGame->set_click_listener([]() {
GameWindow::get_instance()->get_gui_renderer()->show_screen(new NewGameScreen());
});
btnLoadGame->set_click_listener([]() {
nfdchar_t *outPath = nullptr;
nfdresult_t result = NFD_OpenDialog("bin,nk", nullptr, &outPath);
if (result == NFD_OKAY) {
std::string path = std::string(outPath);
Field *field = FieldIO::read_field(path);
GameWindow::get_instance()->set_field(field);
GameWindow::get_instance()->show_ingame_gui();
delete outPath;
}
});
btnExitGame->set_click_listener([]() {
GameWindow::get_instance()->close();
});
}
|
#include <bits/stdc++.h>
using namespace std;
vector<int> sortA(int a[], int n) {
vector<int> b(n, 1); // 0 from 0 .... pt1-1, 1 from pt1 ..... pt2-1, 2 from pt2 to n-1
int pt1 = 0, pt2 = n-1;
for (int i = 0; i < n; i++) {
if (a[i] == 0) b[pt1++] = 0;
else if (a[i] == 2) b[pt2--] = 2;
}
return b;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int a[n];
for (int i = 0; i < n; i++) cin >> a[i];
vector<int> b = sortA(a, n);
for (int i = 0; i < n; i++) cout << b[i] << " ";
cout << "\n";
}
return 0;
}
|
/*
* observer.h
*
* Created on: Oct 27, 2013
* Author: leal
*/
#ifndef OBSERVER_H_
#define OBSERVER_H_
/**
* Define an object that is the “keeper” of the data model and/or business logic (the Subject).
* Delegate all “view” functionality to decoupled and distinct Observer objects.
* Observers register themselves with the Subject as they are created.
* Whenever the Subject changes, it broadcasts to all registered Observers that it has changed,
* and each Observer queries the Subject for that subset of the Subject’s state
* that it is responsible for monitoring.
*
* inspired from: http://sourcemaking.com/design_patterns/observer
*
*/
#include <iostream>
#include <vector>
using namespace std;
class Observer;
/**
* Subject
* Going to spread the news to its subscribers / observers
*/
class Subject {
public:
// Observer will register them selves using this command
void registerObserver(Observer *obs) {
listOfRegisteredObservers.push_back(obs);
}
void setNews(string news_) {
news = news_;
notify();
}
string getNews() {
return news;
}
void notify();
private:
vector<class Observer *> listOfRegisteredObservers; // 3. Coupled only to "interface"
string news;
};
class Observer {
public:
Observer(Subject *subject_) {
subject = subject_;
// Observers register themselves with the Subject
subject->registerObserver(this);
}
virtual ~Observer(){}
virtual void update() = 0;
protected:
Subject *getSubject() {
return subject;
}
private:
// 2. "dependent" functionality
Subject *subject;
};
class HtmlObserver: public Observer {
public:
HtmlObserver(Subject *mod) :
Observer(mod) {}
void update() {
// 6. "Pull" information of interest
string news = getSubject()->getNews();
cout << "<html>" << news << "</html>" << '\n';
}
};
class TextObserver: public Observer {
public:
TextObserver(Subject *mod) :
Observer(mod) {}
void update() {
// 6. "Pull" information of interest
string news = getSubject()->getNews();
cout << news << '\n';
}
};
#endif /* OBSERVER_H_ */
|
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_COMPILER_MLIR_TOSA_TRANSFORMS_LEGALIZE_COMMON_H
#define TENSORFLOW_COMPILER_MLIR_TOSA_TRANSFORMS_LEGALIZE_COMMON_H
// This file contains legalizations common to mapping both TensorFlow and
// TensorFlow Lite to TOSA.
//
// Conversion functions return nullptr on a lowerization failure or a lowered
// operator on success. Callers must check and return a LogicalResult failure
// on nullptr.
//
// For these functions, the framework-specific operands/attributes/defaults
// are already extracted and placed in a common form for lowering.
#include "mlir/Dialect/Quant/FakeQuantSupport.h"
#include "mlir/Dialect/Quant/UniformSupport.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include "mlir/Dialect/Tosa/IR/TosaOps.h"
#include "mlir/Dialect/Tosa/Utils/QuantUtils.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/Diagnostics.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/IR/Matchers.h"
#include "mlir/IR/Operation.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/IR/StandardTypes.h"
#include "mlir/IR/TypeUtilities.h"
#include "mlir/IR/Types.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Support/LLVM.h"
#include "mlir/Transforms/DialectConversion.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/FormatVariadic.h"
namespace mlir {
namespace tosa {
// Lowers the Pack operator to TOSA.
Operation* convertPackOp(PatternRewriter& rewriter, Operation* op,
Value result_value, SmallVector<Value, 8>& inputs,
int32_t axis);
// Lowers the Unpack operator to TOSA.
Operation* convertUnpackOp(PatternRewriter& rewriter, Operation* op,
Value input_value, int32_t axis);
// Lowers the Select operator to TOSA.
Operation* convertSelectOp(PatternRewriter& rewriter, Operation* op,
Value result_value, Value condition_value,
Value x_value, Value y_value);
// Lowers the ZerosLike operator to TOSA by creating a constant
// of the desired type and shape.
Operation* convertZerosLikeOp(PatternRewriter& rewriter, Operation* op,
Value result, Value input);
// Lowers the Mul operator to TOSA. For quantized types, this requires
// inserting rescale operators before and after the operation.
Operation* convertMultiplyOp(PatternRewriter& rewriter, Operation* op,
Value output_val, Value input_lhs_val,
Value input_rhs_val);
// Lowers the SquaredDifference operator to TOSA.
Operation* convertSquaredDifferenceOp(PatternRewriter& rewriter, Operation* op,
Value result, Value x, Value y);
// Lowers the Round operator to TOSA.
Operation* convertRoundOp(PatternRewriter& rewriter, Operation* op,
Value result, Value input);
// Lowers ConcatV2 to TOSA.
Operation* convertConcatV2Op(PatternRewriter& rewriter, Operation* op,
Value result_value, SmallVector<Value, 8>& values,
int32_t axis);
// Lowers SpaceToBatchND to TOSA.
Operation* convertSpaceToBatchNDOp(PatternRewriter& rewriter, Operation* op,
Value result_value, Value input_value,
Value block_shape_value,
Value paddings_value);
// Lowers BatchToSpaceND to TOSA.
Operation* convertBatchToSpaceNDOp(PatternRewriter& rewriter, Operation* op,
Value result_value, Value input_value,
Value block_shape_value, Value crops_value);
// Lowers ExpandDims to TOSA.
Operation* convertExpandDimsOp(PatternRewriter& rewriter, Operation* op,
Value result_value, Value input_value,
Value dim_value);
// Lowers Squeeze to TOSA.
Operation* convertSqueezeOp(PatternRewriter& rewriter, Operation* op,
Value result_value, Value input_value,
SmallVector<int32_t, 8>& squeeze_dims);
// Lowers ELU to a sequence of TOSA ops.
Operation* convertEluOp(PatternRewriter& rewriter, Operation* op,
Value result_value, Value features_value);
// Lowers Softmax to a sequence of TOSA ops.
Operation* convertSoftmaxOp(PatternRewriter& rewriter, Operation* op,
Value result_value, Value logits_value);
// Lowers LogSoftmax to a sequence of TOSA ops.
Operation* convertLogSoftmaxOp(PatternRewriter& rewriter, Operation* op,
Value result_value, Value logits_value);
// Lowers SpaceToDepth to a sequence of TOSA ops. Supports NHWC.
Operation* convertSpaceToDepthOp(PatternRewriter& rewriter, Operation* op,
Value result_value, Value input_value,
IntegerAttr block_size_attr,
StringAttr data_format);
// Lowers DepthToSpace to a sequence of TOSA ops. Supports NHWC.
Operation* convertDepthToSpaceOp(PatternRewriter& rewriter, Operation* op,
Value result_value, Value input_value,
IntegerAttr block_size_attr,
StringAttr data_format);
// Lowers Split to a sequence of TOSA ops.
Operation* convertSplitOp(PatternRewriter& rewriter, Operation* op,
Value result_value, Value input_value,
int32_t num_split, int32_t axis);
// Lowers SplitV to a sequence of TOSA ops.
Operation* convertSplitVOp(PatternRewriter& rewriter, Operation* op,
Value result_value, Value input_value,
SmallVector<int32_t, 4>& size_split, int32_t axis);
// Lowers StridedSlice to a sequence of TOSA ops.
Operation* convertStridedSliceOp(PatternRewriter& rewriter, Operation* op,
Value result_value, Value input_value,
Value begin_value, Value end_value,
Value strides_value, int32_t begin_mask,
int32_t end_mask, int32_t ellipsis_mask,
int32_t new_axis_mask,
int32_t shrink_axis_mask);
// Lowers FloorDiv to a sequence of TOSA operators.
Operation* convertFloorDivOp(PatternRewriter& rewriter, Operation* op,
Value result_value, Value lhs_value,
Value rhs_value);
// Lowers FloorMod to a sequence of TOSA operators.
Operation* convertFloorModOp(PatternRewriter& rewriter, Operation* op,
Value result_value, Value lhs_value,
Value rhs_value);
// Lowers FusedActivation to a sequence of TOSA ops.
Operation* convertFusedActivation(PatternRewriter& rewriter, Operation* op,
Value input_value,
StringAttr fused_activation_fn);
// Helper function for implementing quantized divide by power-of-two in TOSA
// ops.
Operation* convertRoundingDivideByPOT(PatternRewriter& rewriter, Operation* op,
Value input_value, Value rshift_value);
// Lowers ReduceAll to a sequence of TOSA ops.
Operation* convertReduceAllOp(PatternRewriter& rewriter, Operation* op,
RankedTensorType output_type, Value input_value,
ElementsAttr axes_elems, bool keep_dims);
// Lowers ReduceAny to a sequence of TOSA ops.
Operation* convertReduceAnyOp(PatternRewriter& rewriter, Operation* op,
RankedTensorType output_type, Value input_value,
ElementsAttr axes_elems, bool keep_dims);
// Lowers ReduceMin to a sequence of TOSA ops.
Operation* convertReduceMinOp(PatternRewriter& rewriter, Operation* op,
RankedTensorType output_type, Value input_value,
ElementsAttr axes_elems, bool keep_dims);
// Lowers ReduceMax to a sequence of TOSA ops.
Operation* convertReduceMaxOp(PatternRewriter& rewriter, Operation* op,
RankedTensorType output_type, Value input_value,
ElementsAttr axes_elems, bool keep_dims);
// Lowers ReduceProd to a sequence of TOSA ops.
Operation* convertReduceProdOp(PatternRewriter& rewriter, Operation* op,
RankedTensorType output_type, Value input_value,
ElementsAttr axes_elems, bool keep_dims);
// Lowers ReduceSum to a sequence of TOSA ops.
Operation* convertReduceSumOp(PatternRewriter& rewriter, Operation* op,
RankedTensorType output_type, Value input_value,
ElementsAttr axes_elems, bool keep_dims);
// Lowers ReduceMean to a sequence of TOSA ops.
Operation* convertReduceMeanOp(PatternRewriter& rewriter, Operation* op,
RankedTensorType output_type, Value input_value,
ElementsAttr axes_elems, bool keep_dims);
// Lowers ResizeBilinear and ResizeNearestNeighbor to TOSA resize.
Operation* convertResizeOp(PatternRewriter& rewriter, Operation* op,
RankedTensorType output_type, Value input_value,
StringRef mode);
// Lowers Quantize to a sequence of TOSA quantization ops.
Operation* convertQuantizeOp(PatternRewriter& rewriter, Operation* op,
RankedTensorType output_type, Value input_value,
double scale, int64_t zeropoint);
// Lowers Dequantize to a sequence of TOSA dequantization ops.
Operation* convertDequantizeOp(PatternRewriter& rewriter, Operation* op,
RankedTensorType output_type, Value input_value,
double scale, int64_t zeropoint);
// Lowers FakeQuant to a sequence of TOSA quantization ops.
Operation* convertFakeQuantOp(PatternRewriter& rewriter, Operation* op,
RankedTensorType output_type, Value input_value,
double min, double max, int64_t num_bits,
bool narrow_range);
Operation* convertTFConv2DCommon(
PatternRewriter& rewriter, Operation* op, RankedTensorType output_type,
Value input, Value filter, Value bias, ArrayAttr strides_attr,
ArrayAttr dilations_attr, ArrayAttr explicit_padding_attr,
StringRef padding_ref, StringRef data_format_ref);
}; // namespace tosa
}; // namespace mlir
#endif // TENSORFLOW_COMPILER_MLIR_TOSA_TRANSFORMS_LEGALIZE_COMMON_H
|
#include <iostream> // cin/cout
#include <string>
#include <vector>
#include "Book.h"
#include "Library.h"
#include "Patron.h"
using namespace std;
// Library Constructor
Library::Library()
{
currentDate = 0;
vector<Book> holdings;
vector<Patron> members;
holdings.reserve(100);
members.reserve(100);
}
void Library::addMember(int index)
{
string tempName = "",
tempID = "";
int count;
// Add a Patron to the members vector
members.push_back(Patron());
cout << "Enter Patron's Name: ";
getline (cin, tempName);
members[index].set_name(tempName);
// Ensure a unique ID # is given
do
{
cout << "Enter Patrons ID Number: ";
getline (cin, tempID);
members[index].set_idNum(tempID);
// Set/reset count to 0
count = 0;
// Search members vector for ID #
for (unsigned a = 0; a < members.size(); a++)
{
if (tempID == members[a].getIdNum())
{
count++;
}
}
if (count > 1)
{
cout << "That ID Number is already taken. Please try"
<< " again. " << endl;
}
}
while(count > 1);
}
void Library::listPatrons(int index)
{
if (index == 0)
{
cout << "There are no Patrons to display." << endl;
}
else
{
for (int a = 0; a < index; a++)
{
cout << "Patron " << a + 1 << " of " << index << ":" << endl;
cout << members[a].getName() << endl
<< "ID Number: " << members[a].getIdNum() << endl
<< endl;
}
}
}
void Library::addBook(int index)
{
string tempTitle = "",
tempAuthor = "",
tempID = "";
int count;
// Add a Book to the holdings vector
holdings.push_back(Book());
cout << "Enter Title: ";
getline (cin, tempTitle);
holdings[index].set_title(tempTitle);
cout << "Enter Author: ";
getline (cin, tempAuthor);
holdings[index].set_author(tempAuthor);
// Ensure a unique ID# is given
do
{
cout << "Enter Book's ID Number: ";
getline (cin, tempID);
holdings[index].set_IdCode(tempID);
// Set/reset count to 0
count = 0;
// Search holdings vector for ID#
for (unsigned a = 0; a < holdings.size(); a++)
{
if (tempID == holdings[a].getIdCode())
{
count++;
}
}
if (count > 1)
{
cout << "That ID Number is already taken. Please try"
<< " again. " << endl;
}
}
while(count > 1);
}
void Library::listBooks(int index)
{
if (index == 0)
{
cout << "There are no Books to display." << endl;
}
else
{
for (int a = 0; a < index; a++)
{
cout << "Book " << a + 1 << " of " << index << ":" << endl;
cout << holdings[a].getTitle() << endl
<< "Author: " << holdings[a].getAuthor() << endl
<< "ID Number: " << holdings[a].getIdCode() << endl
<< "Location: ";
if (holdings[a].getLocation() == 0)
{
cout << "On Shelf" << endl << endl;
}
else if (holdings[a].getLocation() == 1)
{
cout << "On Hold" << endl << endl;
}
else
{
cout << "Checked Out" << endl << endl;
}
}
}
}
void Library::incrementCurrentDate()
{
cout << endl << "Current Date is: " << currentDate << endl;
currentDate++;
cout << "Current Date is now: " << currentDate << endl << endl;
// Find all checked out books and increment their date checked out
for (unsigned a = 0; a < holdings.size(); a++)
{
if (holdings[a].getLocation() == CHECKED_OUT)
{
holdings[a].setDateCheckedOut(holdings[a].getDateCheckedOut() + 1);
// Apply fine if book overdue
if ((Book::CHECK_OUT_LENGTH - holdings[a].getDateCheckedOut()) < 0)
{
holdings[a].getCheckedOutBy() -> amendFine(Library::DAILY_FINE);
}
}
}
}
void Library::viewPatronInfo(std::string patronID)
{
int count = 0;
// Find patron in members vector & dispaly info
for (unsigned a = 0; a < members.size(); a++)
{
if (members[a].getIdNum() == patronID)
{
cout << endl << members[a].getName() << endl
<< "ID#: " << members[a].getIdNum() << endl
<< "Books Checked Out: " << endl;
if (!members[a].getCheckedOutBooks().empty())
{
for (unsigned b = 0; b < members[a].getCheckedOutBooks().size();
b++)
{
cout << members[a].getCheckedOutBooks()[b] -> getTitle()
<< endl;
}
}
cout << "Fines Due: $" << members[a].getFineAmount() << endl;
count++;
}
}
if (count == 0)
{
cout << "Sorry, I can't find a Patron with that ID#." << endl;
}
}
void Library::viewBookInfo(std::string bookID)
{
int count = 0;
// find book in holdings vector & display info
for (unsigned a = 0; a < holdings.size(); a++)
{
if (holdings[a].getIdCode() == bookID)
{
cout << holdings[a].getTitle() << endl
<< "Author: " << holdings[a].getAuthor() << endl
<< "ID Number: " << holdings[a].getIdCode() << endl;
if (holdings[a].getLocation() == 0)
{
cout << "Location: On Shelf" << endl << endl;
}
else if (holdings[a].getLocation() == 1)
{
cout << "On Hold By: "
<< holdings[a].getRequestedBy() -> getName()
<< endl << endl;
}
else if (holdings[a].getLocation() == 2)
{
cout << "Checked Out By: "
<< holdings[a].getCheckedOutBy() -> getName()
<< endl
<< "It is due within the next "
<< Book::CHECK_OUT_LENGTH - holdings[a].getDateCheckedOut()
<< " days." << endl << endl;
}
count++;
}
}
if (count == 0)
{
cout << "Sorry, I can't find a Book with that ID#." << endl;
}
}
void Library::checkOutBook(std::string patronID, std::string bookID)
{
int count = 0;
Book* book_ptr;
Patron* patron_ptr;
string bookName = "", patronName = "";
// Find patron in members vector
for (unsigned a = 0; a < members.size(); a++)
{
if (members[a].getIdNum() == patronID)
{
count++;
// Set pointer to member
patron_ptr = &members[a];
}
}
// If patron not found return to main
if (count == 0)
{
cout << "Sorry, I can't find a Patron with that ID#." << endl;
return;
}
// Reset count to 0
count = 0;
// Find book in holdings vector
for (unsigned a = 0; a < holdings.size(); a++)
{
if (holdings[a].getIdCode() == bookID)
{
count++;
// Set pointer to book
book_ptr = &holdings[a];
}
// If book already checked out return to main
if ((holdings[a].getLocation() == 2) &&
(holdings[a].getIdCode() == bookID))
{
cout << "Sorry, that Book is already checked out." << endl;
return;
}
// If on hold for another patron return to main
if ((holdings[a].getLocation() == 1) &&
(holdings[a].getIdCode() == bookID) &&
(holdings[a].getRequestedBy() != patron_ptr))
{
cout << "Sorry, that Book is on hold for another patron."
<< endl;
return;
}
}
// Return to main if book was not found
if (count == 0)
{
cout << "Sorry, I can't find a Book with that ID#." << endl;
return;
}
// Find book in holdings vector to check it out
for (unsigned a = 0; a < holdings.size(); a++)
{
if (holdings[a].getIdCode() == bookID)
{
holdings[a].setCheckedOutBy(patron_ptr);
holdings[a].setLocation(CHECKED_OUT);
bookName = holdings[a].getTitle();
}
// If book was on hold by requesting patron reset requested by to NULL
if (holdings[a].getRequestedBy() == patron_ptr)
{
holdings[a].setRequestedBy(NULL);
}
}
// Find patron in members vector to add book to their checked out books vector
for (unsigned a = 0; a < members.size(); a++)
{
if (members[a].getIdNum() == patronID)
{
members[a].addBook(book_ptr);
patronName = members[a].getName();
}
}
cout << bookName << " has been checked out by " << patronName
<< endl << endl;
}
void Library::returnBook(std::string bookID)
{
int count = 0;
Book* book_ptr;
string patron = "", book = "";
// Find book in holdings vector
for (unsigned a = 0; a < holdings.size(); a++)
{
// Return to main if book is not checked out
if ((holdings[a].getLocation() != CHECKED_OUT) &&
(holdings[a].getIdCode() == bookID))
{
cout << "Sorry, that Book is not checked out." << endl;
return;
}
if (holdings[a].getIdCode() == bookID)
{
count++;
// Set pointer to book
book_ptr = &holdings[a];
// Get book title
book = holdings[a].getTitle();
// Get who checked book out
patron = holdings[a].getCheckedOutBy()-> getName();
}
// Set Data for returning book
if (holdings[a].getIdCode() == bookID)
{
holdings[a].setCheckedOutBy(NULL);
holdings[a].setDateCheckedOut(0);
if (holdings[a].getRequestedBy() == NULL)
{
holdings[a].setLocation(ON_SHELF);
}
else
{
holdings[a].setLocation(ON_HOLD);
}
}
}
// Return to main if book was not found
if (count == 0)
{
cout << "Sorry, I can't find a Book with that ID#." << endl;
return;
}
// Find patron in members vector to remove book from their checked out books vector
for (unsigned a = 0; a < members.size(); a++)
{
if (members[a].getName() == patron)
{
members[a].removeBook(book_ptr);
}
}
cout << "Thank you " << patron << " for returning " << book << endl;
}
void Library::payFine(std::string patronID, double payment)
{
// Find patron in members vector to amend fine
for (unsigned a = 0; a < members.size(); a++)
{
if (members[a].getIdNum() == patronID)
{
members[a].amendFine(payment);
cout << members[a].getName() << "'s Fines are now: $"
<< members[a].getFineAmount() << endl;
}
}
}
void Library::requestBook(std::string patronID, std::string bookID)
{
int count = 0;
Patron* patron_ptr;
string bookName = "", patronName = "";
// Find patron in members vector
for (unsigned a = 0; a < members.size(); a++)
{
if (members[a].getIdNum() == patronID)
{
count++;
// Set pointer to member
patron_ptr = &members[a];
// Save patron name
patronName = members[a].getName();
}
}
// Return to main if patron was not found
if (count == 0)
{
cout << "Sorry, I can't find a Patron with that ID#." << endl;
return;
}
// Reset count to 0
count = 0;
// Find book in holdings vector
for (unsigned a = 0; a < holdings.size(); a++)
{
if (holdings[a].getIdCode() == bookID)
{
count++;
// Save book title
bookName = holdings[a].getTitle();
}
// Return to main if book already on hold
if (holdings[a].getRequestedBy() != NULL &&
holdings[a].getIdCode() == bookID)
{
cout << "Sorry, that Book is already on hold." << endl;
return;
}
// Set data for requesting book
if (holdings[a].getIdCode() == bookID)
{
holdings[a].setRequestedBy(patron_ptr);
if (holdings[a].getLocation() == ON_SHELF)
{
holdings[a].setLocation(ON_HOLD);
}
}
}
// Return to main if book was not found
if (count == 0)
{
cout << "Sorry, I can't find a Book with that ID#." << endl;
return;
}
cout << bookName << " is on hold for " << patronName << endl;
}
|
//
// Created by Nudzejma on 4/2/2018.
//
#ifndef ADVANCED_ALGORTIHMS_MAXCYCLEDECOMPOSITION_H
#define ADVANCED_ALGORTIHMS_MAXCYCLEDECOMPOSITION_H
#include <stack>
#include "../node/Node.h"
#include "../graph/Graph.h"
vector< vector<Node*> > getMaxCycleDecomposition(const Graph &eulerianGraph) {
vector< vector<Node*> > maxCycleDecomposition = {};
Graph copiedEulerianGraph(eulerianGraph);
stack<Node*> nodes;
stack<Node*> dfsVisitedNodes;
for (int i=0; i<copiedEulerianGraph.getNodes().size(); i++) {
copiedEulerianGraph.getNodeAt(i)->setVisited(false);
}
Node *node = copiedEulerianGraph.getNodes()[0];
dfsVisitedNodes.push(node);
Node *toTop = node;
while(!dfsVisitedNodes.empty()) {
node = dfsVisitedNodes.top();
if (!node->isVisited()) {
node->setVisited(true);
dfsVisitedNodes.pop();
if (!nodes.empty()) {
toTop = nodes.top();
}
nodes.push(node);
for (int i = 0; i < node->getAdjacentNodes().size(); i++) {
Node *adjacentNode = node->getAdjacentNodeAt(i);
if (!adjacentNode->isVisited()) {
dfsVisitedNodes.push(adjacentNode);
} else {
if (toTop != adjacentNode) {
vector<Node*> cycleDecomposition;
Node *n = nodes.top();
nodes.pop();
cycleDecomposition.push_back(n);
while (n != adjacentNode && !nodes.empty()) {
copiedEulerianGraph.removeEdgesBetweenNodes(n, nodes.top());
n = nodes.top();
nodes.pop();
cycleDecomposition.push_back(n);
}
copiedEulerianGraph.removeEdgesBetweenNodes(cycleDecomposition[0], cycleDecomposition[cycleDecomposition.size()-1]);
maxCycleDecomposition.push_back(cycleDecomposition);
for (int j=0; j<copiedEulerianGraph.getNodes().size(); j++) {
copiedEulerianGraph.getNodeAt(j)->setVisited(false);
}
toTop = nullptr;
}
}
}
} else {
dfsVisitedNodes.pop();
}
}
return maxCycleDecomposition;
}
#endif //ADVANCED_ALGORTIHMS_MAXCYCLEDECOMPOSITION_H
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "TestingGrounds.h"
#include "ChooseNextWaypoint.h"
#include "BehaviorTree/BlackboardComponent.h"
#include "AIController.h"
#include "PatrolComponent.h"
EBTNodeResult::Type UChooseNextWaypoint::ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory)
{
auto BlackboardComponent = OwnerComp.GetBlackboardComponent();
auto CurrentIndex = BlackboardComponent->GetValueAsInt(Index.SelectedKeyName);
auto AIController = OwnerComp.GetAIOwner();
if (!ensure(AIController)) {
EBTNodeResult::Failed;
}
auto Pawn = AIController->GetPawn();
if (!ensure(Pawn)) {
return EBTNodeResult::Failed;
}
UPatrolComponent *PatrolComponent = Pawn->FindComponentByClass<UPatrolComponent>();
if (PatrolComponent) {
auto Waypoints = PatrolComponent->GetPatrolPoints();
auto NextWayPoint = (CurrentIndex + 1) % Waypoints.Num();
BlackboardComponent->SetValueAsInt(Index.SelectedKeyName, NextWayPoint);
BlackboardComponent->SetValueAsObject(Waypoint.SelectedKeyName, Waypoints[NextWayPoint]);
}
return EBTNodeResult::Succeeded;
}
|
#include <cstdio>
#include <cstring>
#include <iostream>
#include <set>
#include <string>
using namespace std;
typedef long long ll;
// 字母表的大小
const int max_size = 30, maxn = 5e5 + 5;
// 根节点编号为0
struct Trie {
// ch[i][j]表示节点i的第j个字母存放的节点编号,若不存在则为0
// count表示前缀(单词)出现的次数
int ch[maxn][max_size], index, count[maxn];
bool isWord[maxn], ask[maxn];
Trie() {
// 初始时只有根节点
index = 1;
memset(ch, 0, sizeof(ch));
memset(isWord, false, sizeof(isWord));
memset(count, 0, sizeof(count));
}
void insert(char* s) {
int u = 0, len = strlen(s);
for (int i = 0; i < len; ++i) {
int v = s[i] - 'a';
if (!ch[u][v])
ch[u][v] = index++;
u = ch[u][v];
}
// 如果单词尚未存在
if (!isWord[u]) {
isWord[u] = true;
ask[u] = false;
u = 0;
// 更新沿途节点作为前缀出现的次数
for (int i = 0; i < len; ++i) {
int v = s[i] - 'a';
u = ch[u][v];
++count[u];
}
}
}
void remove(char* s) {
int u = 0, len = strlen(s);
for (int i = 0; i < len; ++i) {
int v = s[i] - 'a';
if (!ch[u][v])
return;
u = ch[u][v];
}
// 单词不存在
if (!isWord[u])
return;
u = 0;
int pre, v;
// 更新沿途节点作为前缀出现的次数
for (int i = 0; i < len; ++i) {
pre = u;
v = s[i] - 'a';
u = ch[u][v];
--count[u];
}
// 删除单词
isWord[u] = false;
if (count[u] == 1)
ch[pre][v] = 0;
}
// 0-不存在,1-存在,-1-被点过名
int find(char* s) {
int u = 0, len = strlen(s);
for (int i = 0; i < len; ++i) {
int v = s[i] - 'a';
if (!ch[u][v])
return 0;
u = ch[u][v];
}
if (!isWord[u])
return 0;
if (ask[u])
return -1;
ask[u] = true;
return 1;
}
} trie;
// #define DEBUG
int main() {
#ifdef DEBUG
freopen("d:\\.in", "r", stdin);
freopen("d:\\.out", "w", stdout);
#endif
int n, m;
scanf("%d", &n);
char name[55];
while (n--) {
scanf("%s", name);
trie.insert(name);
}
scanf("%d", &m);
while (m--) {
scanf("%s", name);
int ans = trie.find(name);
if (ans == 0)
printf("WRONG\n");
else if (ans == -1)
printf("REPEAT\n");
else
printf("OK\n");
}
return 0;
}
|
#ifndef __COMMON_H
#define __COMMON_H
#include "NetworkIDObject.h"
#include "MessageIdentifiers.h"
#include "PacketLogger.h"
#include "BitStream.h"
#define SERVER_MAXCLIENTS 4
#define DOLOG 1
// Define our custom message ID's
enum {
ID_USER_SERVERAPPLE_CREATED = ID_USER_PACKET_ENUM+1
};
#if (defined(__GNUC__) || defined(__GCCXML__))
#define __cdecl
#endif
// Create a logger that knows about our own message IDs
// That way we can see what's happening
class CustomPacketLogger : public PacketLogger
{
public:
CustomPacketLogger(){
}
const char* UserIDTOString(unsigned char id){
switch (id){
case ID_USER_SERVERAPPLE_CREATED : return "ID_USER_SERVERAPPLE_CREATED"; break;
default: return "Unknown user message ID";
}
}
};
// Classes that use class member RPCs must derive from NetworkIDObject
class Apple : public NetworkIDObject
{
public:
// RPC member Functions MUST be marked __cdecl!
virtual void __cdecl func1(RPCParameters *rpcParms)
{
if (rpcParms->input)
printf("\nBase Apple func1: %s\n", rpcParms->input);
else
printf("\nBase Apple func1\n");
}
// RPC member Functions MUST be marked __cdecl!
virtual void __cdecl func1(char *blah)
{
printf("\nFunc1. Does not match function signature and should never be called.\n");
}
// RPC member Functions MUST be marked __cdecl!
virtual void __cdecl func2(RPCParameters *rpcParms)
{
if (rpcParms->input)
printf("\nBase Apple func2: %s\n", rpcParms->input);
else
printf("\nBase Apple func2\n");
}
// RPC member Functions MUST be marked __cdecl!
virtual void __cdecl func3(RPCParameters *rpcParms)
{
if (rpcParms->input)
printf("\nBase Apple func3: %s\n", rpcParms->input);
else
printf("\nBase Apple func3\n");
}
};
class GrannySmith : public Apple
{
public:
void __cdecl func1(RPCParameters *rpcParms)
{
printf("\nDerived GrannySmith func1: %s\n", rpcParms->input);
}
};
#endif
|
#include <iostream>
#include <string>
using namespace std;
int main(){
string a, b;
cin >> a >> b;
int sum1 = 1, sum2 = 1;
for(int i = 0; i < a.length(); i++){
sum1 *= a[i] - 'A' + 1;
}
for(int i = 0; i < b.length(); i++){
sum2 *= b[i] - 'A' + 1;
}
// cout << sum1 << sum2;
if(sum1%47 == sum2%47)
cout << "GO";
else
cout << "STAY";
return 0;
}
|
#include <SimbleeCOM.h>
#include "Wire/Wire.h"
#include "config.h"
#include "rtc.h"
#include "rom.h"
#include "accel.h"
#include "radio_common.h"
#include "debug.h"
// Time keeping data structure
Time timer;
// RTC time data structure
struct ts rtcTime;
// Time keeping and time sharing variables
int interruptTime;
unsigned long ms;
bool foundRTCTransition;
/*
* Starts the RTC clock
*/
void setRTCTime(int month, int date, int year, int day, int hours, int minutes, int seconds)
{
rtcTime.mon = month;
rtcTime.mday = date;
rtcTime.year = 2000 + year;
rtcTime.wday = day;
rtcTime.hour = hours;
rtcTime.min = minutes;
rtcTime.sec = seconds;
DS3231_set(rtcTime);
}
/*
* Starts the RTC interrupt
*/
void EnableRTCInterrupt()
{
DS3231_set_creg(DS3231_BBSQW);
}
/*
* Stops the RTC interrupt
*/
void DisableRTCInterrupt()
{
DS3231_set_creg(DS3231_INTCN);
}
/*
* Sets an RTC alarm for 9am
* TODO: skip weekends
*/
void SetAlarmAtNine()
{
// flags define what calendar component to be checked against the current time in order
// to trigger the alarm - see datasheet
// A1M1 (seconds) (0 to enable, 1 to disable)
// A1M2 (minutes) (0 to enable, 1 to disable)
// A1M3 (hour) (0 to enable, 1 to disable)
// A1M4 (day) (0 to enable, 1 to disable)
// DY/DT (dayofweek == 1/dayofmonth == 0)
uint8_t flags[5] = {1, 1, 0, 1, 1};
DS3231_set_a1(0, 0, 9, 0, flags); // second, minute, hour, day
// Enable alarm & put it on int pin
DS3231_set_creg(DS3231_INTCN | DS3231_A1IE);
}
////////// Time Functions //////////
/*
* Sets system time sent from serial monitor
* Format:
*/
void programSystemTime()
{
d("Waiting for time");
char systemTime[16];
while (Serial.available() < 16) {
delay(10);
}
Serial.readBytes(systemTime, 16);
for (int i = 0; i < 16; i++) {
Serial.print(systemTime[i]);
}
Serial.println();
int initialMS = (systemTime[13] - '0') * 100 + (systemTime[14] - '0') * 10 + (systemTime[15] - '0');
delay(1000 - initialMS);
uint8_t month = (systemTime[0] - '0') * 10 + (systemTime[1] - '0'); // MM
uint8_t date = (systemTime[2] - '0') * 10 + (systemTime[3] - '0'); // DD
uint8_t year = (systemTime[4] - '0') * 10 + (systemTime[5] - '0'); // YY
uint8_t day = (systemTime[6] - '0'); // Day
uint8_t hour = (systemTime[7] - '0') * 10 + (systemTime[8] - '0'); // HH
uint8_t minute = (systemTime[9] - '0') * 10 + (systemTime[10] - '0'); // MM
uint8_t second = (systemTime[11] - '0') * 10 + (systemTime[12] - '0'); // SS
timer.secondsElapsed = 1;
d(String(month));
d(String(date));
d(String(year));
d(String(day));
d(String(hour));
d(String(minute));
d(String(second));
setRTCTime(month, date, year, day, hour, minute, second);
timer.setInitialTime(month, date, year, day, hour, minute, second);
#ifdef DEBUG
Serial.print("Time set to ");
timer.displayDateTime();
#endif
}
|
int GetMajor()
{
return 0;
}
int GetMinor()
{
return 0;
}
|
#ifndef _TNA_VKRENDERER_TOOLS_H_
#define _TNA_VKRENDERER_TOOLS_H_ value
#include "vkrenderer.h"
namespace tna
{
VkFormat
find_supported_format(VkPhysicalDevice physical_device,
VkFormat* candidates,
uint32_t num_candidates,
VkImageTiling tiling,
VkFormatFeatureFlags feature_flags);
VkCommandBuffer
begin_single_time_commands(VkDevice device,
VkCommandPool command_pool);
void
end_single_time_commands(VkDevice device,
VkQueue graphics_queue,
VkCommandPool command_pool,
VkCommandBuffer command_buffer);
void
transition_image_layout(VkDevice device,
VkCommandPool command_pool,
VkQueue queue,
VkImage image,
VkFormat format,
VkImageLayout oldLayout,
VkImageLayout newLayout);
} /* tna */
#endif /* ifndef _TNA_VKRENDERER_TOOLS_H_ */
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
string a, b;
cin>>a>>b;
char ans[a.length()];
bool f = 0;
for(int i=0; i<a.length(); i++)
{
if(a[i]==b[i])
{
if(a[i]=='z') ans[i] = 'z';
else ans[i] = a[i]+1;
}
else if(b[i]>a[i])
{
f = 1;
break;
}
else if(a[i]>b[i]) ans[i] = b[i];
}
if(f) cout<<-1<<endl;
else
{
for(int i=0; i<a.length(); i++)
{
cout<<ans[i];
}
}
cout<<endl;
return 0;
}
|
// Author: Daniel Rush
#pragma once
#include <stdarg.h>
#include <string.h>
#include <stdio.h>
#include "pico/stdlib.h"
enum LoggerLevel {
kLogDebug = 0,
kLogInfo = 1,
kLogError = 2,
kLogFatal = 3,
kLogLevels,
};
const int32_t MSG_SIZE = 256;
class Logger {
public:
void Printf(LoggerLevel Level, const char* format, ...);
private:
void Write(const char* msg);
void FormatMessage(LoggerLevel level, const char* format, va_list args);
int foo;
char msg_buffer_[MSG_SIZE];
};
|
#ifndef COMPUTERLOADING_H
#define COMPUTERLOADING_H
class GameWindow;
class ComputerLoading
{
public:
ComputerLoading();
ComputerLoading(GameWindow *gameWindowP);
void update();
private:
GameWindow *gameWindowP = 0;
};
#endif // COMPUTERLOADING_H
|
#include <iostream>
#include <stdlib.h>
#include <time.h>
//zaeem: 19L-1196
//--------------- function prototypes
int show_menu();
int Search(int [],int);
bool Delete(int [], int &, int );
bool Insert(int [], int, int &, int);
void Print(int [],int &);
using namespace std;
int main(){
const int capacity=10;
int array[capacity];
int choice, index=0, num,key;
bool rvalue;
choice= show_menu();
while(choice !=5){
switch(choice){
case 1:
cout <<"==============================\n";
cout <<"enter a number to insert: ";
cin >> num;
Insert(array,capacity,index,num);
break;
case 2:
cout <<"==============================\n";
cout << "enter a key to delete: ";
cin >> key;
Delete(array,index,key);
break;
case 3:
cout <<"==============================\n";
// search
cout << "what to search: ";
cin >> key;
Search(array,key);
break;
case 4:
cout <<"==============================\n";
Print(array,index);
break;
}
choice=show_menu();
}
system("pause");
return 0;
}
// Defining functions here
int Search(int arr[],int key){
for(int i=0; i< 10; i++){
if(key==arr[i]) {
cout <<"found at 0 based index: " << i <<endl;
return i;}
}
cout << key << " not found in the array.\n" << endl;
return -1; // if program come here, means not found
}
bool Delete(int arr[], int &index, int key){
int location= Search(arr,key);
if(location == -1) {
cout << "Specified element not found in Array!" <<endl;
return -1; // not found
}
else{
int newArray[10]; //copy
int counter=0;
for(int i=0; i<index; i++){
if(i !=location){
newArray[counter]=arr[i];
counter++;
}
for(int i=0; i<counter; i++){
arr[i]=newArray[i];
}
}
index=index-1; // after deleting, index decreases
return true;}
}
bool Insert(int arr[], int capacity, int & index, int element){
if(index < capacity){
arr[index] = element;
index++;
return true;
}
else{
cout << "no room to insertion.\n";
return false; // in case of error
}
}
//---------------------------
void Print(int arr[],int & index){
cout << "Elements of an array: ";
for(int i=0; i < index; i++){
cout << arr[i] << " ";
}
cout << endl;
}
int show_menu(){
// to avoid long line, I used folowing backslash
cout << "Enter your choice\n\
1: Insert\n\
2: Delete\n\
3: Search\n\
4: Print\n\
5: Exit: ";
int c; //choice
cin >> c;
return c;
}
|
////////////////////////////////////////////////////////////////////////////////
// Module Name: main.cpp
// Authors: Sergey Shershakov
// Version: 0.1.0
// Date: 01.05.2017
//
// This is a part of the course "Algorithms and Data Structures"
// provided by the School of Software Engineering of the Faculty
// of Computer Science at the Higher School of Economics.
////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include "rbtree.h"
using namespace std;
void simplestTest()
{
using namespace xi;
// просто создаем объект дерева
RBTree<int> tree1;
try
{
const int k = 15;
int array[k] = { 10,9,20,-7,4,1,0,5,-2,12,6,15,-21,25,8 };//, 12, 6, 15, -21, 25, 8};
for (int i = 0; i < k; ++i)
tree1.insert(array[i]);
const RBTree<int>::Node* node = tree1.find(10);
if (node)
cout << node->getKey() << endl;
else
cout << "No node with such key found" << endl;
}
catch (exception& ex)
{
cout << ex.what() << endl;
}
}
int main()
{
cout << "Hello, World!" << endl;
simplestTest();
return 0;
}
|
//
// SMImageEditorCropGuideView.cpp
// iPet
//
// Created by KimSteve on 2017. 4. 19..
// Copyright © 2017년 KimSteve. All rights reserved.
//
#include "SMImageEditorCropGuideView.h"
#include "../../SMFrameWork/Base/SMButton.h"
#include "../../SMFrameWork/Util/ViewUtil.h"
#define kCropGuideBorderLineWidth 4.0f
#define kCropGuideBorderLineColor cocos2d::Color4F::WHITE
#define kCropGuideInnerLineWidth 2.0f
#define kCropGuideAreaColor cocos2d::Color4F(0, 0, 0, 0.9f)
#define kCropGuideMinSize 50.0f
#define kKnobButtonSize 88.0f
SMImageEditorCropGuideView::SMImageEditorCropGuideView() :
_outLine(nullptr)
, _guideLine1(nullptr)
, _guideLine2(nullptr)
, _guideLine3(nullptr)
, _guideLine4(nullptr)
, _stencilView(nullptr)
, _cropView(nullptr)
{
}
SMImageEditorCropGuideView::~SMImageEditorCropGuideView()
{
}
SMImageEditorCropGuideView * SMImageEditorCropGuideView::create(int tag, float x, float y, float width, float height, cocos2d::Rect rect)
{
SMImageEditorCropGuideView * view = new SMImageEditorCropGuideView();
if (view != nullptr) {
view->setAnchorPoint(cocos2d::Vec2::ZERO);
view->setPosition(cocos2d::Vec2(x, y));
view->setContentSize(cocos2d::Size(width, height));
view->imageRect = rect;
view->cropType = kCropMenuRect;
if (view->init()) {
view->autorelease();
}
} else {
CC_SAFE_DELETE(view);
}
return view;
}
bool SMImageEditorCropGuideView::init()
{
if (!SMView::init()) {
return false;
}
cocos2d::Size s = cocos2d::Director::getInstance()->getWinSize();
setScissorEnable(false);
// init crop rect
cropRect.size.width = imageRect.size.width*0.95f;
cropRect.size.height = imageRect.size.height*0.95f;
cropRect.origin.x = imageRect.origin.x+imageRect.size.width/2-cropRect.size.width/2;
cropRect.origin.y = imageRect.origin.y+imageRect.size.height/2-cropRect.size.height/2;
_cropView = SMView::create(0, cropRect.origin.x, cropRect.origin.y, cropRect.size.width, cropRect.size.height);
_cropView->setBackgroundColor4F(cocos2d::Color4F::BLACK);
_stencilView = StencilView::create(0, imageRect.origin.x, imageRect.origin.y, imageRect.size.width, imageRect.size.height, _cropView);
_stencilView->getCoverView()->setBackgroundColor4F(cocos2d::Color4F(0, 0, 0, 0.7f));
addChild(_stencilView);
sizeWithPanningBeginPoint = cocos2d::Vec2::ZERO;
leftTopButton = SMButton::create(0, SMButton::Style::SOLID_CIRCLE, 0, 0, kKnobButtonSize, kKnobButtonSize);
rightTopButton = SMButton::create(0, SMButton::Style::SOLID_CIRCLE, 0, 0, kKnobButtonSize, kKnobButtonSize);
leftBottomButton = SMButton::create(0, SMButton::Style::SOLID_CIRCLE, 0, 0, kKnobButtonSize, kKnobButtonSize);
rightBottomButton = SMButton::create(0, SMButton::Style::SOLID_CIRCLE, 0, 0, kKnobButtonSize, kKnobButtonSize);
leftTopButton->setLocalZOrder(90);
rightTopButton->setLocalZOrder(90);
leftBottomButton->setLocalZOrder(90);
rightBottomButton->setLocalZOrder(90);
leftTopButton->setButtonColor(SMButton::State::NORMAL, MAKE_COLOR4F(0xe94253, 1.0f));
rightTopButton->setButtonColor(SMButton::State::NORMAL, MAKE_COLOR4F(0xe94253, 1.0f));
leftBottomButton->setButtonColor(SMButton::State::NORMAL, MAKE_COLOR4F(0xe94253, 1.0f));
rightBottomButton->setButtonColor(SMButton::State::NORMAL, MAKE_COLOR4F(0xe94253, 1.0f));
leftTopButton->setButtonColor(SMButton::State::PRESSED, MAKE_COLOR4F(0x37c267, 1.0f));
rightTopButton->setButtonColor(SMButton::State::PRESSED, MAKE_COLOR4F(0x37c267, 1.0f));
leftBottomButton->setButtonColor(SMButton::State::PRESSED, MAKE_COLOR4F(0x37c267, 1.0f));
rightBottomButton->setButtonColor(SMButton::State::PRESSED, MAKE_COLOR4F(0x37c267, 1.0f));
leftTopButton->setOutlineColor(SMButton::State::NORMAL, MAKE_COLOR4F(0x333333, 1.0f));
rightTopButton->setOutlineColor(SMButton::State::NORMAL, MAKE_COLOR4F(0x333333, 1.0f));
leftBottomButton->setOutlineColor(SMButton::State::NORMAL, MAKE_COLOR4F(0x333333, 1.0f));
rightBottomButton->setOutlineColor(SMButton::State::NORMAL, MAKE_COLOR4F(0x333333, 1.0f));
leftTopButton->setOutlineColor(SMButton::State::NORMAL, MAKE_COLOR4F(0x999999, 1.0f));
rightTopButton->setOutlineColor(SMButton::State::NORMAL, MAKE_COLOR4F(0x999999, 1.0f));
leftBottomButton->setOutlineColor(SMButton::State::NORMAL, MAKE_COLOR4F(0x999999, 1.0f));
rightBottomButton->setOutlineColor(SMButton::State::NORMAL, MAKE_COLOR4F(0x999999, 1.0f));
leftTopButton->setOutlineWidth(2.0f);
rightTopButton->setOutlineWidth(2.0f);
leftBottomButton->setOutlineWidth(2.0f);
rightBottomButton->setOutlineWidth(2.0f);
addChild(leftTopButton);
addChild(rightTopButton);
addChild(leftBottomButton);
addChild(rightBottomButton);
adjustmentButtonPosition();
lineAlpha = 0.5f;
_outLine = cocos2d::DrawNode::create();
addChild(_outLine);
_guideLine1 = cocos2d::DrawNode::create();
_guideLine2 = cocos2d::DrawNode::create();
_guideLine3 = cocos2d::DrawNode::create();
_guideLine4 = cocos2d::DrawNode::create();
addChild(_guideLine1);
addChild(_guideLine2);
addChild(_guideLine3);
addChild(_guideLine4);
setCropType(kCropMenuRect);
return true;
}
void SMImageEditorCropGuideView::adjustmentButtonPosition()
{
leftBottomButton->setPosition(cocos2d::Vec2(cropRect.origin.x-kKnobButtonSize/2, cropRect.origin.y-kKnobButtonSize/2));
rightBottomButton->setPosition(cocos2d::Vec2(cropRect.origin.x+cropRect.size.width-kKnobButtonSize/2, cropRect.origin.y-kKnobButtonSize/2));
leftTopButton->setPosition(cocos2d::Vec2(cropRect.origin.x-kKnobButtonSize/2, cropRect.origin.y+cropRect.size.height-kKnobButtonSize/2));
rightTopButton->setPosition(cocos2d::Vec2(cropRect.origin.x+cropRect.size.width-kKnobButtonSize/2, cropRect.origin.y+cropRect.size.height-kKnobButtonSize/2));
}
void SMImageEditorCropGuideView::visit(cocos2d::Renderer *renderer, const cocos2d::Mat4 &parentTransform, uint32_t parentFlags)
{
SMView::visit(renderer, parentTransform, parentFlags);
_outLine->clear();
_guideLine1->clear();
_guideLine2->clear();
_guideLine3->clear();
_guideLine4->clear();
_outLine->setLineWidth(kCropGuideBorderLineWidth);
_outLine->drawRect(cocos2d::Vec2(cropRect.origin.x, cropRect.origin.y), cocos2d::Vec2(cropRect.origin.x+cropRect.size.width, cropRect.origin.y+cropRect.size.height), kCropGuideBorderLineColor);
_guideLine1->setLineWidth(kCropGuideInnerLineWidth);
_guideLine2->setLineWidth(kCropGuideInnerLineWidth);
_guideLine3->setLineWidth(kCropGuideInnerLineWidth);
_guideLine4->setLineWidth(kCropGuideInnerLineWidth);
_guideLine1->drawLine(cocos2d::Vec2(cropRect.origin.x, cropRect.origin.y + cropRect.size.height/3), cocos2d::Vec2(cropRect.origin.x+cropRect.size.width, cropRect.origin.y + cropRect.size.height/3), MAKE_COLOR4F(0xffffff, lineAlpha));
_guideLine2->drawLine(cocos2d::Vec2(cropRect.origin.x, cropRect.origin.y + cropRect.size.height/3*2), cocos2d::Vec2(cropRect.origin.x+cropRect.size.width, cropRect.origin.y + cropRect.size.height/3*2), MAKE_COLOR4F(0xffffff, lineAlpha));
_guideLine3->drawLine(cocos2d::Vec2(cropRect.origin.x + cropRect.size.width/3, cropRect.origin.y), cocos2d::Vec2(cropRect.origin.x+cropRect.size.width/3, cropRect.origin.y+cropRect.size.height), MAKE_COLOR4F(0xffffff, lineAlpha));
_guideLine4->drawLine(cocos2d::Vec2(cropRect.origin.x + cropRect.size.width/3*2, cropRect.origin.y), cocos2d::Vec2(cropRect.origin.x+cropRect.size.width/3*2, cropRect.origin.y+cropRect.size.height), MAKE_COLOR4F(0xffffff, lineAlpha));
}
void SMImageEditorCropGuideView::setCropType(kCropMenu type)
{
cropType = type;
if (type==kCropMenuFree) {
return;
}
float widthRatio;
float heightRatio;
switch (cropType) {
case kCropMenuOriginal:
{
cropRect = imageRect;
}
break;
case kCropMenuSquare:
{
if (imageRect.size.width>imageRect.size.height) {
float height = imageRect.size.height;
cropRect = cocos2d::Rect(getContentSize().width/2.0f-height/2.0f, imageRect.origin.y, height, height);
} else {
float width = imageRect.size.width;
cropRect = cocos2d::Rect(imageRect.origin.x, getContentSize().height/2.0f-width/2.0f, width, width);
}
}
break;
case kCropMenu16_9:
{
float ratio = imageRect.size.width / imageRect.size.height;
widthRatio = 16.0f;
heightRatio = 9.0f;
if (ratio > widthRatio/heightRatio) {
float height = imageRect.size.height;
float width = height / heightRatio * widthRatio;
cropRect = cocos2d::Rect(getContentSize().width/2.0f - width/2.0f, imageRect.origin.y, width, height);
} else {
float width = imageRect.size.width;
float height = width / widthRatio * heightRatio;
cropRect = cocos2d::Rect(imageRect.origin.x, getContentSize().height/2.0f-height/2.0f, width, height);
}
}
break;
case kCropMenu3_2:
{
float ratio = imageRect.size.width / imageRect.size.height;
widthRatio = 3.0f;
heightRatio = 2.0f;
if (ratio > widthRatio/heightRatio) {
float height = imageRect.size.height;
float width = height / heightRatio * widthRatio;
cropRect = cocos2d::Rect(getContentSize().width/2.0f - width/2.0f, imageRect.origin.y, width, height);
} else {
float width = imageRect.size.width;
float height = width / widthRatio * heightRatio;
cropRect = cocos2d::Rect(imageRect.origin.x, getContentSize().height/2.0f-height/2.0f, width, height);
}
}
break;
case kCropMenu4_3:
{
float ratio = imageRect.size.width / imageRect.size.height;
widthRatio = 4.0f;
heightRatio = 3.0f;
if (ratio > widthRatio/heightRatio) {
float height = imageRect.size.height;
float width = height / heightRatio * widthRatio;
cropRect = cocos2d::Rect(getContentSize().width/2.0f - width/2.0f, imageRect.origin.y, width, height);
} else {
float width = imageRect.size.width;
float height = width / widthRatio * heightRatio;
cropRect = cocos2d::Rect(imageRect.origin.x, getContentSize().height/2.0f-height/2.0f, width, height);
}
}
break;
case kCropMenu4_6:
{
float ratio = imageRect.size.width / imageRect.size.height;
widthRatio = 4.0f;
heightRatio = 6.0f;
if (ratio > widthRatio/heightRatio) {
float height = imageRect.size.height;
float width = height / heightRatio * widthRatio;
cropRect = cocos2d::Rect(getContentSize().width/2.0f - width/2.0f, imageRect.origin.y, width, height);
} else {
float width = imageRect.size.width;
float height = width / widthRatio * heightRatio;
cropRect = cocos2d::Rect(imageRect.origin.x, getContentSize().height/2.0f-height/2.0f, width, height);
}
}
break;
case kCropMenu5_7:
{
float ratio = imageRect.size.width / imageRect.size.height;
widthRatio = 5.0f;
heightRatio = 7.0f;
if (ratio > widthRatio/heightRatio) {
float height = imageRect.size.height;
float width = height / heightRatio * widthRatio;
cropRect = cocos2d::Rect(getContentSize().width/2.0f - width/2.0f, imageRect.origin.y, width, height);
} else {
float width = imageRect.size.width;
float height = width / widthRatio * heightRatio;
cropRect = cocos2d::Rect(imageRect.origin.x, getContentSize().height/2.0f-height/2.0f, width, height);
}
}
break;
case kCropMenu8_10:
{
float ratio = imageRect.size.width / imageRect.size.height;
widthRatio = 8.0f;
heightRatio = 10.0f;
if (ratio > widthRatio/heightRatio) {
float height = imageRect.size.height;
float width = height / heightRatio * widthRatio;
cropRect = cocos2d::Rect(getContentSize().width/2.0f - width/2.0f, imageRect.origin.y, width, height);
} else {
float width = imageRect.size.width;
float height = width / widthRatio * heightRatio;
cropRect = cocos2d::Rect(imageRect.origin.x, getContentSize().height/2.0f-height/2.0f, width, height);
}
}
break;
case kCropMenu14_8:
{
float ratio = imageRect.size.width / imageRect.size.height;
widthRatio = 14.0f;
heightRatio = 8.0f;
if (ratio > widthRatio/heightRatio) {
float height = imageRect.size.height;
float width = height / heightRatio * widthRatio;
cropRect = cocos2d::Rect(getContentSize().width/2.0f - width/2.0f, imageRect.origin.y, width, height);
} else {
float width = imageRect.size.width;
float height = width / widthRatio * heightRatio;
cropRect = cocos2d::Rect(imageRect.origin.x, getContentSize().height/2.0f-height/2.0f, width, height);
}
}
break;
default:
break;
}
cocos2d::Vec2 cropPoint = cropRect.origin - imageRect.origin;
_cropView->setPosition(cropPoint);
_cropView->setContentSize(cropRect.size);
_cropView->scheduleUpdate();
adjustmentButtonPosition();
scheduleUpdate();
}
void SMImageEditorCropGuideView::startFadeIn(float dt)
{
lineAlpha += 0.15f;
scheduleUpdate();
if (0.5f <= lineAlpha) {
lineAlpha = 0.5f;
unschedule(schedule_selector(SMImageEditorCropGuideView::startFadeIn));
}
}
void SMImageEditorCropGuideView::startFadeOut(float dt)
{
lineAlpha -= 0.03f;
scheduleUpdate();
if (0.0f >= lineAlpha) {
lineAlpha = 0.0f;
unschedule(schedule_selector(SMImageEditorCropGuideView::startFadeOut));
}
}
void SMImageEditorCropGuideView::innerLineFadeIn()
{
if (isScheduled(schedule_selector(SMImageEditorCropGuideView::startFadeIn))) {
unschedule(schedule_selector(SMImageEditorCropGuideView::startFadeIn));
}
if (isScheduled(schedule_selector(SMImageEditorCropGuideView::startFadeOut))) {
unschedule(schedule_selector(SMImageEditorCropGuideView::startFadeOut));
}
schedule(schedule_selector(SMImageEditorCropGuideView::startFadeIn), 0.1f);
}
void SMImageEditorCropGuideView::innerLineFadeOut()
{
if (isScheduled(schedule_selector(SMImageEditorCropGuideView::startFadeOut))) {
unschedule(schedule_selector(SMImageEditorCropGuideView::startFadeOut));
}
schedule(schedule_selector(SMImageEditorCropGuideView::startFadeOut), 0.1f);
}
int SMImageEditorCropGuideView::dispatchTouchEvent(const int action, const cocos2d::Touch* touch, const cocos2d::Vec2* point, MotionEvent* event)
{
SMView::dispatchTouchEvent(action, touch, point, event);
float x = point->x;
float y = point->y;
if (getMotionTarget()==leftTopButton || getMotionTarget()==rightTopButton || getMotionTarget()==leftBottomButton || getMotionTarget()==rightBottomButton) {
// resize
switch (action) {
case MotionEvent::ACTION_DOWN:
{
innerLineFadeIn();
}
break;
case MotionEvent::ACTION_UP:
case MotionEvent::ACTION_CANCEL:
{
innerLineFadeOut();
}
break;
case MotionEvent::ACTION_MOVE:
{
float oldLeft = cropRect.origin.x;
float oldBottom = cropRect.origin.y;
float oldRight = cropRect.origin.x+cropRect.size.width;
float oldTop = cropRect.origin.y+cropRect.size.height;
float newLeft = 0.0f;
float newTop = 0.0f;
float newRight = 0.0f;
float newBottom = 0.0f;
if (getMotionTarget()==leftTopButton) {
// 왼쪽 상단 버튼이 움직일때는 우측 하단이 고정
newLeft = MIN(MAX(x, imageRect.origin.x), oldRight - kCropGuideMinSize);
newTop = MAX(MIN(y, imageRect.origin.y+imageRect.size.height), oldBottom + kCropGuideMinSize);
newRight = oldRight;
newBottom = oldBottom;
} else if (getMotionTarget()==rightTopButton) {
// 우측 상단 버튼이 움직일때는 좌측 하단이 고정
newLeft = oldLeft;
newTop = MAX(MIN(y, imageRect.origin.y+imageRect.size.height), oldBottom + kCropGuideMinSize);
newRight = MAX(MIN(x, imageRect.origin.x+imageRect.size.width), oldLeft + kCropGuideMinSize);
newBottom = oldBottom;
} else if (getMotionTarget()==leftBottomButton) {
// 좌측 하단 버튼이 움직일때는 우측 상단이 고정
newLeft = MIN(MAX(x, imageRect.origin.x), oldRight - kCropGuideMinSize);
newTop = oldTop;
newRight = oldRight;
newBottom = MIN(MAX(y, imageRect.origin.y), oldTop-kCropGuideMinSize);
} else if (getMotionTarget()==rightBottomButton) {
// 우측 하단 버튼이 움직일때는 좌측 상단이 고정
newLeft = oldLeft;
newTop = oldTop;
newRight = MAX(MIN(x, imageRect.origin.x + imageRect.size.width), oldLeft + kCropGuideMinSize);
newBottom = MIN(MAX(y, imageRect.origin.y), oldTop-kCropGuideMinSize);
} else {
CCLOG("[[[[[ WTF????");
}
if (cropType!=kCropMenuRect) {
float ratio = 1.0f;
switch (cropType) {
case kCropMenuOriginal:
{
ratio = imageRect.size.height / imageRect.size.width;
}
break;
case kCropMenu16_9:
{
ratio = 9.0f/16.0f;
}
break;
case kCropMenu3_2:
{
ratio = 2.0f/3.0f;
}
break;
case kCropMenu4_3:
{
ratio = 3.0f/4.0f;
}
break;
case kCropMenu4_6:
{
ratio = 6.0f/4.0f;
}
break;
case kCropMenu5_7:
{
ratio = 7.0f/5.0f;
}
break;
case kCropMenu8_10:
{
ratio = 10.0f/8.0f;
}
break;
case kCropMenu14_8: // --> sns profile cover... Do not use.
{
ratio = 8.0f/14.0f;
}
break;
default:
break;
}
float width = newRight - newLeft;
float newWidth = width;
float newHeight = width*ratio;
if (getMotionTarget()==leftTopButton) {
if (newBottom+newHeight > imageRect.origin.y + imageRect.size.height) {
newHeight = imageRect.origin.y + imageRect.size.height - newBottom;
newWidth = newHeight / ratio;
}
newLeft = newRight-newWidth;
newTop = newBottom + newHeight;
} else if (getMotionTarget()==rightTopButton) {
if (newBottom+newHeight > imageRect.origin.y + imageRect.size.height) {
newHeight = imageRect.origin.y + imageRect.size.height - newBottom;
newWidth = newHeight / ratio;
}
newRight = newLeft+newWidth;
newTop = newBottom + newHeight;
} else if (getMotionTarget()==leftBottomButton) {
if (newTop-newHeight < imageRect.origin.y) {
newHeight = newTop - imageRect.origin.y;
newWidth = newHeight / ratio;
}
newLeft = newRight-newWidth;
newBottom = newTop - newHeight;
} else if (getMotionTarget()==rightBottomButton) {
if (newTop-newHeight < imageRect.origin.y) {
newHeight = newTop - imageRect.origin.y;
newWidth = newHeight / ratio;
}
newRight = newLeft+newWidth;
newBottom = newTop - newHeight;
} else {
CCLOG("[[[[[ WTF????");
}
}
cropRect = cocos2d::Rect(newLeft, newBottom, newRight-newLeft, newTop-newBottom);
cocos2d::Vec2 cropPoint = cropRect.origin - imageRect.origin;
_cropView->setPosition(cropPoint);
_cropView->setContentSize(cropRect.size);
_cropView->scheduleUpdate();
adjustmentButtonPosition();
scheduleUpdate();
}
break;
}
} else {
// panning
// CCLOG("[[[[[ Guide View Panning");
switch (action) {
case MotionEvent::ACTION_DOWN:
{
sizeWithPanningBeginPoint.width = x - cropRect.origin.x;
sizeWithPanningBeginPoint.height = y - cropRect.origin.y;
innerLineFadeIn();
}
break;
case MotionEvent::ACTION_UP:
case MotionEvent::ACTION_CANCEL:
{
sizeWithPanningBeginPoint = cocos2d::Size::ZERO;
innerLineFadeOut();
}
break;
case MotionEvent::ACTION_MOVE:
{
if (sizeWithPanningBeginPoint.width != 0 && sizeWithPanningBeginPoint.height != 0) {
float changeX = x - sizeWithPanningBeginPoint.width;
float changeY = y - sizeWithPanningBeginPoint.height;
if (changeX <= imageRect.origin.x) {
changeX = imageRect.origin.x;
}
if (changeY <= imageRect.origin.y) {
changeY = imageRect.origin.y;
}
if (changeX + cropRect.size.width >= imageRect.origin.x + imageRect.size.width) {
changeX = imageRect.size.width - cropRect.size.width + imageRect.origin.x;
}
if (changeY + cropRect.size.height >= imageRect.origin.y + imageRect.size.height) {
changeY = imageRect.size.height - cropRect.size.height + imageRect.origin.y;
}
cropRect.origin.x = changeX;
cropRect.origin.y = changeY;
cocos2d::Vec2 cropPoint = cropRect.origin - imageRect.origin;
_cropView->setPosition(cropPoint);
_cropView->setContentSize(cropRect.size);
_cropView->scheduleUpdate();
adjustmentButtonPosition();
scheduleUpdate();
}
}
break;
}
}
return TOUCH_TRUE;
}
|
#include<iostream>
using namespace std;
long long w(long long a,long long b,long long c)
{
if(a<=0 || b<=0 || c<=0)
{
return 1;
}
if(a>20 || b>20 || c>20)
{
return w(20,20,20);
}
if(a<b && b<c)
{
return w(a,b,c-1)+w(a,b-1,c-1)-w(a,b-1,c);
}
return w(a-1,b,c)+w(a-1,b-1,c)+w(a-1,b,c-1)-w(a-1,b-1,c-1);
}
int main()
{
long long a,b,c;
while(cin >>a>>b>>c)
{
if(a==-1 && b==-1 && c==-1)break;
cout <<"w("<<a<<", "<<b<<", "<<c<<") = "<<w(a,b,c)<<endl;
}
return 0;
}
|
/* Copyright 2017-2018 All Rights Reserved.
* Gyeonghwan Hong (redcarrottt@gmail.com)
* Eunsoo Park (esevan.park@gmail.com)
* Injung Hwang (sinban04@gmail.com)
*
* [Contact]
* Gyeonghwan Hong (redcarrottt@gmail.com)
*
* Licensed under the Apache License, Version 2.0(the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __SC_CORE_H__
#define __SC_CORE_H__
#include "APIInternal.h"
#include "ControlMessageReceiver.h"
#include "ControlMessageSender.h"
#include "SegmentManager.h"
#include "ServerAdapter.h"
#include "../../common/inc/Counter.h"
#include "../../common/inc/ArrivalTimeCounter.h"
#include <mutex>
#include <stdint.h>
#include <vector>
namespace sc {
class Core;
/*
* Auxiliary Classes (Transactions)
* Series of asynchronous callbacks, especially used for
* connection/disconnection callbacks.
*/
class StartCoreTransaction {
public:
static bool run(Core *caller);
void start();
static void connect_first_adapter_callback(ServerAdapter *adapter,
bool is_success);
private:
void done(bool is_success);
StartCoreTransaction(Core *caller) { this->mCaller = caller; }
static StartCoreTransaction *sOngoing;
Core *mCaller;
}; /* class StartCoreTransaction */
class StopCoreTransaction {
public:
static bool run(Core *caller);
void start();
static void disconnect_adapter_callback(ServerAdapter *adapter,
bool is_success);
private:
void done(bool is_success);
StopCoreTransaction(Core *caller) { this->mCaller = caller; }
static StopCoreTransaction *sOngoing;
Core *mCaller;
int mAdaptersCount;
std::mutex mAdaptersCountLock;
}; /* class StopCoreTransaction */
/* Core State */
typedef enum {
kCoreStateIdle = 0,
kCoreStateStarting = 1,
kCoreStateReady = 2,
kCoreStateStopping = 3
} CoreState; /* enum CoreState */
class ServerAdapter;
/*
* Core
*/
class Core {
public:
/*
* APIs
* These functions are mapped to ones in API.h
*/
void start();
void done_start(bool is_success);
void stop();
void done_stop(bool is_success);
void register_adapter(ServerAdapter *adapter);
int send(const void *dataBuffer, uint32_t dataLength, bool is_control);
int receive(void **pDataBuffer, bool is_control);
public:
/* Switch preparation APIs */
void prepare_switch(int prev_id, int next_id);
void cancel_preparing_switch(int prev_id, int next_id);
public:
/* Control Message Receiver/Sender Getter */
ControlMessageSender *get_control_sender(void) {
return this->mControlMessageSender;
}
ControlMessageReceiver *get_control_receiver(void) {
return this->mControlMessageReceiver;
}
private:
/* Control Message Receiver/Sender */
ControlMessageSender *mControlMessageSender;
ControlMessageReceiver *mControlMessageReceiver;
public:
/* Get statistics */
int get_total_bandwidth() {
int num_adapters = 0;
int now_total_bandwidth = 0;
/* Statistics from adapters */
int adapter_count = this->get_adapter_count();
for (int i = 0; i < adapter_count; i++) {
ServerAdapter *adapter = this->get_adapter(i);
if (adapter == NULL)
continue;
int bandwidth_up = adapter->get_bandwidth_up();
int bandwidth_down = adapter->get_bandwidth_down();
now_total_bandwidth += (bandwidth_up + bandwidth_down);
num_adapters++;
}
return now_total_bandwidth;
}
float get_ema_send_request_size() {
return this->mSendRequestSize.get_em_average();
}
float get_ema_send_arrival_time() {
return this->mSendArrivalTime.get_em_average();
}
// Send RTT, Media RTT (Unit: ms)
float get_ema_send_rtt() { return this->mSendRTT.get_em_average(); }
void set_send_rtt(int send_rtt) { this->mSendRTT.set_value(send_rtt / 1000); }
float get_ema_media_rtt() { return this->mMediaRTT.get_em_average(); }
void set_media_rtt(int media_rtt) { this->mMediaRTT.set_value(media_rtt / 1000); }
float get_average_send_rtt() { return this->mSendRTT.get_total_average(); }
private:
/* Statistics */
Counter mSendRTT;
Counter mMediaRTT;
public:
/* State getter */
CoreState get_state(void) {
std::unique_lock<std::mutex> lck(this->mStateLock);
return this->mState;
}
private:
/* State setter */
void set_state(CoreState new_state) {
std::unique_lock<std::mutex> lck(this->mStateLock);
this->mState = new_state;
}
/* State */
CoreState mState;
std::mutex mStateLock;
public:
/* Adapter list handling */
ServerAdapter *find_adapter_by_id(int adapter_id) {
std::unique_lock<std::mutex> lck(this->mAdaptersLock);
for (std::vector<ServerAdapter *>::iterator it = this->mAdapters.begin();
it != this->mAdapters.end(); it++) {
ServerAdapter *adapter = *it;
if (adapter->get_id() == adapter_id) {
return adapter;
}
}
return NULL;
}
ServerAdapter *get_adapter(int index) {
std::unique_lock<std::mutex> lck(this->mAdaptersLock);
assert(index < this->mAdapters.size());
return this->mAdapters.at(index);
}
ServerAdapter *get_active_adapter() {
return this->get_adapter(this->get_active_adapter_index());
}
int get_adapter_count(void) {
std::unique_lock<std::mutex> lck(this->mAdaptersLock);
return this->mAdapters.size();
}
/* Handling adapter index */
int get_active_adapter_index(void) { return this->mActiveAdapterIndex; }
void set_active_adapter_index(int active_control_adapter_index) {
this->mActiveAdapterIndex = active_control_adapter_index;
}
private:
/* Adapter list */
std::vector<ServerAdapter *> mAdapters;
std::mutex mAdaptersLock;
int mActiveAdapterIndex;
private:
/* Statistics */
Counter mSendRequestSize;
ArrivalTimeCounter mSendArrivalTime;
public:
/* Singleton */
static Core *singleton(void) {
if (sSingleton == NULL) {
sSingleton = new Core();
}
return sSingleton;
}
~Core() { SegmentManager::singleton()->deallocate_all_the_free_segments(); }
private:
/* Singleton */
static Core *sSingleton;
Core(void) {
SegmentManager *sm = SegmentManager::singleton();
this->mState = kCoreStateIdle;
this->mActiveAdapterIndex = 0;
this->mControlMessageReceiver = new ControlMessageReceiver();
this->mControlMessageSender = new ControlMessageSender();
}
public:
/* Its private members can be accessed by auxiliary classes */
friend StartCoreTransaction;
friend StopCoreTransaction;
}; /* class Core */
} /* namespace sc */
#endif /* !defined(__SC_CORE_H__) */
|
#include <bits/stdc++.h>
using namespace std;
#define ll long long
std::random_device rd;
mt19937 gen(rd());
const uint32_t MOD = 4294967291;
const uint32_t BASE = 53;
class hashSet {
uint32_t cnt;
uint32_t sz;
vector<list<pair<string, string> > > table;
vector<list<pair<string, string> > > newTable;
public:
hashSet() {
sz = 10;
table.resize(sz);
cnt = 0;
}
uint32_t getHash(string s) {
uint32_t hash = 0;
for (char &i : s) {
hash = ((hash * BASE) % MOD + (uint32_t) i) % MOD;
}
return hash % sz;
}
void expand() {
if (cnt * 3 > ((uint32_t)sz * 4)) {
sz *= 2;
newTable.clear();
newTable.resize(sz);
for (const list<pair<string, string> > &L : table) {
for (const pair<string, string> &elem : L) {
uint32_t key = getHash(elem.first);
newTable[key].push_back(elem);
}
}
table.swap(newTable);
}
}
void insert(string x, string y) {
erase(x);
uint32_t k = getHash(x);
table[k].push_back({x, y});
cnt++;
expand();
}
void erase(const string &x) {
int t = getHash(x);
for (auto it = table[t].begin(); it != table[t].end(); it++) {
if ((*it).first == x) {
table[t].erase(it);
cnt--;
return;
}
}
}
string get(const string &x) {
int t = getHash(x);
for (pair<string, string> &p : table[t]) {
if (p.first == x) {
return p.second;
}
}
return "$";
}
};
int main() {
// freopen("file.in", "r", stdin);
freopen("map.in", "r", stdin);
freopen("map.out", "w", stdout);
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
hashSet H;
string key, val;
string act, ans = "", curr;
while (cin >> act) {
if (act == "put") {
cin >> key >> val;
H.insert(key, val);
} else if (act == "delete") {
cin >> key;
H.erase(key);
} else if (act == "get") {
cin >> key;
curr = H.get(key);
if (curr != "$") {
ans += (curr + "\n");
} else {
ans += "none\n";
}
}
}
cout << ans;
return 0;
}
|
#include "builder.hpp"
int main(int argc, char *argv[]) {
Consumer consumer;
F18 f18;
A320 a320;
consumer.ProducePlane(&f18);
consumer.SeePlane();
consumer.ProducePlane(&a320);
consumer.SeePlane();
return 0;
}
|
#ifndef __ItemFlyFish_H__
#define __ItemFlyFish_H__
#include "Item.h"
class ItemFlyFish : public Item
{
public:
static ItemFlyFish* create(CCDictionary* dict);
bool init(CCDictionary* dict);
int _duration;
int _offsetH;
int _offsetV;
bool _alreadyFly;
void updateStatus();
void move(float dt);
void collision();
};
#endif
|
//! Bismillahi-Rahamanirahim.
/** ========================================**
** @Author: Md. Abu Farhad ( RUET, CSE'15)
** @Category:
/** ========================================**/
#include<bits/stdc++.h>
#include<stdio.h>
using namespace std;
#define ll long long
#define scl(n) cin>>n;
#define scc(c) cin>>c;
#define fr(i,n) for (ll i=0;i<n;i++)
#define fr1(i,n) for(ll i=1;i<=n;i++)
#define pfl(x) printf("%lld\n",x)
#define pb push_back
#define l(s) s.size()
#define asort(a) sort(a,a+n)
#define all(x) (x).begin(), (x).end()
#define dsort(a) sort(a,a+n,greater<int>())
#define vasort(v) sort(v.begin(), v.end());
#define vdsort(v) sort(v.begin(), v.end(),greater<int>());
#define uniquee(x) x.erase(unique(x.begin(), x.end()),x.end())
#define pn cout<<endl;
#define md 10000007
#define inf 1e18
#define debug cout<<"Monti valo nei "<<endl;
#define ps cout<<" ";
#define Pi acos(-1.0)
#define mem(a,i) memset(a, i, sizeof(a))
#define tcas(i,t) for(ll i=1;i<=t;i++)
#define pcas(i) cout<<"Case "<<i<<": "<<"\n";
#define fast ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL)
#define N 15000005
#define MAX sqrt(10000000)+1
vector<ll> primes;
bool isPrime[10000001];
void sieve()
{
for (ll i = 0; i < MAX; ++i) isPrime[i] = true;
for (ll i = 3; i * i <= MAX; i += 2)
{
if (isPrime[i])
{
for (ll j = i * i; j <= MAX; j += i)
{
isPrime[j] = false;
}
}
}
primes.push_back(2);
for (ll i = 3; i < MAX; i += 2) if (isPrime[i]) primes.push_back(i);
}
ll cnt[N+1];
ll a[N+1];
int main()
{
fast;
sieve();
//cout<<primes.size()<<endl;
// fr(i, 20)cout<<primes[i]<<" ";
//pn;
ll t;
ll m,n,b,d,i,j,k,x,y,z,l,q,r;
scl(n);
fr(i,n)cin>>a[i];
ll gcd=a[0];
fr1(i, n-1)gcd=__gcd(gcd, a[i]);
fr(i, n)a[i]/=gcd;
// fr(i, n)cout<<a[i]<<" "; pn;
fr(i, n)
{
ll p=a[i];
fr(j, primes.size())
{
ll c=0;
while(p%primes[j]==0)
{
c++;
p/=primes[j];
}
if(c)cnt[primes[j] ]++;//, cout<<c<<" "<<primes[j]<<endl;;
}
if(p>1)cnt[p ]++;
}
ll ans=0;
fr(i, N+1)
{
ans=max(ans, cnt[i]);
}
if(ans==0)cout<<-1<<endl;
else cout<<n-ans<<"\n";
return 0;
}
|
#include <iostream>
using namespace std;
struct node{
int data;
node *next;
};
node *head = NULL;
node *tail = NULL;
void InsertNodeAtEnd(int data);
void ReverseList(node *head);
void Print();
void InsertNodeAtEnd(int data){
node *temp = new node;
temp -> data = data;
temp -> next = NULL;
if(head==NULL && tail==NULL){
head = tail = temp;
return;
}
tail -> next = temp;
tail = temp;
}
void ReverseList(node *p){
if(p->next == NULL){
head = p;
return;
}
ReverseList(p->next);
node* q = p->next;
q->next = p;
p->next = NULL;
}
void Print(){
node *temp = head;
while(temp != NULL){
cout << temp -> data << endl;
temp = temp -> next;
}
}
int main(){
cout << "LIST IN FORWARD DIRECTION:" << endl;
InsertNodeAtEnd(5);
InsertNodeAtEnd(10);
InsertNodeAtEnd(15);
InsertNodeAtEnd(25);
Print();
cout << "REVERSED LIST:" << endl;
ReverseList(head);
Print();
return 0;
}
|
/**
* \file assert.cpp
* \date Jan 29, 2016
*/
#include "pcsh/assert.hpp"
#include <cstdlib>
#if defined(_MSC_VER)
#define _CRT_SECURE_NO_WARNINGS
#define NOMINMAX
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <io.h>
#else//UNIX
#include <unistd.h>
#include <fcntl.h>
#endif//defined(_MSC_VER)
#define STDERR_FILENO 2
namespace pcsh {
namespace {
void write_char_stderr(const char ch)
{
int rv = 0;
while (rv != 1) {
#if defined(_MSC_VER)
rv = _write(STDERR_FILENO, &ch, 1);
#else//UNIX
rv = write(STDERR_FILENO, &ch, 1);
#endif//defined(_MSC_VER)
}
}
void write_string_stderr(const char* str)
{
while (*str != '\0') {
write_char_stderr(*str++);
}
}
}//namespace
int assert_fail(const char* msg, const char* file, const char* line, const char* fcn)
{
write_string_stderr("ASSERTION failed\n ");
write_string_stderr(file);
write_string_stderr(" (");
write_string_stderr(line);
write_string_stderr(") : ");
write_string_stderr(fcn);
write_string_stderr(" : ");
write_string_stderr(msg);
write_string_stderr("\n");
abort();
return 0;
}
}//namespace pcsh
|
#include <iostream>
#include <initializer_list>
int calc(std::initializer_list<int>);
int main()
{
std::cout << "result is " << calc({0,1,2,3,4,5}) << std::endl;
return 0;
}
int calc(std::initializer_list<int> il)
{
int result = 0;
for (auto it = il.begin(); it != il.end(); ++it)
result += *it;
return result;
}
|
#include<stdio.h>
#include<conio.h>
int main()
{
int num,cube;
printf("enter a no.\n ");
scanf("%d",&num);
cube=num*num*num;
printf("cube of no. is %d ",cube);
return 0;
}
|
//
// Copyright Jason Rice 2016
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#include <assets/TestContext.hpp>
#include <nbdl/detail/make_create_path_type.hpp>
#include <nbdl/make_context.hpp>
#include <nbdl/make_def.hpp>
#include <nbdl/message.hpp>
#include <nbdl/null_store.hpp>
#include <boost/hana/equal.hpp>
#include <boost/hana/value.hpp>
#include <boost/mp11/list.hpp>
#include <catch.hpp>
namespace hana = boost::hana;
namespace entity = test_context::entity;
namespace message = nbdl::message;
namespace channel = nbdl::message::channel;
namespace action = nbdl::message::action;
using namespace boost::mp11;
namespace test_context_
{
struct my_context { };
}
namespace nbdl
{
template <>
struct make_def_impl<test_context_::my_context>
{
static constexpr auto apply()
{
return test_context_def::make(
test_context::producer_tag<>{},
test_context::producer_tag<>{},
test_context::consumer_tag<>{},
test_context::consumer_tag<>{},
nbdl::null_store{}
);
}
};
}
namespace
{
struct check_message_equal_fn
{
template <typename MessageVariant, typename Orig>
constexpr auto operator()(MessageVariant const& m, Orig const& o) const
{
bool result = false;
m.match(
[&](auto const& m)
-> std::enable_if_t<std::is_same<std::decay_t<decltype(m)>, std::decay_t<Orig>>::value>
{
result = hana::equal(m.storage, o.storage);
},
[&](auto const&) { result = false; }
);
return result;
}
};
constexpr struct check_message_equal_fn check_message_equal{};
}
TEST_CASE("Dispatch Downstream Read Message", "[context]")
{
auto context = nbdl::make_unique_context<test_context_::my_context>();
auto& producer0 = context->actor<0>();
auto& producer1 = context->actor<1>();
auto& consumer2 = context->actor<2>();
auto& consumer3 = context->actor<3>();
// Send downstream read to consumers.
auto msg = message::make_downstream_read(
test_context::path1(1, 2)
, message::no_uid
, entity::my_entity<1>{2, 1}
);
nbdl::apply_message(producer0.context, msg);
CHECK(producer0.recorded_messages.size() == 0);
CHECK(producer1.recorded_messages.size() == 0);
CHECK(consumer2.recorded_messages.size() == 1);
CHECK(consumer3.recorded_messages.size() == 1);
// Both consumers got the downstream
// read message from producer0
CHECK(check_message_equal(consumer2.recorded_messages[0], msg));
CHECK(check_message_equal(consumer3.recorded_messages[0], msg));
}
#if 0 // TODO need valid test for upstream_read (can't use null_store)
TEST_CASE("Dispatch Upstream Read Message", "[context]")
{
auto context = nbdl::make_unique_context<test_context_::my_context>();
auto& producer0 = context->actor<0>();
auto& producer1 = context->actor<1>();
auto& consumer2 = context->actor<2>();
auto& consumer3 = context->actor<3>();
// Send upstream read to producer0.
auto msg = message::make_upstream_read(test_context::path1(1, 2));
nbdl::apply_message(consumer2.context, msg);
// producer1 should not receive the message.
REQUIRE(producer0.recorded_messages.size() == 1);
CHECK(producer1.recorded_messages.size() == 0);
CHECK(consumer2.recorded_messages.size() == 0);
CHECK(consumer3.recorded_messages.size() == 0);
// producer0 should record an upstream read message.
CHECK(check_message_equal(producer0.recorded_messages[0], msg));
}
#endif
TEST_CASE("Dispatch Downstream Create Message", "[context]")
{
hana::for_each(hana::make_tuple(
hana::make_pair(hana::type_c<test_context::path<0>>, hana::type_c<entity::my_entity<1>>),
hana::make_pair(hana::type_c<test_context::path<1>>, hana::type_c<entity::my_entity<1>>),
hana::make_pair(hana::type_c<test_context::path<2>>, hana::type_c<entity::my_entity<2>>),
hana::make_pair(hana::type_c<test_context::path<3>>, hana::type_c<entity::my_entity<3>>),
hana::make_pair(hana::type_c<test_context::path<4>>, hana::type_c<entity::my_entity<4>>)
), [](auto types)
{
using Path = typename decltype(+hana::first(types))::type;
using Entity = typename decltype(+hana::second(types))::type;
auto context = nbdl::make_unique_context<test_context_::my_context>();
auto& producer0 = context->actor<0>();
auto& producer1 = context->actor<1>();
auto& consumer2 = context->actor<2>();
auto& consumer3 = context->actor<3>();
// Send downstream create to consumers.
auto msg = message::make_downstream_create(
Path(1, 2)
, message::no_uid
, Entity{2, 1}
, message::no_is_confirmed
);
nbdl::apply_message(producer0.context, msg);
CHECK(producer0.recorded_messages.size() == 0);
CHECK(producer1.recorded_messages.size() == 0);
CHECK(consumer2.recorded_messages.size() == 1);
CHECK(consumer3.recorded_messages.size() == 1);
// Both consumers got the downstream
// create message from producer0
CHECK(check_message_equal(consumer2.recorded_messages[0], msg));
CHECK(check_message_equal(consumer3.recorded_messages[0], msg));
});
}
TEST_CASE("Dispatch Upstream Create Message", "[context]")
{
// root1
hana::for_each(hana::make_tuple(
hana::make_pair(hana::type_c<test_context::path<0>>, hana::type_c<entity::my_entity<1>>)
), [](auto types)
{
using Path = typename decltype(+hana::first(types))::type;
using Entity = typename decltype(+hana::second(types))::type;
auto context = nbdl::make_unique_context<test_context_::my_context>();
auto& producer0 = context->actor<0>();
auto& producer1 = context->actor<1>();
auto& consumer2 = context->actor<2>();
auto& consumer3 = context->actor<3>();
// Send upstream create to producer0.
auto msg = message::make_upstream_create(
message::make_create_path<mp_second<Path>>(hana::tuple<mp_first<Path>>{1})
, message::no_uid
, Entity{2, 1}
);
nbdl::apply_message(consumer2.context, msg);
// producer1 should not receive the message.
CHECK(producer0.recorded_messages.size() == 1);
CHECK(producer1.recorded_messages.size() == 0);
CHECK(consumer2.recorded_messages.size() == 0);
CHECK(consumer3.recorded_messages.size() == 0);
// producer0 should record an upstream create message.
CHECK(check_message_equal(producer0.recorded_messages[0], msg));
});
// root2
hana::for_each(hana::make_tuple(
hana::make_pair(hana::type_c<test_context::path<1>>, hana::type_c<entity::my_entity<1>>),
hana::make_pair(hana::type_c<test_context::path<2>>, hana::type_c<entity::my_entity<2>>),
hana::make_pair(hana::type_c<test_context::path<3>>, hana::type_c<entity::my_entity<3>>),
hana::make_pair(hana::type_c<test_context::path<4>>, hana::type_c<entity::my_entity<4>>)
), [](auto types)
{
using Path = typename decltype(+hana::first(types))::type;
using Entity = typename decltype(+hana::second(types))::type;
auto context = nbdl::make_unique_context<test_context_::my_context>();
auto& producer0 = context->actor<0>();
auto& producer1 = context->actor<1>();
auto& consumer2 = context->actor<2>();
auto& consumer3 = context->actor<3>();
// Send upstream create to producer0.
auto msg = message::make_upstream_create(
message::make_create_path<mp_second<Path>>(hana::tuple<mp_first<Path>>{1})
, message::no_uid
, Entity{2, 1}
);
nbdl::apply_message(consumer2.context, msg);
// producer0 should not receive the message.
CHECK(producer0.recorded_messages.size() == 0);
CHECK(producer1.recorded_messages.size() == 1);
CHECK(consumer2.recorded_messages.size() == 0);
CHECK(consumer3.recorded_messages.size() == 0);
// producer1 should record an upstream create message.
CHECK(check_message_equal(producer1.recorded_messages[0], msg));
});
}
TEST_CASE("Dispatch Downstream Update Message", "[context]")
{
hana::for_each(hana::make_tuple(
hana::make_pair(hana::type_c<test_context::path<0>>, hana::type_c<entity::my_entity<1>>),
hana::make_pair(hana::type_c<test_context::path<1>>, hana::type_c<entity::my_entity<1>>),
hana::make_pair(hana::type_c<test_context::path<2>>, hana::type_c<entity::my_entity<2>>),
hana::make_pair(hana::type_c<test_context::path<3>>, hana::type_c<entity::my_entity<3>>),
hana::make_pair(hana::type_c<test_context::path<4>>, hana::type_c<entity::my_entity<4>>)
), [](auto types)
{
using Path = typename decltype(+hana::first(types))::type;
using Entity = typename decltype(+hana::second(types))::type;
auto context = nbdl::make_unique_context<test_context_::my_context>();
auto& producer0 = context->actor<0>();
auto& producer1 = context->actor<1>();
auto& consumer2 = context->actor<2>();
auto& consumer3 = context->actor<3>();
// Send downstream update to consumers.
auto msg = message::make_downstream_update(
Path(1, 2)
, message::no_uid
, Entity{2, 1}
, message::no_is_confirmed
);
nbdl::apply_message(producer0.context, msg);
CHECK(producer0.recorded_messages.size() == 0);
CHECK(producer1.recorded_messages.size() == 0);
CHECK(consumer2.recorded_messages.size() == 1);
CHECK(consumer3.recorded_messages.size() == 1);
// Both consumers got the downstream
// update message from producer0
CHECK(check_message_equal(consumer2.recorded_messages[0], msg));
CHECK(check_message_equal(consumer3.recorded_messages[0], msg));
});
}
TEST_CASE("Dispatch Upstream Update Message", "[context]")
{
// root1
hana::for_each(hana::make_tuple(
hana::make_pair(hana::type_c<test_context::path<0>>, hana::type_c<entity::my_entity<1>>)
), [](auto types)
{
using Path = typename decltype(+hana::first(types))::type;
using Entity = typename decltype(+hana::second(types))::type;
auto context = nbdl::make_unique_context<test_context_::my_context>();
auto& producer0 = context->actor<0>();
auto& producer1 = context->actor<1>();
auto& consumer2 = context->actor<2>();
auto& consumer3 = context->actor<3>();
// Send upstream update to producer0.
auto msg = message::make_upstream_update(
Path(1, 2)
, message::no_uid
, Entity{2, 1}
);
nbdl::apply_message(consumer2.context, msg);
// producer1 should not receive the message.
CHECK(producer0.recorded_messages.size() == 1);
CHECK(producer1.recorded_messages.size() == 0);
CHECK(consumer2.recorded_messages.size() == 0);
CHECK(consumer3.recorded_messages.size() == 0);
// producer0 should record an upstream update message.
CHECK(check_message_equal(producer0.recorded_messages[0], msg));
});
// root2
hana::for_each(hana::make_tuple(
hana::make_pair(hana::type_c<test_context::path<1>>, hana::type_c<entity::my_entity<1>>),
hana::make_pair(hana::type_c<test_context::path<2>>, hana::type_c<entity::my_entity<2>>),
hana::make_pair(hana::type_c<test_context::path<3>>, hana::type_c<entity::my_entity<3>>),
hana::make_pair(hana::type_c<test_context::path<4>>, hana::type_c<entity::my_entity<4>>)
), [](auto types)
{
using Path = typename decltype(+hana::first(types))::type;
using Entity = typename decltype(+hana::second(types))::type;
auto context = nbdl::make_unique_context<test_context_::my_context>();
auto& producer0 = context->actor<0>();
auto& producer1 = context->actor<1>();
auto& consumer2 = context->actor<2>();
auto& consumer3 = context->actor<3>();
// Send upstream update to producer0.
auto msg = message::make_upstream_update(
Path(1, 2)
, message::no_uid
, Entity{2, 1}
);
nbdl::apply_message(consumer2.context, msg);
// producer0 should not receive the message.
CHECK(producer0.recorded_messages.size() == 0);
CHECK(producer1.recorded_messages.size() == 1);
CHECK(consumer2.recorded_messages.size() == 0);
CHECK(consumer3.recorded_messages.size() == 0);
// producer1 should record an upstream update message.
CHECK(check_message_equal(producer1.recorded_messages[0], msg));
});
}
|
#include <iostream>
#include<Windows.h>
using namespace std;
//Prototipos
void ordenRapido(int a[], int izq,int der);
void llenarArray(int a[], int n);
void mostrarArray(int a[],int n);
double PCFreq = 0.0;
__int64 CounterStart = 0;
void StartCounter()
{
LARGE_INTEGER li;
if(!QueryPerformanceFrequency(&li))
cout << "QueryPerformanceFrequency failed!\n";
PCFreq = double(li.QuadPart)/1000.0;
QueryPerformanceCounter(&li);
CounterStart = li.QuadPart;
}
double GetCounter()
{
LARGE_INTEGER li;
QueryPerformanceCounter(&li);
return double(li.QuadPart-CounterStart)/(PCFreq/1000);
}
int main(int argc, char *argv[]) {
int n;
cout<<"Digite N: ";
cin>>n;
int a[n];
llenarArray(a,n);
mostrarArray(a,n);
StartCounter();
ordenRapido(a,0,n-1);
cout<<GetCounter();
cout<<" ms"<<endl;
mostrarArray(a,n);
}
void ordenRapido(int a[], int izq, int der){
int i,j,v;
int cont=1;
int temp=0;
if(der>izq){
v=a[der];
i=izq-1;
j=der;
while(cont){
while(a[++i]<v);
while(a[--j]>v);
if(i>=j){
cont=0;
}else{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
temp=a[i];
a[i]=a[der];
a[der]=temp;
ordenRapido(a,izq,i-1);
ordenRapido(a,i+1,der);
}
}
void llenarArray(int a[],int n){
int i;
for(i=n-1;i>=0;i--){
if(i!=n/2){
a[i]=n-i;
}else{
a[i]=1;
}
}
a[n-1]=n/2;
}
void mostrarArray(int a[],int n){
int i;
for(i=0;i<n;i++){
cout<<a[i]<<" ";
}
cout<<"\n";
}
|
/*
* Copyright (C) 2007-2015 Frank Mertens.
*
* Use of this source is governed by a BSD-style license that can be
* found in the LICENSE file.
*
*/
#include <flux/Format>
#include <flux/syntax/SyntaxState>
#include <flux/syntax/exceptions>
namespace flux {
namespace syntax {
SyntaxError::SyntaxError(String text, SyntaxState *state, String resource):
TextError(text, state ? state->hintOffset() : -1, resource),
state_(state)
{}
SyntaxError::~SyntaxError() throw()
{}
String SyntaxError::message() const
{
Format format;
const char *error = "Syntax error";
if (state_) if (state_->hint()) {
int line = 0, pos = 0;
text_->offsetToLinePos(state_->hintOffset(), &line, &pos);
if (resource_ != "") format << resource_ << ":";
if (!text_->contains('\n') && text_->trim()->count() > 0) format << "\'" << text_ << "\':";
format << line << ":" << pos << ": ";
}
format << error;
if (state_) if (state_->hint()) format << ": " << state_->hint();
return format;
}
}} // namespace flux
|
#define _USE_MATH_DEFINES // for C++
#include "COD7.h"
#include "./Utility/VectorMath.h"
#include "Engine/Engine.hpp"
#include <cmath>
#include <cstring>
#include <cfloat> // for max float value
#include <fmt/core.h>
bool g_god = false;
bool g_norecoil = false;
bool g_rapidfire = false;
bool g_aimbot = false;
bool g_esp = false;
extern bool g_ammo = false;
// spawn funcs
//G_Callspawn_t G_Callspawn = (G_Callspawn_t)0x517580L;
//G_Spawn_t G_Spawn = (G_Spawn_t)0x4bf260L;
//G_CallSpawnEntity_t G_CallSpawnEntity = (G_CallSpawnEntity_t)0x5001f0L;
//Gscr_Spawn_t Gscr_Spawn = (Gscr_Spawn_t)0x7f15c0L;
// map names with console launch command
std::unordered_map<std::string, std::string> maps = {
{"Kino der Toten", "devmap zombie_theater"},
{"Five", "devmap zombie_pentagon"},
{"Dead Ops Arcade", "devmap zombietron"},
{"Nacht Der Untoten", "devmap zombie_cod5_prototype"},
{"Verruckt", "devmap zombie_cod5_asylum"},
{"Shi No Numa", "devmap zombie_cod5_sumpf"},
{"Der Riese", "devmap zombie_cod5_factory"},
{"Ascension", "devmap zombie_cosmodrome"},
{"Call of The Dead", "devmap zombie_coast"},
{"Shangri-La", "devmap zombie_temple"},
{"Moon", "devmap zombie_moon"}
};
// Functions
void Aimbot()
{
if (!GetAsyncKeyState(VK_RBUTTON))
return;
_centity_t* closest = nullptr;
float closestDistance = FLT_MAX;
for (int i = 0; i < 1024; i++)
{
_centity_t* ent = CG_GetEntity(0, i);
// make sure ent is alive and a zombie
if (ent && !ent->pose.isRagdoll && ent->pose.eType == 0x10)
{
vec3_t head;
vec3_t currentDist;
GetTagPos(ent, "j_neck", &head);
VectorSubtract(head, cg->refdef.viewOrg, currentDist);
float mag = VectorMagnitude(currentDist);
if (mag < closestDistance)
{
closestDistance = mag;
closest = ent;
}
}
}
// by now, we have iterated through and found the closest entity to us, so lets aim at it
if (closest != nullptr && !closest->pose.isRagdoll)
{
vec3_t headPosition = { 0.f, 0.f, 0.f };
vec3_t* currentAngles = (vec3_t*)0x2911E20;
vec3_t deltaVec{};
vec3_t angleVec{};
GetTagPos(closest, "j_head", &headPosition);
VectorSubtract(headPosition, cg->refdef.viewOrg, deltaVec);
VectorToAngles(deltaVec, angleVec);
currentAngles->x = angleVec.x; // pitch
currentAngles->y = angleVec.y - 61.5f; // yaw
}
}
void Esp()
{
int count = 0;
DWORD viewMatrix = 0x00BA6970;
for (int i = 0; i < 1024; i++)
{
_centity_t* ent = CG_GetEntity(0, i);
if (ent)
{
vec3_t head;
vec2_t screenPos;
GetTagPos(ent, "j_neck", &head);
bool onScreen = WorldToScreenMatrix(
head,
screenPos,
(FLOAT*)viewMatrix,
cg->refdef.width,
cg->refdef.height
);
// checking if ragdoll will work for now, later reverse Cscr_IsAlive to check eFlags
if (onScreen && !ent->pose.isRagdoll && ent->pose.eType == 0x10)
{
vec4_t color = { 1.0, 0.f, 0.5f, 1.0f };
DrawEngineString((char*)"o\0", screenPos.x, screenPos.y, 1.0f, &color);
count++;
}
}
}
vec4_t c = { 1.0, 1.0f, 0.5f, 1.0f };
auto str = fmt::format("valid ents: {}", count);
DrawEngineString((char*)str.c_str(), 10, 30, 1.0f, &c);
}
// Hook/Custom versions of Game Functions
void CG_DrawBulletImpactsHooked(int localClientNum, void* entityOrigin, unsigned __int16 rand, void* playerState_s, int weapID, int EVENT_ID, bool bADS_maybe)
{
return CG_DrawBulletImpacts(localClientNum,
entityOrigin,
rand,
playerState_s,
weapID,
EVENT_ID,
bADS_maybe
);
}
int CBuf_AddTextHooked(int clientNum, char* Text)
{
return 0;
}
int R_AddCmdDrawTextHooked(char* Text, int uk1, void* Font, float x, float y, float uk2, float uk3, float uk4, vec4_t* color, int uk5)
{
return 0;
}
void* R_RegisterFontHooked(const char* FontName, int Unknown1)
{
return (void*)0;
}
void RenderSceneHooked(int a1, int a2)
{
if (g_esp) Esp();
if (g_aimbot) Aimbot();
//temp fix for mouse input issue described in CenterCursorHooked()
static int** in_mouse = (int**)0x0276C098;
static bool* b_in_mouse = (bool*)0x0276C0C1;
if (GetAsyncKeyState(VK_MENU)) {
*((*in_mouse) + 0x18) = false;
*b_in_mouse = false;
}
else {
*((*in_mouse) + 0x18) = true;
*b_in_mouse = true;
}
return RenderScene(a1, a2);
}
vec3_t* CL_SetViewAnglesHooked(int clientNum, vec3_t* viewangles)
{
return viewangles;
}
// TODO move
vec3_t* CG_RecoilHooked(int* cgameinfo, vec3_t* viewAngles, vec3_t* origin)
{
if (g_norecoil) return viewAngles;
return CG_Recoil(cgameinfo, viewAngles, origin);
}
BOOL __cdecl CenterCursorHooked()
{
// changing these globals actually make the function not be called at all anymore
// once they have been set to false, they cannot be unset from this function
// temp work-around: we dont check the keystate in the same function as we set the variables with
// keystate polling temporarily moved to RenderSceneHooked
//TODO implement keyboard hook instead of polling per-frame
static int** in_mouse = (int**)0x0276C098;
static bool* b_in_mouse = (bool*)0x0276C0C1;
if (*b_in_mouse || *((*in_mouse) + 0x18))
{
return CenterCursorPos();
}
}
|
/*!
* \file KaiXinApp_PokeList.cpp
* \author GoZone
* \date
* \brief 解析与UI: 动它一下
*
* \ref CopyRight
* =======================================================================<br>
* Copyright ? 2010-2012 GOZONE <br>
* All Rights Reserved.<br>
* The file is generated by Kaixin_Component Wizard for Tranzda Mobile Platform <br>
* =======================================================================<br>
*/
#include "KaiXinAPICommon.h"
#if(LCD_SIZE == LCD_HVGA )
#define POKE_W (100)
#define POKE_H (24)
#elif(LCD_SIZE == LCD_WVGA )
#define POKE_W (150)
#define POKE_H (36)
#endif
void* KaiXinAPI_PokeList_JsonParse(char *text)
{
cJSON *json;
cJSON *pTemp0;
tResponsePokeList* Response = new tResponsePokeList;
memset(Response, 0 , sizeof(tResponsePokeList));
json = cJSON_Parse(text);
pTemp0 = cJSON_GetObjectItem(json,"ret");
if (pTemp0)
{
Response->ret = pTemp0->valueint;
}
//Success
if(Response->ret == 1)
{
pTemp0 = cJSON_GetObjectItem(json, "uid");
if(pTemp0)
{
STRCPY_Ex(Response->uid, pTemp0->valuestring);
}
pTemp0 = cJSON_GetObjectItem(json, "pokes");
if(pTemp0)
{
int nSize1 = 0, i = 0;
nSize1 = cJSON_GetArraySize(pTemp0);
Response->nSize_pokes = nSize1;
if( nSize1 != 0 )
{
Response->pokes = NULL;
Response->pokes = (PokeList_pokes*) malloc(sizeof( PokeList_pokes ) * nSize1 );
memset(Response->pokes, 0 , sizeof(PokeList_pokes) * nSize1 );
}
for ( i = 0; i < nSize1; i++ )
{
cJSON *Item1 = NULL, *pTemp1 = NULL;
Item1 = cJSON_GetArrayItem(pTemp0,i);
pTemp1 = cJSON_GetObjectItem(Item1, "action");
if(pTemp1)
{
STRCPY_Ex(Response->pokes[i].action, pTemp1->valuestring);
}
pTemp1 = cJSON_GetObjectItem(Item1, "actionname");
if(pTemp1)
{
STRCPY_Ex(Response->pokes[i].actionname, pTemp1->valuestring);
}
}
}
}
//Failue
else
{
//pTemp0 = cJSON_GetObjectItem(json,"msg");
//if (pTemp0)
//{
// strcpy(Response->msg, pTemp0 ->valuestring);
//}
}
cJSON_Delete(json);
return Response;
}
void* KaiXinAPI_SendPoke_JsonParse(char *text)
{
cJSON *json;
cJSON *pTemp0;
tResponseSendPoke* Response = new tResponseSendPoke;
memset(Response, 0 , sizeof(tResponseSendPoke));
json = cJSON_Parse(text);
pTemp0 = cJSON_GetObjectItem(json,"ret");
if (pTemp0)
{
Response->ret = pTemp0->valueint;
}
//Success
if(Response->ret == 1)
{
pTemp0 = cJSON_GetObjectItem(json, "uid");
if(pTemp0)
{
STRCPY_Ex(Response->uid, pTemp0->valuestring);
}
pTemp0 = cJSON_GetObjectItem(json, "wordsucc");
if(pTemp0)
{
STRCPY_Ex(Response->wordsucc, pTemp0->valuestring);
}
}
//Failue
else
{
//pTemp0 = cJSON_GetObjectItem(json,"msg");
//if (pTemp0)
//{
// strcpy(Response->msg, pTemp0 ->valuestring);
//}
}
cJSON_Delete(json);
return Response;
}
// 构造函数
TPokeListForm::TPokeListForm(TApplication* pApp):TWindow(pApp)
{
//Create(APP_KA_ID_KaiXinHomePage);
}
TPokeListForm::TPokeListForm(TApplication* pApp, PokeUserData userData):TWindow(pApp)
{
mUserData = userData;
Create(APP_KA_ID_PokeListForm);
}
// 析构函数
TPokeListForm::~TPokeListForm(void)
{
if(Response)
{
delete Response;
}
}
// 窗口事件处理
Boolean TPokeListForm::EventHandler(TApplication * pApp, EventType * pEvent)
{
Boolean bHandled = FALSE;
switch (pEvent->eType)
{
case EVENT_WinInit:
{
_OnWinInitEvent(pApp, pEvent);
bHandled = TRUE;
break;
}
case EVENT_WinClose:
{
_OnWinClose(pApp, pEvent);
break;
}
case EVENT_CtrlSelect:
{
bHandled = _OnCtrlSelectEvent(pApp, pEvent);
break;
}
case EVENT_WinEraseClient:
{
TDC dc(this);
WinEraseClientEventType *pEraseEvent = reinterpret_cast< WinEraseClientEventType* >( pEvent );
TRectangle rc(pEraseEvent->rc);
TRectangle rcBack(5, 142, 310, 314);
GetBounds(&rcBack);
// 擦除
dc.EraseRectangle(&rc, 0);
dc.DrawBitmapsH(TResource::LoadConstBitmap(APP_KA_ID_BITMAP_title_bg), 0, 0, SCR_W,
GUI_API_STYLE_ALIGNMENT_LEFT);
//dc.DrawBitmapsH(TResource::LoadConstBitmap(APP_KA_ID_BITMAP_bottom_bg), 0, rcBack.Bottom()-44,
//320, GUI_API_STYLE_ALIGNMENT_LEFT|GUI_API_STYLE_ALIGNMENT_TOP);
pEraseEvent->result = 1;
bHandled = TRUE;
}
break;
case MSG_DL_THREAD_NOTIFY:
{
NotifyMsgDataType notifyData;
Sys_GetMessageBody((MESSAGE_t *)pEvent, ¬ifyData, sizeof(NotifyMsgDataType));
switch(notifyData.nAccessType)
{
case KX_SendPoke:
{
if(KaiXinAPI_JsonParse_bSuccess(KX_SendPoke))
{
TUChar wordSucc[256] = {0};
//TUChar sWordSucc[256] = {0};
int iRet = eFailed;
tResponseSendPoke* SendPokeResponse = NULL;
iRet = KaiXinAPI_JsonParse(KX_SendPoke, (void **)&SendPokeResponse);
if(iRet)
{
TUString::StrUtf8ToStrUnicode(wordSucc,(const Char *)SendPokeResponse->wordsucc);
//TUString::StrPrintF(sWordSucc,wordSucc,mUserData.name,mUserData.name);
pApp->MessageBox(wordSucc,TResource::LoadConstString(APP_KA_ID_STRING_Poke),WMB_OK);
}
if(SendPokeResponse)
{
delete SendPokeResponse;
}
}
else//动它一下失败
{
pApp->MessageBox(TResource::LoadConstString(APP_KA_ID_STRING_Fail),TResource::LoadConstString(APP_KA_ID_STRING_Poke),WMB_OK);
}
break;
}
default:
break;
}
bHandled = TRUE;
break;
}
case EVENT_KeyCommand:
{
// 抓取右软键事件
if (pEvent->sParam1 == SYS_KEY_SOFTKEY_RIGHT_UP
|| pEvent->sParam1 == SYS_KEY_SOFTKEY_RIGHT_LONG)
{
// 模拟退出按钮选中消息
HitControl(m_BackBtn);
bHandled = TRUE;
}
}
break;
default:
break;
}
if (!bHandled)
{
bHandled = TWindow::EventHandler(pApp, pEvent);
}
return bHandled;
}
// 窗口初始化
Boolean TPokeListForm::_OnWinInitEvent(TApplication * pApp, EventType * pEvent)
{
TFont objFontType;
objFontType.Create(FONT_CONTENT, FONT_CONTENT);
m_BackBtn = SetAppBackButton(this);
SetAppTilte(this,APP_KA_ID_STRING_Poke);//设置标题
TLabel *pPokeFriend = static_cast<TLabel*>(GetControlPtr(APP_KA_ID_PokeListForm_ChoosePokeFriend));
if(pPokeFriend)
{
pPokeFriend->SetFont(objFontType);
}
TLabel *pChoosePoke = static_cast<TLabel*>(GetControlPtr(APP_KA_ID_PokeListForm_ChoosePokeLabel));
if(pChoosePoke)
{
pChoosePoke->SetFont(objFontType);
}
TCheckBox *pPrivacyCheckBox = static_cast<TCheckBox*>(GetControlPtr(APP_KA_ID_PokeListForm_PrivacyCheckBox));
if(pPrivacyCheckBox)
{
pPrivacyCheckBox->SetFont(objFontType);
}
TLabel *pPrivacyTextLabel = static_cast<TLabel*>(GetControlPtr(APP_KA_ID_PokeListForm_PrivacyTextLabel));
if(pPrivacyTextLabel)
{
pPrivacyTextLabel->SetFont(objFontType);
}
TButton *pSendPokeButton = static_cast<TButton*>(GetControlPtr(APP_KA_ID_PokeListForm_SendPokeButton));
if(pSendPokeButton)
{
pSendPokeButton->SetFont(objFontType);
}
TLabel *pFriendName = static_cast<TLabel*>(GetControlPtr(APP_KA_ID_PokeListForm_PokeFriendName));
if(pFriendName)
{
objFontType.Create(FONT_CONTENT, FONT_CONTENT, FONT_STYLE_BOLD);
pFriendName->SetCaption(mUserData.name,FALSE);
pFriendName->SetFont(objFontType);
}
_SetPokeList(pApp);
return TRUE;
}
// 关闭窗口时,保存设置信息
Boolean TPokeListForm::_OnWinClose(TApplication * pApp, EventType * pEvent)
{
return TRUE;
}
// 控件点击事件处理
Boolean TPokeListForm::_OnCtrlSelectEvent(TApplication * pApp, EventType * pEvent)
{
Boolean bHandled;
bHandled = FALSE;
if(m_BackBtn == pEvent->sParam1)
{
bHandled = TRUE;
this->CloseWindow();
return bHandled;
}
switch(pEvent->sParam1)
{
case APP_KA_ID_PokeListForm_SendPokeButton:
{
//设置action
for(int i = 0; i < Response->nSize_pokes; i++)
{
if(tRadioBtn[i] && tRadioBtn[i]->GetValue() == TRUE)
{
Set_Url_Params(KX_SendPoke, "action", Response->pokes[i].action);
break;
}
}
//设置动一下好友id
Set_Url_Params(KX_SendPoke, "touid", mUserData.uid);
//设置是否私密
TCheckBox *pPrivacyCheckBox = static_cast<TCheckBox*>(GetControlPtr(APP_KA_ID_PokeListForm_PrivacyCheckBox));
if(pPrivacyCheckBox && pPrivacyCheckBox->GetValue() == TRUE)
{
Set_Url_Params(KX_SendPoke, "private", "1");
}
else
{
Set_Url_Params(KX_SendPoke, "private", "0");
}
KaiXinAPICommon_Download(KX_SendPoke, this->GetWindowHwndId());
break;
}
default:
break;
}
return bHandled;
}
Int32 TPokeListForm::_SetPokeList(TApplication * pApp)
{
int iRet = eFailed;
iRet = KaiXinAPI_JsonParse(KX_PokesList, (void **)&this->Response);
TPanel *pPokeListPanel = static_cast<TPanel*>(GetControlPtr(APP_KA_ID_PokeListForm_PokeListPanel));
if(iRet == eSucceed && pPokeListPanel)
{
TRectangle rect(10,10,100,24);
TFont tFont;
TUChar RadioCaption[32] = {0};
pPokeListPanel->Show(TRUE);
tFont.Create(FONT_CONTENT_DETAIL, FONT_CONTENT_DETAIL);
for(int i = 0; i < Response->nSize_pokes; i++)
{
tRadioBtn[i] = NULL;
tRadioBtn[i] = new TRadioButton;
rect.SetRect(20+(i%2)*(POKE_W+40), 10+(i/2)*POKE_H, POKE_W, POKE_H);
if(tRadioBtn[i]->Create(pPokeListPanel))
{
TUString::StrUtf8ToStrUnicode(RadioCaption,(const Char *)Response->pokes[i].actionname);
if(i==0)
{
tRadioBtn[i]->SetValue(TRUE);
}
tRadioBtn[i]->SetBounds(&rect);
tRadioBtn[i]->SetFont(tFont);
tRadioBtn[i]->SetCaption(RadioCaption,FALSE);
tRadioBtn[i]->SetGroupID(1);
tRadioBtn[i]->Show(TRUE);
}
}
}
return 0;
}
|
#include "TradosUnit.h"
TradosUnit::TradosUnit()
{
}
TradosUnit::~TradosUnit()
{
}
std::wostream& operator<<(std::wostream& s, const TradosUnit& tu) {
s << L"TradosUnit [";
s << L"id=";
s << tu.id();
s << L", creationdate='";
s << tu.creationdate();
s << L"', creationid='";
s << tu.creationid();
s << L"']" << std::endl;
std::map<std::wstring, std::wstring>::const_iterator it = tu.pairs().begin();
for (; it != tu.pairs().end(); it++)
{
s << L"\t" << Tags::ATTR_XML_LANG << L"='" << it->first << L"', Text='" << it->second << '\'' << std::endl;
}
s << std::flush;
return(s);
}
|
#include <math.h>
#include <conio.h>
#include <stdio.h>
#include <locale.h>
#include <stdlib.h>
#include <string.h>
typedef struct tipo_no no;
struct tipo_no
{
int info;
struct tipo_no *prox;
};
int main ()
{
setlocale (LC_ALL, "Portuguese");
no *lista = NULL;
system ("PAUSE");
return 0;
}
|
#include <boost/asio.hpp>
#include <string>
#include "gtest/gtest.h"
#include "session.h"
#include <fstream>
#include "logger.h"
#include "request_handler.h"
#include "request_parser.h"
#include <map>
#include "request.h"
using boost::asio::ip::tcp;
class MockSession : public session
{
public:
MockSession(boost::asio::io_service& io_service, std::ifstream& is,
std::map<std::string, std::string> handler_table, std::map<std::string, std::string> location_table, std::map<std::string, request_handler*> path_map)
: session(io_service, handler_table, location_table, path_map),
written_data_(""),
read_data_(""),
bytes_read_(0),
inputBuffer(is) {}
~MockSession() {}
void start()
{
do_read();
}
void handle_read()
{
std::array<char, 8192> data_array;
std::copy(std::begin(read_data_), std::end(read_data_), std::begin(data_array));
request_parser::result_type result;
std::tie(result, std::ignore) = request_parser_.parse(
request_, data_array.data(), data_array.data() + bytes_read_);
if (result == request_parser::good)
{
std::string response = request_handler_.handle_good_request(request_, data_array);
do_write(response);
}
else if (result == request_parser::bad)
{
std::string response = request_handler_.handle_bad_request();
do_write(response);
}
}
std::string get_request() { return read_data_; }
std::string get_response() { return written_data_; }
private:
void do_read()
{
try
{
// Read from input
inputBuffer.seekg(0, inputBuffer.end);
int size = inputBuffer.tellg();
inputBuffer.seekg(0, inputBuffer.beg);
char* data = new char[size];
inputBuffer.read(data, size);
// Save read data
read_data_ = std::string(data);
bytes_read_ = size;
// Close buffer and delete dynamic char array
inputBuffer.clear();
inputBuffer.close();
delete[] data;
}
catch (const std::exception& e)
{
std::cout << "Error reading from input\n";
}
}
void do_write(std::string data)
{
written_data_ = data;
}
std::ifstream& inputBuffer;
std::string read_data_;
size_t bytes_read_;
std::string written_data_;
Request request_;
request_parser request_parser_;
};
class SessionTest : public ::testing::Test {
protected:
boost::asio::io_service io_service;
std::map<std::string, std::string> handler_table;
std::map<std::string, std::string> location_table;
std::map<std::string, request_handler*> path_map_;
session test_session = session(io_service, handler_table, location_table, path_map_);
std::string good_request = "GET /echo HTTP/1.1\r\nHost: www.tutorialspoint.com\r\nConnection: Keep-Alive\r\n\r\n";
std::string good_response = "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nGET /echo HTTP/1.1\r\nHost: www.tutorialspoint.com\r\nConnection: Keep-Alive\r\n\r\n";
std::string bad_response = "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\n\r\nBad Request";
};
TEST_F(SessionTest, ConstructorTest) {
EXPECT_EQ(&io_service, &test_session.socket().get_io_service());
}
// TEST_F(SessionTest, GoodRequestTest) {
// // TODO(!): change relative paths to absolute paths?
// // Currently assuming running from /build
// std::ifstream is("../tests/request_examples/good_request.txt");
// handler_table.insert(std::pair <std::string, std::string> ("/echo", "echo"));
// MockSession s(io_service, is, handler_table, location_table);
// s.start();
// EXPECT_EQ(s.get_request(), good_request);
// s.handle_read();
// EXPECT_EQ(s.get_response(), good_response);
// }
// TEST_F(SessionTest, ReadBadRequestTest) {
// // TODO(!): change relative paths to absolute paths?
// // Currently assuming running from /build
// std::ifstream is("../tests/request_examples/bad_request.txt");
// MockSession s(io_service, is, handler_table, location_table);
// s.start();
// EXPECT_EQ(s.get_request(), "hi\nanother line\n\n\nhi");
// s.handle_read();
// EXPECT_EQ(s.get_response(), bad_response);
// }
|
#ifndef __MovingWall_H__
#define __MovingWall_H__
class MovingWall : public GameObject
{
protected:
double m_changeMovementTimer;
double m_timeChangeMovement;
Vector2 m_velocity;
public:
MovingWall(double timerToChange,Vector2 moveVelocity,Scene* pScene, std::string name, Vector3 pos, Vector3 rot, Vector3 scale, Mesh* pMesh, ShaderProgram* pShader, GLuint texture);
virtual ~MovingWall();
virtual void Update(double timeStep);
};
#endif
|
// -*- C++ -*-
//
// Copyright (C) 1998, 1999, 2000, 2002 Los Alamos National Laboratory,
// Copyright (C) 1998, 1999, 2000, 2002 CodeSourcery, LLC
//
// This file is part of FreePOOMA.
//
// FreePOOMA is free software; you can redistribute it and/or modify it
// under the terms of the Expat license.
//
// 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 Expat
// license for more details.
//
// You should have received a copy of the Expat license along with
// FreePOOMA; see the file LICENSE.
//
//-----------------------------------------------------------------------------
// Classes:
// DynamicArray<T, EngineTag>
// ElementProperties< DynamicArray<T, EngineTag> >
// CreateLeaf< DynamicArray<T, EngineTag> >
//-----------------------------------------------------------------------------
/** @file
* @ingroup Array
* @brief
* Dynamic arrays.
*/
#ifndef POOMA_DYNAMIC_ARRAY_DYNAMIC_ARRAY_H
#define POOMA_DYNAMIC_ARRAY_DYNAMIC_ARRAY_H
//-----------------------------------------------------------------------------
// Forward declarations
//-----------------------------------------------------------------------------
template<class T, class EngineTag> class DynamicArray;
//-----------------------------------------------------------------------------
// Includes
//-----------------------------------------------------------------------------
// The following hack was put in the POOMA 2.3 to avoid a template
// instantiation error in KCC 3.4d. The problem has been reported to KAI,
// but until it is fixed, the following odd ordering of includes fixes the
// problem. The correct set of includes should be:
//
// include "Array/Array.h"
// include "DynamicArray/DynamicArrayOperators.h"
// include "DynamicArray/PoomaDynamicArrayOperators.h"
// include "DynamicArray/VectorDynamicArrayOperators.h"
// include "Layout/DynamicEvents.h"
// include "Engine/EnginePatch.h"
template<int Dim, class T, class EngineTag> class Array;
#include "PETE/PETE.h"
#include "Pooma/PETEExtras.h"
#include "DynamicArray/DynamicArrayOperators.h"
#include "DynamicArray/PoomaDynamicArrayOperators.h"
#include "DynamicArray/VectorDynamicArrayOperators.h"
#include "Array/Array.h"
#include "Layout/DynamicEvents.h"
#include "Engine/EnginePatch.h"
#include "Domain/IteratorPairDomain.h"
//-----------------------------------------------------------------------------
// Prototype for the assign function used to assign a DynamicArray to an Array.
//
// Prototypes defined here:
// Array = DynamicArray
//-----------------------------------------------------------------------------
template<int Dim, class T, class EngineTag,
class OtherT, class OtherEngineTag, class Op>
inline const Array<Dim, T, EngineTag> &
assign(const Array<Dim, T, EngineTag> &lhs,
const DynamicArray<OtherT, OtherEngineTag> &rhs,
const Op &op);
//-----------------------------------------------------------------------------
// View specializations for DynamicArray.
//-----------------------------------------------------------------------------
/// General versions. Just defer to Array<1>.
template<class T, class EngineTag, class Sub1>
struct View1<DynamicArray<T, EngineTag>, Sub1>
{
// Convenience typedef for the thing we're taking a view of.
typedef DynamicArray<T, EngineTag> Subject_t;
typedef Array<1, T, EngineTag> Base_t;
// Deduce domains for the output type.
typedef typename Subject_t::Domain_t Domain_t;
typedef TemporaryNewDomain1<Domain_t, Sub1> NewDomain_t;
typedef typename NewDomain_t::SliceType_t SDomain_t;
// Deduce appropriate version of implementation to dispatch to.
enum { sv = DomainTraits<SDomain_t>::singleValued };
typedef View1Implementation<Base_t, SDomain_t, sv> Dispatch_t;
// The optimized domain combiner:
typedef CombineDomainOpt<NewDomain_t, sv> Combine_t;
// The return type.
typedef typename Dispatch_t::Type_t Type_t;
// A function that creates the view.
inline static
Type_t make(const Subject_t &a, const Sub1 &s1)
{
SDomain_t s(Combine_t::make(a, s1));
return Dispatch_t::make(a, s);
}
};
template<class T1, class E1, class T2, class E2>
struct View1<DynamicArray<T1, E1>, Array<1, T2, E2> >
{
typedef DynamicArray<T1, E1> Array1_t;
typedef Array<1, T1, E1> BaseArray1_t;
typedef Array<1, T2, E2> Array2_t;
typedef typename View1<BaseArray1_t, Array2_t>::Type_t Type_t;
inline static
Type_t make(const Array1_t &a, const Array2_t &s)
{
return View1<BaseArray1_t, Array2_t>::make(a, s);
}
};
template<class T1, class E1, class T2, class E2>
struct View1<DynamicArray<T1, E1>, DynamicArray<T2, E2> >
{
typedef DynamicArray<T1, E1> Array1_t;
typedef Array<1, T1, E1> BaseArray1_t;
typedef DynamicArray<T2, E2> Array2_t;
typedef Array<1, T2, E2> BaseArray2_t;
typedef typename View1<BaseArray1_t, BaseArray2_t>::Type_t Type_t;
inline static
Type_t make(const Array1_t &a, const Array2_t &s)
{
return View1<BaseArray1_t, BaseArray2_t>::make(a, s);
}
};
template<int D, class T1, class E1, class T2, class E2>
struct View1<Array<D, T1, E1>, DynamicArray<T2, E2> >
{
typedef Array<D, T1, E1> Array1_t;
typedef DynamicArray<T2, E2> Array2_t;
typedef Array<1, T2, E2> BaseArray2_t;
typedef typename View1<Array1_t, BaseArray2_t>::Type_t Type_t;
inline static
Type_t make(const Array1_t &a, const Array2_t &s)
{
return View1<Array1_t, BaseArray2_t>::make(a, s);
}
};
//-----------------------------------------------------------------------------
// Patch specialization for DynamicArray.
//-----------------------------------------------------------------------------
template<class T, class EngineTag>
struct Patch<DynamicArray<T, EngineTag> >
{
typedef DynamicArray<T, EngineTag> Subject_t;
typedef Array<1, T, EngineTag> Base_t;
typedef typename Patch<Base_t>::Type_t Type_t;
inline static
Type_t make(const Subject_t &subject, int i)
{
return Patch<Base_t>::make(subject, i);
}
};
//-----------------------------------------------------------------------------
// ComponentView specialization for DynamicArray.
//-----------------------------------------------------------------------------
template <class Components, class T, class EngineTag>
struct ComponentView< Components, DynamicArray<T, EngineTag> >
{
// Convenience typedef for the thing we're taking a component view of.
typedef DynamicArray<T, EngineTag> Subject_t;
typedef Array<1, T, EngineTag> Base_t;
// The output type.
typedef typename ComponentView<Components, Base_t>::Type_t Type_t;
// A function that creates the view.
inline static
Type_t make(const Subject_t &a, const Components &loc)
{
return ComponentView<Components, Base_t>::make(a, loc);
}
};
//-----------------------------------------------------------------------------
// DynamicArray
//-----------------------------------------------------------------------------
/**
* A DynamicArray is a read-write array with extra create/destroy methods.
* It can act just like a regular Array, but can have a dynamically-changing
* domain. Create and destroy methods will preserve the values of elements
* that remain after these operations. It is by definition 1-Dimensional,
* and so it does not have a Dim parameter. It provides the following extra
* interface, beyond that of the standard Array class:
* - void create(int num)
* - void create(int num, PatchID_t patch)
* - void destroy(const Domain &killlist, const DeleteMethod &method)
* - void destroy(const Domain &killlist, PatchID_t patch,
* const DeleteMethod &method)
* - void copy(const Domain &dom, PatchID_t topatch)
* - void copy(const Domain &dom, PatchID_t frompatch, PatchID_t topatch)
* - void sync()
*
* BackFill and ShiftUp are tag classes used to indicate how elements should
* be deleted - either by back-filling (moving elements from the bottom up)
* or shift-up (just like the "erase" method in the STL vector class).
*
* shrink() will make sure the engine within a DynamicArray is not using any
* more memory than necessary.
*
* sync() is something that a user should call if they perform some dynamic
* create/destroy operations, and then want to use the DynamicArray in
* expressions that will require knowledge of the global domain of the system.
* Normally, create/destroy ops only modify the domain information for the
* patches within the engine that are local to a context. sync() will
* syncronize with other contexts to make sure all contexts have up-to-date
* domain information for the whole domain and all the patches, even those
* that are on another context.
*/
template<class T = POOMA_DEFAULT_ELEMENT_TYPE,
class EngineTag = POOMA_DEFAULT_DYNAMIC_ENGINE_TYPE>
class DynamicArray : public Array<1, T, EngineTag>
{
public:
//===========================================================================
// Exported typedefs and constants
//===========================================================================
//---------------------------------------------------------------------------
// Base_t is a convenience typedef referring to this class's base class.
// This_t is a convenience typedef referring to this class.
typedef Array<1, T, EngineTag> Base_t;
typedef DynamicArray<T, EngineTag> This_t;
typedef typename Base_t::Engine_t Engine_t;
typedef typename Base_t::Element_t Element_t;
typedef typename Base_t::ElementRef_t ElementRef_t;
typedef typename Base_t::Domain_t Domain_t;
typedef typename Engine_t::Layout_t Layout_t;
typedef typename Layout_t::PatchID_t PatchID_t;
typedef typename Layout_t::CreateSize_t CreateSize_t;
typedef EngineTag EngineTag_t;
enum { dynamic = Engine_t::dynamic };
//===========================================================================
// Constructors
//===========================================================================
//---------------------------------------------------------------------------
/// Default constructor for DynamicArray. Exists so this can be resized
/// or given another layout.
DynamicArray()
{
CTAssert(dynamic == true);
}
//---------------------------------------------------------------------------
// Engine DynamicArray constructors.
explicit DynamicArray(const Engine_t &modelEngine)
: Array<1, T, EngineTag>(modelEngine)
{
CTAssert(dynamic == true);
}
template<class T2, class EngineTag2>
explicit DynamicArray(const Engine<1, T2, EngineTag2> &engine)
: Array<1, T, EngineTag>(engine)
{
CTAssert(dynamic == true);
}
template<class T2, class EngineTag2, class Initializer>
DynamicArray(const Engine<1, T2, EngineTag2> &engine, const Initializer &init)
: Array<1, T, EngineTag>(engine, init)
{
CTAssert(dynamic == true);
}
/// One way for a user to construct a DynamicArray is to use another as a
/// model. The non-templated version is the copy constructor.
/// For the templated versions to work, Engine_t must possess a constructor
/// that takes an OtherEngine and, perhaps, an OtherDomain.
DynamicArray(const This_t &model)
: Array<1, T, EngineTag>(model.engine())
{
CTAssert(dynamic == true);
}
template<class OtherT, class OtherEngineTag, class OtherDomain>
DynamicArray(const DynamicArray<OtherT, OtherEngineTag> &model,
const OtherDomain &domain)
: Array<1, T, EngineTag>(model.engine(), domain)
{
CTAssert(dynamic == true);
}
/// All of these constructors pass domain information to the engine.
/// Since DynamicArray is by definition 1-D, we only need the one-argument
/// version. These constructors call the default constructor
/// for Element_t.
template<class Sub1>
explicit DynamicArray(const Sub1 &s1)
: Array<1, T, EngineTag>(s1)
{
CTAssert(dynamic == true);
}
/// All of these constructors pass domain information to the engine along
/// with a model element, which is used to initialize all array elements.
/// Therefore, it is assumed that Element_t either has deep-copy semantics
/// by default, or can be made to have it using a wrapper class.
/// Since DynamicArray is by definition 1-D, we only need the one-argument
/// version.
template<class Sub1>
DynamicArray(const Sub1 &s1, const ModelElement<Element_t> &model)
: Array<1, T, EngineTag>(s1, model)
{
CTAssert(dynamic == true);
}
//===========================================================================
// Destructor
//===========================================================================
//---------------------------------------------------------------------------
// The destructor is trivial since the base class is the only thing that
// owns data.
~DynamicArray()
{
}
//===========================================================================
// Accessors and mutators
//===========================================================================
/// Get a reference to this same object, but cast to the Array base class
inline Base_t &array()
{
return *this;
}
inline const Base_t &array() const
{
return *this;
}
inline Base_t &arrayAll()
{
return *this;
}
inline const Base_t &arrayAll() const
{
return *this;
}
/// Return a reference to the layout for this array.
inline Layout_t &layout()
{
return this->engine().layout();
}
inline const Layout_t &layout() const
{
return this->engine().layout();
}
//===========================================================================
// Dynamic interface methods.
//===========================================================================
///@name Dynamic interface methods
/// Dynamic interface methods are used to create or
/// destroy elements in the array (this is what makes this class dynamic).
/// These operations are passed on to the engine, so this class must
/// be used with engines that support dynamic operations. These
/// operations will modify the domain of the array, and will rearrange
/// values, but will not erase the values of existing elements that are
/// meant to remain after the create/destroy operations.
///
/// NOTE: Create/destroy operations only properly update the domain
/// information for patches that are on the local context. If the user
/// needs to have all contexts have correct layout information about the
/// dynamic array following create/destroy operations, they must call
/// the sync() method, in an SPMD operations (that is, all contexts must
/// call sync() at the same general time).
//@{
/// Create new elements for a DynamicArray, by extending the current domain
/// on the local context by the requested number of elements, or the
/// specified local patch.
/// 'local' means on this same context. The patch is refered to
/// by local index, from 0 ... # local patches - 1.
inline void create(CreateSize_t num)
{
this->engine().create(num);
}
inline void create(CreateSize_t num, PatchID_t patch)
{
this->engine().create(num, patch);
}
/// Delete the elements within our domain specified by the given
/// Range, using either a backfill mechanism or a shift-up mechanism
/// to delete the data. The second argument should be one of the
/// following types:
/// - BackFill() will move elements from the bottom up to fill the holes.
/// - ShiftUp() will shift elements up to fill in holes.
/// The domain must be within the total domain of the DynamicArray.
template <class Dom>
inline void destroy(const Dom &killlist, BackFill method)
{
this->engine().destroy(killlist, method);
}
template <class Dom>
inline void destroy(const Dom &killlist, ShiftUp method)
{
this->engine().destroy(killlist, method);
}
/// Use the default destroy method, BackFill.
template <class Dom>
inline void destroy(const Dom &killlist)
{
this->engine().destroy(killlist);
}
/// Versions that take a pair of random-access iterators.
template <class Iter>
inline void destroy(Iter begin, Iter end, BackFill method)
{
Pooma::IteratorPairDomain<Iter> dom(begin, end);
this->engine().destroy(dom, method);
}
template <class Iter>
inline void destroy(Iter begin, Iter end, ShiftUp method)
{
Pooma::IteratorPairDomain<Iter> dom(begin, end);
this->engine().destroy(dom, method);
}
template <class Iter>
inline void destroy(Iter begin, Iter end)
{
Pooma::IteratorPairDomain<Iter> dom(begin, end);
this->engine().destroy(dom);
}
/// Delete the elements within the specific local domain for the given
/// patch. The domain values in this case should all be zero-based,
/// so that they are relative to the first element of the specified
/// local patch. The domain values should all be contained within the
/// specified local patch as well. To perform cross-patch destroy's,
/// use the form where you do not specify a local patch number.
template <class Dom>
inline void destroy(const Dom &killlist, PatchID_t frompatch,
BackFill method)
{
this->engine().destroy(killlist, frompatch, method);
}
template <class Dom>
inline void destroy(const Dom &killlist, PatchID_t frompatch,
ShiftUp method)
{
this->engine().destroy(killlist, frompatch, method);
}
template <class Dom>
inline void destroy(const Dom &killlist, PatchID_t frompatch)
{
this->engine().destroy(killlist, frompatch, BackFill());
}
/// For the patch-specific destroy operations, the iterators must be
/// convertible to "const int *" iterators as that is the type for
/// which the underlying DynamicEventDomain objects are specialized.
template <class Iter>
inline void destroy(Iter begin, Iter end, PatchID_t frompatch,
BackFill method)
{
Pooma::IteratorPairDomain<const int *> dom(begin, end);
this->engine().destroy(dom, frompatch, method);
}
template <class Iter>
inline void destroy(Iter begin, Iter end, PatchID_t frompatch,
ShiftUp method)
{
Pooma::IteratorPairDomain<const int *> dom(begin, end);
this->engine().destroy(dom, frompatch, method);
}
template <class Iter>
inline void destroy(Iter begin, Iter end, PatchID_t frompatch)
{
Pooma::IteratorPairDomain<const int *> dom(begin, end);
this->engine().destroy(dom, frompatch, BackFill());
}
/// Copy all elements of domain n to the end of the last patch or
/// to the end of the specified patch.
template<class Dom>
inline void copy(const Dom ©list)
{
this->engine().copy(copylist);
}
template<class Dom>
inline void copy(const Dom ©list, PatchID_t patch)
{
this->engine().copy(copylist, patch);
}
/// Copy all elements from the specified local patch to the end of
/// the local to-patch. The domain values in this case should all be zero-
/// based,/ so that they are relative to the first element of the specified
/// local patch. The domain values should all be contained within the
/// specified local patch as well. To perform cross-patch copies,
/// use the form where you do not specify a local from-patch number.
template<class Dom>
inline void copy(const Dom ©list, PatchID_t frompatch, PatchID_t topatch)
{
this->engine().copy(copylist, frompatch, topatch);
}
/// Synchronize all the contexts to update their domain information.
/// This should be used after create/destroy operations have modified
/// the domain of local context's data, and all contexts must be told
/// of the new situation. This should be an SPMD call.
void sync()
{
this->engine().sync();
}
//@}
//---------------------------------------------------------------------------
// Copy assignment operators. Just use the versions from the base class.
//
// Note: PARTIAL ORDERING is required for the scalar assignment operator
// to be distinguishable from the others.
inline This_t &operator=(const DynamicArray<T, EngineTag> &rhs)
{
Base_t::operator=(static_cast<const Base_t &>(rhs));
return *this;
}
inline const This_t &operator=(const DynamicArray<T, EngineTag> &rhs) const
{
Base_t::operator=(static_cast<const Base_t &>(rhs));
return *this;
}
template<class T1>
const This_t &operator=(const T1 &rhs) const
{
Base_t::operator=(rhs);
return *this;
}
//---------------------------------------------------------------------------
// Op-assignment operators.
//
// Note: PARTIAL ORDERING is required for the scalar assignment operator
// to be distinguishable from the others.
// Addition.
template<class OtherT, class OtherETag>
const This_t &operator+=(const DynamicArray<OtherT, OtherETag> &rhs) const
{
typedef Array<1,OtherT,OtherETag> Array_t;
Base_t::operator+=(static_cast<const Array_t &>(rhs));
return *this;
}
template<class T1>
const This_t &operator+=(const T1 &rhs) const
{
Base_t::operator+=(rhs);
return *this;
}
// Subtraction.
template<class OtherT, class OtherETag>
const This_t &operator-=(const DynamicArray<OtherT, OtherETag> &rhs) const
{
typedef Array<1,OtherT,OtherETag> Array_t;
Base_t::operator-=(static_cast<const Array_t &>(rhs));
return *this;
}
template<class T1>
const This_t &operator-=(const T1 &rhs) const
{
Base_t::operator-=(rhs);
return *this;
}
// Multiplication.
template<class OtherT, class OtherETag>
const This_t &operator*=(const DynamicArray<OtherT, OtherETag> &rhs) const
{
typedef Array<1,OtherT,OtherETag> Array_t;
Base_t::operator*=(static_cast<const Array_t &>(rhs));
return *this;
}
template<class T1>
const This_t &operator*=(const T1 &rhs) const
{
Base_t::operator*=(rhs);
return *this;
}
// Division.
template<class OtherT, class OtherETag>
const This_t &operator/=(const DynamicArray<OtherT, OtherETag> &rhs) const
{
typedef Array<1,OtherT,OtherETag> Array_t;
Base_t::operator/=(static_cast<const Array_t &>(rhs));
return *this;
}
template<class T1>
const This_t &operator/=(const T1 &rhs) const
{
Base_t::operator/=(rhs);
return *this;
}
// Modulus.
template<class OtherT, class OtherETag>
const This_t &operator%=(const DynamicArray<OtherT, OtherETag> &rhs) const
{
typedef Array<1,OtherT,OtherETag> Array_t;
Base_t::operator%=(static_cast<const Array_t &>(rhs));
return *this;
}
template<class T1>
const This_t &operator%=(const T1 &rhs) const
{
Base_t::operator%=(rhs);
return *this;
}
// Bitwise-Or.
template<class OtherT, class OtherETag>
const This_t &operator|=(const DynamicArray<OtherT, OtherETag> &rhs) const
{
typedef Array<1,OtherT,OtherETag> Array_t;
Base_t::operator|=(static_cast<const Array_t &>(rhs));
return *this;
}
template<class T1>
const This_t &operator|=(const T1 &rhs) const
{
Base_t::operator|=(rhs);
return *this;
}
// Bitwise-And.
template<class OtherT, class OtherETag>
const This_t &operator&=(const DynamicArray<OtherT, OtherETag> &rhs) const
{
typedef Array<1,OtherT,OtherETag> Array_t;
Base_t::operator&=(static_cast<const Array_t &>(rhs));
return *this;
}
template<class T1>
const This_t &operator&=(const T1 &rhs) const
{
Base_t::operator&=(rhs);
return *this;
}
// Bitwise-Xor.
template<class OtherT, class OtherETag>
const This_t &operator^=(const DynamicArray<OtherT, OtherETag> &rhs) const
{
typedef Array<1,OtherT,OtherETag> Array_t;
Base_t::operator^=(static_cast<const Array_t &>(rhs));
return *this;
}
template<class T1>
const This_t &operator^=(const T1 &rhs) const
{
Base_t::operator^=(rhs);
return *this;
}
// Left shift.
template<class OtherT, class OtherETag>
const This_t &operator<<=(const DynamicArray<OtherT, OtherETag> &rhs) const
{
typedef Array<1,OtherT,OtherETag> Array_t;
Base_t::operator<<=(static_cast<const Array_t &>(rhs));
return *this;
}
template<class T1>
const This_t &operator<<=(const T1 &rhs) const
{
Base_t::operator<<=(rhs);
return *this;
}
// Right shift.
template<class OtherT, class OtherETag>
const This_t &operator>>=(const DynamicArray<OtherT, OtherETag> &rhs) const
{
typedef Array<1,OtherT,OtherETag> Array_t;
Base_t::operator>>=(static_cast<const Array_t &>(rhs));
return *this;
}
template<class T1>
const This_t &operator>>=(const T1 &rhs) const
{
Base_t::operator>>=(rhs);
return *this;
}
};
//---------------------------------------------------------------------------
/// Implementation for assignment operators. We define here the
/// extra versions of assign that tell how to assign
/// Array = DynamicArray
/// the other versions of assign are handled by routines in the base class.
///
/// Note: PARTIAL ORDERING is required for the scalar assignment operator
/// to be distinguishable from the others.
//---------------------------------------------------------------------------
template<int Dim, class T, class EngineTag,
class OtherT, class OtherEngineTag, class Op>
inline const Array<Dim, T, EngineTag> &
assign(const Array<Dim, T, EngineTag> &lhs,
const DynamicArray<OtherT, OtherEngineTag> &rhs,
const Op &op)
{
// Cast the rhs to be an Array, and then invoke the version of
// assign for Array = Array.
typedef Array<1, OtherT, OtherEngineTag> Array_t;
const Array_t &arhs = rhs;
return assign(lhs, arhs, op);
}
//-----------------------------------------------------------------------------
/// Traits class telling RefCountedBlockPointer that this class has
/// shallow semantics and a makeOwnCopy method.
//-----------------------------------------------------------------------------
template <class T, class EngineTag>
struct ElementProperties< DynamicArray<T, EngineTag> >
: public MakeOwnCopyProperties< DynamicArray<T, EngineTag> >
{
};
//-----------------------------------------------------------------------------
/// A traits class that tells PETE how to make a DynamicArray into
/// an expression element. DynamicArray just returns a reference to
/// itself, but cast as an Array.
//-----------------------------------------------------------------------------
template<class T, class EngineTag>
struct CreateLeaf< DynamicArray<T, EngineTag> >
{
typedef DynamicArray<T, EngineTag> Input_t;
typedef Reference<Array<1, T, EngineTag> > Leaf_t;
typedef Reference<Array<1, T, EngineTag> > Return_t;
inline static
Return_t make(const Input_t &a)
{
return Return_t(a);
}
};
//-----------------------------------------------------------------------------
/// Generalized Engine Functors.
//-----------------------------------------------------------------------------
template<class T, class E, class Tag>
struct LeafFunctor<DynamicArray<T, E>, EngineFunctorTag<Tag> >
{
typedef typename DynamicArray<T,E>::Engine_t Engine_t;
typedef typename EngineFunctor<Engine_t,Tag>::Type_t Type_t;
inline static
Type_t apply(const DynamicArray<T, E> &array,
const EngineFunctorTag<Tag> &tag)
{
return EngineFunctor<Engine_t,Tag>::apply(array.engine(), tag.tag());
}
};
#endif
// ACL:rcsinfo
// ----------------------------------------------------------------------
// $RCSfile: DynamicArray.h,v $ $Author: richard $
// $Revision: 1.35 $ $Date: 2004/11/01 18:16:34 $
// ----------------------------------------------------------------------
// ACL:rcsinfo
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "Windows.Devices.Enumeration.Pnp.1.h"
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_bb78502a_f79d_54fa_92c9_90c5039fdf7e
#define WINRT_GENERIC_bb78502a_f79d_54fa_92c9_90c5039fdf7e
template <> struct __declspec(uuid("bb78502a-f79d-54fa-92c9-90c5039fdf7e")) __declspec(novtable) IMapView<hstring, Windows::Foundation::IInspectable> : impl_IMapView<hstring, Windows::Foundation::IInspectable> {};
#endif
#ifndef WINRT_GENERIC_e2fcc7c1_3bfc_5a0b_b2b0_72e769d1cb7e
#define WINRT_GENERIC_e2fcc7c1_3bfc_5a0b_b2b0_72e769d1cb7e
template <> struct __declspec(uuid("e2fcc7c1-3bfc-5a0b-b2b0-72e769d1cb7e")) __declspec(novtable) IIterable<hstring> : impl_IIterable<hstring> {};
#endif
#ifndef WINRT_GENERIC_2f13c006_a03a_5f69_b090_75a43e33423e
#define WINRT_GENERIC_2f13c006_a03a_5f69_b090_75a43e33423e
template <> struct __declspec(uuid("2f13c006-a03a-5f69-b090-75a43e33423e")) __declspec(novtable) IVectorView<hstring> : impl_IVectorView<hstring> {};
#endif
#ifndef WINRT_GENERIC_1b0d3570_0877_5ec2_8a2c_3b9539506aca
#define WINRT_GENERIC_1b0d3570_0877_5ec2_8a2c_3b9539506aca
template <> struct __declspec(uuid("1b0d3570-0877-5ec2-8a2c-3b9539506aca")) __declspec(novtable) IMap<hstring, Windows::Foundation::IInspectable> : impl_IMap<hstring, Windows::Foundation::IInspectable> {};
#endif
#ifndef WINRT_GENERIC_98b9acc1_4b56_532e_ac73_03d5291cca90
#define WINRT_GENERIC_98b9acc1_4b56_532e_ac73_03d5291cca90
template <> struct __declspec(uuid("98b9acc1-4b56-532e-ac73-03d5291cca90")) __declspec(novtable) IVector<hstring> : impl_IVector<hstring> {};
#endif
#ifndef WINRT_GENERIC_09335560_6c6b_5a26_9348_97b781132b20
#define WINRT_GENERIC_09335560_6c6b_5a26_9348_97b781132b20
template <> struct __declspec(uuid("09335560-6c6b-5a26-9348-97b781132b20")) __declspec(novtable) IKeyValuePair<hstring, Windows::Foundation::IInspectable> : impl_IKeyValuePair<hstring, Windows::Foundation::IInspectable> {};
#endif
#ifndef WINRT_GENERIC_cce5a798_d269_5fce_99ce_ef0ae3cd0569
#define WINRT_GENERIC_cce5a798_d269_5fce_99ce_ef0ae3cd0569
template <> struct __declspec(uuid("cce5a798-d269-5fce-99ce-ef0ae3cd0569")) __declspec(novtable) IVectorView<Windows::Devices::Enumeration::Pnp::PnpObject> : impl_IVectorView<Windows::Devices::Enumeration::Pnp::PnpObject> {};
#endif
#ifndef WINRT_GENERIC_30b50092_36ee_53ff_9450_029004436c60
#define WINRT_GENERIC_30b50092_36ee_53ff_9450_029004436c60
template <> struct __declspec(uuid("30b50092-36ee-53ff-9450-029004436c60")) __declspec(novtable) IIterable<Windows::Devices::Enumeration::Pnp::PnpObject> : impl_IIterable<Windows::Devices::Enumeration::Pnp::PnpObject> {};
#endif
}
namespace ABI::Windows::Foundation {
#ifndef WINRT_GENERIC_d578eed2_58e5_5825_8af2_12f89387b656
#define WINRT_GENERIC_d578eed2_58e5_5825_8af2_12f89387b656
template <> struct __declspec(uuid("d578eed2-58e5-5825-8af2-12f89387b656")) __declspec(novtable) TypedEventHandler<Windows::Devices::Enumeration::Pnp::PnpObjectWatcher, Windows::Devices::Enumeration::Pnp::PnpObject> : impl_TypedEventHandler<Windows::Devices::Enumeration::Pnp::PnpObjectWatcher, Windows::Devices::Enumeration::Pnp::PnpObject> {};
#endif
#ifndef WINRT_GENERIC_af8f929d_8058_5c38_a3d8_30aa7a08b588
#define WINRT_GENERIC_af8f929d_8058_5c38_a3d8_30aa7a08b588
template <> struct __declspec(uuid("af8f929d-8058-5c38-a3d8-30aa7a08b588")) __declspec(novtable) TypedEventHandler<Windows::Devices::Enumeration::Pnp::PnpObjectWatcher, Windows::Devices::Enumeration::Pnp::PnpObjectUpdate> : impl_TypedEventHandler<Windows::Devices::Enumeration::Pnp::PnpObjectWatcher, Windows::Devices::Enumeration::Pnp::PnpObjectUpdate> {};
#endif
#ifndef WINRT_GENERIC_2ee2b4c9_b696_5ecc_b29b_f1e0ef5fe1f7
#define WINRT_GENERIC_2ee2b4c9_b696_5ecc_b29b_f1e0ef5fe1f7
template <> struct __declspec(uuid("2ee2b4c9-b696-5ecc-b29b-f1e0ef5fe1f7")) __declspec(novtable) TypedEventHandler<Windows::Devices::Enumeration::Pnp::PnpObjectWatcher, Windows::Foundation::IInspectable> : impl_TypedEventHandler<Windows::Devices::Enumeration::Pnp::PnpObjectWatcher, Windows::Foundation::IInspectable> {};
#endif
#ifndef WINRT_GENERIC_22b0fb93_30e6_501a_bd3b_9fa3063e9c16
#define WINRT_GENERIC_22b0fb93_30e6_501a_bd3b_9fa3063e9c16
template <> struct __declspec(uuid("22b0fb93-30e6-501a-bd3b-9fa3063e9c16")) __declspec(novtable) IAsyncOperation<Windows::Devices::Enumeration::Pnp::PnpObject> : impl_IAsyncOperation<Windows::Devices::Enumeration::Pnp::PnpObject> {};
#endif
#ifndef WINRT_GENERIC_f383c2cc_f326_5bbe_95d1_cbc24714ef86
#define WINRT_GENERIC_f383c2cc_f326_5bbe_95d1_cbc24714ef86
template <> struct __declspec(uuid("f383c2cc-f326-5bbe-95d1-cbc24714ef86")) __declspec(novtable) IAsyncOperation<Windows::Devices::Enumeration::Pnp::PnpObjectCollection> : impl_IAsyncOperation<Windows::Devices::Enumeration::Pnp::PnpObjectCollection> {};
#endif
}
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_8c304ebb_6615_50a4_8829_879ecd443236
#define WINRT_GENERIC_8c304ebb_6615_50a4_8829_879ecd443236
template <> struct __declspec(uuid("8c304ebb-6615-50a4-8829-879ecd443236")) __declspec(novtable) IIterator<hstring> : impl_IIterator<hstring> {};
#endif
#ifndef WINRT_GENERIC_51ded63f_e60f_5205_b778_680d5e39b5fc
#define WINRT_GENERIC_51ded63f_e60f_5205_b778_680d5e39b5fc
template <> struct __declspec(uuid("51ded63f-e60f-5205-b778-680d5e39b5fc")) __declspec(novtable) IVector<Windows::Devices::Enumeration::Pnp::PnpObject> : impl_IVector<Windows::Devices::Enumeration::Pnp::PnpObject> {};
#endif
#ifndef WINRT_GENERIC_6bb6d2f1_b5fb_57f0_8251_f20cde5a6871
#define WINRT_GENERIC_6bb6d2f1_b5fb_57f0_8251_f20cde5a6871
template <> struct __declspec(uuid("6bb6d2f1-b5fb-57f0-8251-f20cde5a6871")) __declspec(novtable) IIterator<Windows::Devices::Enumeration::Pnp::PnpObject> : impl_IIterator<Windows::Devices::Enumeration::Pnp::PnpObject> {};
#endif
}
namespace ABI::Windows::Foundation {
#ifndef WINRT_GENERIC_9d615463_6879_521f_8e97_e66d3ddbc95e
#define WINRT_GENERIC_9d615463_6879_521f_8e97_e66d3ddbc95e
template <> struct __declspec(uuid("9d615463-6879-521f-8e97-e66d3ddbc95e")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Devices::Enumeration::Pnp::PnpObject> : impl_AsyncOperationCompletedHandler<Windows::Devices::Enumeration::Pnp::PnpObject> {};
#endif
#ifndef WINRT_GENERIC_811d834c_a15e_5522_b7f4_e53004fc58ff
#define WINRT_GENERIC_811d834c_a15e_5522_b7f4_e53004fc58ff
template <> struct __declspec(uuid("811d834c-a15e-5522-b7f4-e53004fc58ff")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Devices::Enumeration::Pnp::PnpObjectCollection> : impl_AsyncOperationCompletedHandler<Windows::Devices::Enumeration::Pnp::PnpObjectCollection> {};
#endif
}
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_fe2f3d47_5d47_5499_8374_430c7cda0204
#define WINRT_GENERIC_fe2f3d47_5d47_5499_8374_430c7cda0204
template <> struct __declspec(uuid("fe2f3d47-5d47-5499-8374-430c7cda0204")) __declspec(novtable) IIterable<Windows::Foundation::Collections::IKeyValuePair<hstring, Windows::Foundation::IInspectable>> : impl_IIterable<Windows::Foundation::Collections::IKeyValuePair<hstring, Windows::Foundation::IInspectable>> {};
#endif
#ifndef WINRT_GENERIC_5db5fa32_707c_5849_a06b_91c8eb9d10e8
#define WINRT_GENERIC_5db5fa32_707c_5849_a06b_91c8eb9d10e8
template <> struct __declspec(uuid("5db5fa32-707c-5849-a06b-91c8eb9d10e8")) __declspec(novtable) IIterator<Windows::Foundation::Collections::IKeyValuePair<hstring, Windows::Foundation::IInspectable>> : impl_IIterator<Windows::Foundation::Collections::IKeyValuePair<hstring, Windows::Foundation::IInspectable>> {};
#endif
}
namespace Windows::Devices::Enumeration::Pnp {
struct IPnpObject :
Windows::Foundation::IInspectable,
impl::consume<IPnpObject>
{
IPnpObject(std::nullptr_t = nullptr) noexcept {}
};
struct IPnpObjectStatics :
Windows::Foundation::IInspectable,
impl::consume<IPnpObjectStatics>
{
IPnpObjectStatics(std::nullptr_t = nullptr) noexcept {}
};
struct IPnpObjectUpdate :
Windows::Foundation::IInspectable,
impl::consume<IPnpObjectUpdate>
{
IPnpObjectUpdate(std::nullptr_t = nullptr) noexcept {}
};
struct IPnpObjectWatcher :
Windows::Foundation::IInspectable,
impl::consume<IPnpObjectWatcher>
{
IPnpObjectWatcher(std::nullptr_t = nullptr) noexcept {}
};
}
}
|
//auto create by tocpp.rb, plz don't modify it!
//2013-10-29 17:14:25 +0800
#include "TemplateSkill.h"
using std::string;
TemplateSkill::TemplateSkill()
{
m_sn = 0;
m_Distance = 0;
m_SkillCD = 0;
m_TrajectorySpeed = 0;
m_scriptFunc = "20";
////////
}
bool TemplateSkill::ReadJsonImpl(const CSJson::Value& obj)
{
//sn
getJsonVal(obj["sn"], m_sn);
//显示名
getJsonVal(obj["ShowName"], m_ShowName);
//施法距离
getJsonVal(obj["Distance"], m_Distance);
//是否自动播放
getJsonVal(obj["IsAutoPlay"], (int&)m_IsAutoPlay);
//技能CD
getJsonVal(obj["SkillCD"], m_SkillCD);
//弹道特效的移动速度
getJsonVal(obj["TrajectorySpeed"], m_TrajectorySpeed);
//造成伤害的脚本函数
getJsonVal(obj["scriptFunc"], m_scriptFunc);
//技能升级设定
m_UpLevelSetting.ReadJsonImpl(obj["UpLevelSetting"]);
//AOE判定范围类型
getJsonVal(obj["AOEType"], (int&)m_AOEType);
//这个时间结束开始播放弹道或者AOE特效
getJsonVal(obj["StartPlaySkillEffectTime"], m_StartPlaySkillEffectTime);
//AOE判定范围类型-直线
m_LineSetting.ReadJsonImpl(obj["LineSetting"]);
//AOE判定范围类型扇形,以人物朝向逆时针为正方向,范围为[-180,180]
m_SectorSetting.ReadJsonImpl(obj["SectorSetting"]);
//特效资源
const CSJson::Value& tmp = obj["effectRes"];
uint32t nSize = tmp.size();
for (uint32t i = 0; i < nSize; ++i)
{
SkillEffect n;
n.ReadJsonImpl(tmp[i]);
m_effectRes.push_back(n);
}
return true;
}
|
/*
* Ticker.h
*
* Created on: Dec 2, 2019
* Author: annuar
*/
#ifndef OURS_TICKER_H_
#define OURS_TICKER_H_
#include "Arduino.h"
class Ticker {
private:
unsigned long _gap;
unsigned long _lock;
public:
bool set;
Ticker(unsigned long gap, unsigned long lock){
this->_gap = gap;
this->_lock = lock;
this->set = false;
}
bool Update(){
bool ret = false;
if((millis() - this->_lock) >= this->_gap){
this->_lock = millis();
ret = true;
this->set = true;
}
return ret;
}
void Reset(){
this->_lock = millis();
this->set = false;
}
};
#endif /* OURS_TICKER_H_ */
//if((millis()-gtickNyamukTime) >= 60000){
// gtickNyamukTime = millis();
// gtockBeat = !gtockBeat;
// locMqtt->hantar(gMAC, gtockBeat?"1":"0");
//}
|
#include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
int main()
{
int gd=DETECT,gm,i, x2,y2,x1,y1,x,y;
printf("Enter the 2 line end points :x1,y1,x2,y2: ");
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
initgraph(&gd,&gm,(char*)"");
line(x1,y1,x2,y2);
printf("Enter translation co-ordinates :tx,ty: ");
scanf("%d%d",&x,&y);
x1=x1+x;
y1=y1+y;
x2=x2+x;
y2=y2+y;
printf("Line after translation");
initgraph(&gd,&gm,(char*)"");
line(x1,y1,x2,y2);
getch();
closegraph();
return 0;
}
|
//
// Created by ikigai on 15.09.18.
//
#include "AnalysisOfGronsfeld.h"
#include "Gronsfeld.h"
#include <fstream>
#include <math.h>
#include <iostream>
char AnalysisOfGronsfeld::searchKeyForOnePartOfText(const std::string &onePartOfText) {
std::map<char, float> characters;
for (char symb : onePartOfText) {
characters[symb] += 1;
}
char res = ' ';
float charSymb = 0;
for (char symb : onePartOfText) {
if (characters[symb] > charSymb) {
res = static_cast<char>(symb - 48);
charSymb = characters[symb];
}
}
return res;
}
void AnalysisOfGronsfeld::decryptText(const std::string &text) {
std::vector<std::string> monoAlphabeticalTexts = divisionText(text);
std::string key;
for (const auto &onePartOfText : monoAlphabeticalTexts) {
key += searchKeyForOnePartOfText(onePartOfText);
}
std::cout << "Key analysis: " << key << std::endl;
Gronsfeld gronsfeld;
gronsfeld.decryptText(text, key);
}
std::vector<std::string> AnalysisOfGronsfeld::divisionText(const std::string &text) {
int keyLenght = findKeyLength(text);
std::vector<std::string> partsOfText;
for (int j = 0; j < keyLenght; j++) {
std::string onePart;
for (int i = j; i < text.length(); i += keyLenght) {
onePart += text[i];
}
partsOfText.push_back(onePart);
}
return partsOfText;
}
int AnalysisOfGronsfeld::findKeyLength(const std::string &text) {
std::string piecesOfText;
int N = static_cast<int>(text.length()), res = 0;
float IC = 0;
for (int i = 2; i < N; i++) {
for (int j = 0; j < N; j++) {
if (j % i == 0)
piecesOfText += text[j];
}
IC = indexOfCoincidence(piecesOfText);
if (IC > 0.07) {
res = i;
break;
}
piecesOfText.clear();
}
return res;
}
float AnalysisOfGronsfeld::indexOfCoincidence(const std::string &text) {
std::map<char, float> characters;
for (char symb : text) {
characters[symb]++;
}
float IC = 0;
int N = static_cast<int>(text.length());
for (const auto &character : characters)
IC += (character.second * (character.second - 1)) / (N * (N - 1));
return IC;
}
|
// Copyright (c) 2015 University of Szeged.
// Copyright (c) 2015 The Chromium Authors.
// All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sprocket/browser/ui/context_menu_model.h"
#include "base/strings/utf_string_conversions.h"
#include "ui/base/accelerators/accelerator.h"
SprocketContextMenuModel::SprocketContextMenuModel(
SprocketWebContents* sprocket_web_contents,
const content::ContextMenuParams& params)
: ui::SimpleMenuModel(this),
sprocket_web_contents_(sprocket_web_contents),
params_(params) {
AddItem(COMMAND_BACK, base::ASCIIToUTF16("Back"));
AddItem(COMMAND_FORWARD, base::ASCIIToUTF16("Forward"));
AddItem(COMMAND_RELOAD, base::ASCIIToUTF16("Reload"));
}
bool SprocketContextMenuModel::IsCommandIdChecked(
int command_id) const {
return false;
}
bool SprocketContextMenuModel::IsCommandIdEnabled(
int command_id) const {
switch (command_id) {
case COMMAND_BACK:
return sprocket_web_contents_->CanGoBack();
case COMMAND_FORWARD:
return sprocket_web_contents_->CanGoForward();
case COMMAND_RELOAD:
return true;
};
return false;
}
bool SprocketContextMenuModel::GetAcceleratorForCommandId(
int command_id,
ui::Accelerator* accel) {
return false;
}
void SprocketContextMenuModel::ExecuteCommand(
int command_id, int event_flags) {
switch (command_id) {
case COMMAND_BACK:
sprocket_web_contents_->GoBackOrForward(-1);
break;
case COMMAND_FORWARD:
sprocket_web_contents_->GoBackOrForward(1);
break;
case COMMAND_RELOAD:
sprocket_web_contents_->Reload();
break;
};
}
|
#include "Board.hpp"
#include "City.hpp"
#include "Player.hpp"
#include "FieldDoctor.hpp"
using namespace pandemic;
const int MAX_CARDS =48;
const int six = 6;
FieldDoctor::FieldDoctor(Board &board, enum City city){
CurrentCity = city;
theBorad = &board;
}
Player& FieldDoctor::treat(enum City a){
bool connect = false;
if(CurrentCity == a){
connect=true;
}
for (size_t i = 0; i < six; i++){
if(getMap().at(CurrentCity).t.count(a)!=0 ||connect){
connect = true;
break;
}
}
if(!connect){
throw invalid_argument("you cant treat there");
}
if(getMap()[a].cube == 0){
throw invalid_argument("there are no cubes in this city");
}
if(getCures()[getMap()[a].colorOfCity]){
getMap()[a].cube=0;
}
else{
getMap()[a].cube--;
}
return *this;
}
string FieldDoctor::role(){
return "FieldDoctor";
}
|
/**
* @file StaticSelectorMacros.h
* @author seckler
* @date 02.05.19
*/
#pragma once
/**
* Macro to execute the code defined in ... with a static bool.
* The bool will be renamed to be called c_BOOLNAME,
* where BOOLNAME is the name of the bool passed in this macro.
*/
#define AUTOPAS_WITH_STATIC_BOOL(theBool, ...) \
{ \
if (theBool) { \
constexpr bool c_##theBool = true; \
__VA_ARGS__ \
} else { \
constexpr bool c_##theBool = false; \
__VA_ARGS__ \
} \
}
|
#ifndef TESTARRAYUTILS_H
#define TESTARRAYUTILS_H
namespace cpp_class2_test {
void testGetPowerOfTwoCount();
void testGetPrimeCount();
void testMultiplyArrays();
void testMergeSortedArray();
void testReverseArray();
void testTruncateArray();
void testXorArrays();
}
#endif // !TESTARRAYUTILS_H
|
#ifndef _MESH_H_
#define _MESH_H_
#include <vector>
// #include "payoff.h"
class Mesh {
public:
/* Constructor and Destructor */
Mesh();
Mesh(double lower, double upper, double maturity,
unsigned int imax, unsigned int jmax);
~Mesh();
/* operator overloading */
std::vector<double>& operator[] (unsigned int j);
/* Find a certain value at a specified time index */
int findIndex(double value, unsigned int timeindex = 0);
/* print mesh */
void print();
/* get imax, jmax, dt, ds */
int getImax() const;
int getJmax() const;
double getdt() const;
double getds() const;
private:
double mLower, mUpper, mMaturity;
unsigned int mImax, mJmax;
double mPriceStep, mTimeStep;
std::vector< std::vector<double> > mGrid;
};
#endif
|
#include "boss.h"
#include "ui_boss.h"
#include "mainwindow.h"
#include "client.h"
Boss::Boss(QWidget *parent) :
QDialog(parent),
ui(new Ui::Boss)
{
ui->setupUi(this);
this->setWindowTitle("Administrator");
}
//Named Boss for Administrator
Boss::~Boss()
{
delete ui;
}
//Show Adminisrator WindowPane
void Boss::on_btnAdmin_clicked()
{
MainWindow *ma= new MainWindow();
ma->show();
this->hide();
}
//Show client WindowPane
void Boss::on_btnClient_clicked()
{
Client *cl=new Client();
cl->show();
this->hide();
}
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "TempCapstoneProjectCharacter.h"
#include "TempCapstoneProject.h"
#include "PaladinCharacter.generated.h"
UCLASS()
class TEMPCAPSTONEPROJECT_API APaladinCharacter : public ATempCapstoneProjectCharacter
{
GENERATED_BODY()
public:
ECharacterType GetCharacterType() override;
};
|
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
class QGraphicsScene;
class QGraphicsView;
class Panel;
class QDockWidget;
class Scene;
class Triangle;
class QPen;
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
~MainWindow();
virtual QSize minimumSizeHint() const override;
virtual QSize sizeHint() const override;
private slots:
void _change_font_size(int i);
void _clear();
void _generate();
void _hexagoanl();
bool _convex_hull();
void _convex_hull_auto();
void _cdt();
void _decompose();
void _accomplish();
void _zoom_in();
void _zoom_out();
void _zoom_fit();
private:
void _create_dock_widget();
void _create_actions();
void _create_menus();
void _connect_panel();
void _draw_input();
void _init_cdt_display(const QVector<Triangle>& triangles);
void _draw_cdt(int idx);
void _draw_triangle(const Triangle& t, const QPen& pen);
QMenu* _file_menu;
QMenu* _view_menu;
QAction* _clear_act;
QAction* _generate_act;
QAction* _zoom_in_act;
QAction* _zoom_out_act;
QAction* _zoom_fit_act;
Scene* _scene;
QGraphicsView* _view;
Panel* _panel;
QDockWidget* _dock;
QVector<bool> _cdt_display;
int _con_secs;
int _dec_secs;
int _total_secs;
};
#endif // MAINWINDOW_H
|
// $Id: FunctionSymbol.h,v 1.5 2013-05-11 22:15:29 ist164787 Exp $ -*- c++ -*-
#ifndef __MF_SEMANTICS_FUNCTIONSYMBOL_H__
#define __MF_SEMANTICS_FUNCTIONSYMBOL_H__
#include <string>
#include "semantics/Symbol.h"
class FunctionSymbol : public Symbol {
public:
const std::string TYPE = "FUNCTION";
protected:
bool _is_public;
bool _is_defined;
// arguments?
public:
inline FunctionSymbol(ExpressionType *type, const std::string &name, bool is_public, bool is_defined) :
Symbol(type, name), _is_public(is_public), _is_defined(is_defined) {
}
inline FunctionSymbol(ExpressionType *type, const char *name, bool is_public, bool is_defined) :
FunctionSymbol(type, name, is_public, is_defined) {
}
virtual ~FunctionSymbol() {
}
bool is_public() { return _is_public; }
bool is_defined() { return _is_defined; }
void is_public(bool is_public) { _is_public = is_public; }
void is_defined(bool is_defined) { _is_defined = is_defined; }
const std::string symbolType() const {
return "TYPE";
}
};
#endif
// $Log: FunctionSymbol.h,v $
// Revision 1.5 2013-05-11 22:15:29 ist164787
// Function arguments may be working... havent tested lol
//
// Revision 1.4 2013-05-11 18:18:41 ist164787
// function declarations working, part of vardecls working
//
// Revision 1.3 2013-05-10 22:22:09 ist164787
// forgot to add FunctionSymbol file; fixed return value POP
//
//
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "Windows.Storage.Search.1.h"
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_bb78502a_f79d_54fa_92c9_90c5039fdf7e
#define WINRT_GENERIC_bb78502a_f79d_54fa_92c9_90c5039fdf7e
template <> struct __declspec(uuid("bb78502a-f79d-54fa-92c9-90c5039fdf7e")) __declspec(novtable) IMapView<hstring, Windows::Foundation::IInspectable> : impl_IMapView<hstring, Windows::Foundation::IInspectable> {};
#endif
#ifndef WINRT_GENERIC_e2fcc7c1_3bfc_5a0b_b2b0_72e769d1cb7e
#define WINRT_GENERIC_e2fcc7c1_3bfc_5a0b_b2b0_72e769d1cb7e
template <> struct __declspec(uuid("e2fcc7c1-3bfc-5a0b-b2b0-72e769d1cb7e")) __declspec(novtable) IIterable<hstring> : impl_IIterable<hstring> {};
#endif
#ifndef WINRT_GENERIC_2f13c006_a03a_5f69_b090_75a43e33423e
#define WINRT_GENERIC_2f13c006_a03a_5f69_b090_75a43e33423e
template <> struct __declspec(uuid("2f13c006-a03a-5f69-b090-75a43e33423e")) __declspec(novtable) IVectorView<hstring> : impl_IVectorView<hstring> {};
#endif
#ifndef WINRT_GENERIC_1b0d3570_0877_5ec2_8a2c_3b9539506aca
#define WINRT_GENERIC_1b0d3570_0877_5ec2_8a2c_3b9539506aca
template <> struct __declspec(uuid("1b0d3570-0877-5ec2-8a2c-3b9539506aca")) __declspec(novtable) IMap<hstring, Windows::Foundation::IInspectable> : impl_IMap<hstring, Windows::Foundation::IInspectable> {};
#endif
}
namespace ABI::Windows::Foundation {
#ifndef WINRT_GENERIC_ef60385f_be78_584b_aaef_7829ada2b0de
#define WINRT_GENERIC_ef60385f_be78_584b_aaef_7829ada2b0de
template <> struct __declspec(uuid("ef60385f-be78-584b-aaef-7829ada2b0de")) __declspec(novtable) IAsyncOperation<uint32_t> : impl_IAsyncOperation<uint32_t> {};
#endif
}
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_98b9acc1_4b56_532e_ac73_03d5291cca90
#define WINRT_GENERIC_98b9acc1_4b56_532e_ac73_03d5291cca90
template <> struct __declspec(uuid("98b9acc1-4b56-532e-ac73-03d5291cca90")) __declspec(novtable) IVector<hstring> : impl_IVector<hstring> {};
#endif
#ifndef WINRT_GENERIC_bb8b8418_65d1_544b_b083_6d172f568c73
#define WINRT_GENERIC_bb8b8418_65d1_544b_b083_6d172f568c73
template <> struct __declspec(uuid("bb8b8418-65d1-544b-b083-6d172f568c73")) __declspec(novtable) IIterable<Windows::Storage::IStorageItem> : impl_IIterable<Windows::Storage::IStorageItem> {};
#endif
#ifndef WINRT_GENERIC_80646519_5e2a_595d_a8cd_2a24b4067f1b
#define WINRT_GENERIC_80646519_5e2a_595d_a8cd_2a24b4067f1b
template <> struct __declspec(uuid("80646519-5e2a-595d-a8cd-2a24b4067f1b")) __declspec(novtable) IVectorView<Windows::Storage::StorageFile> : impl_IVectorView<Windows::Storage::StorageFile> {};
#endif
#ifndef WINRT_GENERIC_fcbc8b8b_6103_5b4e_ba00_4bc2cedb6a35
#define WINRT_GENERIC_fcbc8b8b_6103_5b4e_ba00_4bc2cedb6a35
template <> struct __declspec(uuid("fcbc8b8b-6103-5b4e-ba00-4bc2cedb6a35")) __declspec(novtable) IVector<Windows::Storage::StorageFile> : impl_IVector<Windows::Storage::StorageFile> {};
#endif
#ifndef WINRT_GENERIC_09335560_6c6b_5a26_9348_97b781132b20
#define WINRT_GENERIC_09335560_6c6b_5a26_9348_97b781132b20
template <> struct __declspec(uuid("09335560-6c6b-5a26-9348-97b781132b20")) __declspec(novtable) IKeyValuePair<hstring, Windows::Foundation::IInspectable> : impl_IKeyValuePair<hstring, Windows::Foundation::IInspectable> {};
#endif
#ifndef WINRT_GENERIC_2f245f9d_eb5f_5641_9dcc_6ab1946cc7e6
#define WINRT_GENERIC_2f245f9d_eb5f_5641_9dcc_6ab1946cc7e6
template <> struct __declspec(uuid("2f245f9d-eb5f-5641-9dcc-6ab1946cc7e6")) __declspec(novtable) IVectorView<Windows::Data::Text::TextSegment> : impl_IVectorView<Windows::Data::Text::TextSegment> {};
#endif
#ifndef WINRT_GENERIC_85575a41_06cb_58d0_b98a_7c8f06e6e9d7
#define WINRT_GENERIC_85575a41_06cb_58d0_b98a_7c8f06e6e9d7
template <> struct __declspec(uuid("85575a41-06cb-58d0-b98a-7c8f06e6e9d7")) __declspec(novtable) IVectorView<Windows::Storage::IStorageItem> : impl_IVectorView<Windows::Storage::IStorageItem> {};
#endif
#ifndef WINRT_GENERIC_35aff6f9_ef75_5280_bb84_a2bf8317cf35
#define WINRT_GENERIC_35aff6f9_ef75_5280_bb84_a2bf8317cf35
template <> struct __declspec(uuid("35aff6f9-ef75-5280-bb84-a2bf8317cf35")) __declspec(novtable) IIterable<Windows::Storage::Search::SortEntry> : impl_IIterable<Windows::Storage::Search::SortEntry> {};
#endif
#ifndef WINRT_GENERIC_f4512416_6bb8_5c6f_b83a_bf8a2788ce9f
#define WINRT_GENERIC_f4512416_6bb8_5c6f_b83a_bf8a2788ce9f
template <> struct __declspec(uuid("f4512416-6bb8-5c6f-b83a-bf8a2788ce9f")) __declspec(novtable) IVectorView<Windows::Storage::Search::IIndexableContent> : impl_IVectorView<Windows::Storage::Search::IIndexableContent> {};
#endif
#ifndef WINRT_GENERIC_6c26b7be_5f01_5a60_9dd7_fd17be3a9dd6
#define WINRT_GENERIC_6c26b7be_5f01_5a60_9dd7_fd17be3a9dd6
template <> struct __declspec(uuid("6c26b7be-5f01-5a60-9dd7-fd17be3a9dd6")) __declspec(novtable) IVector<Windows::Storage::StorageFolder> : impl_IVector<Windows::Storage::StorageFolder> {};
#endif
#ifndef WINRT_GENERIC_e20debc6_dc4e_542e_a2e7_a24d19c8dd62
#define WINRT_GENERIC_e20debc6_dc4e_542e_a2e7_a24d19c8dd62
template <> struct __declspec(uuid("e20debc6-dc4e-542e-a2e7-a24d19c8dd62")) __declspec(novtable) IVectorView<Windows::Storage::StorageFolder> : impl_IVectorView<Windows::Storage::StorageFolder> {};
#endif
#ifndef WINRT_GENERIC_d8ea401b_47b3_5254_84f4_eea10c4cf068
#define WINRT_GENERIC_d8ea401b_47b3_5254_84f4_eea10c4cf068
template <> struct __declspec(uuid("d8ea401b-47b3-5254-84f4-eea10c4cf068")) __declspec(novtable) IVector<Windows::Storage::Search::SortEntry> : impl_IVector<Windows::Storage::Search::SortEntry> {};
#endif
}
namespace ABI::Windows::Foundation {
#ifndef WINRT_GENERIC_4ba22861_00c4_597f_b6bf_3af516f3b870
#define WINRT_GENERIC_4ba22861_00c4_597f_b6bf_3af516f3b870
template <> struct __declspec(uuid("4ba22861-00c4-597f-b6bf-3af516f3b870")) __declspec(novtable) TypedEventHandler<Windows::Storage::Search::IStorageQueryResultBase, Windows::Foundation::IInspectable> : impl_TypedEventHandler<Windows::Storage::Search::IStorageQueryResultBase, Windows::Foundation::IInspectable> {};
#endif
#ifndef WINRT_GENERIC_88694b1f_f380_574d_8a05_4f67bd52cd11
#define WINRT_GENERIC_88694b1f_f380_574d_8a05_4f67bd52cd11
template <> struct __declspec(uuid("88694b1f-f380-574d-8a05-4f67bd52cd11")) __declspec(novtable) IAsyncOperation<winrt::Windows::Storage::Search::IndexedState> : impl_IAsyncOperation<winrt::Windows::Storage::Search::IndexedState> {};
#endif
}
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_9ac00304_83ea_5688_87b6_ae38aab65d0b
#define WINRT_GENERIC_9ac00304_83ea_5688_87b6_ae38aab65d0b
template <> struct __declspec(uuid("9ac00304-83ea-5688-87b6-ae38aab65d0b")) __declspec(novtable) IIterable<Windows::Storage::StorageFile> : impl_IIterable<Windows::Storage::StorageFile> {};
#endif
#ifndef WINRT_GENERIC_802508e2_9c2c_5b91_89a8_39bcf7223344
#define WINRT_GENERIC_802508e2_9c2c_5b91_89a8_39bcf7223344
template <> struct __declspec(uuid("802508e2-9c2c-5b91-89a8-39bcf7223344")) __declspec(novtable) IVector<Windows::Storage::IStorageItem> : impl_IVector<Windows::Storage::IStorageItem> {};
#endif
#ifndef WINRT_GENERIC_8c304ebb_6615_50a4_8829_879ecd443236
#define WINRT_GENERIC_8c304ebb_6615_50a4_8829_879ecd443236
template <> struct __declspec(uuid("8c304ebb-6615-50a4-8829-879ecd443236")) __declspec(novtable) IIterator<hstring> : impl_IIterator<hstring> {};
#endif
}
namespace ABI::Windows::Foundation {
#ifndef WINRT_GENERIC_9343b6e7_e3d2_5e4a_ab2d_2bce4919a6a4
#define WINRT_GENERIC_9343b6e7_e3d2_5e4a_ab2d_2bce4919a6a4
template <> struct __declspec(uuid("9343b6e7-e3d2-5e4a-ab2d-2bce4919a6a4")) __declspec(novtable) AsyncOperationCompletedHandler<uint32_t> : impl_AsyncOperationCompletedHandler<uint32_t> {};
#endif
}
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_05b487c2_3830_5d3c_98da_25fa11542dbd
#define WINRT_GENERIC_05b487c2_3830_5d3c_98da_25fa11542dbd
template <> struct __declspec(uuid("05b487c2-3830-5d3c-98da-25fa11542dbd")) __declspec(novtable) IIterator<Windows::Storage::IStorageItem> : impl_IIterator<Windows::Storage::IStorageItem> {};
#endif
#ifndef WINRT_GENERIC_43e29f53_0298_55aa_a6c8_4edd323d9598
#define WINRT_GENERIC_43e29f53_0298_55aa_a6c8_4edd323d9598
template <> struct __declspec(uuid("43e29f53-0298-55aa-a6c8-4edd323d9598")) __declspec(novtable) IIterator<Windows::Storage::StorageFile> : impl_IIterator<Windows::Storage::StorageFile> {};
#endif
#ifndef WINRT_GENERIC_66b1a575_7c1a_5dfc_92f3_e8a49e92f109
#define WINRT_GENERIC_66b1a575_7c1a_5dfc_92f3_e8a49e92f109
template <> struct __declspec(uuid("66b1a575-7c1a-5dfc-92f3-e8a49e92f109")) __declspec(novtable) IVector<Windows::Data::Text::TextSegment> : impl_IVector<Windows::Data::Text::TextSegment> {};
#endif
#ifndef WINRT_GENERIC_645a39b4_f001_5272_9015_fb4a327179ae
#define WINRT_GENERIC_645a39b4_f001_5272_9015_fb4a327179ae
template <> struct __declspec(uuid("645a39b4-f001-5272-9015-fb4a327179ae")) __declspec(novtable) IIterator<Windows::Data::Text::TextSegment> : impl_IIterator<Windows::Data::Text::TextSegment> {};
#endif
#ifndef WINRT_GENERIC_5498f4f3_cee4_5b72_9729_815c4ad7b9dc
#define WINRT_GENERIC_5498f4f3_cee4_5b72_9729_815c4ad7b9dc
template <> struct __declspec(uuid("5498f4f3-cee4-5b72-9729-815c4ad7b9dc")) __declspec(novtable) IIterable<Windows::Data::Text::TextSegment> : impl_IIterable<Windows::Data::Text::TextSegment> {};
#endif
#ifndef WINRT_GENERIC_823c7604_b37b_5465_a169_29497893cdb9
#define WINRT_GENERIC_823c7604_b37b_5465_a169_29497893cdb9
template <> struct __declspec(uuid("823c7604-b37b-5465-a169-29497893cdb9")) __declspec(novtable) IVectorView<Windows::Storage::Search::SortEntry> : impl_IVectorView<Windows::Storage::Search::SortEntry> {};
#endif
#ifndef WINRT_GENERIC_520434a2_acf7_58c9_b47a_2741f2fac2c2
#define WINRT_GENERIC_520434a2_acf7_58c9_b47a_2741f2fac2c2
template <> struct __declspec(uuid("520434a2-acf7-58c9-b47a-2741f2fac2c2")) __declspec(novtable) IIterator<Windows::Storage::Search::SortEntry> : impl_IIterator<Windows::Storage::Search::SortEntry> {};
#endif
#ifndef WINRT_GENERIC_d44eaa11_4871_50c5_8e70_ab765b5bb332
#define WINRT_GENERIC_d44eaa11_4871_50c5_8e70_ab765b5bb332
template <> struct __declspec(uuid("d44eaa11-4871-50c5-8e70-ab765b5bb332")) __declspec(novtable) IVector<Windows::Storage::Search::IIndexableContent> : impl_IVector<Windows::Storage::Search::IIndexableContent> {};
#endif
#ifndef WINRT_GENERIC_6cdb32ba_2361_57a8_a39d_be1df041bdb8
#define WINRT_GENERIC_6cdb32ba_2361_57a8_a39d_be1df041bdb8
template <> struct __declspec(uuid("6cdb32ba-2361-57a8-a39d-be1df041bdb8")) __declspec(novtable) IIterator<Windows::Storage::Search::IIndexableContent> : impl_IIterator<Windows::Storage::Search::IIndexableContent> {};
#endif
#ifndef WINRT_GENERIC_4a6edbfe_0c41_5042_ac58_a885a8fc7928
#define WINRT_GENERIC_4a6edbfe_0c41_5042_ac58_a885a8fc7928
template <> struct __declspec(uuid("4a6edbfe-0c41-5042-ac58-a885a8fc7928")) __declspec(novtable) IIterable<Windows::Storage::Search::IIndexableContent> : impl_IIterable<Windows::Storage::Search::IIndexableContent> {};
#endif
#ifndef WINRT_GENERIC_5aac96fb_b3b9_5a7f_a920_4b5a8df81168
#define WINRT_GENERIC_5aac96fb_b3b9_5a7f_a920_4b5a8df81168
template <> struct __declspec(uuid("5aac96fb-b3b9-5a7f-a920-4b5a8df81168")) __declspec(novtable) IIterator<Windows::Storage::StorageFolder> : impl_IIterator<Windows::Storage::StorageFolder> {};
#endif
#ifndef WINRT_GENERIC_4669befc_ae5c_52b1_8a97_5466ce61e94e
#define WINRT_GENERIC_4669befc_ae5c_52b1_8a97_5466ce61e94e
template <> struct __declspec(uuid("4669befc-ae5c-52b1-8a97-5466ce61e94e")) __declspec(novtable) IIterable<Windows::Storage::StorageFolder> : impl_IIterable<Windows::Storage::StorageFolder> {};
#endif
}
namespace ABI::Windows::Foundation {
#ifndef WINRT_GENERIC_b67a3cba_f5f7_5e51_968a_385126d1f918
#define WINRT_GENERIC_b67a3cba_f5f7_5e51_968a_385126d1f918
template <> struct __declspec(uuid("b67a3cba-f5f7-5e51-968a-385126d1f918")) __declspec(novtable) AsyncOperationCompletedHandler<winrt::Windows::Storage::Search::IndexedState> : impl_AsyncOperationCompletedHandler<winrt::Windows::Storage::Search::IndexedState> {};
#endif
}
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_172a655b_b3b8_5eae_bc2e_a6a1f1708b4b
#define WINRT_GENERIC_172a655b_b3b8_5eae_bc2e_a6a1f1708b4b
template <> struct __declspec(uuid("172a655b-b3b8-5eae-bc2e-a6a1f1708b4b")) __declspec(novtable) IVectorView<Windows::Foundation::Collections::IMapView<hstring, Windows::Foundation::IInspectable>> : impl_IVectorView<Windows::Foundation::Collections::IMapView<hstring, Windows::Foundation::IInspectable>> {};
#endif
#ifndef WINRT_GENERIC_fe2f3d47_5d47_5499_8374_430c7cda0204
#define WINRT_GENERIC_fe2f3d47_5d47_5499_8374_430c7cda0204
template <> struct __declspec(uuid("fe2f3d47-5d47-5499-8374-430c7cda0204")) __declspec(novtable) IIterable<Windows::Foundation::Collections::IKeyValuePair<hstring, Windows::Foundation::IInspectable>> : impl_IIterable<Windows::Foundation::Collections::IKeyValuePair<hstring, Windows::Foundation::IInspectable>> {};
#endif
}
namespace ABI::Windows::Foundation {
#ifndef WINRT_GENERIC_4b1c0fd7_7a01_5e7a_a6fe_be4500283f23
#define WINRT_GENERIC_4b1c0fd7_7a01_5e7a_a6fe_be4500283f23
template <> struct __declspec(uuid("4b1c0fd7-7a01-5e7a-a6fe-be4500283f23")) __declspec(novtable) IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Storage::IStorageItem>> : impl_IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Storage::IStorageItem>> {};
#endif
#ifndef WINRT_GENERIC_5dcbee48_9965_51da_a461_177c885be7e5
#define WINRT_GENERIC_5dcbee48_9965_51da_a461_177c885be7e5
template <> struct __declspec(uuid("5dcbee48-9965-51da-a461-177c885be7e5")) __declspec(novtable) IAsyncOperation<Windows::Foundation::Collections::IMapView<hstring, Windows::Foundation::IInspectable>> : impl_IAsyncOperation<Windows::Foundation::Collections::IMapView<hstring, Windows::Foundation::IInspectable>> {};
#endif
#ifndef WINRT_GENERIC_919850e1_084b_5f9b_a0a0_50db0cd5da91
#define WINRT_GENERIC_919850e1_084b_5f9b_a0a0_50db0cd5da91
template <> struct __declspec(uuid("919850e1-084b-5f9b-a0a0-50db0cd5da91")) __declspec(novtable) IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Storage::Search::IIndexableContent>> : impl_IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Storage::Search::IIndexableContent>> {};
#endif
#ifndef WINRT_GENERIC_03362e33_e413_5f29_97d0_48a4780935f9
#define WINRT_GENERIC_03362e33_e413_5f29_97d0_48a4780935f9
template <> struct __declspec(uuid("03362e33-e413-5f29-97d0-48a4780935f9")) __declspec(novtable) IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Storage::StorageFile>> : impl_IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Storage::StorageFile>> {};
#endif
#ifndef WINRT_GENERIC_ca40b21b_aeb1_5a61_9e08_3bd5d9594023
#define WINRT_GENERIC_ca40b21b_aeb1_5a61_9e08_3bd5d9594023
template <> struct __declspec(uuid("ca40b21b-aeb1-5a61-9e08-3bd5d9594023")) __declspec(novtable) IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Storage::StorageFolder>> : impl_IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Storage::StorageFolder>> {};
#endif
}
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_a31b6540_b2b1_536d_818f_8ade7051c3b3
#define WINRT_GENERIC_a31b6540_b2b1_536d_818f_8ade7051c3b3
template <> struct __declspec(uuid("a31b6540-b2b1-536d-818f-8ade7051c3b3")) __declspec(novtable) IMap<hstring, Windows::Foundation::Collections::IVectorView<Windows::Data::Text::TextSegment>> : impl_IMap<hstring, Windows::Foundation::Collections::IVectorView<Windows::Data::Text::TextSegment>> {};
#endif
#ifndef WINRT_GENERIC_5db5fa32_707c_5849_a06b_91c8eb9d10e8
#define WINRT_GENERIC_5db5fa32_707c_5849_a06b_91c8eb9d10e8
template <> struct __declspec(uuid("5db5fa32-707c-5849-a06b-91c8eb9d10e8")) __declspec(novtable) IIterator<Windows::Foundation::Collections::IKeyValuePair<hstring, Windows::Foundation::IInspectable>> : impl_IIterator<Windows::Foundation::Collections::IKeyValuePair<hstring, Windows::Foundation::IInspectable>> {};
#endif
#ifndef WINRT_GENERIC_9ac5167a_7c19_53d6_85b8_1e479a971d1e
#define WINRT_GENERIC_9ac5167a_7c19_53d6_85b8_1e479a971d1e
template <> struct __declspec(uuid("9ac5167a-7c19-53d6-85b8-1e479a971d1e")) __declspec(novtable) IVector<Windows::Foundation::Collections::IMapView<hstring, Windows::Foundation::IInspectable>> : impl_IVector<Windows::Foundation::Collections::IMapView<hstring, Windows::Foundation::IInspectable>> {};
#endif
#ifndef WINRT_GENERIC_53a2e825_9bf1_5083_8a7b_9d94f312dade
#define WINRT_GENERIC_53a2e825_9bf1_5083_8a7b_9d94f312dade
template <> struct __declspec(uuid("53a2e825-9bf1-5083-8a7b-9d94f312dade")) __declspec(novtable) IIterator<Windows::Foundation::Collections::IMapView<hstring, Windows::Foundation::IInspectable>> : impl_IIterator<Windows::Foundation::Collections::IMapView<hstring, Windows::Foundation::IInspectable>> {};
#endif
#ifndef WINRT_GENERIC_e1670fae_49cd_5c47_a8c8_f6fa2c650c6c
#define WINRT_GENERIC_e1670fae_49cd_5c47_a8c8_f6fa2c650c6c
template <> struct __declspec(uuid("e1670fae-49cd-5c47-a8c8-f6fa2c650c6c")) __declspec(novtable) IIterable<Windows::Foundation::Collections::IMapView<hstring, Windows::Foundation::IInspectable>> : impl_IIterable<Windows::Foundation::Collections::IMapView<hstring, Windows::Foundation::IInspectable>> {};
#endif
}
namespace ABI::Windows::Foundation {
#ifndef WINRT_GENERIC_51436e75_ace1_5a68_b260_f843b846f0db
#define WINRT_GENERIC_51436e75_ace1_5a68_b260_f843b846f0db
template <> struct __declspec(uuid("51436e75-ace1-5a68-b260-f843b846f0db")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Foundation::Collections::IVectorView<Windows::Storage::IStorageItem>> : impl_AsyncOperationCompletedHandler<Windows::Foundation::Collections::IVectorView<Windows::Storage::IStorageItem>> {};
#endif
#ifndef WINRT_GENERIC_89981889_1207_5ae6_9b28_ccc58f3aac6e
#define WINRT_GENERIC_89981889_1207_5ae6_9b28_ccc58f3aac6e
template <> struct __declspec(uuid("89981889-1207-5ae6-9b28-ccc58f3aac6e")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Foundation::Collections::IMapView<hstring, Windows::Foundation::IInspectable>> : impl_AsyncOperationCompletedHandler<Windows::Foundation::Collections::IMapView<hstring, Windows::Foundation::IInspectable>> {};
#endif
#ifndef WINRT_GENERIC_6a29f493_efb7_5fdb_a13e_f2c28b4dab58
#define WINRT_GENERIC_6a29f493_efb7_5fdb_a13e_f2c28b4dab58
template <> struct __declspec(uuid("6a29f493-efb7-5fdb-a13e-f2c28b4dab58")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Foundation::Collections::IVectorView<Windows::Storage::Search::IIndexableContent>> : impl_AsyncOperationCompletedHandler<Windows::Foundation::Collections::IVectorView<Windows::Storage::Search::IIndexableContent>> {};
#endif
#ifndef WINRT_GENERIC_cb4206c5_0988_5104_afa9_253c298f86fd
#define WINRT_GENERIC_cb4206c5_0988_5104_afa9_253c298f86fd
template <> struct __declspec(uuid("cb4206c5-0988-5104-afa9-253c298f86fd")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Foundation::Collections::IVectorView<Windows::Storage::StorageFile>> : impl_AsyncOperationCompletedHandler<Windows::Foundation::Collections::IVectorView<Windows::Storage::StorageFile>> {};
#endif
#ifndef WINRT_GENERIC_ed2d1d9b_26ec_5be7_a8a3_56458933d25f
#define WINRT_GENERIC_ed2d1d9b_26ec_5be7_a8a3_56458933d25f
template <> struct __declspec(uuid("ed2d1d9b-26ec-5be7-a8a3-56458933d25f")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Foundation::Collections::IVectorView<Windows::Storage::StorageFolder>> : impl_AsyncOperationCompletedHandler<Windows::Foundation::Collections::IVectorView<Windows::Storage::StorageFolder>> {};
#endif
}
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_77b4daf4_4f4f_5568_90ee_1a32cf0caaea
#define WINRT_GENERIC_77b4daf4_4f4f_5568_90ee_1a32cf0caaea
template <> struct __declspec(uuid("77b4daf4-4f4f-5568-90ee-1a32cf0caaea")) __declspec(novtable) IKeyValuePair<hstring, Windows::Foundation::Collections::IVectorView<Windows::Data::Text::TextSegment>> : impl_IKeyValuePair<hstring, Windows::Foundation::Collections::IVectorView<Windows::Data::Text::TextSegment>> {};
#endif
#ifndef WINRT_GENERIC_91d443d6_3777_5102_b0bc_3d4183a26ff9
#define WINRT_GENERIC_91d443d6_3777_5102_b0bc_3d4183a26ff9
template <> struct __declspec(uuid("91d443d6-3777-5102-b0bc-3d4183a26ff9")) __declspec(novtable) IMapView<hstring, Windows::Foundation::Collections::IVectorView<Windows::Data::Text::TextSegment>> : impl_IMapView<hstring, Windows::Foundation::Collections::IVectorView<Windows::Data::Text::TextSegment>> {};
#endif
}
namespace ABI::Windows::Foundation {
#ifndef WINRT_GENERIC_fc227365_219d_5d59_8b5b_58eb0a91ca0a
#define WINRT_GENERIC_fc227365_219d_5d59_8b5b_58eb0a91ca0a
template <> struct __declspec(uuid("fc227365-219d-5d59-8b5b-58eb0a91ca0a")) __declspec(novtable) IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Foundation::Collections::IMapView<hstring, Windows::Foundation::IInspectable>>> : impl_IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Foundation::Collections::IMapView<hstring, Windows::Foundation::IInspectable>>> {};
#endif
#ifndef WINRT_GENERIC_a782a13a_16a0_5326_b985_c4ca49e54e77
#define WINRT_GENERIC_a782a13a_16a0_5326_b985_c4ca49e54e77
template <> struct __declspec(uuid("a782a13a-16a0-5326-b985-c4ca49e54e77")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Foundation::Collections::IVectorView<Windows::Foundation::Collections::IMapView<hstring, Windows::Foundation::IInspectable>>> : impl_AsyncOperationCompletedHandler<Windows::Foundation::Collections::IVectorView<Windows::Foundation::Collections::IMapView<hstring, Windows::Foundation::IInspectable>>> {};
#endif
}
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_00078aa3_8676_5f06_adf5_ffe5d661d670
#define WINRT_GENERIC_00078aa3_8676_5f06_adf5_ffe5d661d670
template <> struct __declspec(uuid("00078aa3-8676-5f06-adf5-ffe5d661d670")) __declspec(novtable) IIterator<Windows::Foundation::Collections::IKeyValuePair<hstring, Windows::Foundation::Collections::IVectorView<Windows::Data::Text::TextSegment>>> : impl_IIterator<Windows::Foundation::Collections::IKeyValuePair<hstring, Windows::Foundation::Collections::IVectorView<Windows::Data::Text::TextSegment>>> {};
#endif
#ifndef WINRT_GENERIC_f819a276_b3f5_54d4_b8fd_c9adb7f700e3
#define WINRT_GENERIC_f819a276_b3f5_54d4_b8fd_c9adb7f700e3
template <> struct __declspec(uuid("f819a276-b3f5-54d4-b8fd-c9adb7f700e3")) __declspec(novtable) IIterable<Windows::Foundation::Collections::IKeyValuePair<hstring, Windows::Foundation::Collections::IVectorView<Windows::Data::Text::TextSegment>>> : impl_IIterable<Windows::Foundation::Collections::IKeyValuePair<hstring, Windows::Foundation::Collections::IVectorView<Windows::Data::Text::TextSegment>>> {};
#endif
}
namespace Windows::Storage::Search {
struct IContentIndexer :
Windows::Foundation::IInspectable,
impl::consume<IContentIndexer>
{
IContentIndexer(std::nullptr_t = nullptr) noexcept {}
};
struct IContentIndexerQuery :
Windows::Foundation::IInspectable,
impl::consume<IContentIndexerQuery>
{
IContentIndexerQuery(std::nullptr_t = nullptr) noexcept {}
};
struct IContentIndexerQueryOperations :
Windows::Foundation::IInspectable,
impl::consume<IContentIndexerQueryOperations>
{
IContentIndexerQueryOperations(std::nullptr_t = nullptr) noexcept {}
};
struct IContentIndexerStatics :
Windows::Foundation::IInspectable,
impl::consume<IContentIndexerStatics>
{
IContentIndexerStatics(std::nullptr_t = nullptr) noexcept {}
};
struct IIndexableContent :
Windows::Foundation::IInspectable,
impl::consume<IIndexableContent>
{
IIndexableContent(std::nullptr_t = nullptr) noexcept {}
};
struct IQueryOptions :
Windows::Foundation::IInspectable,
impl::consume<IQueryOptions>
{
IQueryOptions(std::nullptr_t = nullptr) noexcept {}
};
struct IQueryOptionsFactory :
Windows::Foundation::IInspectable,
impl::consume<IQueryOptionsFactory>
{
IQueryOptionsFactory(std::nullptr_t = nullptr) noexcept {}
};
struct IQueryOptionsWithProviderFilter :
Windows::Foundation::IInspectable,
impl::consume<IQueryOptionsWithProviderFilter>
{
IQueryOptionsWithProviderFilter(std::nullptr_t = nullptr) noexcept {}
};
struct IStorageFileQueryResult :
Windows::Foundation::IInspectable,
impl::consume<IStorageFileQueryResult>,
impl::require<IStorageFileQueryResult, Windows::Storage::Search::IStorageQueryResultBase>
{
IStorageFileQueryResult(std::nullptr_t = nullptr) noexcept {}
};
struct IStorageFileQueryResult2 :
Windows::Foundation::IInspectable,
impl::consume<IStorageFileQueryResult2>,
impl::require<IStorageFileQueryResult2, Windows::Storage::Search::IStorageQueryResultBase>
{
IStorageFileQueryResult2(std::nullptr_t = nullptr) noexcept {}
};
struct IStorageFolderQueryOperations :
Windows::Foundation::IInspectable,
impl::consume<IStorageFolderQueryOperations>
{
IStorageFolderQueryOperations(std::nullptr_t = nullptr) noexcept {}
};
struct IStorageFolderQueryResult :
Windows::Foundation::IInspectable,
impl::consume<IStorageFolderQueryResult>,
impl::require<IStorageFolderQueryResult, Windows::Storage::Search::IStorageQueryResultBase>
{
IStorageFolderQueryResult(std::nullptr_t = nullptr) noexcept {}
};
struct IStorageItemQueryResult :
Windows::Foundation::IInspectable,
impl::consume<IStorageItemQueryResult>,
impl::require<IStorageItemQueryResult, Windows::Storage::Search::IStorageQueryResultBase>
{
IStorageItemQueryResult(std::nullptr_t = nullptr) noexcept {}
};
struct IStorageLibraryContentChangedTriggerDetails :
Windows::Foundation::IInspectable,
impl::consume<IStorageLibraryContentChangedTriggerDetails>
{
IStorageLibraryContentChangedTriggerDetails(std::nullptr_t = nullptr) noexcept {}
};
struct IStorageQueryResultBase :
Windows::Foundation::IInspectable,
impl::consume<IStorageQueryResultBase>
{
IStorageQueryResultBase(std::nullptr_t = nullptr) noexcept {}
};
struct IValueAndLanguage :
Windows::Foundation::IInspectable,
impl::consume<IValueAndLanguage>
{
IValueAndLanguage(std::nullptr_t = nullptr) noexcept {}
};
}
}
|
#include <Bridge.h>
#define BugPin1 2 //蟲罐
#define BugPin2 3 //蟲罐
int BugCounter = 0;
int BugPin1state = 0;
long suspendTimestamp = millis();
void blink1(){//BugPin1
//Serial.println("Bug Pin1 triggered.");
BugPin1state = 1;
}
void blink2(){//BugPin2
//Serial.println("Bug Pin2 triggered.");
if (BugPin1state != 1) return;
if (millis()-suspendTimestamp > 500){
BugCounter += 1;
BugPin1state = 0;
suspendTimestamp = millis();
}
else{
suspendTimestamp = millis();
}
}
void setup() {
pinMode(BugPin1, INPUT_PULLUP);
pinMode(BugPin2, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(BugPin1), blink1, RISING); //BugPin register to Interrupt
attachInterrupt(digitalPinToInterrupt(BugPin2), blink2, RISING); //BugPin register to Interrupt
Serial.begin(115200);
Bridge.begin(); // D0 and D1 are used by the Bridge library.
//IoTtalk successful registration notification
pinMode(13,OUTPUT);
}
void loop() {
char valueStr[23];
int valueInt=0;
Bridge.get("Reg_done", valueStr, 2);
digitalWrite(13, atoi(valueStr));
itoa(BugCounter, valueStr, 10);
Bridge.put("Bugs", valueStr);
Serial.print("Bugs counter: "); Serial.println(BugCounter);
Bridge.get("resetCounter", valueStr, 5);
if (strcmp(valueStr,"") != 0){
BugCounter = 0;
Serial.println("Reset bug's counter.");
Bridge.put("resetCounter", "");
}
Serial.println(" ");
delay(1000);
}
|
#include "wizDocumentListView.h"
#include <QtGui>
#include "wizDocumentListViewItem.h"
#include "wizCategoryView.h"
#include "widgets/wizScrollBar.h"
#include "wiznotestyle.h"
#include "wiztaglistwidget.h"
#include "share/wizsettings.h"
#include "wizFolderSelector.h"
#include "wizProgressDialog.h"
#include "share/wizUserAvatar.h"
class CWizDocumentListViewDelegate : public QStyledItemDelegate
{
public:
CWizDocumentListViewDelegate(QWidget* parent)
: QStyledItemDelegate(parent)
{
}
virtual QSize sizeHint(const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QSize sz = QStyledItemDelegate::sizeHint(option, index);
sz.setHeight(sz.height() + (option.fontMetrics.height() + 2) * 3 + 2 + 16);
return sz;
}
};
// Document actions
#define WIZACTION_LIST_DELETE QObject::tr("Delete")
#define WIZACTION_LIST_TAGS QObject::tr("Tags...")
#define WIZACTION_LIST_MOVE_DOCUMENT QObject::tr("Move Document")
#define WIZACTION_LIST_COPY_DOCUMENT QObject::tr("Copy Document")
// Message actions
#define WIZACTION_LIST_MESSAGE_MARK_READ QObject::tr("Mark as read")
#define WIZACTION_LIST_MESSAGE_DELETE QObject::tr("Delete Message(s)")
CWizDocumentListView::CWizDocumentListView(CWizExplorerApp& app, QWidget *parent /*= 0*/)
: QListWidget(parent)
, m_app(app)
, m_dbMgr(app.databaseManager())
, m_tagList(NULL)
{
setFrameStyle(QFrame::NoFrame);
setAttribute(Qt::WA_MacShowFocusRect, false);
connect(this, SIGNAL(itemSelectionChanged()), SLOT(on_itemSelectionChanged()));
// use custom scrollbar
setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
m_vScroll = new CWizScrollBar(this);
m_vScroll->syncWith(verticalScrollBar());
//QScrollAreaKineticScroller *newScroller = new QScrollAreaKineticScroller();
//newScroller->setWidget(this);
//m_kinecticScroll = new QsKineticScroller(this);
//m_kinecticScroll->enableKineticScrollFor(this);
//#ifndef Q_OS_MAC
// smoothly scroll
m_vscrollCurrent = 0;
m_vscrollOldPos = 0;
connect(verticalScrollBar(), SIGNAL(valueChanged(int)), SLOT(on_vscroll_valueChanged(int)));
connect(verticalScrollBar(), SIGNAL(actionTriggered(int)), SLOT(on_vscroll_actionTriggered(int)));
connect(&m_vscrollTimer, SIGNAL(timeout()), SLOT(on_vscroll_update()));
//#endif //Q_OS_MAC
setItemDelegate(new CWizDocumentListViewDelegate(this));
// setup background
QPalette pal = palette();
pal.setColor(QPalette::Base, QColor(247,247,247));
setPalette(pal);
setStyle(::WizGetStyle(m_app.userSettings().skin()));
connect(&m_dbMgr, SIGNAL(tagCreated(const WIZTAGDATA&)), \
SLOT(on_tag_created(const WIZTAGDATA&)));
connect(&m_dbMgr, SIGNAL(tagModified(const WIZTAGDATA&, const WIZTAGDATA&)), \
SLOT(on_tag_modified(const WIZTAGDATA&, const WIZTAGDATA&)));
connect(&m_dbMgr, SIGNAL(documentCreated(const WIZDOCUMENTDATA&)), \
SLOT(on_document_created(const WIZDOCUMENTDATA&)));
connect(&m_dbMgr, SIGNAL(documentModified(const WIZDOCUMENTDATA&, const WIZDOCUMENTDATA&)), \
SLOT(on_document_modified(const WIZDOCUMENTDATA&, const WIZDOCUMENTDATA&)));
connect(&m_dbMgr, SIGNAL(documentDeleted(const WIZDOCUMENTDATA&)),
SLOT(on_document_deleted(const WIZDOCUMENTDATA&)));
// message
connect(&m_dbMgr.db(), SIGNAL(messageModified(const WIZMESSAGEDATA&, const WIZMESSAGEDATA&)),
SLOT(on_message_modified(const WIZMESSAGEDATA&, const WIZMESSAGEDATA&)));
connect(&m_dbMgr.db(), SIGNAL(messageDeleted(const WIZMESSAGEDATA&)),
SLOT(on_message_deleted(const WIZMESSAGEDATA&)));
// thumb cache
m_thumbCache = new CWizThumbIndexCache(app);
connect(m_thumbCache, SIGNAL(loaded(const WIZABSTRACT&)),
SLOT(on_document_abstractLoaded(const WIZABSTRACT&)));
QThread *thread = new QThread();
m_thumbCache->moveToThread(thread);
thread->start();
// avatar downloader
m_avatarDownloader = new CWizUserAvatarDownloaderHost(m_dbMgr.db().GetAvatarPath(), this);
connect(m_avatarDownloader, SIGNAL(downloaded(const QString&)),
SLOT(on_userAvatar_downloaded(const QString&)));
setDragDropMode(QAbstractItemView::DragDrop);
setDragEnabled(true);
viewport()->setAcceptDrops(true);
setSelectionMode(QAbstractItemView::ExtendedSelection);
// message context menu
m_menuMessage = new QMenu(this);
m_menuMessage->addAction(WIZACTION_LIST_MESSAGE_MARK_READ, this,
SLOT(on_action_message_mark_read()));
m_menuMessage->addAction(WIZACTION_LIST_MESSAGE_DELETE, this,
SLOT(on_action_message_delete()));
// document context menu
m_menuDocument = new QMenu(this);
m_menuDocument->addAction(WIZACTION_LIST_TAGS, this,
SLOT(on_action_selectTags()));
m_menuDocument->addSeparator();
QAction* actionDeleteDoc = m_menuDocument->addAction(WIZACTION_LIST_DELETE,
this, SLOT(on_action_deleteDocument()), QKeySequence::Delete);
QAction* actionMoveDoc = m_menuDocument->addAction(WIZACTION_LIST_MOVE_DOCUMENT,
this, SLOT(on_action_moveDocument()), QKeySequence("Ctrl+Shift+M"));
QAction* actionCopyDoc = m_menuDocument->addAction(WIZACTION_LIST_COPY_DOCUMENT,
this, SLOT(on_action_copyDocument()), QKeySequence("Ctrl+Shift+C"));
// not implement, hide currently.
actionCopyDoc->setVisible(false);
// Add to widget's actions list
addAction(actionDeleteDoc);
addAction(actionMoveDoc);
addAction(actionCopyDoc);
actionDeleteDoc->setShortcutContext(Qt::WidgetWithChildrenShortcut);
actionMoveDoc->setShortcutContext(Qt::WidgetWithChildrenShortcut);
//actionCopyDoc->setShortcutContext(Qt::WidgetWithChildrenShortcut);
//m_actionEncryptDocument = new QAction(tr("Encrypt Document"), m_menu);
//connect(m_actionEncryptDocument, SIGNAL(triggered()), SLOT(on_action_encryptDocument()));
//m_menu->addAction(m_actionEncryptDocument);
}
CWizDocumentListView::~CWizDocumentListView()
{
}
void CWizDocumentListView::resizeEvent(QResizeEvent* event)
{
// reset scrollbar position
m_vScroll->resize(m_vScroll->sizeHint().width(), event->size().height());
m_vScroll->move(event->size().width() - m_vScroll->sizeHint().width(), 0);
QListWidget::resizeEvent(event);
}
void CWizDocumentListView::setDocuments(const CWizDocumentDataArray& arrayDocument)
{
//reset
clear();
verticalScrollBar()->setValue(0);
addDocuments(arrayDocument);
}
void CWizDocumentListView::setDocuments(const CWizMessageDataArray& arrayMessage)
{
//reset
clear();
verticalScrollBar()->setValue(0);
addDocuments(arrayMessage);
}
void CWizDocumentListView::addDocuments(const CWizDocumentDataArray& arrayDocument)
{
CWizDocumentDataArray::const_iterator it;
for (it = arrayDocument.begin(); it != arrayDocument.end(); it++) {
addDocument(*it, false);
}
sortItems();
}
void CWizDocumentListView::addDocuments(const CWizMessageDataArray& arrayMessage)
{
CWizMessageDataArray::const_iterator it;
for (it = arrayMessage.begin(); it != arrayMessage.end(); it++) {
addDocument(*it, false);
}
sortItems();
}
int CWizDocumentListView::addDocument(const WIZDOCUMENTDATA& data, bool sort)
{
CWizDocumentListViewItem* pItem = new CWizDocumentListViewItem(data);
addItem(pItem);
if (sort) {
sortItems();
}
return count();
}
int CWizDocumentListView::addDocument(const WIZMESSAGEDATA& data, bool sort)
{
CWizDocumentListViewItem* pItem = new CWizDocumentListViewItem(data);
addItem(pItem);
if (sort) {
sortItems();
}
return count();
}
bool CWizDocumentListView::acceptDocument(const WIZDOCUMENTDATA& document)
{
return m_app.category().acceptDocument(document);
}
void CWizDocumentListView::addAndSelectDocument(const WIZDOCUMENTDATA& document)
{
Q_ASSERT(acceptDocument(document));
int index = documentIndexFromGUID(document.strGUID);
if (-1 == index) {
index = addDocument(document, false);
}
if (-1 == index)
return;
setCurrentItem(item(index), QItemSelectionModel::ClearAndSelect);
sortItems();
}
void CWizDocumentListView::getSelectedDocuments(CWizDocumentDataArray& arrayDocument)
{
QList<QListWidgetItem*> items = selectedItems();
QList<QListWidgetItem*>::const_iterator it;
for (it = items.begin(); it != items.end(); it++)
{
QListWidgetItem* pItem = *it;
CWizDocumentListViewItem* pDocumentItem = dynamic_cast<CWizDocumentListViewItem*>(pItem);
if (!pDocumentItem)
continue;
// if document is message type
if (pDocumentItem->type() == CWizDocumentListViewItem::MessageDocument) {
QString strKbGUID = pDocumentItem->message().kbGUID;
QString strGUID = pDocumentItem->message().documentGUID;
// document must have record in database.
WIZDOCUMENTDATA doc;
if (!m_dbMgr.db(strKbGUID).DocumentFromGUID(strGUID, doc)) {
qDebug() << "[getSelectedDocuments] failed to query document from guid";
continue;
}
// no matter document exist or not, just push it
arrayDocument.push_back(doc);
} else {
arrayDocument.push_back(pDocumentItem->document());
}
}
}
void CWizDocumentListView::contextMenuEvent(QContextMenuEvent * e)
{
CWizDocumentListViewItem* pItem = dynamic_cast<CWizDocumentListViewItem*>(itemAt(e->pos()));
if (!pItem)
return;
if (pItem->type() == CWizDocumentListViewItem::MessageDocument) {
m_menuMessage->popup(mapToGlobal(e->pos()));
} else {
m_menuDocument->popup(mapToGlobal(e->pos()));
}
}
void CWizDocumentListView::resetPermission()
{
CWizDocumentDataArray arrayDocument;
QList<QListWidgetItem*> items = selectedItems();
foreach (QListWidgetItem* it, items) {
if (CWizDocumentListViewItem* item = dynamic_cast<CWizDocumentListViewItem*>(it)) {
arrayDocument.push_back(item->document());
}
}
bool bGroup = isDocumentsWithGroupDocument(arrayDocument);
bool bDeleted = isDocumentsWithDeleted(arrayDocument);
bool bCanDelete = isDocumentsAllCanDelete(arrayDocument);
// if group documents or deleted documents selected
if (bGroup || bDeleted) {
findAction(WIZACTION_LIST_TAGS)->setEnabled(false);
} else {
findAction(WIZACTION_LIST_TAGS)->setEnabled(true);
}
// deleted user private documents
if (!bGroup) {
findAction(WIZACTION_LIST_MOVE_DOCUMENT)->setEnabled(true);
} else {
findAction(WIZACTION_LIST_MOVE_DOCUMENT)->setEnabled(false);
}
// disable delete if permission is not enough
if (!bCanDelete) {
findAction(WIZACTION_LIST_DELETE)->setEnabled(false);
} else {
findAction(WIZACTION_LIST_DELETE)->setEnabled(true);
}
}
QAction* CWizDocumentListView::findAction(const QString& strName)
{
QList<QAction *> actionList;
actionList.append(m_menuDocument->actions());
QList<QAction *>::const_iterator it;
for (it = actionList.begin(); it != actionList.end(); it++) {
QAction* action = *it;
if (action->text() == strName) {
return action;
}
}
Q_ASSERT(0);
return NULL;
}
bool CWizDocumentListView::isDocumentsWithDeleted(const CWizDocumentDataArray& arrayDocument)
{
foreach (const WIZDOCUMENTDATAEX& doc, arrayDocument) {
if (doc.strLocation.startsWith(LOCATION_DELETED_ITEMS)) {
return true;
}
}
return false;
}
bool CWizDocumentListView::isDocumentsWithGroupDocument(const CWizDocumentDataArray& arrayDocument)
{
QString strUserGUID = m_dbMgr.db().kbGUID();
foreach (const WIZDOCUMENTDATAEX& doc, arrayDocument) {
if (doc.strKbGUID != strUserGUID) {
return true;
}
}
return false;
}
bool CWizDocumentListView::isDocumentsAllCanDelete(const CWizDocumentDataArray& arrayDocument)
{
foreach (const WIZDOCUMENTDATAEX& doc, arrayDocument) {
int nPerm = m_dbMgr.db(doc.strKbGUID).permission();
if (nPerm > WIZ_USERGROUP_EDITOR) {
return false;
}
}
return true;
}
void CWizDocumentListView::mousePressEvent(QMouseEvent* event)
{
if (event->button() == Qt::LeftButton) {
m_dragStartPosition.setX(event->pos().x());
m_dragStartPosition.setY(event->pos().y());
}
QListWidget::mousePressEvent(event);
}
void CWizDocumentListView::mouseMoveEvent(QMouseEvent* event)
{
if ((event->buttons() & Qt::LeftButton) && \
(event->pos() - m_dragStartPosition).manhattanLength() > QApplication::startDragDistance()) {
setState(QAbstractItemView::DraggingState);
}
QListWidget::mouseMoveEvent(event);
}
QPixmap WizGetDocumentDragBadget(int nCount)
{
QString strFileName = WizGetResourcesPath() + "skins/document_drag.png";
QPixmap pixmap(strFileName);
if (pixmap.isNull()) {
return NULL;
}
// default
QSize szPixmap(32, 32);
// count badget width
QFont font;
font.setPixelSize(10);
QFontMetrics fm(font);
int width = fm.width(QString::number(nCount));
QRect rectBadget(0, 0, width + 15, 16);
QPixmap pixmapBadget(rectBadget.size());
pixmapBadget.fill(Qt::transparent);
// draw badget
QPainter p(&pixmapBadget);
p.setRenderHint(QPainter::Antialiasing);
QPen pen = p.pen();
pen.setWidth(2);
pen.setColor("white");
p.setPen(pen);
QBrush brush = p.brush();
brush.setColor("red");
brush.setStyle(Qt::SolidPattern);
p.setBrush(brush);
p.drawEllipse(rectBadget);
p.drawText(rectBadget, Qt::AlignCenter, QString::number(nCount));
// draw badget on icon
QPixmap pixmapDragIcon(szPixmap.width() + rectBadget.width() / 2, szPixmap.height());
pixmapDragIcon.fill(Qt::transparent);
QPainter painter(&pixmapDragIcon);
painter.setRenderHint(QPainter::Antialiasing);
painter.drawPixmap(0, 0, pixmap.scaled(szPixmap));
painter.drawPixmap(pixmapDragIcon.width() - rectBadget.width(),
pixmapDragIcon.height() - rectBadget.height(),
pixmapBadget);
return pixmapDragIcon;
}
void CWizDocumentListView::startDrag(Qt::DropActions supportedActions)
{
Q_UNUSED(supportedActions);
CWizStdStringArray arrayGUID;
QList<QListWidgetItem*> items = selectedItems();
foreach (QListWidgetItem* it, items) {
if (CWizDocumentListViewItem* item = dynamic_cast<CWizDocumentListViewItem*>(it)) {
// not support drag group document currently
if (item->document().strKbGUID != m_dbMgr.db().kbGUID())
return;
arrayGUID.push_back((item->document().strGUID));
}
}
if (arrayGUID.empty())
return;
CString strGUIDs;
::WizStringArrayToText(arrayGUID, strGUIDs, ";");
QDrag* drag = new QDrag(this);
QMimeData* mimeData = new QMimeData();
mimeData->setData(WIZNOTE_MIMEFORMAT_DOCUMENTS, strGUIDs.toUtf8());
drag->setMimeData(mimeData);
drag->setPixmap(WizGetDocumentDragBadget(items.size()));
drag->exec();
}
void CWizDocumentListView::dragEnterEvent(QDragEnterEvent *event)
{
if (event->mimeData()->hasFormat(WIZNOTE_MIMEFORMAT_TAGS)) {
event->acceptProposedAction();
}
//QListWidget::dragEnterEvent(event);
}
void CWizDocumentListView::dragMoveEvent(QDragMoveEvent *event)
{
if (event->mimeData()->hasFormat(WIZNOTE_MIMEFORMAT_TAGS)) {
event->acceptProposedAction();
}
//QListWidget::dragMoveEvent(event);
}
void CWizDocumentListView::dropEvent(QDropEvent * event)
{
if (event->mimeData()->hasFormat(WIZNOTE_MIMEFORMAT_TAGS))
{
if (CWizDocumentListViewItem* item = dynamic_cast<CWizDocumentListViewItem*>(itemAt(event->pos())))
{
QByteArray data = event->mimeData()->data(WIZNOTE_MIMEFORMAT_TAGS);
QString strTagGUIDs = QString::fromUtf8(data, data.length());
CWizStdStringArray arrayTagGUID;
::WizSplitTextToArray(strTagGUIDs, ';', arrayTagGUID);
foreach (const CString& strTagGUID, arrayTagGUID)
{
WIZTAGDATA dataTag;
if (m_dbMgr.db().TagFromGUID(strTagGUID, dataTag))
{
CWizDocument doc(m_dbMgr.db(), item->document());
doc.AddTag(dataTag);
}
}
}
event->acceptProposedAction();
}
}
void CWizDocumentListView::on_itemSelectionChanged()
{
resetPermission();
}
void CWizDocumentListView::on_tag_created(const WIZTAGDATA& tag)
{
Q_UNUSED(tag);
}
void CWizDocumentListView::on_tag_modified(const WIZTAGDATA& tagOld, const WIZTAGDATA& tagNew)
{
Q_UNUSED(tagOld);
Q_UNUSED(tagNew);
}
void CWizDocumentListView::on_document_created(const WIZDOCUMENTDATA& document)
{
if (acceptDocument(document))
{
if (-1 == documentIndexFromGUID(document.strGUID))
{
addDocument(document, true);
}
}
}
void CWizDocumentListView::on_document_modified(const WIZDOCUMENTDATA& documentOld,
const WIZDOCUMENTDATA& documentNew)
{
Q_UNUSED(documentOld);
// FIXME: if user search on-going, acceptDocument will remove this document from the list.
if (acceptDocument(documentNew))
{
int index = documentIndexFromGUID(documentNew.strGUID);
if (-1 == index) {
addDocument(documentNew, true);
} else {
if (CWizDocumentListViewItem* pItem = documentItemAt(index)) {
pItem->reload(m_dbMgr.db(documentNew.strKbGUID));
}
}
} else {
int index = documentIndexFromGUID(documentNew.strGUID);
if (-1 != index) {
takeItem(index);
}
}
}
void CWizDocumentListView::on_document_deleted(const WIZDOCUMENTDATA& document)
{
int index = documentIndexFromGUID(document.strGUID);
if (-1 != index) {
takeItem(index);
}
}
void CWizDocumentListView::on_document_abstractLoaded(const WIZABSTRACT& abs)
{
int index = documentIndexFromGUID(abs.guid);
if (-1 == index)
return;
// kbGUID also should equal
CWizDocumentListViewItem* pItem = documentItemAt(index);
if (!pItem->document().strKbGUID.isEmpty() &&
pItem->document().strKbGUID != abs.strKbGUID) {
return;
}
if (!pItem->message().kbGUID.isEmpty() &&
pItem->message().kbGUID != abs.strKbGUID) {
return;
}
pItem->resetAbstract(abs);
update(indexFromItem(pItem));
}
void CWizDocumentListView::on_userAvatar_downloaded(const QString& strUserGUID)
{
CWizDocumentListViewItem* pItem = NULL;
for (int i = 0; i < count(); i++) {
pItem = documentItemAt(i);
if (pItem->message().senderGUID == strUserGUID) {
QString strFileName = m_dbMgr.db().GetAvatarPath() + strUserGUID + ".png";
pItem->resetAvatar(strFileName);
update(indexFromItem(pItem));
}
}
}
void CWizDocumentListView::on_message_created(const WIZMESSAGEDATA& data)
{
}
void CWizDocumentListView::on_message_modified(const WIZMESSAGEDATA& oldMsg,
const WIZMESSAGEDATA& newMsg)
{
Q_UNUSED(oldMsg);
int index = documentIndexFromGUID(newMsg.documentGUID);
if (-1 != index) {
if (CWizDocumentListViewItem* pItem = documentItemAt(index)) {
pItem->reload(m_dbMgr.db());
update(indexFromItem(pItem));
}
}
}
void CWizDocumentListView::on_message_deleted(const WIZMESSAGEDATA& data)
{
int index = documentIndexFromGUID(data.documentGUID);
if (-1 != index) {
takeItem(index);
}
}
void CWizDocumentListView::on_action_message_mark_read()
{
QList<QListWidgetItem*> items = selectedItems();
CWizMessageDataArray arrayMessage;
foreach (QListWidgetItem* it, items) {
if (CWizDocumentListViewItem* pItem = dynamic_cast<CWizDocumentListViewItem*>(it)) {
if (pItem->type() == CWizDocumentListViewItem::MessageDocument) {
arrayMessage.push_back(pItem->message());
}
}
}
// 1 means read
m_dbMgr.db().setMessageReadStatus(arrayMessage, 1);
}
void CWizDocumentListView::on_action_message_delete()
{
QList<QListWidgetItem*> items = selectedItems();
foreach (QListWidgetItem* it, items) {
if (CWizDocumentListViewItem* pItem = dynamic_cast<CWizDocumentListViewItem*>(it)) {
if (pItem->type() == CWizDocumentListViewItem::MessageDocument) {
m_dbMgr.db().deleteMessageEx(pItem->message());
}
}
}
}
void CWizDocumentListView::on_action_selectTags()
{
QList<QListWidgetItem*> items = selectedItems();
if (items.isEmpty())
return;
if (CWizDocumentListViewItem* item = dynamic_cast<CWizDocumentListViewItem*>(items.at(0)))
{
Q_UNUSED(item);
if (!m_tagList)
{
m_tagList = new CWizTagListWidget(m_dbMgr, this);
m_tagList->setLeftAlign(true);
}
m_tagList->setDocument(item->document());
m_tagList->showAtPoint(QCursor::pos());
}
}
void CWizDocumentListView::on_action_deleteDocument()
{
QList<QListWidgetItem*> items = selectedItems();
foreach (QListWidgetItem* it, items) {
if (CWizDocumentListViewItem* item = dynamic_cast<CWizDocumentListViewItem*>(it)) {
if (item->type() == CWizDocumentListViewItem::MessageDocument) {
continue;
}
CWizDocument doc(m_dbMgr.db(item->document().strKbGUID), item->document());
doc.Delete();
}
}
}
void CWizDocumentListView::on_action_moveDocument()
{
CWizFolderSelector* selector = new CWizFolderSelector("Move documents", m_app, this);
selector->setAcceptRoot(false);
connect(selector, SIGNAL(finished(int)), SLOT(on_action_moveDocument_confirmed(int)));
selector->open();
}
void CWizDocumentListView::on_action_moveDocument_confirmed(int result)
{
CWizFolderSelector* selector = qobject_cast<CWizFolderSelector*>(sender());
QString strSelectedFolder = selector->selectedFolder();
sender()->deleteLater();
if (result != QDialog::Accepted) {
return;
}
if (strSelectedFolder.isEmpty()) {
return;
}
// collect documents
CWizDocumentDataArray arrayDocument;
QList<QListWidgetItem*> items = selectedItems();
foreach (QListWidgetItem* it, items) {
if (CWizDocumentListViewItem* item = dynamic_cast<CWizDocumentListViewItem*>(it)) {
arrayDocument.push_back(item->document());
}
}
// only move user private documents
if (isDocumentsWithGroupDocument(arrayDocument)) {
TOLOG("on_action_moveDocument_confirmed: selected documents with group document!");
return;
}
// move, show progress if size > 3
CWizFolder folder(m_dbMgr.db(), strSelectedFolder);
if (arrayDocument.size() <= 3) {
foreach (const WIZDOCUMENTDATAEX& data, arrayDocument) {
CWizDocument doc(m_dbMgr.db(), data);
doc.MoveDocument(&folder);
}
} else {
MainWindow* mainWindow = qobject_cast<MainWindow*>(m_app.mainWindow());
CWizProgressDialog* progress = mainWindow->progressDialog();
int i = 0;
foreach (const WIZDOCUMENTDATAEX& data, arrayDocument) {
CWizDocument doc(m_dbMgr.db(), data);
doc.MoveDocument(&folder);
progress->setActionString(tr("Move Document: %1 to %2").arg(data.strLocation).arg(strSelectedFolder));
progress->setNotifyString(data.strTitle);
progress->setProgress(arrayDocument.size(), i);
progress->open();
i++;
}
// hide progress dialog
mainWindow->progressDialog()->hide();
}
}
void CWizDocumentListView::on_action_copyDocument()
{
CWizFolderSelector* selector = new CWizFolderSelector("Copy documents", m_app, this);
selector->setCopyStyle();
selector->setAcceptRoot(false);
connect(selector, SIGNAL(finished(int)), SLOT(on_action_copyDocument_confirmed(int)));
selector->open();
}
void CWizDocumentListView::on_action_copyDocument_confirmed(int result)
{
CWizFolderSelector* selector = qobject_cast<CWizFolderSelector*>(sender());
QString strSelectedFolder = selector->selectedFolder();
sender()->deleteLater();
if (strSelectedFolder.isEmpty()) {
return;
}
if (result == QDialog::Accepted) {
qDebug() << "user select: " << strSelectedFolder;
}
}
void CWizDocumentListView::on_action_encryptDocument()
{
QList<QListWidgetItem*> items = selectedItems();
foreach (QListWidgetItem* it, items) {
if (CWizDocumentListViewItem* item = dynamic_cast<CWizDocumentListViewItem*>(it)) {
CWizDocument doc(m_dbMgr.db(), item->document());
doc.encryptDocument();
}
}
}
int CWizDocumentListView::documentIndexFromGUID(const QString& strGUID)
{
for (int i = 0; i < count(); i++) {
if (CWizDocumentListViewItem *pItem = documentItemAt(i)) {
if (!pItem->document().strGUID.isEmpty() && pItem->document().strGUID == strGUID) {
return i;
} else if (!pItem->message().documentGUID.isEmpty()
&& pItem->message().documentGUID == strGUID) {
return i;
}
}
}
return -1;
}
CWizDocumentListViewItem *CWizDocumentListView::documentItemAt(int index)
{
return dynamic_cast<CWizDocumentListViewItem*>(item(index));
}
CWizDocumentListViewItem *CWizDocumentListView::documentItemFromIndex(const QModelIndex &index) const
{
return dynamic_cast<CWizDocumentListViewItem*>(itemFromIndex(index));
}
const WIZMESSAGEDATA& CWizDocumentListView::messageFromIndex(const QModelIndex& index) const
{
return documentItemFromIndex(index)->message();
}
const QImage& CWizDocumentListView::messageSenderAvatarFromIndex(const QModelIndex& index) const
{
return documentItemFromIndex(index)->avatar(m_dbMgr.db(), *m_avatarDownloader);
}
const WIZDOCUMENTDATA& CWizDocumentListView::documentFromIndex(const QModelIndex &index) const
{
return documentItemFromIndex(index)->document();
}
const WIZABSTRACT& CWizDocumentListView::documentAbstractFromIndex(const QModelIndex &index) const
{
return documentItemFromIndex(index)->abstract(*m_thumbCache);
}
const QString& CWizDocumentListView::documentTagsFromIndex(const QModelIndex &index) const
{
return documentItemFromIndex(index)->tags(m_dbMgr.db());
}
//#ifndef Q_OS_MAC
//void CWizDocumentListView::updateGeometries()
//{
// QListWidget::updateGeometries();
//
// // singleStep will initialized to item height(94 pixel), reset it
// verticalScrollBar()->setSingleStep(1);
//}
void CWizDocumentListView::wheelEvent(QWheelEvent* event)
{
//if (event->orientation() == Qt::Vertical) {
//vscrollBeginUpdate(event->delta());
//return;
//}
//#ifdef Q_OS_MAC
// QWheelEvent* wEvent = new QWheelEvent(event->pos(),
// event->globalPos(),
// event->delta()/2,
// event->buttons(),
// event->modifiers(),
// event->orientation());
//#endif
QListWidget::wheelEvent(event);
}
void CWizDocumentListView::vscrollBeginUpdate(int delta)
{
//if (m_vscrollDelta > 0) {
// if (delta > 0 && delta < m_vscrollDelta) {
// return;
// }
//}
//
//if (m_vscrollDelta < 0) {
// if (delta > m_vscrollDelta && delta < 0) {
// return;
// }
//}
//m_vscrollDelta = delta;
//qDebug() << "start:" << m_vscrollDelta;
if (!m_scrollAnimation) {
m_scrollAnimation = new QPropertyAnimation();
m_scrollAnimation->setDuration(300);
m_scrollAnimation->setTargetObject(verticalScrollBar());
m_scrollAnimation->setEasingCurve(QEasingCurve::Linear);
connect(m_scrollAnimation, SIGNAL(valueChanged(const QVariant&)), SLOT(on_vscrollAnimation_valueChanged(const QVariant&)));
connect(m_scrollAnimation, SIGNAL(finished()), SLOT(on_vscrollAnimation_finished()));
}
if (delta > 0) {
m_scrollAnimation->setStartValue(0);
m_scrollAnimation->setEndValue(delta);
} else {
m_scrollAnimation->setStartValue(delta);
m_scrollAnimation->setEndValue(0);
}
m_scrollAnimation->start();
}
void CWizDocumentListView::on_vscrollAnimation_valueChanged(const QVariant& value)
{
QPropertyAnimation* animation = qobject_cast<QPropertyAnimation *>(sender());
QScrollBar* scrollBar = qobject_cast<QScrollBar *>(animation->targetObject());
int delta = value.toInt();
//if (qAbs(delta) > m_vscrollCurrent) {
// qDebug() << "change:" << delta;
scrollBar->setValue(scrollBar->value() - delta/8);
// m_vscrollCurrent += qAbs(delta);
//} else {
// animation->stop();
//}
}
void CWizDocumentListView::on_vscrollAnimation_finished()
{
QPropertyAnimation* animation = qobject_cast<QPropertyAnimation *>(sender());
qDebug() << "end:" << animation->startValue() << ":" << animation->endValue();
//reset
//m_vscrollDelta = 0;
//m_vscrollCurrent = 0;
}
void CWizDocumentListView::on_vscroll_update()
{
// scroll animation stop condition
//if (qAbs(m_vscrollDelta) > m_vscrollCurrent) {
// verticalScrollBar()->setValue(m_vscrollOldPos - m_vscrollDelta/2);
// m_vscrollCurrent += qAbs(m_vscrollDelta/2);
//} else {
// m_vscrollTimer.stop();
//}
}
void CWizDocumentListView::on_vscroll_valueChanged(int value)
{
m_vscrollOldPos = value;
}
void CWizDocumentListView::on_vscroll_actionTriggered(int action)
{
switch (action) {
case QAbstractSlider::SliderSingleStepAdd:
vscrollBeginUpdate(-120);
break;
case QAbstractSlider::SliderSingleStepSub:
vscrollBeginUpdate(120);
break;
default:
return;
}
}
//#endif // Q_OS_MAC
|
#ifndef BLOCKORIENTEDDATAMAPPER_H
#define BLOCKORIENTEDDATAMAPPER_H
#include "Definitions.h"
#include "SpaceDefinition.h"
#include "IDataPersistenceHandler.h"
#include "SpaceMappedDataPersistenceHandler.h"
namespace Utilities
{
template<typename T>
class BlockOrientedDataMapper
{
public:
BlockOrientedDataMapper() = delete;
BlockOrientedDataMapper(Space const& spaceIn, std::shared_ptr<IDataPersistenceHandler<_storage3D<T>>>& handlerIn,
std::string const& storageRootIn, int lbX, int lbY, int lbZ);
virtual ~BlockOrientedDataMapper();
Utilities::_storage3D<T>* GetBlockData(int blckX, int blckY, int blckZ);
void PutBlockData(Utilities::_storage3D<T>* data);
protected:
private:
Space _mappedToSpace;
int _infX;
int _infY;
int _infZ;
std::shared_ptr<SpaceMappedDataPersistenceHandler<T>> _dataHandler;
};
template<typename T>
BlockOrientedDataMapper<T>::BlockOrientedDataMapper(Space const& spaceIn, std::shared_ptr<IDataPersistenceHandler<_storage3D<T>>>& handlerIn,
std::string const& storageRootIn, int lbX, int lbY, int lbZ)
: _mappedToSpace {spaceIn}, _infX {lbX}, _infY {lbY}, _infZ {lbZ}, _dataHandler {nullptr}
{
if(std::abs(_infX) > _mappedToSpace.blockDimX()
|| std::abs(_infY) > _mappedToSpace.blockDimY()
|| std::abs(_infZ) > _mappedToSpace.blockDimZ())
{
throw std::invalid_argument("At least one lower bound for the data mapper is out of the boundaries of the space");
}
_dataHandler.reset(new SpaceMappedDataPersistenceHandler<T>(spaceIn, handlerIn, storageRootIn));
}
template<typename T>
BlockOrientedDataMapper<T>::~BlockOrientedDataMapper()
{
//dtor
}
template<typename T>
Utilities::_storage3D<T>* BlockOrientedDataMapper<T>::GetBlockData(int blckX, int blckY, int blckZ)
{
blckX += (-1 * _infX);
blckY += (-1 * _infY);
blckZ += (-1 * _infZ);
return _dataHandler->GetBlockData(blckX, blckY, blckZ);
}
template<typename T>
void BlockOrientedDataMapper<T>::PutBlockData(Utilities::_storage3D<T>* data)
{
_dataHandler->PutBlockData(data);
}
}
#endif // BLOCKORIENTEDDATAMAPPER_H
|
#include <cmath>
#include <cstdio>
#include <ctime>
#include <iostream>
#include <queue>
using namespace std;
typedef long long ll;
const int INF = 0x7fffffff;
#define HB pair<Treap*, Treap*>
#define siz(v) ((v) ? ((v)->size) : 0)
struct Treap {
int prior, data, size;
Treap *lc, *rc;
Treap() {}
Treap(int _data) : data(_data), prior(rand()), size(1), lc(NULL), rc(NULL) {}
inline void update() { size = 1 + siz(lc) + siz(rc); }
}* root = NULL;
// 将以v为根的树中前k个元素分裂出来,得到两棵树
HB split(Treap* v, int k) {
if (!v)
return HB(NULL, NULL);
HB hb;
if (k <= siz(v->lc)) {
hb = split(v->lc, k);
v->lc = hb.second;
v->update();
hb.second = v;
} else {
hb = split(v->rc, k - siz(v->lc) - 1);
v->rc = hb.first;
v->update();
hb.first = v;
}
return hb;
}
// 将以u为根和以v为根的树合并(默认u中的元素都小于v)
Treap* merge(Treap* u, Treap* v) {
if (!u)
return v;
if (!v)
return u;
if (u->prior > v->prior) {
u->rc = merge(u->rc, v);
u->update();
return u;
} else {
v->lc = merge(u, v->lc);
v->update();
return v;
}
}
// 查询排名为k的数(注意传引用)
int ranc(Treap*& v, int k) {
if (!v)
return 0;
HB x = split(v, k - 1);
HB y = split(x.second, 1);
v = merge(x.first, merge(y.first, y.second));
return y.first->data;
}
// 查询key的排名
int find(Treap* v, int key) {
if (!v)
return 1;
if (key <= v->data)
return find(v->lc, key);
return siz(v->lc) + 1 + find(v->rc, key);
}
// 插入key(注意传引用)
void insert(Treap*& v, int key) {
HB hb = split(v, find(v, key) - 1);
v = merge(hb.first, merge(new Treap(key), hb.second));
}
// 删除key(注意传引用)
void remove(Treap*& v, int key) {
HB x = split(v, find(v, key) - 1);
HB y = split(x.second, 1);
if (y.first->data != key)
v = merge(x.first, merge(y.first, y.second));
else
v = merge(x.first, y.second);
}
// 查询比key小的最大数
int prec(int key) { return ranc(root, find(root, key) - 1); }
// 查询比key大的最小数
int succ(int key) { return ranc(root, find(root, key + 1)); }
// --------------------------------------------------------------------------
struct PN {
int lev;
Treap *p, *v;
PN() {}
PN(int _lev, Treap* _p, Treap* _v) : lev(_lev), p(_p), v(_v) {}
};
void print(int i) {
puts("");
printf("line %d:\n", i);
queue<PN> q;
q.push(PN(1, NULL, root));
int pre = 0;
while (!q.empty()) {
PN pn = q.front();
q.pop();
if (pn.v) {
pre == pn.lev ? printf("\t%d\t%d\t%d\n", pn.p ? pn.p->data : -1, pn.v->data, pn.v->size)
: printf("%d:\t%d\t%d\t%d\n", pre = pn.lev, pn.p ? pn.p->data : -1, pn.v->data, pn.v->size);
q.push(PN(pn.lev + 1, pn.v, pn.v->lc));
q.push(PN(pn.lev + 1, pn.v, pn.v->rc));
}
}
fflush(stdout);
}
// #define DEBUG
int main() {
#ifdef DEBUG
freopen("d:\\.in", "r", stdin);
freopen("d:\\.out", "w", stdout);
#endif
srand((unsigned int)time(NULL));
int n, t, x;
scanf("%d", &n);
for (int i = 2; i <= n + 1; ++i) {
scanf("%d%d", &t, &x);
// print(i);
switch (t) {
case 1:
insert(root, x);
break;
case 2:
remove(root, x);
break;
case 3:
printf("%d\n", find(root, x));
break;
case 4:
printf("%d\n", ranc(root, x));
break;
case 5:
printf("%d\n", prec(x));
break;
case 6:
printf("%d\n", succ(x));
break;
}
}
return 0;
}
|
/* Đề bài:
Mô tả Bài toán:
Giả sử chúng ta muốn biết quả của phép lũy thừa A ^ B. Tuy nhiên, bởi vì kết quả phép
lũy thừa trên có thể là một con số rất lớn, nên chúng ta sẽ thực hiện một phép chia
lấy dư với C. Bạn hãy viết chương trình tìm số dư đó.
Mô tả Input:
- Dòng đầu tiên sẽ là ba số nguyên dương A, B, C có giá trị nhỏ hơn 2,147,483,647.
Mô tả Output:
- Kết quả phần dư sau khi thực hiện phép chia giữa A ^ B và C.
Minh họa Input:
2 10 1000
Minh họa Output:
24
*/
// Copyright (C) Quoc Nguyen
// _ ____ __ _ _ __
// (_/_(_(_(_)(__ / (_(_/_(_(_(_/__(/_/ (_
// /( .-/ .-/
// (_) (_/ (_/
#include <iostream>
using namespace std;
long TimSoDu(int a, int b, int c)
{
if (b == 0)
return 1;
else
{
if (b % 2 != 0)
return (a * TimSoDu(a, b - 1, c)) % c;
else
return (TimSoDu(a, b / 2, c) * TimSoDu(a, b / 2, c)) % c;
}
}
void NhapBaSo(int &a, int &b, int &c)
{
cin >> a; cin >> b; cin >> c;
}
int main()
{
int a, b, c;
NhapBaSo(a, b, c);
cout << TimSoDu(a, b, c);
return 0;
}
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll get_div(ll n)
{
if(n==1)
return 1;
for(int i=2;i*i<=n;i++)
{
if(n%i==0)
return i;
}
return n;
}
int main()
{
int t;
cin>>t;
while(t--)
{
ll n,k,i=1;
cin>>n>>k;
for(i=1;i<=k;i++)
{
n=n+get_div(n);
if(n%2==0)
break;
}
n+=2*(k-i);
cout<<n<<"\n";
}
}
|
//
// SMImageEditorStickerListView.h
// iPet
//
// Created by KimSteve on 2017. 5. 22..
// Copyright © 2017년 KimSteve. All rights reserved.
//
#ifndef SMImageEditorStickerListView_h
#define SMImageEditorStickerListView_h
#include "../../SMFrameWork/Base/SMTableView.h"
#include <cocos2d.h>
#include "ItemInfo.h"
#include <vector>
class ItemListView;
class SMImageEditorItemThumbView;
class SMSlider;
class OnItemClickListener {
public:
virtual void onItemClick(ItemListView* sender, SMImageEditorItemThumbView * view) = 0;
};
class ItemListView : public SMTableView, public OnClickListener
{
public:
static const std::string ITEMS;
static const std::string THUMB;
static const std::string NAME;
static const std::string IMG_EXTEND;
static const std::string IMAGE;
static const std::string LAYOUT;
virtual void show();
virtual void hide();
virtual void onEnter() override;
virtual void onExit() override;
void setOnItemClickListener(OnItemClickListener * l){_listener=l;};
virtual void onClick(SMView * view) override;
std::string getResourceRootPath() {return _resourceRootPath;};
virtual void setVisible(bool visible) override;
protected:
ItemListView();
virtual ~ItemListView();
virtual bool initLayout();
virtual bool initLoadItemList();
protected:
bool _initLoaded;
cocos2d::ValueMap _dict;
OnItemClickListener * _listener;
std::string _resourceRootPath;
int _itemSize;
};
class SMImageEditorStickerItemListView : public ItemListView
{
public:
static SMImageEditorStickerItemListView* create();
virtual void show() override;
StickerItem* findItem(const std::string& name);
StickerItem* getItem(const int index);
protected:
SMImageEditorStickerItemListView();
virtual ~SMImageEditorStickerItemListView();
virtual bool initLayout() override;
virtual bool initLoadItemList() override;
cocos2d::Node * getView(const IndexPath& indexPath);
int getItemCount(int section);
bool parseStickerItem(StickerItem& item, int index);
std::vector<StickerItem> _items;
};
#endif /* SMImageEditorStickerListView_h */
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.