blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 986
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 23
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 145
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 122
values | content
stringlengths 3
10.4M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
798e8e1d5ef593ec79fd33543025e162b12b3f70 | 4c1865d446145b160a3bd5afa9527d3fe918e156 | /test/fixtures/example/hello.cc | 767cf503e22436f88b67cc3ed8eb6c6695af0448 | [
"MIT"
] | permissive | webpack-contrib/node-loader | d153dd54cf18f401fdb7161235b489bf028079f6 | 2e556b34d9cc4d9fc7b0814d1482491bed15f357 | refs/heads/master | 2023-08-28T06:48:09.434846 | 2023-06-04T13:43:46 | 2023-06-04T13:43:46 | 8,218,682 | 114 | 38 | MIT | 2023-09-10T00:35:21 | 2013-02-15T13:23:37 | JavaScript | UTF-8 | C++ | false | false | 676 | cc | #include <assert.h>
#include <node_api.h>
napi_value Method(napi_env env, napi_callback_info info) {
napi_status status;
napi_value world;
status = napi_create_string_utf8(env, "world", 5, &world);
assert(status == napi_ok);
return world;
}
#define DECLARE_NAPI_METHOD(name, func) \
{ name, 0, func, 0, 0, 0, napi_default, 0 }
napi_value Init(napi_env env, napi_value exports) {
napi_status status;
napi_property_descriptor desc = DECLARE_NAPI_METHOD("hello", Method);
status = napi_define_properties(env, exports, 1, &desc);
assert(status == napi_ok);
return exports;
}
NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)
| [
"[email protected]"
] | |
6f1bf2d16b46f790d645ea38104d80a8602f982f | ce9bd4b9eef50a903253db4b4cf4878b9e42b61a | /3rdParty/DirectXTex/DirectXTex/DirectXTexCompress.cpp | 3e28c65a6494bfb2592de3f860b28896d297fd3d | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | sahwar/pdn-ddsfiletype-plus | f2a8399cef2d7f97cf59baa7a77aa158ef537ab0 | 562d004a5fc60dde58d25181590088dec0df82ac | refs/heads/master | 2020-04-14T05:45:21.378128 | 2018-12-31T10:51:42 | 2018-12-31T10:51:42 | 163,668,025 | 1 | 0 | MIT | 2018-12-31T12:39:52 | 2018-12-31T12:39:52 | null | UTF-8 | C++ | false | false | 29,365 | cpp | //-------------------------------------------------------------------------------------
// DirectXTexCompress.cpp
//
// DirectX Texture Library - Texture compression
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkId=248926
//-------------------------------------------------------------------------------------
#include "DirectXTexp.h"
#ifdef _OPENMP
#include <omp.h>
#pragma warning(disable : 4616 6993)
#endif
#include "bc.h"
using namespace DirectX;
namespace
{
inline DWORD GetBCFlags(_In_ DWORD compress)
{
static_assert(static_cast<int>(TEX_COMPRESS_RGB_DITHER) == static_cast<int>(BC_FLAGS_DITHER_RGB), "TEX_COMPRESS_* flags should match BC_FLAGS_*");
static_assert(static_cast<int>(TEX_COMPRESS_A_DITHER) == static_cast<int>(BC_FLAGS_DITHER_A), "TEX_COMPRESS_* flags should match BC_FLAGS_*");
static_assert(static_cast<int>(TEX_COMPRESS_DITHER) == static_cast<int>(BC_FLAGS_DITHER_RGB | BC_FLAGS_DITHER_A), "TEX_COMPRESS_* flags should match BC_FLAGS_*");
static_assert(static_cast<int>(TEX_COMPRESS_UNIFORM) == static_cast<int>(BC_FLAGS_UNIFORM), "TEX_COMPRESS_* flags should match BC_FLAGS_*");
static_assert(static_cast<int>(TEX_COMPRESS_BC7_USE_3SUBSETS) == static_cast<int>(BC_FLAGS_USE_3SUBSETS), "TEX_COMPRESS_* flags should match BC_FLAGS_*");
static_assert(static_cast<int>(TEX_COMPRESS_BC7_QUICK) == static_cast<int>(BC_FLAGS_FORCE_BC7_MODE6), "TEX_COMPRESS_* flags should match BC_FLAGS_*");
return (compress & (BC_FLAGS_DITHER_RGB | BC_FLAGS_DITHER_A | BC_FLAGS_UNIFORM | BC_FLAGS_USE_3SUBSETS | BC_FLAGS_FORCE_BC7_MODE6));
}
inline DWORD GetSRGBFlags(_In_ DWORD compress)
{
static_assert(static_cast<int>(TEX_COMPRESS_SRGB_IN) == static_cast<int>(TEX_FILTER_SRGB_IN), "TEX_COMPRESS_SRGB* should match TEX_FILTER_SRGB*");
static_assert(static_cast<int>(TEX_COMPRESS_SRGB_OUT) == static_cast<int>(TEX_FILTER_SRGB_OUT), "TEX_COMPRESS_SRGB* should match TEX_FILTER_SRGB*");
static_assert(static_cast<int>(TEX_COMPRESS_SRGB) == static_cast<int>(TEX_FILTER_SRGB), "TEX_COMPRESS_SRGB* should match TEX_FILTER_SRGB*");
return (compress & TEX_COMPRESS_SRGB);
}
inline bool DetermineEncoderSettings(_In_ DXGI_FORMAT format, _Out_ BC_ENCODE& pfEncode, _Out_ size_t& blocksize, _Out_ DWORD& cflags)
{
switch (format)
{
case DXGI_FORMAT_BC1_UNORM:
case DXGI_FORMAT_BC1_UNORM_SRGB: pfEncode = nullptr; blocksize = 8; cflags = 0; break;
case DXGI_FORMAT_BC2_UNORM:
case DXGI_FORMAT_BC2_UNORM_SRGB: pfEncode = D3DXEncodeBC2; blocksize = 16; cflags = 0; break;
case DXGI_FORMAT_BC3_UNORM:
case DXGI_FORMAT_BC3_UNORM_SRGB: pfEncode = D3DXEncodeBC3; blocksize = 16; cflags = 0; break;
case DXGI_FORMAT_BC4_UNORM: pfEncode = D3DXEncodeBC4U; blocksize = 8; cflags = TEX_FILTER_RGB_COPY_RED; break;
case DXGI_FORMAT_BC4_SNORM: pfEncode = D3DXEncodeBC4S; blocksize = 8; cflags = TEX_FILTER_RGB_COPY_RED; break;
case DXGI_FORMAT_BC5_UNORM: pfEncode = D3DXEncodeBC5U; blocksize = 16; cflags = TEX_FILTER_RGB_COPY_RED | TEX_FILTER_RGB_COPY_GREEN; break;
case DXGI_FORMAT_BC5_SNORM: pfEncode = D3DXEncodeBC5S; blocksize = 16; cflags = TEX_FILTER_RGB_COPY_RED | TEX_FILTER_RGB_COPY_GREEN; break;
case DXGI_FORMAT_BC6H_UF16: pfEncode = D3DXEncodeBC6HU; blocksize = 16; cflags = 0; break;
case DXGI_FORMAT_BC6H_SF16: pfEncode = D3DXEncodeBC6HS; blocksize = 16; cflags = 0; break;
case DXGI_FORMAT_BC7_UNORM:
case DXGI_FORMAT_BC7_UNORM_SRGB: pfEncode = D3DXEncodeBC7; blocksize = 16; cflags = 0; break;
default: pfEncode = nullptr; blocksize = 0; cflags = 0; return false;
}
return true;
}
//-------------------------------------------------------------------------------------
HRESULT CompressBC(
const Image& image,
const Image& result,
DWORD bcflags,
DWORD srgb,
float threshold)
{
if (!image.pixels || !result.pixels)
return E_POINTER;
assert(image.width == result.width);
assert(image.height == result.height);
const DXGI_FORMAT format = image.format;
size_t sbpp = BitsPerPixel(format);
if (!sbpp)
return E_FAIL;
if (sbpp < 8)
{
// We don't support compressing from monochrome (DXGI_FORMAT_R1_UNORM)
return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);
}
// Round to bytes
sbpp = (sbpp + 7) / 8;
uint8_t *pDest = result.pixels;
// Determine BC format encoder
BC_ENCODE pfEncode;
size_t blocksize;
DWORD cflags;
if (!DetermineEncoderSettings(result.format, pfEncode, blocksize, cflags))
return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);
__declspec(align(16)) XMVECTOR temp[16];
const uint8_t *pSrc = image.pixels;
const uint8_t *pEnd = image.pixels + image.slicePitch;
const size_t rowPitch = image.rowPitch;
for (size_t h = 0; h < image.height; h += 4)
{
const uint8_t *sptr = pSrc;
uint8_t* dptr = pDest;
size_t ph = std::min<size_t>(4, image.height - h);
size_t w = 0;
for (size_t count = 0; (count < result.rowPitch) && (w < image.width); count += blocksize, w += 4)
{
size_t pw = std::min<size_t>(4, image.width - w);
assert(pw > 0 && ph > 0);
ptrdiff_t bytesLeft = pEnd - sptr;
assert(bytesLeft > 0);
size_t bytesToRead = std::min<size_t>(rowPitch, bytesLeft);
if (!_LoadScanline(&temp[0], pw, sptr, bytesToRead, format))
return E_FAIL;
if (ph > 1)
{
bytesToRead = std::min<size_t>(rowPitch, bytesLeft - rowPitch);
if (!_LoadScanline(&temp[4], pw, sptr + rowPitch, bytesToRead, format))
return E_FAIL;
if (ph > 2)
{
bytesToRead = std::min<size_t>(rowPitch, bytesLeft - rowPitch * 2);
if (!_LoadScanline(&temp[8], pw, sptr + rowPitch * 2, bytesToRead, format))
return E_FAIL;
if (ph > 3)
{
bytesToRead = std::min<size_t>(rowPitch, bytesLeft - rowPitch * 3);
if (!_LoadScanline(&temp[12], pw, sptr + rowPitch * 3, bytesToRead, format))
return E_FAIL;
}
}
}
if (pw != 4 || ph != 4)
{
// Replicate pixels for partial block
static const size_t uSrc[] = { 0, 0, 0, 1 };
if (pw < 4)
{
for (size_t t = 0; t < ph && t < 4; ++t)
{
for (size_t s = pw; s < 4; ++s)
{
#pragma prefast(suppress: 26000, "PREFAST false positive")
temp[(t << 2) | s] = temp[(t << 2) | uSrc[s]];
}
}
}
if (ph < 4)
{
for (size_t t = ph; t < 4; ++t)
{
for (size_t s = 0; s < 4; ++s)
{
#pragma prefast(suppress: 26000, "PREFAST false positive")
temp[(t << 2) | s] = temp[(uSrc[t] << 2) | s];
}
}
}
}
_ConvertScanline(temp, 16, result.format, format, cflags | srgb);
if (pfEncode)
pfEncode(dptr, temp, bcflags);
else
D3DXEncodeBC1(dptr, temp, threshold, bcflags);
sptr += sbpp * 4;
dptr += blocksize;
}
pSrc += rowPitch * 4;
pDest += result.rowPitch;
}
return S_OK;
}
//-------------------------------------------------------------------------------------
#ifdef _OPENMP
HRESULT CompressBC_Parallel(
const Image& image,
const Image& result,
DWORD bcflags,
DWORD srgb,
float threshold)
{
if (!image.pixels || !result.pixels)
return E_POINTER;
assert(image.width == result.width);
assert(image.height == result.height);
const DXGI_FORMAT format = image.format;
size_t sbpp = BitsPerPixel(format);
if (!sbpp)
return E_FAIL;
if (sbpp < 8)
{
// We don't support compressing from monochrome (DXGI_FORMAT_R1_UNORM)
return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);
}
// Round to bytes
sbpp = (sbpp + 7) / 8;
const uint8_t *pEnd = image.pixels + image.slicePitch;
// Determine BC format encoder
BC_ENCODE pfEncode;
size_t blocksize;
DWORD cflags;
if (!DetermineEncoderSettings(result.format, pfEncode, blocksize, cflags))
return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);
// Refactored version of loop to support parallel independance
const size_t nBlocks = std::max<size_t>(1, (image.width + 3) / 4) * std::max<size_t>(1, (image.height + 3) / 4);
bool fail = false;
#pragma omp parallel for
for (int nb = 0; nb < static_cast<int>(nBlocks); ++nb)
{
int nbWidth = std::max<int>(1, int((image.width + 3) / 4));
int y = nb / nbWidth;
int x = (nb - (y*nbWidth)) * 4;
y *= 4;
assert((x >= 0) && (x < int(image.width)));
assert((y >= 0) && (y < int(image.height)));
size_t rowPitch = image.rowPitch;
const uint8_t *pSrc = image.pixels + (y*rowPitch) + (x*sbpp);
uint8_t *pDest = result.pixels + (nb*blocksize);
size_t ph = std::min<size_t>(4, image.height - y);
size_t pw = std::min<size_t>(4, image.width - x);
assert(pw > 0 && ph > 0);
ptrdiff_t bytesLeft = pEnd - pSrc;
assert(bytesLeft > 0);
size_t bytesToRead = std::min<size_t>(rowPitch, bytesLeft);
__declspec(align(16)) XMVECTOR temp[16];
if (!_LoadScanline(&temp[0], pw, pSrc, bytesToRead, format))
fail = true;
if (ph > 1)
{
bytesToRead = std::min<size_t>(rowPitch, bytesLeft - rowPitch);
if (!_LoadScanline(&temp[4], pw, pSrc + rowPitch, bytesToRead, format))
fail = true;
if (ph > 2)
{
bytesToRead = std::min<size_t>(rowPitch, bytesLeft - rowPitch * 2);
if (!_LoadScanline(&temp[8], pw, pSrc + rowPitch * 2, bytesToRead, format))
fail = true;
if (ph > 3)
{
bytesToRead = std::min<size_t>(rowPitch, bytesLeft - rowPitch * 3);
if (!_LoadScanline(&temp[12], pw, pSrc + rowPitch * 3, bytesToRead, format))
fail = true;
}
}
}
if (pw != 4 || ph != 4)
{
// Replicate pixels for partial block
static const size_t uSrc[] = { 0, 0, 0, 1 };
if (pw < 4)
{
for (size_t t = 0; t < ph && t < 4; ++t)
{
for (size_t s = pw; s < 4; ++s)
{
temp[(t << 2) | s] = temp[(t << 2) | uSrc[s]];
}
}
}
if (ph < 4)
{
for (size_t t = ph; t < 4; ++t)
{
for (size_t s = 0; s < 4; ++s)
{
temp[(t << 2) | s] = temp[(uSrc[t] << 2) | s];
}
}
}
}
_ConvertScanline(temp, 16, result.format, format, cflags | srgb);
if (pfEncode)
pfEncode(pDest, temp, bcflags);
else
D3DXEncodeBC1(pDest, temp, threshold, bcflags);
}
return (fail) ? E_FAIL : S_OK;
}
#endif // _OPENMP
//-------------------------------------------------------------------------------------
DXGI_FORMAT DefaultDecompress(_In_ DXGI_FORMAT format)
{
switch (format)
{
case DXGI_FORMAT_BC1_TYPELESS:
case DXGI_FORMAT_BC1_UNORM:
case DXGI_FORMAT_BC2_TYPELESS:
case DXGI_FORMAT_BC2_UNORM:
case DXGI_FORMAT_BC3_TYPELESS:
case DXGI_FORMAT_BC3_UNORM:
case DXGI_FORMAT_BC7_TYPELESS:
case DXGI_FORMAT_BC7_UNORM:
return DXGI_FORMAT_R8G8B8A8_UNORM;
case DXGI_FORMAT_BC1_UNORM_SRGB:
case DXGI_FORMAT_BC2_UNORM_SRGB:
case DXGI_FORMAT_BC3_UNORM_SRGB:
case DXGI_FORMAT_BC7_UNORM_SRGB:
return DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
case DXGI_FORMAT_BC4_TYPELESS:
case DXGI_FORMAT_BC4_UNORM:
return DXGI_FORMAT_R8_UNORM;
case DXGI_FORMAT_BC4_SNORM:
return DXGI_FORMAT_R8_SNORM;
case DXGI_FORMAT_BC5_TYPELESS:
case DXGI_FORMAT_BC5_UNORM:
return DXGI_FORMAT_R8G8_UNORM;
case DXGI_FORMAT_BC5_SNORM:
return DXGI_FORMAT_R8G8_SNORM;
case DXGI_FORMAT_BC6H_TYPELESS:
case DXGI_FORMAT_BC6H_UF16:
case DXGI_FORMAT_BC6H_SF16:
// We could use DXGI_FORMAT_R32G32B32_FLOAT here since BC6H is always Alpha 1.0,
// but this format is more supported by viewers
return DXGI_FORMAT_R32G32B32A32_FLOAT;
default:
return DXGI_FORMAT_UNKNOWN;
}
}
//-------------------------------------------------------------------------------------
HRESULT DecompressBC(_In_ const Image& cImage, _In_ const Image& result)
{
if (!cImage.pixels || !result.pixels)
return E_POINTER;
assert(cImage.width == result.width);
assert(cImage.height == result.height);
const DXGI_FORMAT format = result.format;
size_t dbpp = BitsPerPixel(format);
if (!dbpp)
return E_FAIL;
if (dbpp < 8)
{
// We don't support decompressing to monochrome (DXGI_FORMAT_R1_UNORM)
return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);
}
// Round to bytes
dbpp = (dbpp + 7) / 8;
uint8_t *pDest = result.pixels;
if (!pDest)
return E_POINTER;
// Promote "typeless" BC formats
DXGI_FORMAT cformat;
switch (cImage.format)
{
case DXGI_FORMAT_BC1_TYPELESS: cformat = DXGI_FORMAT_BC1_UNORM; break;
case DXGI_FORMAT_BC2_TYPELESS: cformat = DXGI_FORMAT_BC2_UNORM; break;
case DXGI_FORMAT_BC3_TYPELESS: cformat = DXGI_FORMAT_BC3_UNORM; break;
case DXGI_FORMAT_BC4_TYPELESS: cformat = DXGI_FORMAT_BC4_UNORM; break;
case DXGI_FORMAT_BC5_TYPELESS: cformat = DXGI_FORMAT_BC5_UNORM; break;
case DXGI_FORMAT_BC6H_TYPELESS: cformat = DXGI_FORMAT_BC6H_UF16; break;
case DXGI_FORMAT_BC7_TYPELESS: cformat = DXGI_FORMAT_BC7_UNORM; break;
default: cformat = cImage.format; break;
}
// Determine BC format decoder
BC_DECODE pfDecode;
size_t sbpp;
switch (cformat)
{
case DXGI_FORMAT_BC1_UNORM:
case DXGI_FORMAT_BC1_UNORM_SRGB: pfDecode = D3DXDecodeBC1; sbpp = 8; break;
case DXGI_FORMAT_BC2_UNORM:
case DXGI_FORMAT_BC2_UNORM_SRGB: pfDecode = D3DXDecodeBC2; sbpp = 16; break;
case DXGI_FORMAT_BC3_UNORM:
case DXGI_FORMAT_BC3_UNORM_SRGB: pfDecode = D3DXDecodeBC3; sbpp = 16; break;
case DXGI_FORMAT_BC4_UNORM: pfDecode = D3DXDecodeBC4U; sbpp = 8; break;
case DXGI_FORMAT_BC4_SNORM: pfDecode = D3DXDecodeBC4S; sbpp = 8; break;
case DXGI_FORMAT_BC5_UNORM: pfDecode = D3DXDecodeBC5U; sbpp = 16; break;
case DXGI_FORMAT_BC5_SNORM: pfDecode = D3DXDecodeBC5S; sbpp = 16; break;
case DXGI_FORMAT_BC6H_UF16: pfDecode = D3DXDecodeBC6HU; sbpp = 16; break;
case DXGI_FORMAT_BC6H_SF16: pfDecode = D3DXDecodeBC6HS; sbpp = 16; break;
case DXGI_FORMAT_BC7_UNORM:
case DXGI_FORMAT_BC7_UNORM_SRGB: pfDecode = D3DXDecodeBC7; sbpp = 16; break;
default:
return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);
}
__declspec(align(16)) XMVECTOR temp[16];
const uint8_t *pSrc = cImage.pixels;
const size_t rowPitch = result.rowPitch;
for (size_t h = 0; h < cImage.height; h += 4)
{
const uint8_t *sptr = pSrc;
uint8_t* dptr = pDest;
size_t ph = std::min<size_t>(4, cImage.height - h);
size_t w = 0;
for (size_t count = 0; (count < cImage.rowPitch) && (w < cImage.width); count += sbpp, w += 4)
{
pfDecode(temp, sptr);
_ConvertScanline(temp, 16, format, cformat, 0);
size_t pw = std::min<size_t>(4, cImage.width - w);
assert(pw > 0 && ph > 0);
if (!_StoreScanline(dptr, rowPitch, format, &temp[0], pw))
return E_FAIL;
if (ph > 1)
{
if (!_StoreScanline(dptr + rowPitch, rowPitch, format, &temp[4], pw))
return E_FAIL;
if (ph > 2)
{
if (!_StoreScanline(dptr + rowPitch * 2, rowPitch, format, &temp[8], pw))
return E_FAIL;
if (ph > 3)
{
if (!_StoreScanline(dptr + rowPitch * 3, rowPitch, format, &temp[12], pw))
return E_FAIL;
}
}
}
sptr += sbpp;
dptr += dbpp * 4;
}
pSrc += cImage.rowPitch;
pDest += rowPitch * 4;
}
return S_OK;
}
}
//-------------------------------------------------------------------------------------
namespace DirectX
{
bool _IsAlphaAllOpaqueBC(_In_ const Image& cImage)
{
if (!cImage.pixels)
return false;
// Promote "typeless" BC formats
DXGI_FORMAT cformat;
switch (cImage.format)
{
case DXGI_FORMAT_BC1_TYPELESS: cformat = DXGI_FORMAT_BC1_UNORM; break;
case DXGI_FORMAT_BC2_TYPELESS: cformat = DXGI_FORMAT_BC2_UNORM; break;
case DXGI_FORMAT_BC3_TYPELESS: cformat = DXGI_FORMAT_BC3_UNORM; break;
case DXGI_FORMAT_BC7_TYPELESS: cformat = DXGI_FORMAT_BC7_UNORM; break;
default: cformat = cImage.format; break;
}
// Determine BC format decoder
BC_DECODE pfDecode;
size_t sbpp;
switch (cformat)
{
case DXGI_FORMAT_BC1_UNORM:
case DXGI_FORMAT_BC1_UNORM_SRGB: pfDecode = D3DXDecodeBC1; sbpp = 8; break;
case DXGI_FORMAT_BC2_UNORM:
case DXGI_FORMAT_BC2_UNORM_SRGB: pfDecode = D3DXDecodeBC2; sbpp = 16; break;
case DXGI_FORMAT_BC3_UNORM:
case DXGI_FORMAT_BC3_UNORM_SRGB: pfDecode = D3DXDecodeBC3; sbpp = 16; break;
case DXGI_FORMAT_BC7_UNORM:
case DXGI_FORMAT_BC7_UNORM_SRGB: pfDecode = D3DXDecodeBC7; sbpp = 16; break;
default:
// BC4, BC5, and BC6 don't have alpha channels
return false;
}
// Scan blocks for non-opaque alpha
static const XMVECTORF32 threshold = { { { 0.99f, 0.99f, 0.99f, 0.99f } } };
__declspec(align(16)) XMVECTOR temp[16];
const uint8_t *pPixels = cImage.pixels;
for (size_t h = 0; h < cImage.height; h += 4)
{
const uint8_t *ptr = pPixels;
size_t ph = std::min<size_t>(4, cImage.height - h);
size_t w = 0;
for (size_t count = 0; (count < cImage.rowPitch) && (w < cImage.width); count += sbpp, w += 4)
{
pfDecode(temp, ptr);
size_t pw = std::min<size_t>(4, cImage.width - w);
assert(pw > 0 && ph > 0);
if (pw == 4 && ph == 4)
{
// Full blocks
for (size_t j = 0; j < 16; ++j)
{
XMVECTOR alpha = XMVectorSplatW(temp[j]);
if (XMVector4Less(alpha, threshold))
return false;
}
}
else
{
// Handle partial blocks
for (size_t y = 0; y < ph; ++y)
{
for (size_t x = 0; x < pw; ++x)
{
XMVECTOR alpha = XMVectorSplatW(temp[y * 4 + x]);
if (XMVector4Less(alpha, threshold))
return false;
}
}
}
ptr += sbpp;
}
pPixels += cImage.rowPitch;
}
return true;
}
};
//=====================================================================================
// Entry-points
//=====================================================================================
//-------------------------------------------------------------------------------------
// Compression
//-------------------------------------------------------------------------------------
_Use_decl_annotations_
HRESULT DirectX::Compress(
const Image& srcImage,
DXGI_FORMAT format,
DWORD compress,
float threshold,
ScratchImage& image,
ProgressProc progressProc)
{
if (IsCompressed(srcImage.format) || !IsCompressed(format))
return E_INVALIDARG;
if (IsTypeless(format)
|| IsTypeless(srcImage.format) || IsPlanar(srcImage.format) || IsPalettized(srcImage.format))
return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);
// Create compressed image
HRESULT hr = image.Initialize2D(format, srcImage.width, srcImage.height, 1, 1);
if (FAILED(hr))
return hr;
const Image *img = image.GetImage(0, 0, 0);
if (!img)
{
image.Release();
return E_POINTER;
}
if (progressProc)
{
progressProc(0, img->height);
}
// Compress single image
if (compress & TEX_COMPRESS_PARALLEL)
{
#ifndef _OPENMP
return E_NOTIMPL;
#else
hr = CompressBC_Parallel(srcImage, *img, GetBCFlags(compress), GetSRGBFlags(compress), threshold);
#endif // _OPENMP
}
else
{
hr = CompressBC(srcImage, *img, GetBCFlags(compress), GetSRGBFlags(compress), threshold);
}
if (progressProc)
{
progressProc(img->height, img->height);
}
if (FAILED(hr))
image.Release();
return hr;
}
_Use_decl_annotations_
HRESULT DirectX::Compress(
const Image* srcImages,
size_t nimages,
const TexMetadata& metadata,
DXGI_FORMAT format,
DWORD compress,
float threshold,
ScratchImage& cImages,
ProgressProc progressProc)
{
if (!srcImages || !nimages)
return E_INVALIDARG;
if (IsCompressed(metadata.format) || !IsCompressed(format))
return E_INVALIDARG;
if (IsTypeless(format)
|| IsTypeless(metadata.format) || IsPlanar(metadata.format) || IsPalettized(metadata.format))
return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);
cImages.Release();
TexMetadata mdata2 = metadata;
mdata2.format = format;
HRESULT hr = cImages.Initialize(mdata2);
if (FAILED(hr))
return hr;
if (nimages != cImages.GetImageCount())
{
cImages.Release();
return E_FAIL;
}
const Image* dest = cImages.GetImages();
if (!dest)
{
cImages.Release();
return E_POINTER;
}
if (progressProc)
{
progressProc(0, nimages);
}
for (size_t index = 0; index < nimages; ++index)
{
assert(dest[index].format == format);
const Image& src = srcImages[index];
if (src.width != dest[index].width || src.height != dest[index].height)
{
cImages.Release();
return E_FAIL;
}
if ((compress & TEX_COMPRESS_PARALLEL))
{
#ifndef _OPENMP
return E_NOTIMPL;
#else
if (compress & TEX_COMPRESS_PARALLEL)
{
hr = CompressBC_Parallel(src, dest[index], GetBCFlags(compress), GetSRGBFlags(compress), threshold);
if (FAILED(hr))
{
cImages.Release();
return hr;
}
}
#endif // _OPENMP
}
else
{
hr = CompressBC(src, dest[index], GetBCFlags(compress), GetSRGBFlags(compress), threshold);
if (FAILED(hr))
{
cImages.Release();
return hr;
}
}
if (progressProc)
{
progressProc(index, nimages);
}
}
if (progressProc)
{
progressProc(nimages, nimages);
}
return S_OK;
}
//-------------------------------------------------------------------------------------
// Decompression
//-------------------------------------------------------------------------------------
_Use_decl_annotations_
HRESULT DirectX::Decompress(
const Image& cImage,
DXGI_FORMAT format,
ScratchImage& image)
{
if (!IsCompressed(cImage.format) || IsCompressed(format))
return E_INVALIDARG;
if (format == DXGI_FORMAT_UNKNOWN)
{
// Pick a default decompressed format based on BC input format
format = DefaultDecompress(cImage.format);
if (format == DXGI_FORMAT_UNKNOWN)
{
// Input is not a compressed format
return E_INVALIDARG;
}
}
else
{
if (!IsValid(format))
return E_INVALIDARG;
if (IsTypeless(format) || IsPlanar(format) || IsPalettized(format))
return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);
}
// Create decompressed image
HRESULT hr = image.Initialize2D(format, cImage.width, cImage.height, 1, 1);
if (FAILED(hr))
return hr;
const Image *img = image.GetImage(0, 0, 0);
if (!img)
{
image.Release();
return E_POINTER;
}
// Decompress single image
hr = DecompressBC(cImage, *img);
if (FAILED(hr))
image.Release();
return hr;
}
_Use_decl_annotations_
HRESULT DirectX::Decompress(
const Image* cImages,
size_t nimages,
const TexMetadata& metadata,
DXGI_FORMAT format,
ScratchImage& images)
{
if (!cImages || !nimages)
return E_INVALIDARG;
if (!IsCompressed(metadata.format) || IsCompressed(format))
return E_INVALIDARG;
if (format == DXGI_FORMAT_UNKNOWN)
{
// Pick a default decompressed format based on BC input format
format = DefaultDecompress(cImages[0].format);
if (format == DXGI_FORMAT_UNKNOWN)
{
// Input is not a compressed format
return E_FAIL;
}
}
else
{
if (!IsValid(format))
return E_INVALIDARG;
if (IsTypeless(format) || IsPlanar(format) || IsPalettized(format))
return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);
}
images.Release();
TexMetadata mdata2 = metadata;
mdata2.format = format;
HRESULT hr = images.Initialize(mdata2);
if (FAILED(hr))
return hr;
if (nimages != images.GetImageCount())
{
images.Release();
return E_FAIL;
}
const Image* dest = images.GetImages();
if (!dest)
{
images.Release();
return E_POINTER;
}
for (size_t index = 0; index < nimages; ++index)
{
assert(dest[index].format == format);
const Image& src = cImages[index];
if (!IsCompressed(src.format))
{
images.Release();
return E_FAIL;
}
if (src.width != dest[index].width || src.height != dest[index].height)
{
images.Release();
return E_FAIL;
}
hr = DecompressBC(src, dest[index]);
if (FAILED(hr))
{
images.Release();
return hr;
}
}
return S_OK;
}
| [
"[email protected]"
] | |
f140791b271b7a36f44c81cbfb77797d552dc22b | f338eb32c45d8d5d002a84798a7df7bb0403b3c4 | /CondCore/Utilities/bin/conddb_migrate.cpp | f6422f670a4c70ee9bc6737244c4e89273cba5ea | [] | permissive | wouf/cmssw | 0a8a8016e6bebc611f1277379e12bef130464afb | 60da16aec83a0fc016cca9e2a5ed0768ba3b161c | refs/heads/CMSSW_7_3_X | 2022-06-30T04:35:45.380754 | 2015-05-08T17:40:17 | 2015-05-08T17:40:17 | 463,028,972 | 0 | 0 | Apache-2.0 | 2022-02-24T06:05:30 | 2022-02-24T06:05:26 | null | UTF-8 | C++ | false | false | 6,359 | cpp | #include "CondCore/DBCommon/interface/DbSession.h"
#include "CondCore/DBCommon/interface/DbTransaction.h"
//#include "CondCore/DBCommon/interface/Exception.h"
#include "CondCore/DBCommon/interface/Auth.h"
#include "CondCore/CondDB/interface/ConnectionPool.h"
#include "CondCore/CondDB/interface/Utils.h"
#include "CondCore/CondDB/interface/IOVEditor.h"
#include "CondCore/CondDB/interface/IOVProxy.h"
#include "CondCore/CondDB/src/DbCore.h"
#include "CondCore/MetaDataService/interface/MetaData.h"
#include "CondCore/Utilities/interface/Utilities.h"
//#include "CondCore/Utilities/interface/CondDBImport.h"
#include "CondCore/Utilities/interface/CondDBTools.h"
#include <iostream>
#include "Cintex/Cintex.h"
#include <sstream>
namespace cond {
class MigrateUtilities : public cond::Utilities {
public:
MigrateUtilities();
~MigrateUtilities();
int execute();
};
}
cond::MigrateUtilities::MigrateUtilities():Utilities("conddb_migrate"){
addConnectOption("sourceConnect","s","source connection string(required)");
addConnectOption("destConnect","d","destionation connection string(required)");
addAuthenticationOptions();
addOption<std::string>("tag","t","migrate only the tag (optional)");
addOption<bool>("replace","r","replace the tag already migrated (optional)");
addOption<bool>("fast","f","fast run without validation (optional)");
addOption<std::string>("log","l","log connection string (required");
ROOT::Cintex::Cintex::Enable();
}
cond::MigrateUtilities::~MigrateUtilities(){
}
int cond::MigrateUtilities::execute(){
bool debug = hasDebug();
int filterPosition = -1;
std::string tag("");
if( hasOptionValue("tag")) {
tag = getOptionValue<std::string>("tag");
if(debug){
std::cout << "tag " << tag << std::endl;
}
if( tag[0] == '*' ){
tag = tag.substr(1);
filterPosition = 0;
}
if( tag[tag.size()-1] == '*' ){
tag = tag.substr(0,tag.size()-1);
filterPosition = 1;
}
}
bool replace = hasOptionValue("replace");
bool validate = !hasOptionValue("fast");
std::string destConnect = getOptionValue<std::string>("destConnect" );
std::string sourceConnect = getOptionValue<std::string>("sourceConnect");
std::tuple<std::string,std::string,std::string> connPars = persistency::parseConnectionString( sourceConnect );
if( std::get<0>( connPars ) == "frontier" ) throwException("Cannot migrate data from FronTier cache.","MigrateUtilities::execute");
std::cout <<"# Connecting to source database on "<<sourceConnect<<std::endl;
cond::DbSession sourcedb = openDbSession( "sourceConnect", cond::Auth::COND_READER_ROLE, true );
sourcedb.transaction().start( true );
cond::MetaData metadata(sourcedb);
std::vector<std::string> tagToProcess;
if( !tag.empty() && filterPosition == -1 ){
tagToProcess.push_back( tag );
} else {
metadata.listAllTags( tagToProcess );
if( filterPosition != -1 ) {
std::vector<std::string> filteredList;
for( const auto& t: tagToProcess ) {
size_t ptr = t.find( tag );
if( ptr != std::string::npos && ptr < filterPosition ) filteredList.push_back( t );
}
tagToProcess = filteredList;
}
}
cond::DbSession logdb = openDbSession("log", cond::Auth::COND_READER_ROLE, true );
persistency::ConnectionPool connPool;
if( hasDebug() ) {
connPool.setMessageVerbosity( coral::Debug );
connPool.configure();
}
persistency::Session sourceSession = connPool.createSession( sourceConnect );
std::cout <<"# Opening session on destination database..."<<std::endl;
persistency::Session destSession = connPool.createSession( destConnect, true, COND_DB );
destSession.transaction().start( false );
if( !destSession.existsDatabase() ) destSession.createDatabase();
destSession.transaction().commit();
std::cout <<"# "<<tagToProcess.size()<<" tag(s) to process."<<std::endl;
std::cout <<std::endl;
size_t nt = 0;
size_t nt_migrated = 0;
size_t nt_validated = 0;
size_t nt_error = 0;
for( auto t : tagToProcess ){
nt++;
std::cout <<"--> Processing tag["<<nt<<"]: "<<t<<std::endl;
std::string destTag("");
cond::MigrationStatus status = ERROR;
destSession.transaction().start( false );
bool existsEntry = destSession.checkMigrationLog( sourceConnect, t, destTag, status );
if( existsEntry ){
std::cout <<" Tag already processed. Current status="<<validationStatusText[status]<<std::endl;
} else {
destTag = t;
if( destSession.existsIov( destTag ) ){
destTag = destTag+"["+std::get<1>( connPars )+"/"+std::get<2>( connPars )+"]";
std::cout <<" Tag "<<t<<" already existing, renamed to "<<destTag<<std::endl;
}
}
destSession.transaction().commit();
if( !existsEntry || status == ERROR || replace ){
try{
persistency::UpdatePolicy policy = persistency::NEW;
if( replace ) policy = persistency::REPLACE;
migrateTag( t, sourceSession, destTag, destSession, policy, logdb );
status = MIGRATED;
nt_migrated++;
} catch ( const std::exception& e ){
nt_error++;
std::cout <<" ERROR in migration: "<<e.what()<<std::endl;
std::cout <<" Tag "<<t<<" has not been migrated."<<std::endl;
}
}
if( validate && status == MIGRATED ){
try{
if( validateTag( t, sourceSession, destTag, destSession ) ){
std::cout <<" Tag validated."<<std::endl;
status = VALIDATED;
nt_validated++;
} else {
std::cout <<" ERROR: Migrated tag different from reference."<<std::endl;
}
} catch ( const std::exception& e ){
std::cout <<" ERROR in validation: "<<e.what()<<std::endl;
}
}
try{
persistency::TransactionScope usc( destSession.transaction() );
usc.start( false );
if( existsEntry ) {
destSession.updateMigrationLog( sourceConnect, t, status );
} else {
destSession.addToMigrationLog( sourceConnect, t, destTag, status );
}
usc.commit();
} catch ( const std::exception& e ){
std::cout <<" ERROR updating the status: "<<e.what()<<std::endl;
}
}
std::cout <<"# "<<nt<<" tag(s) processed. Migrated: "<<nt_migrated<<" Validated: "<<nt_validated<<" Errors:"<<nt_error<<std::endl;
return 0;
}
int main( int argc, char** argv ){
cond::MigrateUtilities utilities;
return utilities.run(argc,argv);
}
| [
"[email protected]"
] | |
3078179b66dd1ae576dc0fb65039e92eeee2026f | b57193090bbfa5838f1e673f37ac82ad26286b54 | /src/certdb/JWS.hxx | 0610cd2f273645476fb25b1b20bc40d34819ec3c | [] | no_license | luckydonald-backup/beng-proxy | 8021e4fe7bb06e24b6f7d2a5464fc6051a8df25f | 34ef0a94c7005bde20390c3b60a6439cc6770573 | refs/heads/master | 2020-05-24T20:56:31.428664 | 2019-05-16T08:40:44 | 2019-05-16T09:14:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,587 | hxx | /*
* Copyright 2007-2018 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* 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.
*
* 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
* FOUNDATION 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.
*/
/* JSON Web Signature library */
#pragma once
#include <openssl/ossl_typ.h>
#include <string>
/**
* Throws on error.
*/
std::string
MakeJwk(EVP_PKEY &key);
| [
"[email protected]"
] | |
618fda5bf9d4b1287f9cc80041904d11e37aa4e7 | 626e37df4e19599f87eb5801f7edbce7127439e1 | /pqSource/symclass.cpp | aed77b64c205aa4f81ecc2b6f09ca1c48a5313cf | [] | no_license | warunanc/loqt | 42ee6b85e07395bd18d92196b9640c19ab944431 | b1365ff55db053a51aafe73729395ece1678187b | refs/heads/master | 2021-06-11T06:35:19.372825 | 2017-04-13T09:01:04 | 2017-04-13T09:01:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,663 | cpp | /*
pqSource : interfacing SWI-Prolog source files and Qt
Author : Carlo Capelli
E-mail : [email protected]
Copyright (C): 2013,2014,2015,2016
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "symclass.h"
// a very simple dictionary
// index on first letter, then linear match the array
//
symclass::symclass(const char *csl) : starts(26) {
int idx = 0;
words = QString(csl).split(",");
foreach(QString x, words) {
x = x.trimmed();
int f = x[0].unicode();
Q_ASSERT(f >= 'a' && f <= 'z');
starts[f - 'a'].append(symidx(x, idx++));
}
}
// peek first char entry
// scan array
//
int symclass::symindex(const char* sym) const {
int f = sym[0];
Q_ASSERT(f >= 'a' && f <= 'z');
foreach (symidx sx, starts[f - 'a'])
if (sx.first == sym)
return sx.second;
return -1;
}
QString symclass::idxsymbol(int idx) {
return words[idx];
}
| [
"[email protected]"
] | |
88ebdeea5cc26f5ec558b0a399fc86553c3afd41 | f44fe1856dc0511ec05081eed4e31d2b0a86dd88 | /download/downloadmanagerFTP.cpp | 870fa7c5e9621824dfdc9b87e34cf800ffb5b7aa | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | emptyewer/MAPster | 97a3d6b61b791fcab8937952c7ae62a982d06581 | f2bd3e8ea64fe7e0a9de91bd2a9147621b870503 | refs/heads/master | 2020-05-29T08:47:35.640095 | 2017-03-17T21:15:46 | 2017-03-17T21:15:46 | 70,012,278 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,789 | cpp | #include "downloadmanagerFTP.h"
#include "../mainwindow.h"
#include <QtGlobal>
#if QT_VERSION < 0x050000
#include <QFileInfo>
#include <QDateTime>
#include <QDebug>
DownloadManagerFTP::DownloadManagerFTP(QObject *parent) :
QObject(parent)
, _pFTP(NULL)
, _pFile(NULL)
, _nDownloadTotal(0)
, _bAcceptRanges(false)
, _nDownloadSize(0)
, _nDownloadSizeAtPause(0)
{
}
DownloadManagerFTP::~DownloadManagerFTP()
{
if (_pFTP != NULL)
{
pause();
_pFTP->deleteLater();
_pFTP = NULL;
}
if (_pFile->isOpen())
{
_pFile->close();
delete _pFile;
_pFile = NULL;
}
}
/*
// http://www.qtforum.org/article/14254/qftp-get-overloaded.html
int QFtp::get(const QString &file, uint offSet, QIODevice *dev, TransferType type)
{
QStringList cmds;
cmds << ("SIZE " + file + "\r\n");
if (type == Binary)
{
cmds << "TYPE I\r\n";
}
else
{
cmds << "TYPE A\r\n";
}
cmds << (d_func()->transferMode == Passive ? "PASV\r\n" : "PORT\r\n");
cmds << ("REST " + QString::number(offSet) + "\r\n");
cmds << ("RETR " + file + "\r\n");
return d_func()->addCommand(new QFtpCommand(Get, cmds, dev));
}
*/
void DownloadManagerFTP::download(QUrl url)
{
qDebug() << "download: URL=" <<url.toString();
_URL = url;
{
QFileInfo fileInfo(url.toString());
_qsFileName = fileInfo.fileName();
}
_nDownloadSize = 0;
_nDownloadSizeAtPause = 0;
if (_pFTP == NULL)
{
_pFTP = new QFtp(this);
connect(_pFTP, SIGNAL(stateChanged(int)), this, SLOT(stateChanged(int)));
connect(_pFTP, SIGNAL(commandStarted(int)), this, SLOT(commandStarted(int)));
connect(_pFTP, SIGNAL(commandFinished(int,bool)), this, SLOT(commandFinished(int,bool)));
connect(_pFTP, SIGNAL(rawCommandReply(int, const QString &)), this, SLOT(rawCommandReply(int, const QString &)));
//connect(_pFTP, SIGNAL(dataTransferProgress(qint64,qint64)), this, SLOT(ftpDataTransferProgress(qint64,qint64)));
connect(_pFTP, SIGNAL(readyRead()), this, SLOT(readyRead()));
}
qDebug() << "connectToHost(" << _URL.host() << "," << url.port(21) << ")";
_pFTP->connectToHost(_URL.host(), url.port(21));
_pFTP->login();
qDebug() << "HELP";
_pFTP->rawCommand("HELP");
_Timer.setInterval(15000);
_Timer.setSingleShot(true);
connect(&_Timer, SIGNAL(timeout()), this, SLOT(timeout()));
_Timer.start();
}
void DownloadManagerFTP::pause()
{
qDebug() << __FUNCTION__ << "(): _nDownloadSize = " << _nDownloadSize;
_Timer.stop();
//disconnect(_pFTP, SIGNAL(dataTransferProgress(qint64,qint64)), this, SLOT(ftpDataTransferProgress(qint64,qint64)));
//disconnect(_pFTP, SIGNAL(readyRead()), this, SLOT(readyRead()));
_pFTP->abort();
// qDebug() << "ABOR";
// _pFTP->rawCommand("ABOR");
_pFile->flush();
_nDownloadSizeAtPause = _nDownloadSize;
_nDownloadSize = 0;
}
void DownloadManagerFTP::resume()
{
qDebug() << __FUNCTION__ << "(): _nDownloadSizeAtPause = " << _nDownloadSizeAtPause;
download();
}
void DownloadManagerFTP::download()
{
qDebug() << __FUNCTION__ << "():";
//connect(_pFTP, SIGNAL(dataTransferProgress(qint64,qint64)), this, SLOT(ftpDataTransferProgress(qint64,qint64)));
connect(_pFTP, SIGNAL(readyRead()), this, SLOT(readyRead()));
if (_bAcceptRanges && (_nDownloadSizeAtPause > 0))
{
qDebug() << "TYPE I";
_pFTP->rawCommand("TYPE I"); // Binary mode
// qDebug() << "PASV";
// _pFTP->rawCommand("PASV"); // Passive mode
qDebug() << "PORT";
_pFTP->rawCommand("PORT"); // Active mode
qDebug() << "REST " << _nDownloadSizeAtPause;
_pFTP->rawCommand(QString("REST %1").arg(_nDownloadSizeAtPause));
qDebug() << "RETR " << _qsFileName;
_pFTP->rawCommand(QString("RETR " + _qsFileName));
}
else
{
_pFTP->get(_qsFileName);
}
_Timer.setInterval(15000);
_Timer.setSingleShot(true);
connect(&_Timer, SIGNAL(timeout()), this, SLOT(timeout()));
_Timer.start();
}
void DownloadManagerFTP::finished()
{
qDebug() << __FUNCTION__;
_Timer.stop();
_pFile->close();
QFile::remove(_qsFileName);
_pFile->rename(_qsFileName + ".part", _qsFileName);
delete _pFile;
_pFile = NULL;
emit downloadComplete();
}
void DownloadManagerFTP::error(QNetworkReply::NetworkError code)
{
qDebug() << __FUNCTION__ << "(" << code << ")";
}
void DownloadManagerFTP::timeout()
{
qDebug() << __FUNCTION__;
}
void DownloadManagerFTP::stateChanged(int state)
{
QString qsState;
switch (static_cast<QFtp::State>(state))
{
case QFtp::Unconnected: qsState = "Unconnected"; break;
case QFtp::HostLookup: qsState = "HostLookup"; break;
case QFtp::Connecting: qsState = "Connecting"; break;
case QFtp::Connected: qsState = "Connected"; break;
case QFtp::LoggedIn: qsState = "LoggedIn"; break;
case QFtp::Closing: qsState = "Closing"; break;
default: qsState = "Unknown"; break;
}
qDebug() << __FUNCTION__ << "(" << state << "=" << qsState << ")";
}
QString DownloadManagerFTP::ftpCmd(QFtp::Command eCmd)
{
QString qsCmd;
switch (eCmd)
{
case QFtp::None: qsCmd = "None"; break;
case QFtp::SetTransferMode: qsCmd = "SetTransferMode"; break;
case QFtp::SetProxy: qsCmd = "SetProxy"; break;
case QFtp::ConnectToHost: qsCmd = "ConnectToHost"; break;
case QFtp::Login: qsCmd = "Login"; break;
case QFtp::Close: qsCmd = "Close"; break;
case QFtp::List: qsCmd = "List"; break;
case QFtp::Cd: qsCmd = "Cd"; break;
case QFtp::Get: qsCmd = "Get"; break;
case QFtp::Put: qsCmd = "Put"; break;
case QFtp::Remove: qsCmd = "Remove"; break;
case QFtp::Mkdir: qsCmd = "Mkdir"; break;
case QFtp::Rmdir: qsCmd = "Rmdir"; break;
case QFtp::Rename: qsCmd = "Rename"; break;
case QFtp::RawCommand: qsCmd = "RawCommand"; break;
default: qsCmd = "Unknown"; break;
}
return qsCmd;
}
void DownloadManagerFTP::commandStarted(int id)
{
qDebug() << __FUNCTION__ << "(" << id << ")";
}
void DownloadManagerFTP::commandFinished(int id, bool error)
{
qDebug() << __FUNCTION__ << "(" << id << "," << error << ")";
}
void DownloadManagerFTP::rawCommandReply(int replyCode, const QString &detail)
{
int id = _pFTP->currentId();
qDebug() << __FUNCTION__ << "(" << replyCode << "," << detail << "): " << id;
switch (replyCode)
{
case 200:
case 214: // HELP
{
addLine(detail);
if (detail.contains(QLatin1String("REST"), Qt::CaseSensitive))
{
_bAcceptRanges = true;
}
ftpFinishedHelp();
}
break;
case 213: // SIZE
{
_nDownloadTotal = detail.toInt();
download();
}
break;
case 226: // RETR
{
if (_pFile->isOpen())
{
finished();
}
}
break;
case 550:
{
}
break;
}
}
void DownloadManagerFTP::readyRead()
{
// qDebug() << __FUNCTION__ << "()";
QByteArray data = _pFTP->readAll();
if (data.size() == 0)
{
return;
}
_pFile->write(data);
if (_nDownloadSize == 0)
{
_nDownloadSize = _nDownloadSizeAtPause;
}
_nDownloadSize += data.size();
int nPercentage = static_cast<int>((static_cast<float>(_nDownloadSize) * 100.0) / static_cast<float>(_nDownloadTotal));
emit progress(nPercentage);
qDebug() << "Download Progress: Received=" << _nDownloadSize <<": Total=" << _nDownloadTotal << " %" << nPercentage;
if (_nDownloadSize == _nDownloadTotal)
{
if (_pFile->isOpen())
{
finished();
}
}
else
{
_Timer.start(15000);
}
}
void DownloadManagerFTP::ftpFinishedHelp()
{
// From finishedHead()
_pFile = new QFile(_qsFileName + ".part");
if (!_bAcceptRanges)
{
_pFile->remove();
}
if (!_pFile->open(QIODevice::ReadWrite | QIODevice::Append))
{
qDebug() << "Failed to open file " << _qsFileName << ".part";
}
_nDownloadSizeAtPause = _pFile->size();
// End finishedHead()+
if (!_URL.path().isEmpty())
{
QFileInfo fileInfo(_URL.path());
qDebug() << "cd(" << fileInfo.path() << ")";
_pFTP->cd(fileInfo.path());
}
qDebug() << "SIZE " << _qsFileName;
_pFTP->rawCommand("SIZE " + _qsFileName);
}
#endif // QT_VERSION < 0x050000
| [
"[email protected]"
] | |
91dde796f586b0c506f37a0414eb947cdbccffec | 0805b803ad608e07810af954048359c927294a0e | /bvheditor/data/ImageFile.cpp | a9f7d84db3850a542adb3d783e6f69039e014780 | [] | no_license | yiyongc/BvhEditor | 005feb3f44537544d66d54ab419186b73e184f57 | b512e240bc7b1ad5f54fd2e77f0a3194302aab2d | refs/heads/master | 2023-03-15T14:19:31.292081 | 2017-03-30T17:27:17 | 2017-03-30T17:27:17 | 66,918,016 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,506 | cpp | #include "ImageFile.h"
ImageFile::ImageFile(QString name, QImage img) :
m_imgName(name),
m_img(img),
m_imgTexture(0),
m_meshImg(0),
m_deformedMesh(new TTextureMesh),
m_deformer(RigidMeshDeformer2D())
{
//column by column initialize transform matrix to identity
m_transformMatrix[0] = 1;
m_transformMatrix[1] = 0;
m_transformMatrix[2] = 0;
m_transformMatrix[3] = 0;
m_transformMatrix[4] = 0;
m_transformMatrix[5] = 1;
m_transformMatrix[6] = 0;
m_transformMatrix[7] = 0;
m_transformMatrix[8] = 0;
m_transformMatrix[9] = 0;
m_transformMatrix[10] = 1;
m_transformMatrix[11] = 0;
m_transformMatrix[12] = 0;
m_transformMatrix[13] = 0;
m_transformMatrix[14] = 0;
m_transformMatrix[15] = 1;
}
ImageFile::~ImageFile() {}
QString ImageFile::getImageName() {
return m_imgName;
}
void ImageFile::setImageName(QString name) {
m_imgName = name;
}
QImage ImageFile::getQImage() {
return m_img;
}
void ImageFile::setQImage(QImage img) {
m_img = img;
}
TMeshImageP ImageFile::getMeshImage() {
return m_meshImg;
}
void ImageFile::setMeshImage(TMeshImageP mesh) {
m_meshImg = mesh;
}
GLfloat* ImageFile::getTransformMatrix() {
return m_transformMatrix;
}
void ImageFile::setTransformMatrix(float rotAngle, float xTrans, float yTrans, float scaleFactor) {
GLfloat scale[16] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 };
GLfloat rotate[16] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 };
GLfloat translate[16] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 };
float pi = 3.14159265;
//Set up rotation about z axis
rotate[0] = cosf(rotAngle /180 * pi);
rotate[4] = -sinf(rotAngle / 180 * pi);
rotate[1] = sinf(rotAngle / 180 * pi);
rotate[5] = cosf(rotAngle / 180 * pi);
//Set up translation
translate[12] = xTrans;
translate[13] = yTrans;
//Set up scale
scale[0] = scaleFactor;
scale[5] = scaleFactor;
scale[10] = scaleFactor;
//final transform matrix
glPushMatrix();
glLoadIdentity();
glMultMatrixf(translate);
glMultMatrixf(rotate);
glMultMatrixf(scale);
glGetFloatv(GL_MODELVIEW_MATRIX, m_transformMatrix);
glPopMatrix();
}
int ImageFile::getImageRotation() {
return rotAngleImg;
}
float ImageFile::getImageXTrans() {
return xTransImg;
}
float ImageFile::getImageYTrans() {
return yTransImg;
}
void ImageFile::setImageRotation(int rot) {
rotAngleImg = rot;
}
void ImageFile::setImageXTrans(float xTrans) {
xTransImg = xTrans;
}
void ImageFile::setImageYTrans(float yTrans) {
yTransImg = yTrans;
}
float ImageFile::getImageScale() {
return scaleImg;
}
void ImageFile::setImageScale(float scaleValue) {
scaleImg = scaleValue;
}
void ImageFile::validateConstraints(int imageIndex, std::unordered_multimap<int, std::pair<int, int>>* map, cacani::data::Layer* m_layer, int curFrame)
{
if (m_bConstraintsValid)
return;
size_t nConstraints = m_vSelected.size();
std::set<unsigned int>::iterator cur(m_vSelected.begin()), end(m_vSelected.end());
while (cur != end) {
unsigned int nVertex = *cur++;
Wml::Vector3f vVertex;
int jointIndex = findJointIndex(map, imageIndex, nVertex);
Wml::GMatrixd coordinates = getGlobalCoord(m_layer, jointIndex, curFrame);
vVertex.X() = coordinates(0, 0) * figure_scale;
vVertex.Y() = coordinates(1, 0) * figure_scale;
vVertex.Z() = 0;
//Original working
//vVertex.X() = m_deformedMesh->vertex(nVertex).P().x;
//vVertex.Y() = m_deformedMesh->vertex(nVertex).P().y;
//vVertex.Z() = 0;
m_deformer.SetDeformedHandle(nVertex, Wml::Vector2f(vVertex.X(), vVertex.Y()));
}
m_deformer.ForceValidation();
m_bConstraintsValid = true;
}
Wml::GMatrixd ImageFile::calculateGlobalCoordMatrix(cacani::data::Layer* m_layer, int jointIndex, int frameNum) {
double iden[] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 };
Wml::GMatrixd translation(4, 4, iden);
Wml::GMatrixd rotateX(4, 4, iden);
Wml::GMatrixd rotateY(4, 4, iden);
Wml::GMatrixd rotateZ(4, 4, iden);
cacani::data::Joint* currJoint = m_layer->GetJoint(jointIndex);
double* motionData;
if (m_layer->m_sheets.size() != 0)
motionData = m_layer->sheetAtIndex(frameNum)->getMotion();
else
motionData = dynamic_cast<cacani::data::LayerGroup*> (m_layer)->childAtIndex(0)->sheetAtIndex(frameNum)->getMotion();
double transValues[] = { 0, 0, 0, 1 };
//Obtain translation matrix value
if (currJoint->parent == NULL) {
transValues[0] = motionData[0];
transValues[1] = motionData[1];
transValues[2] = motionData[2];
}
else {
double* offsetValues = currJoint->offset;
transValues[0] = offsetValues[0];
transValues[1] = offsetValues[1];
transValues[2] = offsetValues[2];
}
Wml::GVectord transVector(4, transValues);
translation.SetColumn(3, transVector);
int numChannels = currJoint->channels.size();
//Obtain rotation matrices based on offset in motion data
for (int i = 0; i < numChannels; i++) {
cacani::data::Channel* channel = currJoint->channels[i];
double rotValue = motionData[channel->index];
double sValue, cValue;
if (rotValue < 0)
rotValue += 360;
sValue = sin(rotValue * M_PI / 180);
cValue = cos(rotValue * M_PI / 180);
if (channel->type == cacani::data::Xrotation) {
double col1Values[] = { 0, cValue, sValue, 0 };
double col2Values[] = { 0, -sValue, cValue, 0 };
Wml::GVectord column1(4, col1Values);
Wml::GVectord column2(4, col2Values);
rotateX.SetColumn(1, column1);
rotateX.SetColumn(2, column2);
}
else if (channel->type == cacani::data::Yrotation) {
double col0Values[] = { cValue, 0, -sValue, 0 };
double col2Values[] = { sValue, 0, cValue, 0 };
Wml::GVectord column0(4, col0Values);
Wml::GVectord column2(4, col2Values);
rotateY.SetColumn(0, column0);
rotateY.SetColumn(2, column2);
}
else if (channel->type == cacani::data::Zrotation) {
double col0Values[] = { cValue, sValue, 0, 0 };
double col1Values[] = { -sValue, cValue, 0, 0 };
Wml::GVectord column0(4, col0Values);
Wml::GVectord column1(4, col1Values);
rotateY.SetColumn(0, column0);
rotateY.SetColumn(1, column1);;
}
}
cacani::data::ChannelOrder order = currJoint->channel_order;
Wml::GMatrixd rotMatrix(4, 4);
switch (order) {
case (cacani::data::XYZ) :
rotMatrix = rotateX * rotateY * rotateZ;
break;
case (cacani::data::XZY) :
rotMatrix = rotateX * rotateZ * rotateY;
break;
case (cacani::data::YXZ) :
rotMatrix = rotateY * rotateX * rotateZ;
break;
case (cacani::data::YZX) :
rotMatrix = rotateY * rotateZ * rotateX;
break;
case (cacani::data::ZXY) :
rotMatrix = rotateZ * rotateX * rotateY;
break;
case (cacani::data::ZYX) :
rotMatrix = rotateZ * rotateY * rotateX;
break;
}
Wml::GMatrixd myMatrix = translation * rotMatrix;
if (currJoint->parent == NULL)
return myMatrix;
else
return calculateGlobalCoordMatrix(m_layer, currJoint->parent->index, frameNum) * myMatrix;
}
Wml::GMatrixd ImageFile::getGlobalCoord(cacani::data::Layer* m_layer, int jointIndex, int frameNum) {
Wml::GMatrixd localCoord(4, 1);
double local[] = { 0, 0, 0, 1 };
Wml::GVectord vectorToSet(4, local);
localCoord.SetColumn(0, vectorToSet);
return calculateGlobalCoordMatrix(m_layer, jointIndex, frameNum) * localCoord;
}
int ImageFile::findJointIndex(std::unordered_multimap<int, std::pair<int, int>>* map, int imageIndex, int vertID) {
auto it = map->begin();
for (; it != map->end(); it++) {
pair<int, int> cur = it->second;
if (cur.first != imageIndex)
continue;
else {
if (cur.second == vertID)
return it->first;
}
}
return -1;
} | [
"[email protected]"
] | |
c1b0b9f01c7e3b450c05f1b9a6cf143e6896092f | 20bbebc8f0a6cb8cc274f860b8aad8253091535b | /nrf52_bot_fw/src/lib/ble_bluefruit/utility/AdaMsg.cpp | 5c0f43b05fdee5a5bbc7610a71b44ddc041d7da9 | [
"MIT",
"Apache-2.0"
] | permissive | chcbaram/nrf52_bot | 797a9ba475fb7878e8d414cc3cd5fa21bee363a0 | aa9f61c4266c51dcf31bf3cd28d8793c19936f85 | refs/heads/master | 2022-09-09T21:49:38.799364 | 2020-06-04T04:38:50 | 2020-06-04T04:38:50 | 250,185,264 | 0 | 3 | Apache-2.0 | 2020-04-02T14:37:03 | 2020-03-26T07:05:39 | C | UTF-8 | C++ | false | false | 3,204 | cpp | /**************************************************************************/
/*!
@file AdaMsg.cpp
@author hathach (tinyusb.org)
@section LICENSE
Software License Agreement (BSD License)
Copyright (c) 2018, Adafruit Industries (adafruit.com)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holders 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 ''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 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 "AdaMsg.h"
void AdaMsg::_init(void)
{
_dynamic = true;
_waiting = false;
_sem = NULL;
buffer = NULL;
remaining = xferlen = 0;
}
AdaMsg::AdaMsg(void)
{
_init();
}
// dynamic mean semaphore is malloced and freed only when in action
void AdaMsg::begin(bool dynamic)
{
_dynamic = dynamic;
if ( !_dynamic )
{
_sem = xSemaphoreCreateCounting(10, 0);
}
}
void AdaMsg::stop(void)
{
if (!_dynamic) vSemaphoreDelete(_sem);
_init();
}
void AdaMsg::prepare(void* buf, uint16_t bufsize)
{
buffer = (uint8_t*) buf;
remaining = bufsize;
xferlen = 0;
}
/**
*
* @param ms
* @return -1 if timeout
*/
int32_t AdaMsg::waitUntilComplete(uint32_t ms)
{
if (_dynamic)
{
_sem = xSemaphoreCreateBinary();
VERIFY(_sem, -1);
}
int result = -1;
_waiting = true;
if ( xSemaphoreTake(_sem, ms2tick(ms) ) )
{
result = xferlen;
}
_waiting = false;
if (_dynamic)
{
vSemaphoreDelete(_sem);
_sem = NULL;
}
return result;
}
bool AdaMsg::isWaiting(void)
{
return _waiting;
}
uint16_t AdaMsg::feed(void* data, uint16_t len)
{
len = min16(len, remaining);
// pass NULL to skip copy
if ( data ) memcpy(buffer, data, len);
buffer += len;
remaining -= len;
xferlen += len;
return len;
}
void AdaMsg::complete(void)
{
if(_sem) xSemaphoreGive(_sem);
}
| [
"[email protected]"
] | |
d3d33855533b94d981d94c77e51a572c49b00e74 | 0bd75c652d87b948c99b7789e2c5d98c4e25f064 | /src/test/bech32_tests.cpp | f6bd3e0b192a7ceb07705db8486360060e619ddc | [
"MIT"
] | permissive | volta-im/volta-core | f7ff299a304f844e6c4b885a97db3f5e98ba3b44 | c98596a41dc28589b1dd95f5c0a71dc4abdd4d6f | refs/heads/master | 2020-05-03T09:16:54.391955 | 2019-08-16T19:48:49 | 2019-08-16T19:48:49 | 178,550,099 | 1 | 2 | MIT | 2019-06-25T16:07:06 | 2019-03-30T11:31:22 | C++ | UTF-8 | C++ | false | false | 2,146 | cpp | // Copyright (c) 2017 Pieter Wuille
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <bech32.h>
#include <test/test_volta.h>
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(bech32_tests, BasicTestingSetup)
static bool CaseInsensitiveEqual(const std::string &s1, const std::string &s2)
{
if (s1.size() != s2.size()) return false;
for (size_t i = 0; i < s1.size(); ++i) {
char c1 = s1[i];
if (c1 >= 'A' && c1 <= 'Z') c1 -= ('A' - 'a');
char c2 = s2[i];
if (c2 >= 'A' && c2 <= 'Z') c2 -= ('A' - 'a');
if (c1 != c2) return false;
}
return true;
}
BOOST_AUTO_TEST_CASE(bip173_testvectors_valid)
{
static const std::string CASES[] = {
"A12UEL5L",
"a12uel5l",
"an83characterlonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio1tt5tgs",
"abcdef1qpzry9x8gf2tvdw0s3jn54khce6mua7lmqqqxw",
"11qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqc8247j",
"split1checkupstagehandshakeupstreamerranterredcaperred2y9e3w",
"?1ezyfcl",
};
for (const std::string& str : CASES) {
auto ret = bech32::Decode(str);
BOOST_CHECK(!ret.first.empty());
std::string recode = bech32::Encode(ret.first, ret.second);
BOOST_CHECK(!recode.empty());
BOOST_CHECK(CaseInsensitiveEqual(str, recode));
}
}
BOOST_AUTO_TEST_CASE(bip173_testvectors_invalid)
{
static const std::string CASES[] = {
" 1nwldj5",
"\x7f""1axkwrx",
"\x80""1eym55h",
"an84characterslonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio1569pvx",
"pzry9x0s0muk",
"1pzry9x0s0muk",
"x1b4n0q5v",
"li1dgmt3",
"de1lg7wt\xff",
"A1G7SGD8",
"10a06t8",
"1qzzfhee",
"a12UEL5L",
"A12uEL5L",
};
for (const std::string& str : CASES) {
auto ret = bech32::Decode(str);
BOOST_CHECK(ret.first.empty());
}
}
BOOST_AUTO_TEST_SUITE_END()
| [
"[email protected]"
] | |
d19bd6dfa005c48a7e0034609f92195067c020c1 | f88379b6a44b1a449911a0f62372d30e8f33e104 | /mesh_study_re100_transient/cylinder_fine/system/fvSolution | d67ede5883ee6d3ead5bf59cc8b3b9988d6e4496 | [] | no_license | pomtojoer/vortex_shedding_openfoam | 70ba895ef63fc4973b2747fbbde24cea939304db | 486f48714d3693dc221040fe646f9e8620b25a44 | refs/heads/main | 2023-05-23T16:44:07.648247 | 2021-06-17T23:32:58 | 2021-06-17T23:32:58 | 377,980,214 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,914 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 4.x |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class dictionary;
object fvSolution;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
solvers
{
p
{
solver PCG;
preconditioner DIC;
tolerance 1e-06;
relTol 0.01;
}
/*
p
{
solver GAMG;
tolerance 1e-6;
relTol 0;
smoother GaussSeidel;
nPreSweeps 0;
nPostSweeps 2;
cacheAgglomeration on;
agglomerator faceAreaPair;
nCellsInCoarsestLevel 100;
mergeLevels 1;
}
*/
pFinal
{
solver PCG;
preconditioner DIC;
tolerance 1e-06;
relTol 0;
}
U
{
solver PBiCG;
preconditioner DILU;
tolerance 1e-08;
relTol 0;
}
/*
U
{
type coupled;
solver PBiCCCG;
preconditioner DILU;
tolerance (1e-08 1e-08 1e-08);
relTol (0 0 0);
}
*/
}
PISO
{
nCorrectors 2;
nNonOrthogonalCorrectors 1;
pRefCell 0;
pRefValue 0;
}
// ************************************************************************* //
| [
"[email protected]"
] | ||
69c6d456aef2c5d379c6fcc5cd13e6b47fc7f32b | 6488b363ca49a8ac9854a9f11f371dbb552552a0 | /tools/camera_calibration_fisheye/main.cpp | 726d7b368e85ef3f6e76bc8340902012b8b53826 | [] | no_license | MLauper/sc_analyzer | ac8e611525d1bb42074b6b72c043121ce13ade33 | 3f36ada16cbb3447d951ef579254c485fb0143a0 | refs/heads/master | 2021-09-11T06:49:34.137417 | 2018-01-16T21:24:07 | 2018-01-16T21:24:07 | 105,157,481 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,765 | cpp | #include <iostream>
#include <sstream>
#include <string>
#include <ctime>
#include <cstdio>
#include <opencv2/core.hpp>
#include <opencv2/core/utility.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/calib3d.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/highgui.hpp>
using namespace cv;
using namespace std;
static void help()
{
cout << "This is a camera calibration sample." << endl
<< "Usage: camera_calibration [configuration_file -- default ./default.xml]" << endl
<< "Near the sample file you'll find the configuration file, which has detailed help of "
"how to edit it. It may be any OpenCV supported file format XML/YAML." << endl;
}
class Settings
{
public:
Settings() : calibrationPattern(), squareSize(0), nrFrames(0), aspectRatio(0), delay(0), writePoints(false),
writeExtrinsics(false), calibZeroTangentDist(false), calibFixPrincipalPoint(false), flipVertical(false),
showUndistorsed(false), useFisheye(false), fixK1(false), fixK2(false), fixK3(false), fixK4(false),
fixK5(false), cameraID(0), atImageList(0), inputType(),
goodInput(false), flag(0)
{
}
enum Pattern { NOT_EXISTING, CHESSBOARD, CIRCLES_GRID, ASYMMETRIC_CIRCLES_GRID };
enum InputType { INVALID, CAMERA, VIDEO_FILE, IMAGE_LIST };
void write(FileStorage& fs) const //Write serialization for this class
{
fs << "{"
<< "BoardSize_Width" << boardSize.width
<< "BoardSize_Height" << boardSize.height
<< "Square_Size" << squareSize
<< "Calibrate_Pattern" << patternToUse
<< "Calibrate_NrOfFrameToUse" << nrFrames
<< "Calibrate_FixAspectRatio" << aspectRatio
<< "Calibrate_AssumeZeroTangentialDistortion" << calibZeroTangentDist
<< "Calibrate_FixPrincipalPointAtTheCenter" << calibFixPrincipalPoint
<< "Write_DetectedFeaturePoints" << writePoints
<< "Write_extrinsicParameters" << writeExtrinsics
<< "Write_outputFileName" << outputFileName
<< "Show_UndistortedImage" << showUndistorsed
<< "Input_FlipAroundHorizontalAxis" << flipVertical
<< "Input_Delay" << delay
<< "Input" << input
<< "}";
}
void read(const FileNode& node) //Read serialization for this class
{
node["BoardSize_Width"] >> boardSize.width;
node["BoardSize_Height"] >> boardSize.height;
node["Calibrate_Pattern"] >> patternToUse;
node["Square_Size"] >> squareSize;
node["Calibrate_NrOfFrameToUse"] >> nrFrames;
node["Calibrate_FixAspectRatio"] >> aspectRatio;
node["Write_DetectedFeaturePoints"] >> writePoints;
node["Write_extrinsicParameters"] >> writeExtrinsics;
node["Write_outputFileName"] >> outputFileName;
node["Calibrate_AssumeZeroTangentialDistortion"] >> calibZeroTangentDist;
node["Calibrate_FixPrincipalPointAtTheCenter"] >> calibFixPrincipalPoint;
node["Calibrate_UseFisheyeModel"] >> useFisheye;
node["Input_FlipAroundHorizontalAxis"] >> flipVertical;
node["Show_UndistortedImage"] >> showUndistorsed;
node["Input"] >> input;
node["Input_Delay"] >> delay;
node["Fix_K1"] >> fixK1;
node["Fix_K2"] >> fixK2;
node["Fix_K3"] >> fixK3;
node["Fix_K4"] >> fixK4;
node["Fix_K5"] >> fixK5;
validate();
}
void validate()
{
goodInput = true;
if (boardSize.width <= 0 || boardSize.height <= 0)
{
cerr << "Invalid Board size: " << boardSize.width << " " << boardSize.height << endl;
goodInput = false;
}
if (squareSize <= 10e-6)
{
cerr << "Invalid square size " << squareSize << endl;
goodInput = false;
}
if (nrFrames <= 0)
{
cerr << "Invalid number of frames " << nrFrames << endl;
goodInput = false;
}
if (input.empty()) // Check for valid input
inputType = INVALID;
else
{
if (input[0] >= '0' && input[0] <= '9')
{
stringstream ss(input);
ss >> cameraID;
inputType = CAMERA;
}
else
{
if (isListOfImages(input) && readStringList(input, imageList))
{
inputType = IMAGE_LIST;
nrFrames = nrFrames < static_cast<int>(imageList.size()) ? nrFrames : static_cast<int>(imageList.size());
}
else
inputType = VIDEO_FILE;
}
if (inputType == CAMERA)
inputCapture.open(cameraID);
if (inputType == VIDEO_FILE)
inputCapture.open(input);
if (inputType != IMAGE_LIST && !inputCapture.isOpened())
inputType = INVALID;
}
if (inputType == INVALID)
{
cerr << " Input does not exist: " << input;
goodInput = false;
}
flag = 0;
if (calibFixPrincipalPoint) flag |= CALIB_FIX_PRINCIPAL_POINT;
if (calibZeroTangentDist) flag |= CALIB_ZERO_TANGENT_DIST;
if (aspectRatio) flag |= CALIB_FIX_ASPECT_RATIO;
if (fixK1) flag |= CALIB_FIX_K1;
if (fixK2) flag |= CALIB_FIX_K2;
if (fixK3) flag |= CALIB_FIX_K3;
if (fixK4) flag |= CALIB_FIX_K4;
if (fixK5) flag |= CALIB_FIX_K5;
if (useFisheye)
{
// the fisheye model has its own enum, so overwrite the flags
flag = fisheye::CALIB_FIX_SKEW | fisheye::CALIB_RECOMPUTE_EXTRINSIC;
if (fixK1) flag |= fisheye::CALIB_FIX_K1;
if (fixK2) flag |= fisheye::CALIB_FIX_K2;
if (fixK3) flag |= fisheye::CALIB_FIX_K3;
if (fixK4) flag |= fisheye::CALIB_FIX_K4;
if (calibFixPrincipalPoint) flag |= fisheye::CALIB_FIX_PRINCIPAL_POINT;
}
calibrationPattern = NOT_EXISTING;
if (!patternToUse.compare("CHESSBOARD")) calibrationPattern = CHESSBOARD;
if (!patternToUse.compare("CIRCLES_GRID")) calibrationPattern = CIRCLES_GRID;
if (!patternToUse.compare("ASYMMETRIC_CIRCLES_GRID")) calibrationPattern = ASYMMETRIC_CIRCLES_GRID;
if (calibrationPattern == NOT_EXISTING)
{
cerr << " Camera calibration mode does not exist: " << patternToUse << endl;
goodInput = false;
}
atImageList = 0;
}
Mat nextImage()
{
Mat result;
if (inputCapture.isOpened())
{
Mat view0;
inputCapture >> view0;
view0.copyTo(result);
}
else if (atImageList < imageList.size())
result = imread(imageList[atImageList++], IMREAD_COLOR);
return result;
}
static bool readStringList(const string& filename, vector<string>& l)
{
l.clear();
FileStorage fs(filename, FileStorage::READ);
if (!fs.isOpened())
return false;
auto n = fs.getFirstTopLevelNode();
if (n.type() != FileNode::SEQ)
return false;
auto it = n.begin();
const auto it_end = n.end();
for (; it != it_end; ++it)
l.push_back(static_cast<string>(*it));
return true;
}
static bool isListOfImages(const string& filename)
{
auto s(filename);
// Look for file extension
if (s.find(".xml") == string::npos && s.find(".yaml") == string::npos && s.find(".yml") == string::npos)
return false;
return true;
}
Size boardSize; // The size of the board -> Number of items by width and height
Pattern calibrationPattern; // One of the Chessboard, circles, or asymmetric circle pattern
float squareSize; // The size of a square in your defined unit (point, millimeter,etc).
int nrFrames; // The number of frames to use from the input for calibration
float aspectRatio; // The aspect ratio
int delay; // In case of a video input
bool writePoints; // Write detected feature points
bool writeExtrinsics; // Write extrinsic parameters
bool calibZeroTangentDist; // Assume zero tangential distortion
bool calibFixPrincipalPoint; // Fix the principal point at the center
bool flipVertical; // Flip the captured images around the horizontal axis
string outputFileName; // The name of the file where to write
bool showUndistorsed; // Show undistorted images after calibration
string input; // The input ->
bool useFisheye; // use fisheye camera model for calibration
bool fixK1; // fix K1 distortion coefficient
bool fixK2; // fix K2 distortion coefficient
bool fixK3; // fix K3 distortion coefficient
bool fixK4; // fix K4 distortion coefficient
bool fixK5; // fix K5 distortion coefficient
int cameraID;
vector<string> imageList;
size_t atImageList;
VideoCapture inputCapture;
InputType inputType;
bool goodInput;
int flag;
private:
string patternToUse;
};
static void read(const FileNode& node, Settings& x, const Settings& default_value = Settings())
{
if (node.empty())
x = default_value;
else
x.read(node);
}
static void write(FileStorage& fs, const String&, const Settings& s)
{
s.write(fs);
}
enum { DETECTION = 0, CAPTURING = 1, CALIBRATED = 2 };
bool runCalibrationAndSave(Settings& s, Size imageSize, Mat& cameraMatrix, Mat& distCoeffs,
vector<vector<Point2f>> imagePoints);
int main(const int argc, char* argv[])
{
help();
//! [file_read]
Settings s;
const string inputSettingsFile = argc > 1 ? argv[1] : "default.xml";
FileStorage fs(inputSettingsFile, FileStorage::READ); // Read the settings
if (!fs.isOpened())
{
cout << "Could not open the configuration file: \"" << inputSettingsFile << "\"" << endl;
return -1;
}
fs["Settings"] >> s;
fs.release(); // close Settings file
//! [file_read]
//FileStorage fout("settings.yml", FileStorage::WRITE); // write config as YAML
//fout << "Settings" << s;
if (!s.goodInput)
{
cout << "Invalid input detected. Application stopping. " << endl;
return -1;
}
vector<vector<Point2f>> imagePoints;
Mat cameraMatrix, distCoeffs;
Size imageSize;
int mode = s.inputType == Settings::IMAGE_LIST ? CAPTURING : DETECTION;
clock_t prevTimestamp = 0;
const Scalar RED(0, 0, 255), GREEN(0, 255, 0);
const char ESC_KEY = 27;
//! [get_input]
for (;;)
{
auto blinkOutput = false;
auto view = s.nextImage();
//----- If no more image, or got enough, then stop calibration and show result -------------
if (mode == CAPTURING && imagePoints.size() >= static_cast<size_t>(s.nrFrames))
{
if (runCalibrationAndSave(s, imageSize, cameraMatrix, distCoeffs, imagePoints))
mode = CALIBRATED;
else
mode = DETECTION;
}
if (view.empty()) // If there are no more images stop the loop
{
// if calibration threshold was not reached yet, calibrate now
if (mode != CALIBRATED && !imagePoints.empty())
runCalibrationAndSave(s, imageSize, cameraMatrix, distCoeffs, imagePoints);
break;
}
//! [get_input]
imageSize = view.size(); // Format input image.
if (s.flipVertical) flip(view, view, 0);
//! [find_pattern]
vector<Point2f> pointBuf;
bool found;
auto chessBoardFlags = CALIB_CB_ADAPTIVE_THRESH | CALIB_CB_NORMALIZE_IMAGE;
if (!s.useFisheye)
{
// fast check erroneously fails with high distortions like fisheye
chessBoardFlags |= CALIB_CB_FAST_CHECK;
}
switch (s.calibrationPattern) // Find feature points on the input format
{
case Settings::CHESSBOARD:
found = findChessboardCorners(view, s.boardSize, pointBuf, chessBoardFlags);
break;
case Settings::CIRCLES_GRID:
found = findCirclesGrid(view, s.boardSize, pointBuf);
break;
case Settings::ASYMMETRIC_CIRCLES_GRID:
found = findCirclesGrid(view, s.boardSize, pointBuf, CALIB_CB_ASYMMETRIC_GRID);
break;
default:
found = false;
break;
}
//! [find_pattern]
//! [pattern_found]
if (found) // If done with success,
{
// improve the found corners' coordinate accuracy for chessboard
if (s.calibrationPattern == Settings::CHESSBOARD)
{
Mat viewGray;
cvtColor(view, viewGray, COLOR_BGR2GRAY);
cornerSubPix(viewGray, pointBuf, Size(11, 11),
Size(-1, -1), TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 30, 0.1));
}
if (mode == CAPTURING && // For camera only take new samples after delay time
(!s.inputCapture.isOpened() || clock() - prevTimestamp > s.delay * 1e-3 * CLOCKS_PER_SEC))
{
imagePoints.push_back(pointBuf);
prevTimestamp = clock();
blinkOutput = s.inputCapture.isOpened();
}
// Draw the corners.
drawChessboardCorners(view, s.boardSize, Mat(pointBuf), found);
}
//! [pattern_found]
//----------------------------- Output Text ------------------------------------------------
//! [output_text]
string msg = mode == CAPTURING ? "100/100" : mode == CALIBRATED ? "Calibrated" : "Press 'g' to start";
auto baseLine = 0;
const auto textSize = getTextSize(msg, 1, 1, 1, &baseLine);
const Point textOrigin(view.cols - 2 * textSize.width - 10, view.rows - 2 * baseLine - 10);
if (mode == CAPTURING)
{
if (s.showUndistorsed)
msg = format("%d/%d Undist", static_cast<int>(imagePoints.size()), s.nrFrames);
else
msg = format("%d/%d", static_cast<int>(imagePoints.size()), s.nrFrames);
}
putText(view, msg, textOrigin, 1, 1, mode == CALIBRATED ? GREEN : RED);
if (blinkOutput)
bitwise_not(view, view);
//! [output_text]
//------------------------- Video capture output undistorted ------------------------------
//! [output_undistorted]
if (mode == CALIBRATED && s.showUndistorsed)
{
const auto temp = view.clone();
if (s.useFisheye)
fisheye::undistortImage(temp, view, cameraMatrix, distCoeffs);
else
undistort(temp, view, cameraMatrix, distCoeffs);
}
//! [output_undistorted]
//------------------------------ Show image and check for input commands -------------------
//! [await_input]
imshow("Image View", view);
const auto key = static_cast<char>(waitKey(s.inputCapture.isOpened() ? 50 : s.delay));
if (key == ESC_KEY)
break;
if (key == 'u' && mode == CALIBRATED)
s.showUndistorsed = !s.showUndistorsed;
if (s.inputCapture.isOpened() && key == 'g')
{
mode = CAPTURING;
imagePoints.clear();
}
//! [await_input]
}
// -----------------------Show the undistorted image for the image list ------------------------
//! [show_results]
if (s.inputType == Settings::IMAGE_LIST && s.showUndistorsed)
{
Mat rview, map1, map2;
if (s.useFisheye)
{
Mat newCamMat;
fisheye::estimateNewCameraMatrixForUndistortRectify(cameraMatrix, distCoeffs, imageSize,
Matx33d::eye(), newCamMat, 1);
fisheye::initUndistortRectifyMap(cameraMatrix, distCoeffs, Matx33d::eye(), newCamMat, imageSize,
CV_16SC2, map1, map2);
}
else
{
initUndistortRectifyMap(
cameraMatrix, distCoeffs, Mat(),
getOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, 1, imageSize, nullptr), imageSize,
CV_16SC2, map1, map2);
}
for (size_t i = 0; i < s.imageList.size(); i++)
{
auto view = imread(s.imageList[i], IMREAD_COLOR);
if (view.empty())
continue;
remap(view, rview, map1, map2, INTER_LINEAR);
imshow("Image View", rview);
const auto c = static_cast<char>(waitKey());
if (c == ESC_KEY || c == 'q' || c == 'Q')
break;
}
}
//! [show_results]
return 0;
}
//! [compute_errors]
static double computeReprojectionErrors(const vector<vector<Point3f>>& objectPoints,
const vector<vector<Point2f>>& imagePoints,
const vector<Mat>& rvecs, const vector<Mat>& tvecs,
const Mat& cameraMatrix, const Mat& distCoeffs,
vector<float>& perViewErrors, const bool fisheye)
{
vector<Point2f> imagePoints2;
size_t totalPoints = 0;
double totalErr = 0;
perViewErrors.resize(objectPoints.size());
for (size_t i = 0; i < objectPoints.size(); ++i)
{
if (fisheye)
{
fisheye::projectPoints(objectPoints[i], imagePoints2, rvecs[i], tvecs[i], cameraMatrix,
distCoeffs);
}
else
{
projectPoints(objectPoints[i], rvecs[i], tvecs[i], cameraMatrix, distCoeffs, imagePoints2);
}
const auto err = norm(imagePoints[i], imagePoints2, NORM_L2);
const auto n = objectPoints[i].size();
perViewErrors[i] = static_cast<float>(std::sqrt(err * err / n));
totalErr += err * err;
totalPoints += n;
}
return std::sqrt(totalErr / totalPoints);
}
//! [compute_errors]
//! [board_corners]
static void calcBoardCornerPositions(const Size boardSize, const float squareSize, vector<Point3f>& corners,
const Settings::Pattern patternType /*= Settings::CHESSBOARD*/)
{
corners.clear();
switch (patternType)
{
case Settings::CHESSBOARD:
case Settings::CIRCLES_GRID:
for (auto i = 0; i < boardSize.height; ++i)
for (auto j = 0; j < boardSize.width; ++j)
corners.push_back(Point3f(j * squareSize, i * squareSize, 0));
break;
case Settings::ASYMMETRIC_CIRCLES_GRID:
for (auto i = 0; i < boardSize.height; i++)
for (auto j = 0; j < boardSize.width; j++)
corners.push_back(Point3f((2 * j + i % 2) * squareSize, i * squareSize, 0));
break;
default:
break;
}
}
//! [board_corners]
static bool runCalibration(Settings& s, Size& imageSize, Mat& cameraMatrix, Mat& distCoeffs,
vector<vector<Point2f>> imagePoints, vector<Mat>& rvecs, vector<Mat>& tvecs,
vector<float>& reprojErrs, double& totalAvgErr)
{
//! [fixed_aspect]
cameraMatrix = Mat::eye(3, 3, CV_64F);
if (s.flag & CALIB_FIX_ASPECT_RATIO)
cameraMatrix.at<double>(0, 0) = s.aspectRatio;
//! [fixed_aspect]
if (s.useFisheye)
{
distCoeffs = Mat::zeros(4, 1, CV_64F);
}
else
{
distCoeffs = Mat::zeros(8, 1, CV_64F);
}
vector<vector<Point3f>> objectPoints(1);
calcBoardCornerPositions(s.boardSize, s.squareSize, objectPoints[0], s.calibrationPattern);
objectPoints.resize(imagePoints.size(), objectPoints[0]);
//Find intrinsic and extrinsic camera parameters
double rms;
if (s.useFisheye)
{
Mat _rvecs, _tvecs;
rms = fisheye::calibrate(objectPoints, imagePoints, imageSize, cameraMatrix, distCoeffs, _rvecs,
_tvecs, s.flag);
rvecs.reserve(_rvecs.rows);
tvecs.reserve(_tvecs.rows);
for (auto i = 0; i < int(objectPoints.size()); i++)
{
rvecs.push_back(_rvecs.row(i));
tvecs.push_back(_tvecs.row(i));
}
}
else
{
rms = calibrateCamera(objectPoints, imagePoints, imageSize, cameraMatrix, distCoeffs, rvecs, tvecs,
s.flag);
}
cout << "Re-projection error reported by calibrateCamera: " << rms << endl;
const auto ok = checkRange(cameraMatrix) && checkRange(distCoeffs);
totalAvgErr = computeReprojectionErrors(objectPoints, imagePoints, rvecs, tvecs, cameraMatrix,
distCoeffs, reprojErrs, s.useFisheye);
return ok;
}
// Print camera parameters to the output file
static void saveCameraParams(Settings& s, Size& imageSize, Mat& cameraMatrix, Mat& distCoeffs,
const vector<Mat>& rvecs, const vector<Mat>& tvecs,
const vector<float>& reprojErrs, const vector<vector<Point2f>>& imagePoints,
const double totalAvgErr)
{
FileStorage fs(s.outputFileName, FileStorage::WRITE);
time_t tm;
time(&tm);
auto t2 = localtime(&tm);
char buf[1024];
strftime(buf, sizeof buf, "%c", t2);
fs << "calibration_time" << buf;
if (!rvecs.empty() || !reprojErrs.empty())
fs << "nr_of_frames" << static_cast<int>(std::max(rvecs.size(), reprojErrs.size()));
fs << "image_width" << imageSize.width;
fs << "image_height" << imageSize.height;
fs << "board_width" << s.boardSize.width;
fs << "board_height" << s.boardSize.height;
fs << "square_size" << s.squareSize;
if (s.flag & CALIB_FIX_ASPECT_RATIO)
fs << "fix_aspect_ratio" << s.aspectRatio;
if (s.flag)
{
stringstream flagsStringStream;
if (s.useFisheye)
{
flagsStringStream << "flags:"
<< (s.flag & fisheye::CALIB_FIX_SKEW ? " +fix_skew" : "")
<< (s.flag & fisheye::CALIB_FIX_K1 ? " +fix_k1" : "")
<< (s.flag & fisheye::CALIB_FIX_K2 ? " +fix_k2" : "")
<< (s.flag & fisheye::CALIB_FIX_K3 ? " +fix_k3" : "")
<< (s.flag & fisheye::CALIB_FIX_K4 ? " +fix_k4" : "")
<< (s.flag & fisheye::CALIB_RECOMPUTE_EXTRINSIC ? " +recompute_extrinsic" : "");
}
else
{
flagsStringStream << "flags:"
<< (s.flag & CALIB_USE_INTRINSIC_GUESS ? " +use_intrinsic_guess" : "")
<< (s.flag & CALIB_FIX_ASPECT_RATIO ? " +fix_aspectRatio" : "")
<< (s.flag & CALIB_FIX_PRINCIPAL_POINT ? " +fix_principal_point" : "")
<< (s.flag & CALIB_ZERO_TANGENT_DIST ? " +zero_tangent_dist" : "")
<< (s.flag & CALIB_FIX_K1 ? " +fix_k1" : "")
<< (s.flag & CALIB_FIX_K2 ? " +fix_k2" : "")
<< (s.flag & CALIB_FIX_K3 ? " +fix_k3" : "")
<< (s.flag & CALIB_FIX_K4 ? " +fix_k4" : "")
<< (s.flag & CALIB_FIX_K5 ? " +fix_k5" : "");
}
fs.writeComment(flagsStringStream.str());
}
fs << "flags" << s.flag;
fs << "fisheye_model" << s.useFisheye;
fs << "camera_matrix" << cameraMatrix;
fs << "distortion_coefficients" << distCoeffs;
fs << "avg_reprojection_error" << totalAvgErr;
if (s.writeExtrinsics && !reprojErrs.empty())
fs << "per_view_reprojection_errors" << Mat(reprojErrs);
if (s.writeExtrinsics && !rvecs.empty() && !tvecs.empty())
{
CV_Assert(rvecs[0].type() == tvecs[0].type()) ;
const Mat bigmat(static_cast<int>(rvecs.size()), 6, CV_MAKETYPE(rvecs[0].type(), 1));
const auto needReshapeR = rvecs[0].depth() != 1 ? true : false;
const auto needReshapeT = tvecs[0].depth() != 1 ? true : false;
for (size_t i = 0; i < rvecs.size(); i++)
{
auto r = bigmat(Range(int(i), int(i + 1)), Range(0, 3));
auto t = bigmat(Range(int(i), int(i + 1)), Range(3, 6));
if (needReshapeR)
rvecs[i].reshape(1, 1).copyTo(r);
else
{
//*.t() is MatExpr (not Mat) so we can use assignment operator
CV_Assert(rvecs[i].rows == 3 && rvecs[i].cols == 1) ;
r = rvecs[i].t();
}
if (needReshapeT)
tvecs[i].reshape(1, 1).copyTo(t);
else
{
CV_Assert(tvecs[i].rows == 3 && tvecs[i].cols == 1) ;
t = tvecs[i].t();
}
}
fs.writeComment("a set of 6-tuples (rotation vector + translation vector) for each view");
fs << "extrinsic_parameters" << bigmat;
}
if (s.writePoints && !imagePoints.empty())
{
Mat imagePtMat(static_cast<int>(imagePoints.size()), static_cast<int>(imagePoints[0].size()), CV_32FC2);
for (size_t i = 0; i < imagePoints.size(); i++)
{
auto r = imagePtMat.row(int(i)).reshape(2, imagePtMat.cols);
Mat imgpti(imagePoints[i]);
imgpti.copyTo(r);
}
fs << "image_points" << imagePtMat;
}
}
//! [run_and_save]
bool runCalibrationAndSave(Settings& s, Size imageSize, Mat& cameraMatrix, Mat& distCoeffs,
const vector<vector<Point2f>> imagePoints)
{
vector<Mat> rvecs, tvecs;
vector<float> reprojErrs;
double totalAvgErr = 0;
const auto ok = runCalibration(s, imageSize, cameraMatrix, distCoeffs, imagePoints, rvecs, tvecs, reprojErrs,
totalAvgErr);
cout << (ok ? "Calibration succeeded" : "Calibration failed")
<< ". avg re projection error = " << totalAvgErr << endl;
if (ok)
saveCameraParams(s, imageSize, cameraMatrix, distCoeffs, rvecs, tvecs, reprojErrs, imagePoints,
totalAvgErr);
return ok;
}
//! [run_and_save]
| [
"[email protected]"
] | |
d9848869b1ca88d1d24ce4ad38b77dd5077bb109 | 6e22d7679ebeb092232de6052ced81c7d8ab97a6 | /IMFC/FrameOne/MY.cpp | 376c244a3846733783491b10218a9f91699ba50d | [] | no_license | chengguixing/iArt | e3de63161bd91a18522612d6320453431824061d | c2d60e36f2f2a6a04b2188f20e7264cfc5d05dc4 | refs/heads/master | 2021-01-02T09:27:11.010862 | 2014-06-28T12:34:56 | 2014-06-28T12:34:56 | 22,207,953 | 4 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 115 | cpp | #include "my.h"
CMyWinApp theApp;
int main(void)
{
CWinApp* pApp = AfxGetApp();
system("pause");
return 0;
} | [
"[email protected]"
] | |
afad0a8d94c1b1b2b5d8e50204917278d6de5e38 | 8e4480aa00d78c5ebc36967b6c608c992246cb93 | /mem_sim_block.hpp | 7bdfb16fe6e7c1d931d54fbc2825121f459469b6 | [] | no_license | ppp2211/arch-cw2 | 92a48337efe722b3f5bee033cf665e8dcb12a82f | 327283919f5d534e12352a21ab03d9be20fbcf55 | refs/heads/master | 2021-03-27T19:10:14.068992 | 2016-01-21T21:21:06 | 2016-01-21T21:21:06 | 49,667,317 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 683 | hpp | #ifndef MEM_SIM_BLOCK_HPP
#define MEM_SIM_BLOCK_HPP
#include <vector>
#include <stdint.h>
using namespace std;
class block{
public:
block(int bw, int wb);
~block();
bool tag_match(unsigned searchtag) const;
bool is_valid() const;
bool is_dirty() const;
void read_data(vector<uint8_t> &dest) const;
int get_tag() const;
void validate();
void dirt();
void clean();
void store(vector<uint8_t> &src, unsigned newtag);
void replace_data(vector<uint8_t> &src);
void flush(vector<uint8_t> &toflush, vector<unsigned> &tags);
private:
unsigned tag;
bool valid;
bool dirty;
vector<uint8_t> data;
};
#endif
| [
"[email protected]"
] | |
6110fcc80e4cb53a076ba796ffd2ca92ce1727ca | ce690903b0cad896ea15642460c1d14c8ec4250e | /good/Filmora-Screen-Windows/FSCommonLib/VolumeSlider.cpp | 506923041230eff8138351b3c1aecb6ceb61bb6d | [] | no_license | LuckyKingSSS/demo | a572e280979a019246e6d51cb7c6bfa947829a5c | db4f55389d4ed2d3ada29083116654e2107e333e | refs/heads/master | 2021-07-05T22:09:17.065287 | 2017-09-28T05:51:51 | 2017-09-28T05:51:51 | 105,107,036 | 1 | 3 | null | null | null | null | GB18030 | C++ | false | false | 5,043 | cpp | #include "stdafx.h"
#include "inc_FSCommonlib/VolumeSlider.h"
#include "VolumeSlider_p.h"
#include "CommonWidgets.h"
VolumeSlider::VolumeSlider(QWidget *parent)
: QWidget(parent)
{
m_value = 0;
m_min = -51;
m_max = 100;
m_position = 0;
m_chunkWidth = 8;
m_grooveHeight = 2;
m_horizonal = false;
resize(20, 100);
}
void VolumeSlider::SetValue(int value)
{
m_value = qBound(m_min, value, m_max);
if (m_horizonal)
m_position = 1.0 * (m_value - m_min) / (m_max - m_min) * GetWidth();
else
m_position = GetWidth() - 1.0 * (m_value - m_min) / (m_max - m_min) * GetWidth();
update();
}
void VolumeSlider::SetRange(int minvalue, int maxvalue)
{
Q_ASSERT(maxvalue > minvalue);
m_min = minvalue;
m_max = maxvalue;
}
void VolumeSlider::GetRange(int &minvalue, int &maxvalue)
{
minvalue = m_min;
maxvalue = m_max;
}
int VolumeSlider::GetValue()
{
return m_value;
}
void VolumeSlider::SetChunkWidth(int w)
{
Q_ASSERT(w > 0);
m_chunkWidth = w;
}
void VolumeSlider::SetGrooveHeight(int h)
{
Q_ASSERT(h > 0);
m_grooveHeight = h;
}
void VolumeSlider::SetHorizontal(bool horizontal)
{
m_horizonal = horizontal;
}
bool VolumeSlider::GetHorizontal()
{
return m_horizonal;
}
void VolumeSlider::DoModal(QPoint p)
{
//if (m_show)
//{
// hide();
//}
//else
//{
// m_show = true;
p.setY(p.y() - height());
move(p);
show();
//}
}
int VolumeSlider::GetWidth()
{
if (m_horizonal)
return width() - m_chunkWidth;
else
return height() - m_chunkWidth;
}
void VolumeSlider::resizeEvent(QResizeEvent *event)
{
SetValue(m_value);
}
void VolumeSlider::mousePressEvent(QMouseEvent *event)
{
int value = CalculateValue(event->pos());
if (value != m_value)
{
m_value = value;
emit ValueChanged(m_value);
}
update();
}
//void Slider::mouseReleaseEvent(QMouseEvent *event)
//{
//}
//
void VolumeSlider::mouseMoveEvent(QMouseEvent *event)
{
mousePressEvent(event);
}
void VolumeSlider::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Left)
{
SetValue(GetValue() - 1);
}
else if (event->key() == Qt::Key_Right)
{
SetValue(GetValue() + 1);
}
}
void VolumeSlider::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
int left = 0;
int top = (height() - m_grooveHeight) / 2;
int h = m_grooveHeight;
//painter.fillRect(rect(), Qt::black);
if (m_horizonal)
{
painter.fillRect(QRect(left , top, width(), h), Qt::gray);
painter.fillRect(QRect(left, top, m_position, h), Qt::black);
painter.fillRect(QRect(m_position, (height() - m_chunkWidth) / 2, m_chunkWidth, m_chunkWidth), Qt::black);
}
else
{
painter.setBrush(QColor(0, 0, 0));
left = (width() - m_grooveHeight) / 2;
painter.fillRect(QRect(left, 0, m_grooveHeight, height()), Qt::gray);
painter.fillRect(QRect(left, m_position, m_grooveHeight, height() - m_position), Qt::black);
painter.fillRect(QRect((width() - m_chunkWidth) / 2, m_position, m_chunkWidth, m_chunkWidth), Qt::black);
}
}
int VolumeSlider::CalculateValue(QPoint p)
{
int position = m_horizonal ? p.x() : p.y();
m_position = qBound(0, position - m_chunkWidth / 2, GetWidth());
int value = 0;
if (m_horizonal)
{
value = qBound<int>(m_min, 1.0 * m_position / GetWidth() * (m_max - m_min) + m_min, m_max);
}
else
{
value = qBound<int>(m_min, 1.0 * (GetWidth() - m_position) / GetWidth() * (m_max - m_min) + m_min, m_max);
}
return value;
}
int VolumeSlider::CalculatePosition(int value)
{
m_position = (float)value / (m_max - m_min) * GetWidth();
return m_position;
}
//////////////////////////////////////////////////////////////////////////
AudioVolumeSlider::AudioVolumeSlider(QWidget *parent)
:QDialog(parent)
{
setWindowFlags(Qt::Popup);
setObjectName("AudioVolumeSliderDialog");
m_show = false;
m_slider = new ToolBarSlider(this, Qt::Vertical);
m_slider->setObjectName("myVolueSlider");
m_slider->setDuration(200.00);
m_slider->setValue(100);
resize(20, 100);
connect(m_slider, &ToolBarSlider::valueChanged, this, &AudioVolumeSlider::ValueChanged);
}
void AudioVolumeSlider::SetValue(int value)
{
m_slider->setValue(value);
}
int AudioVolumeSlider::GetValue()
{
return m_slider->value();
}
void AudioVolumeSlider::SetRange(int min, int max)
{
m_slider->setDuration(max - min);
}
void AudioVolumeSlider::SetHorizontal(bool horizontal)
{
if (horizontal)
{
m_slider->close();
m_slider = new ToolBarSlider(this, Qt::Horizontal);
m_slider->setObjectName("myVolueSlider");
m_slider->setDuration(200.00);
m_slider->setValue(100.00);
//重新设置大小
resize(100, 20);
}
else
{
m_slider->close();
m_slider = new ToolBarSlider(this, Qt::Vertical);
m_slider->setObjectName("myVolueSlider");
m_slider->setDuration(200.00);
m_slider->setValue(100.00);
}
}
void AudioVolumeSlider::DoModal(QPoint p)
{
p.setY(p.y() - height());
move(p);
show();
}
void AudioVolumeSlider::resizeEvent(QResizeEvent *event)
{
const int space = 5;
m_slider->setGeometry(space, space, width() - 2 * space, height() - 2 * space);
m_slider->SetChunkHeight(width() - 2 * space);
} | [
"[email protected]"
] | |
055af2f0663c821f2fc4964aa0e0c87a950db545 | 46cbd8ca773c1481bb147b54765985c636627d29 | /Ubuntu/Qt/FyCh/Supervisor.cpp | 943436bc3c15adfc87e1540aad480a351f3d9748 | [] | no_license | ator89/Cpp | e7ddb1ccd59ffa5083fced14c4d54403160f2ca7 | 9d6bd29e7d97022703548cbef78719536bc149fe | refs/heads/master | 2021-06-01T13:14:27.508828 | 2020-10-21T05:15:52 | 2020-10-21T05:15:52 | 150,691,862 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 55 | cpp | #include "Supervisor.h"
Supervisor::Supervisor()
{
}
| [
"[email protected]"
] | |
840c4c5be0af0bee964fd843bce4c0d71fde6c7c | c7105d7261f3bee66c1e8f29aedb465a8afdc040 | /CS12/Programs/Program_7/main.cpp | 035f97ffc00d1aa4c9e1952361241bf545d2c2e9 | [] | no_license | adrianmoo2/College-Schoolwork | 6d93122dbc248a89b613e617c5b03c61e63a34a9 | b042fab56515fea50d0881ad40c69b9f920896a8 | refs/heads/master | 2020-03-26T00:11:43.495623 | 2019-03-27T07:48:35 | 2019-03-27T07:48:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 648 | cpp | #include "SortedSet.h"
int main()
{
SortedSet set;
SortedSet set2;
set.add(5);
set.push_front(6);
set.push_back(8);
set2.add(10);
set2.add(11);
set2.add(5);
set2.add(6);
set.display();
cout << endl;
set2.display();
cout << endl;
cout << set.in(5) << endl;
cout << set.in(0) << endl;
SortedSet set3 = set &= set2;
set.display();
cout << endl;
set3.display();
set.pop_front();
set.pop_front();
set.pop_front();
set2.pop_front();
set2.pop_front();
set2.pop_front();
set2.pop_front();
} | [
"[email protected]"
] | |
028acd35d98dc86fca667347c81f476c2560769c | fab3558facbc6d6f5f9ffba1d99d33963914027f | /include/fcppt/log/error.hpp | 2d3892579ccb000db29d5a77d01fad953fc5ccba | [] | no_license | pmiddend/sgedoxy | 315aa941979a26c6f840c6ce6b3765c78613593b | 00b8a4aaf97c2c927a008929fb4892a1729853d7 | refs/heads/master | 2021-01-20T04:32:43.027585 | 2011-10-28T17:30:23 | 2011-10-28T17:30:23 | 2,666,694 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 545 | hpp | // Copyright Carl Philipp Reh 2009 - 2011.
// 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 FCPPT_LOG_ERROR_HPP_INCLUDED
#define FCPPT_LOG_ERROR_HPP_INCLUDED
#include <fcppt/log/level.hpp>
#include <fcppt/log/detail/level_if_enabled.hpp>
/// Log to a stream if the error level is enabled
#define FCPPT_LOG_ERROR(stream, x)\
FCPPT_LOG_DETAIL_LEVEL_IF_ENABLED(stream, fcppt::log::level::error, x)
#endif
| [
"[email protected]"
] | |
b6ce7040cdbee5e51075d92e6aa42e714e6c2bdd | a7764174fb0351ea666faa9f3b5dfe304390a011 | /drv/TopoDS/TopoDS_TCompound.ixx | b528b19f8a89bb15e7dffae32e3aad15c4c60830 | [] | no_license | uel-dataexchange/Opencascade_uel | f7123943e9d8124f4fa67579e3cd3f85cfe52d91 | 06ec93d238d3e3ea2881ff44ba8c21cf870435cd | refs/heads/master | 2022-11-16T07:40:30.837854 | 2020-07-08T01:56:37 | 2020-07-08T01:56:37 | 276,290,778 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 748 | ixx | // This file is generated by WOK (CPPExt).
// Please do not edit this file; modify original file instead.
// The copyright and license terms as defined for the original file apply to
// this header file considered to be the "object code" form of the original source.
#include <TopoDS_TCompound.jxx>
#ifndef _Standard_Type_HeaderFile
#include <Standard_Type.hxx>
#endif
IMPLEMENT_STANDARD_TYPE(TopoDS_TCompound)
IMPLEMENT_STANDARD_SUPERTYPE_ARRAY()
STANDARD_TYPE(TopoDS_TShape),
STANDARD_TYPE(MMgt_TShared),
STANDARD_TYPE(Standard_Transient),
IMPLEMENT_STANDARD_SUPERTYPE_ARRAY_END()
IMPLEMENT_STANDARD_TYPE_END(TopoDS_TCompound)
IMPLEMENT_DOWNCAST(TopoDS_TCompound,Standard_Transient)
IMPLEMENT_STANDARD_RTTI(TopoDS_TCompound)
| [
"[email protected]"
] | |
8d65017783019238fab11cda557a565e2a34b7e8 | 23e266370db7b2969d7ab34555c6975ebebb056a | /src/qt/peertablemodel.h | 655587f1d805743cdb675e89aeef11fb43e32e2c | [
"MIT"
] | permissive | FINALFINANCE/xnode | dff69e2e5ad0bf70d4453e600b643a609db9101c | f00b70da3876674e7fe2f2f399443285784086fe | refs/heads/master | 2023-02-17T17:57:06.510189 | 2021-01-10T11:08:55 | 2021-01-10T11:08:55 | 331,884,224 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,138 | h | // Copyright (c) 2011-2013 The Bitcoin developers
//Copyright (c) 2017-2019 The PIVX developers
//Copyright (c) 2020 The xnode developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_QT_PEERTABLEMODEL_H
#define BITCOIN_QT_PEERTABLEMODEL_H
#include "main.h"
#include "net.h"
#include <QAbstractTableModel>
#include <QStringList>
class ClientModel;
class PeerTablePriv;
QT_BEGIN_NAMESPACE
class QTimer;
QT_END_NAMESPACE
struct CNodeCombinedStats {
CNodeStats nodeStats;
CNodeStateStats nodeStateStats;
bool fNodeStateStatsAvailable;
};
class NodeLessThan
{
public:
NodeLessThan(int nColumn, Qt::SortOrder fOrder) : column(nColumn), order(fOrder) {}
bool operator()(const CNodeCombinedStats& left, const CNodeCombinedStats& right) const;
private:
int column;
Qt::SortOrder order;
};
/**
Qt model providing information about connected peers, similar to the
"getpeerinfo" RPC call. Used by the rpc console UI.
*/
class PeerTableModel : public QAbstractTableModel
{
Q_OBJECT
public:
explicit PeerTableModel(ClientModel* parent = 0);
const CNodeCombinedStats* getNodeStats(int idx);
int getRowByNodeId(NodeId nodeid);
void startAutoRefresh();
void stopAutoRefresh();
enum ColumnIndex {
Address = 0,
Subversion = 1,
Ping = 2
};
/** @name Methods overridden from QAbstractTableModel
@{*/
int rowCount(const QModelIndex& parent) const;
int columnCount(const QModelIndex& parent) const;
QVariant data(const QModelIndex& index, int role) const;
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
QModelIndex index(int row, int column, const QModelIndex& parent) const;
Qt::ItemFlags flags(const QModelIndex& index) const;
void sort(int column, Qt::SortOrder order);
/*@}*/
public Q_SLOTS:
void refresh();
private:
ClientModel* clientModel;
QStringList columns;
PeerTablePriv* priv;
QTimer* timer;
};
#endif // BITCOIN_QT_PEERTABLEMODEL_H
| [
"[email protected]"
] | |
bb20fcf4995ec4969e7f17521a240a5781db6f51 | 03a44baca9e6ed95705432d96ba059f16e62a662 | /Opentrains_Contest/10411/G.cpp | eb5122c71ce55bd722dc09ab38886f42a9305094 | [] | no_license | ytz12345/2019_ICPC_Trainings | 5c6e113afb8e910dd91c8340ff43af00a701c7c7 | cf0ce781675a7dbc454fd999693239e235fbbe87 | refs/heads/master | 2020-05-14T08:29:19.671739 | 2020-04-03T03:21:30 | 2020-04-03T03:21:30 | 181,722,314 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,609 | cpp | #include<cstring>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
#define rep(i,l,r) for(int i=l;i<=r;i++)
#define dow(i,l,r) for(int i=r;i>=l;i--)
#define rep0(i,r) for(int i=0,rr=(int)r;i<rr;i++)
#define fir first
#define sec second
#define mp make_pair
#define pb push_back
const int N=100510;
const int Mod = 1e9 + 7;
typedef long long ll;
ll px[N],py[N],vk[N],vv[N];
int n;
ll normal(ll x) {
return (x % Mod + Mod) % Mod;
}
ll calc(ll x) {
ll res = 1, k = Mod - 2;
for (x %= Mod ; k > 0; k >>= 1, x = x * x % Mod)
if (k & 1) res = res * x % Mod;
return normal(res);
}
int check(ll k,ll b,ll x,ll y)
{
return normal(y-(k*x+b))==0;
}
int check()
{
ll sumk=0,sumb=0;
rep(i,2,n-1) sumb=normal(sumb+vv[i-1]*px[i]);
rep(i,2,n-1) sumk=normal(sumk-vv[i-1]);
rep(i,1,n) {
if (!check(sumk,sumb,px[i],py[i])) return 0;
if (i>1 && i<n) sumb=normal(sumb-vv[i-1]*px[i]*2),sumk=normal(sumk+2*vv[i-1]);
}
return 1;
}
void solve()
{
scanf("%d",&n);
n++;
rep(i,1,n) {
scanf("%lld %lld",&px[i],&py[i]);
if (i>1) vk[i-1]=normal((py[i]-py[i-1])*calc(px[i]-px[i-1]));
}
ll sum=0;
// puts("");
// rep(i,1,n-1) printf("%.8lf ",vk[i]);puts("");
rep(i,2,n-1) sum=normal(sum+(vv[i-1]=normal((vk[i]-vk[i-1])*calc(2))));
// rep(i,1,n-2) printf("%.8lf ",vv[i]);puts("");
if (normal(sum+vk[1])==0 && check()) puts("Yes");
else puts("No");
}
int main()
{
solve();
return 0;
}
/*
2
-1 2
1 0
2 1
3
-3 -1
-1 -1
1 1
4 1
3
-3 1
-2 0
0 1
1 1
*/ | [
"[email protected]"
] | |
6320c9f7a67173c01aee7e58e79edf2aef7bec8a | 50bfe7fed2f3c30bbb209c42659f8fd525e672db | /PA2/include/object.h | 0e2dda76dc6a00154eec30bb9bbc8c2f256e69a6 | [] | no_license | samsonhaile14/OpenGL-Projects | b81f0c0870acd8127aed73fb56bf5d34bc906805 | 2bae05bf6ac557d2794e511ae05b03ddb7b36ce9 | refs/heads/master | 2021-06-20T22:03:21.924952 | 2017-08-14T03:29:09 | 2017-08-14T03:29:09 | 67,268,748 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 453 | h | #ifndef OBJECT_H
#define OBJECT_H
#include <vector>
#include "graphics_headers.h"
class Object
{
public:
Object();
~Object();
void Update(unsigned int dt, float movement[], bool pause);
void Render();
glm::mat4 GetModel();
private:
glm::mat4 model;
std::vector<Vertex> Vertices;
std::vector<unsigned int> Indices;
GLuint VB;
GLuint IB;
float orbitAngle;
float rotAngle;
};
#endif /* OBJECT_H */
| [
"[email protected]"
] | |
8415dc2883274c9312b4084291ffbcb21a91e0e4 | 73cfd700522885a3fec41127e1f87e1b78acd4d3 | /_Include/boost/range/algorithm/unique_copy.hpp | 7068be44b9183130e3bedf1d9d14827beeb223d8 | [] | no_license | pu2oqa/muServerDeps | 88e8e92fa2053960671f9f57f4c85e062c188319 | 92fcbe082556e11587887ab9d2abc93ec40c41e4 | refs/heads/master | 2023-03-15T12:37:13.995934 | 2019-02-04T10:07:14 | 2019-02-04T10:07:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,037 | hpp | ////////////////////////////////////////////////////////////////////////////////
// unique_copy.hpp
// Copyright Neil Groves 2009. Use, modification and
// distribution is subject to 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)
//
//
// For more information, see http://www.boost.org/libs/range/
//
#ifndef BOOST_RANGE_ALGORITHM_UNIQUE_COPY_HPP_INCLUDED
#define BOOST_RANGE_ALGORITHM_UNIQUE_COPY_HPP_INCLUDED
#include <boost/concept_check.hpp>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>
#include <boost/range/concepts.hpp>
#include <algorithm>
namespace boost
{
namespace range
{
/// \brief template function unique_copy
///
/// range-based version of the unique_copy std algorithm
///
/// \pre SinglePassRange is a model of the SinglePassRangeConcept
/// \pre OutputIterator is a model of the OutputIteratorConcept
/// \pre BinaryPredicate is a model of the BinaryPredicateConcept
template< class SinglePassRange, class OutputIterator >
inline OutputIterator
unique_copy( const SinglePassRange& rng, OutputIterator out_it )
{
BOOST_RANGE_CONCEPT_ASSERT(( SinglePassRangeConcept<const SinglePassRange> ));
return std::unique_copy(boost::begin(rng), boost::end(rng), out_it);
}
/// \overload
template< class SinglePassRange, class OutputIterator, class BinaryPredicate >
inline OutputIterator
unique_copy( const SinglePassRange& rng, OutputIterator out_it,
BinaryPredicate pred )
{
BOOST_RANGE_CONCEPT_ASSERT(( SinglePassRangeConcept<const SinglePassRange> ));
return std::unique_copy(boost::begin(rng), boost::end(rng), out_it, pred);
}
} // namespace range
using range::unique_copy;
} // namespace boost
#endif // include guard
/////////////////////////////////////////////////
// vnDev.Games - Trong.LIVE - DAO VAN TRONG //
////////////////////////////////////////////////////////////////////////////////
| [
"[email protected]"
] | |
9ad54f51858eeea72eeb9ecd3cad994b6d3314ef | a1259ba819f057205f5ce3ddd84a01ab7a378bdf | /src/DataLayer/FileInfoList.h | d7005ad93e57c5425558f97362bfa4ef0405acd2 | [] | no_license | Mesrop-Gevorgyan/ATRChipset | f47a66f38d5579a60cf89ee439c949fd026d7fe3 | 8bc9ca3f922befc3d09492748f291968fc3ff91a | refs/heads/master | 2020-04-14T18:47:35.684894 | 2017-04-30T12:52:55 | 2017-04-30T12:52:55 | 68,121,974 | 1 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 606 | h | #ifndef __FILEINFOLIST__
#define __FILEINFOLIST__
#include <QList>
#include "FileInfo.h"
class CFileInfoList
{
public:
CFileInfoList();
CFileInfoList(QList<FileInfo>);
void append(const FileInfo&);
const FileInfo& at(unsigned) const;
int count(const FileInfo&) const;
int count() const;
IDList getIDList() const;
int indexof(const FileInfo&) const;
bool contains(const FileInfo&) const;
bool isEmpty() const;
const FileInfo& operator[](unsigned ) const;
private:
QList <FileInfo> m_infos;
};
#endif // __FILEINFOLIST__
| [
"[email protected]"
] | |
6a48e90ead109e1e9134835b7ff311ec8080b773 | e9a0e4bac5c0676efec1e1f5d3008ab183a89f12 | /PET/src/NaISD.cc | b2b15493ccee75630c699a5651579eaeb39e85c5 | [] | no_license | fizyczny/G4_homework | d64344ffe656121ae2ee7166e9ff533ca1d73e2a | 5d28cd87dd0fd0f31ed6d80147eb1d6fb67b1908 | refs/heads/master | 2022-11-24T23:12:04.834936 | 2020-08-01T17:49:13 | 2020-08-01T17:49:13 | 254,691,109 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,935 | cc |
#include "NaISD.hh"
#include "G4HCofThisEvent.hh"
#include "G4Step.hh"
#include "G4ThreeVector.hh"
#include "G4SDManager.hh"
#include "G4ios.hh"
NaISD::NaISD(const G4String& name,
const G4String& hitsCollectionName,
G4int depthVal) : G4VSensitiveDetector(name)
{
collectionName.insert(hitsCollectionName);
hitsCollection=0L;
depth = depthVal;
}
NaISD::~NaISD()
{
}
void NaISD::Initialize(G4HCofThisEvent* hce)
{
hitsCollection = new NaIHitsCollection(SensitiveDetectorName, collectionName[0]);
//last - check
auto hitsCollId = G4SDManager::GetSDMpointer()->GetCollectionID(collectionName[0]);
hce->AddHitsCollection( hitsCollId, hitsCollection );
}
G4bool NaISD::ProcessHits(G4Step* step, G4TouchableHistory*)
{
G4double edep = GetEnergyDeposit(step);
G4double trackLenght = GetTrackLength(step);
G4int copyNr = GetCopyNr(step);
if ( edep==0. && trackLenght == 0. ) return false;
G4int hitsNr = hitsCollection->entries();
G4bool moduleAlreadyHit = false;
for(G4int i=0; i<hitsNr; i++)
{
G4int moduleCopyNr = (*hitsCollection)[i]->GetCopyNr();
if(copyNr == moduleCopyNr)
{
(*hitsCollection)[i]->Add(edep, trackLenght);
moduleAlreadyHit = true;
break;
}
}
if(!moduleAlreadyHit)
{
NaIHit* aHit = new NaIHit(copyNr);
aHit->Add(edep, trackLenght);
hitsCollection->insert( aHit );
}
return true;
}
G4double NaISD::GetEnergyDeposit(G4Step* step)
{
return step->GetTotalEnergyDeposit();
}
G4double NaISD::GetTrackLength(G4Step* step)
{
G4double stepLength = 0.;
//if ( step->GetTrack()->GetDefinition()->GetPDGCharge() != 0. )
//{
stepLength = step->GetStepLength();
//}
return stepLength;
}
G4int NaISD::GetCopyNr(G4Step* step)
{
G4int voulmeNr =
step->GetPostStepPoint()->GetTouchable()->GetReplicaNumber(depth);
return voulmeNr;
}
| [
"[email protected]"
] | |
bf1326d98da8d021b1ad06b8c3a3a0835a6a67b5 | 2f10f807d3307b83293a521da600c02623cdda82 | /deps/boost/win/debug/include/boost/metaparse/v1/if_.hpp | 7784f94dbcc3b48566c981cf763712e981e7aeed | [] | no_license | xpierrohk/dpt-rp1-cpp | 2ca4e377628363c3e9d41f88c8cbccc0fc2f1a1e | 643d053983fce3e6b099e2d3c9ab8387d0ea5a75 | refs/heads/master | 2021-05-23T08:19:48.823198 | 2019-07-26T17:35:28 | 2019-07-26T17:35:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 128 | hpp | version https://git-lfs.github.com/spec/v1
oid sha256:e98b3cda7e7d954be79d09bdcdec4ea2d1a646b6d9239c53bca79a4ab0744304
size 903
| [
"[email protected]"
] | |
c04212d24f29479246d9adf9324372c7189d00e8 | 6aeccfb60568a360d2d143e0271f0def40747d73 | /sandbox/SOC/2011/simd/libs/simd/mini_nt2/nt2/include/constants/fact_10.hpp | 9841f94fd0ea7d61feae9d257c22c3682cc7c3af | [] | no_license | ttyang/sandbox | 1066b324a13813cb1113beca75cdaf518e952276 | e1d6fde18ced644bb63e231829b2fe0664e51fac | refs/heads/trunk | 2021-01-19T17:17:47.452557 | 2013-06-07T14:19:55 | 2013-06-07T14:19:55 | 13,488,698 | 1 | 3 | null | 2023-03-20T11:52:19 | 2013-10-11T03:08:51 | C++ | UTF-8 | C++ | false | false | 173 | hpp | #ifndef NT2_INCLUDE_CONSTANTS_FACT_10_HPP_INCLUDED
#define NT2_INCLUDE_CONSTANTS_FACT_10_HPP_INCLUDED
#include <nt2/toolbox/constant/include/constants/fact_10.hpp>
#endif
| [
"[email protected]"
] | |
8676b9b1c0d1445591fc5c2147383bed7cef7d15 | b2531eced9be01fe6c8daf6949633454f24db47f | /CISCO/MFCApplication1/CBuildingBlocks.h | f81db311823128f65be8f71db1fa7dd5afbb9338 | [] | no_license | CheretaevIvan/VisualStudioProjects | 6f7575c97ead4b118a21d70c5a3ba1895e955cb5 | abdcac001e0d73387e2f7a704b8ea69e30ade2be | refs/heads/master | 2021-01-10T18:17:30.379719 | 2016-03-20T21:10:21 | 2016-03-20T21:10:21 | 54,338,383 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 1,922 | h | // Автоматически создаваемые классы-оболочки IDispatch, созданные при помощи мастера добавления класса из библиотеки типов
#import "C:\\Program Files (x86)\\Microsoft Office\\Office15\\MSWORD.OLB" no_namespace
// CBuildingBlocks класс-оболочка
class CBuildingBlocks : public COleDispatchDriver
{
public:
CBuildingBlocks(){} // Вызывает конструктор по умолчанию для COleDispatchDriver
CBuildingBlocks(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {}
CBuildingBlocks(const CBuildingBlocks& dispatchSrc) : COleDispatchDriver(dispatchSrc) {}
// Атрибуты
public:
// Операции
public:
// BuildingBlocks методы
public:
LPDISPATCH get_Application()
{
LPDISPATCH result;
InvokeHelper(0x3e8, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL);
return result;
}
long get_Creator()
{
long result;
InvokeHelper(0x3e9, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL);
return result;
}
LPDISPATCH get_Parent()
{
LPDISPATCH result;
InvokeHelper(0x3ea, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL);
return result;
}
long get_Count()
{
long result;
InvokeHelper(0x1, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL);
return result;
}
LPDISPATCH Item(VARIANT * Index)
{
LPDISPATCH result;
static BYTE parms[] = VTS_PVARIANT;
InvokeHelper(0x0, DISPATCH_METHOD, VT_DISPATCH, (void*)&result, parms, Index);
return result;
}
LPDISPATCH Add(LPCTSTR Name, LPDISPATCH Range, VARIANT * Description, long InsertOptions)
{
LPDISPATCH result;
static BYTE parms[] = VTS_BSTR VTS_DISPATCH VTS_PVARIANT VTS_I4;
InvokeHelper(0x65, DISPATCH_METHOD, VT_DISPATCH, (void*)&result, parms, Name, Range, Description, InsertOptions);
return result;
}
// BuildingBlocks свойства
public:
};
| [
"[email protected]"
] | |
d5654daa3bdc14a55e15bc432877e02cc071ae13 | 206bc173b663425bea338b7eb7bc8efc094167b5 | /aoj/ad/start/gcd.cpp | 37ca6a0eb64af8a63d4354eccbc99bbcc8527be9 | [] | no_license | rika77/competitive_programming | ac6e7664fe95249a3623c814e6a0c363c5af5f33 | a0f860c801e9197bcdd6b029ca3e46e73dfc4253 | refs/heads/master | 2022-03-01T09:03:01.056933 | 2019-11-07T01:45:28 | 2019-11-07T01:45:28 | 122,687,377 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 321 | cpp | //商は実はいらないのでした。
#include<iostream>
using namespace std;
//Euclid
int gcd(int x, int y){
if (x < y) swap(x,y);
// int q = x /y;
int r = x%y;
while (r!=0) {
x = y;
y = r;
// q = x/y;
r = x%y;
}
return y;
}
int main(){
int x,y;
cin >> x >> y;
cout << gcd(x,y) << endl;
return 0;
}
| [
"[email protected]"
] | |
852fdbd938ab4b2e814092a8f5e755ecdbafccae | 973e6b6952070cc2923d117aaa7772d9d010439b | /src/drivers/include/drivers/timer.h | 56e89b59074c66be5de000d0681de5a5ca0148ba | [] | no_license | delta/codecharacter-simulator-2020 | af4169dc79e709341ec61a0ad0263bdb0077ecbb | 1f1224aee3a15a8adaa7e68ee05dd35e053f2470 | refs/heads/master | 2023-03-25T22:17:03.967380 | 2021-03-19T15:30:08 | 2021-03-19T15:30:08 | 190,995,166 | 2 | 0 | null | 2021-03-22T10:58:31 | 2019-06-09T10:54:15 | C++ | UTF-8 | C++ | false | false | 1,829 | h | /**
* @file timer.h
* Declarations for a timer utility
*/
#pragma once
#include "drivers/drivers_export.h"
#include <atomic>
#include <chrono>
#include <cstdint>
#include <functional>
#include <thread>
namespace drivers {
/**
* An asynchronous timer class
*/
class DRIVERS_EXPORT Timer {
public:
/**
* Interval of time
*/
typedef std::chrono::milliseconds Interval;
private:
/**
* True if this timer is running, false otherwise
*/
std::atomic_bool is_running;
/**
* Temporary used by the stop method
* Set to true by stop, and reset to false right before stop returns
*/
std::atomic_bool stop_timer;
/**
* Amount of time the timer has been running for
* Valid if is_running is true
*/
Interval timer_run_duration;
/**
* Timer wakes up every timer_wake_up_duration ms to check if it has been
* stopped
*/
Interval timer_wake_up_duration;
public:
/**
* Callback that timer can call
*/
typedef std::function<void(void)> Callback;
/**
* Constructor for Timer
*/
Timer();
Timer(Interval timer_wake_up_duration);
/**
* Starts this timer. Works only if is_running is false.
* Spawns a separate thread for the timer
*
* @param[in] total_timer_duration The total timer run duration
* @param[in] callback The callback when timer expires
*
* @return false if is_running is true, else true
*/
bool start(Interval total_timer_duration, const Callback &callback);
/**
* Method to stop the timer
*
* Stopped timer won't call callback unless it's very close to expiring
* already.
* Blocks for at most timer_wake_up_duration ms
*/
void stop();
};
} // namespace drivers
| [
"[email protected]"
] | |
70be104bf34f0595e6901d57a220cad9175c55e0 | fa5924957c3261a28c05d64d4c589d09331a0a67 | /bullet_testbed/simulator.h | a3b61e9031611f5dd652fc181119a1053579350f | [] | no_license | emezeske/museum-of-ancient-artifacts | 8388be7ef5868fb53985a1352b88ddab93f9a22b | 2c5d02dcbd96f2d98d13888de163fddb349e0c1a | refs/heads/master | 2022-11-16T16:08:35.224440 | 2020-07-12T22:24:09 | 2020-07-12T22:24:09 | 279,150,235 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 612 | h | #ifndef SIMULATOR_H
#define SIMULATOR_H
#include <btBulletDynamicsCommon.h>
class Simulator
{
public:
Simulator();
virtual ~Simulator();
virtual void addRigidBody( btRigidBody *body );
virtual void removeRigidBody( btRigidBody *body );
virtual void resetCollisionObjects();
virtual void doOneStep( double stepTime );
protected:
static const float SIMULATION_STEP_SIZE = 1.0f / 60.0f;
btDynamicsWorld *dynamicsWorld;
btOverlappingPairCache *overlappingPairCache;
btCollisionDispatcher *dispatcher;
btConstraintSolver *solver;
double timeAccumulator;
};
#endif // SIMULATOR_H
| [
"[email protected]"
] | |
18d3031718c511d9155a163ec04b50ea5defaa3d | eb95f49fc2a0d6f83172894588fc5e520fbfddc2 | /test/test.cpp | d57b536db6ef19f0e3d907354802fa88ad731e49 | [
"MIT"
] | permissive | hitrich/Autonomous_Car_Lane_Det | 72373437fd551ec4811240a7f56ffec35feca993 | c4546663e2ac4a922f79aa17ade0994b57d13b58 | refs/heads/master | 2023-05-28T05:16:37.958425 | 2021-06-01T05:28:09 | 2021-06-01T05:28:09 | 372,710,598 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,767 | cpp | #include <opencv2/highgui/highgui.hpp>
#include <gtest/gtest.h>
#include<iostream>
#include <string>
#include <vector>
#include "opencv2/opencv.hpp"
#include "../include/LaneDetector.hpp"
/**
*@brief Function very similar to demo.cpp. It tests only one iteration of the algorithm for a single image.
*@param video is a flag that selects the demo video or an image without lanes for testing purposes
*@param frame_number gives the exact frame number of the input video
*@return flag_plot tells if the demo has sucessfully finished
*/
int testing_lanes(int video, int frame_number) {
LaneDetector lanedetector; // LaneDetector class object
cv::Mat frame;
cv::Mat img_denoise;
cv::Mat img_edges;
cv::Mat img_mask;
cv::Mat img_lines;
std::vector<cv::Vec4i> lines;
std::vector<std::vector<cv::Vec4i> > left_right_lines;
std::vector<cv::Point> lane;
std::string turn;
int flag_plot = -1;
// Select demo video or image without any lines
if (video == 1) {
cv::VideoCapture cap("project_video.mp4");
cap.set(cv::CAP_PROP_POS_FRAMES, frame_number);
cap.read(frame);
} else {
frame = cv::imread("gradient1.png");
}
// The input argument is the location of the video
img_denoise = lanedetector.deNoise(frame);
// Detect edges in the image
img_edges = lanedetector.edgeDetector(img_denoise);
// Mask the image so that we only get the ROI
img_mask = lanedetector.mask(img_edges);
// Obtain Hough lines in the cropped image
lines = lanedetector.houghLines(img_mask);
if (!lines.empty()) {
// Separate lines into left and right lines
left_right_lines = lanedetector.lineSeparation(lines, img_edges);
// Apply regression to obtain only one line for each side of the lane
lane = lanedetector.regression(left_right_lines, frame);
// Predict the turn by determining the vanishing point of the the lines
turn = lanedetector.predictTurn();
// Plot lane detection
flag_plot = lanedetector.plotLane(frame, lane, turn);
} else {
flag_plot = -1;
}
return flag_plot;
}
/**
*@brief Test case to test if lane is detected and if the lane is turning left.
*/
TEST(LaneTest, lane_detected) {
EXPECT_EQ(testing_lanes(1, 3), 0);
}
/**
*@brief Test cases to test if lane is detected and if the lane is going straight.
*/
TEST(LaneTest, no_turn) {
EXPECT_EQ(testing_lanes(1, 530), 0);
}
/**
*@brief Test cases to test if lane is detected and if the lane is turning right.
*/
TEST(LaneTest, right_turn) {
EXPECT_EQ(testing_lanes(1, 700), 0);
}
/**
*@brief Test cases to test if lane is not detected at all.
*/
TEST(LaneTest, lane_not_detected) {
EXPECT_EQ(testing_lanes(0, 1), -1);
}
| [
"[email protected]"
] | |
36806e7d6d489ec2a9b839601d86a861dddae829 | 242e828547e81581606d68ea05327880ff80076d | /src/Worker.cpp | bed428c09e0b8bc0ce2a7a5fc19f049e96cedc03 | [
"MIT"
] | permissive | entanmo/node-pow-addon | af7da117b93fd7e4e79130727eaeb33eaa2a028e | 88260e0b36006e182b05fe0f8d85a2b43e635adc | refs/heads/master | 2020-03-23T19:19:59.140387 | 2018-07-23T06:16:32 | 2018-07-23T06:16:32 | 141,969,691 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,596 | cpp | #include "Worker.h"
#include <iostream>
using namespace std;
namespace entanmo {
void Worker::startWorking() {
lock_guard<mutex> l(mMutex);
if (mWork) {
WorkerState ex = WorkerState::kStopped;
mState.compare_exchange_strong(ex, WorkerState::kStarting);
} else {
mState = WorkerState::kStarting;
mWork.reset(new thread([&]() {
while (mState != WorkerState::kKilling) {
WorkerState ex = WorkerState::kStarting;
bool ok = mState.compare_exchange_strong(ex, WorkerState::kStarted);
(void)ok;
try {
workLoop();
} catch (const std::exception &_e) {
std::cerr << "Exception throw in Worker thread: " << _e.what() << std::endl;
}
ex = mState.exchange(WorkerState::kStopped);
if (ex == WorkerState::kKilling || ex == WorkerState::kStarting) {
mState.exchange(ex);
}
while (mState == WorkerState::kStopped) {
this_thread::sleep_for(chrono::milliseconds(20));
}
}
}));
}
while (mState == WorkerState::kStarting) {
this_thread::sleep_for(chrono::microseconds(20));
}
}
void Worker::stopWorking() {
lock_guard<mutex> l(mMutex);
if (mWork) {
WorkerState ex = WorkerState::kStarted;
mState.compare_exchange_strong(ex, WorkerState::kStopping);
while (mState != WorkerState::kStopped) {
this_thread::sleep_for(chrono::microseconds(20));
}
}
}
Worker::~Worker() {
lock_guard<mutex> l(mMutex);
if (mWork) {
mState.exchange(WorkerState::kKilling);
mWork->join();
mWork.reset();
}
}
} | [
"[email protected]"
] | |
e7a092d14467eb0c7c9014d399a48a83bb073ae0 | 2a5d4544cf877439f4d274738750e0bb607d1c72 | /spoj/anarc09c.cpp | 34911c83c9084a2a30efeccc7acd79775f010067 | [] | no_license | shivam215/code | 65294836832a0eb76a2156a872b1803bb0b68075 | d70751ca0add4a42a0b91ee8805eda140028452a | refs/heads/master | 2021-01-11T08:32:55.557166 | 2017-09-13T16:00:41 | 2017-09-13T16:00:41 | 76,486,143 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,030 | cpp | #include <bits/stdc++.h>
using namespace std;
int fac1[1000006],fac2[1000006];
int main()
{
int a,b,i,coun,res;
cin>>a>>b;
int test=1;
while(a!=0 && b!=0)
{
memset(fac1,0,sizeof(fac1));
memset(fac2,0,sizeof(fac2));
while(a%2==0)
{
fac1[2]++;
a = a/2;
}
for(i=3;i*i<=a;i+=2)
{
while(a%i==0){fac1[i]++;a=a/i;}
}
if(a>1)fac1[a]++;
while(b%2==0)
{
fac2[2]++;
b = b/2;
}
for(i=3;i*i<=b;i+=2)
{
while(b%i==0){fac2[i]++;b=b/i;}
}
if(b>1)fac2[b]++;
//for(i=1;i<12;i++)cout<<fac1[i]<<' '<<fac2[i]<<endl;
coun=0;res=0;
for(i=2;i<=1000000;i++)
{
if(fac1[i] || fac2[i])
{
coun++;
res += abs(fac1[i]-fac2[i]);
}
}
cout<<test<<". "<<coun<<":"<<res<<endl;
test++;
cin>>a>>b;
}
}
| [
"[email protected]"
] | |
3979f756e218f08ad8649477be2052ab88f9d58e | 761edd39dd74aca01efa60eb6948c12b3edf560e | /Increasing Array.cpp | 5d34ab1a22550259b8b6390dafd774ae5407e59a | [] | no_license | nduchuyvp123/Hamic-Algo | 9cbabca41c4ded8efe2b52b14e92a81d06061203 | 08452f0fe5e26e798c1b4476312baeabcd33215d | refs/heads/master | 2023-05-07T17:17:12.170644 | 2021-05-31T17:26:25 | 2021-05-31T17:26:25 | 324,581,769 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 566 | cpp | #include <vector>
#include <iostream>
#include <string>
#include <algorithm>
#include <cmath>
using namespace std;
int main(int argc, char const *argv[])
{
unsigned long long int n;
cin >> n;
vector<unsigned long long int> a(n);
for (unsigned long long int i = 0; i < n; i++)
{
cin >> a[i];
}
unsigned long long int c = 0;
for (unsigned long long int i = 1; i < n; i++)
{
if (a[i] < a[i - 1])
{
c += a[i - 1] - a[i];
a[i] = a[i - 1];
}
}
cout << c;
return 0;
} | [
"[email protected]"
] | |
c28fe0c4a57185b888286e190529b659819c1808 | 6848723448cc22474863f6506f30bdbac2b6293e | /tools/mosesdecoder-master/lm/builder/combine_counts.hh | 2eda5170492eb971a15d567448da4acc6c4b652b | [
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"LGPL-2.1-or-later",
"LicenseRef-scancode-other-copyleft",
"GPL-2.0-only",
"Apache-2.0"
] | permissive | Pangeamt/nectm | 74b3052ba51f227cd508b89d3c565feccc0d2f4f | 6b84f048698f2530b9fdbb30695f2e2217c3fbfe | refs/heads/master | 2022-04-09T11:21:56.646469 | 2020-03-30T07:37:41 | 2020-03-30T07:37:41 | 250,306,101 | 1 | 0 | Apache-2.0 | 2020-03-26T16:05:11 | 2020-03-26T16:05:10 | null | UTF-8 | C++ | false | false | 904 | hh | #ifndef LM_BUILDER_COMBINE_COUNTS_H
#define LM_BUILDER_COMBINE_COUNTS_H
#include "lm/builder/payload.hh"
#include "lm/common/ngram.hh"
#include "lm/common/compare.hh"
#include "lm/word_index.hh"
#include "util/stream/sort.hh"
#include <functional>
#include <string>
namespace lm {
namespace builder {
// Sum counts for the same n-gram.
struct CombineCounts {
bool operator()(void *first_void, const void *second_void, const SuffixOrder &compare) const {
NGram<BuildingPayload> first(first_void, compare.Order());
// There isn't a const version of NGram.
NGram<BuildingPayload> second(const_cast<void*>(second_void), compare.Order());
if (memcmp(first.begin(), second.begin(), sizeof(WordIndex) * compare.Order())) return false;
first.Value().count += second.Value().count;
return true;
}
};
} // namespace builder
} // namespace lm
#endif // LM_BUILDER_COMBINE_COUNTS_H
| [
"[email protected]"
] | |
192e35e28c7566cdaa1ee8d15aca9305fbc71863 | 112d4a263c3e9fc775fa82288a20a34b1efbe52d | /Material/RobertLafore_Book/Book_SourceCode/Progs/Ch07/sstrchar.cpp | b9e59beb2ad3187b190dfc109837edd6b4292542 | [
"MIT"
] | permissive | hpaucar/OOP-C-plus-plus-repo | 369e788eb451f7d5804aadc1eb5bd2afb0758100 | e1fedd376029996a53d70d452b7738d9c43173c0 | refs/heads/main | 2023-02-03T12:23:19.095175 | 2020-12-26T03:07:54 | 2020-12-26T03:07:54 | 324,466,086 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 661 | cpp | //sstrchar.cpp
//accessing characters in string objects
#include <iostream>
#include <string>
using namespace std;
int main()
{
char charray[80];
string word;
cout << "Enter a word: ";
cin >> word;
int wlen = word.length(); //length of string object
cout << "One character at a time: ";
for(int j=0; j<wlen; j++)
cout << word.at(j); //exception if out-of-bounds
// cout << word[j]; //no warning if out-of-bounds
word.copy(charray, wlen, 0); //copy string object to array
charray[wlen] = 0; //terminate with '\0'
cout << "\nArray contains: " << charray << endl;
return 0;
} | [
"[email protected]"
] | |
53f85f30bfb6eac3daf2c17e03252e24297c73c5 | 86df6f8f4f3c03cccc96459ad82bcdf3bf942492 | /misc/google/clone-graph.cc | cd57daf5d294160b9d441e1aa22b65a81b6e2f5c | [] | no_license | bdliyq/algorithm | 369d1fd2ae3925a559ebae3fa8f5deab233daab1 | e1c993a5d1531e1fb10cd3c8d686f533c9a5cbc8 | refs/heads/master | 2016-08-11T21:49:31.259393 | 2016-04-05T11:10:30 | 2016-04-05T11:10:30 | 44,576,582 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,411 | cc | // Question: 克隆有向图。
struct GraphNode {
int val;
vector<GraphNode*> neighbors;
GraphNode(int x) : val(x) {}
};
typedef unordered_set<GraphNode*> DirectedGraph;
// non recursion.
DirectedGraph clone(DirectedGraph& g) {
DirectedGraph ans;
unordered_map<GraphNode*, GraphNode*> m;
queue<GraphNode*> q;
for (auto node : g) {
q.push(node);
}
while (!q.empty()) {
auto node = q.front();
q.pop();
if (m.count(node) == 0) {
m[node] = new GraphNode(node->val);
}
auto new_node = m[node];
for (auto nei : node->neighbors) {
if (m.count(nei) == 0) {
q.push(nei);
m[nei] = new GraphNode(nei->val);
}
new_node->neighbors.push_back(m[nei]);
}
ans.insert(new_node);
}
return ans;
}
// recursion.
DirectedGraph clone(DirectedGraph& g) {
DirectedGraph ans;
unordered_map<GraphNode*, GraphNode*> m;
for (auto node : g) {
ans.insert(bfs(node, m));
}
return ans;
}
GraphNode* bfs(GraphNode* node, unordered_map<GraphNode*, GraphNode*>& m) {
if (m.count(node) > 0) {
return m[node];
}
m[node] = new GraphNode(node->val);
auto newnode = m[node];
for (auto nei : node->neighbors) {
newnode->neighbors.push_back(bfs(nei, m));
}
return newnode;
}
| [
"[email protected]"
] | |
ff5509db4db934e912a44aabd6e9a7f4eb403854 | 39eae5cc024b6631a3a77853afed6983d8af31fe | /mix/workspace_vs/YY_WJX/TRANSACTION/Transaction.cpp | ae69cba79c3887188321e384edd555ca4f1714a0 | [] | no_license | SniperXiaoJun/mix-src | cd83fb5fedf99b0736dd3a5a7e24e86ab49c4c3b | 4d05804fd03894fa7859b4837c50b3891fc45619 | refs/heads/master | 2020-03-30T06:21:14.855395 | 2018-09-28T03:32:55 | 2018-09-28T03:32:55 | 150,854,539 | 1 | 0 | null | 2018-09-29T10:44:41 | 2018-09-29T10:44:41 | null | GB18030 | C++ | false | false | 1,212 | cpp | #include <iostream>
using namespace std;
#include "Transaction.h"
#include "../SIPProtocol/MsgFactory.h"
#ifdef MEMORY_TEST
#include "../Test/debug_new.h"
#endif
CTransaction::~CTransaction()
{
delete m_pLastReqMsg;
m_pLastReqMsg = NULL;
};
//////////////////////////////////////////////////////////////////////
// void CTransaction::handle_receive_data()
// 输入参数:
// 无
// 输出参数:
// 无
// 说明:
// 处理异步接受数据
// 返回值:
// 无
// 创建人
// 2010-08-03 闫海成
//////////////////////////////////////////////////////////////////////
void CTransaction::HandleReceiveData(const Byte *pMsg, u32 ulLen)
{
CMsgFactory myFactory(m_pSIPFunc);
CUAPMsg *pSipMsg = myFactory.CreateMsg(pMsg, ulLen);
int iFlag = pSipMsg->ParseMsg();
string strLastBran = m_pLastReqMsg->GetField(VIA_BRANCH).GetValueString();
string strNewBran = pSipMsg->GetField(VIA_BRANCH).GetValueString();
if (m_pLastReqMsg != NULL && (strLastBran != strNewBran))
{
m_pDataReceiver->ReceiveData(this);
delete pSipMsg;
pSipMsg = NULL;
return;
}
if (0 == iFlag)
{
SetResponse(*pSipMsg);
}
delete pSipMsg;
pSipMsg = NULL;
}
| [
"[email protected]"
] | |
73304ea7bf8ae0aa470e321b3ae1e1785e84a8bf | 54d9dc6b0ef41db57426dce1586d12ed571fded6 | /student.cpp | ce15f9da5bf977ae6c6eab206a53df176818c9ce | [] | no_license | rick-richardson/rosterProject | f8d748e48d21f4dcd7bfcca32f617342129be140 | 614950d343be1f758c62597cdc59768fec39fffa | refs/heads/main | 2023-08-15T00:44:07.219292 | 2021-10-01T04:23:19 | 2021-10-01T04:23:19 | 412,323,129 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,150 | cpp | #include <string>
#include <iostream>
#include "student.h"
using namespace std;
//D.2.a.
string Student::getID()
{
return studentID;
}
string Student::getFirstName()
{
return firstName;
}
string Student::getLastName()
{
return lastName;
}
string Student::getEmailAddress()
{
return emailAddress;
}
string Student::getAge()
{
return age;
}
int Student::getDays(int daysArray)
{
return daysInCourse[daysArray];
}
DegreeProgram Student::getDegreeProgram()
{
return degree;
}
//D.2.b.
void Student::setID(string studentID)
{
this->studentID = studentID;
}
void Student::setFirstName(string firstName)
{
this->firstName = firstName;
}
void Student::setLastName(string lastName)
{
this->lastName = lastName;
}
void Student::setEmailAddress(string emailAddress)
{
this->emailAddress = emailAddress;
}
void Student::setAge(string age)
{
this->age = age;
}
void Student::setDays(int day1, int day2, int day3)
{
this->daysInCourse[0] = day1; this->daysInCourse[1] = day2; this->daysInCourse[2] = day3;
}
void Student::setDegreeProgram(DegreeProgram degree)
{
this->degree = degree;
}
//D.2.d.
Student::Student() {
this->studentID = "";
this->firstName = "";
this->lastName = "";
this->emailAddress = "";
this->age = "";
for (int i = 0; i < 3; i++)
{
this->daysInCourse[i] = 0;
}
this->degree = UNDECIDED;
};
//D.2.e.
void Student::print(int arrayPosition) {
switch (arrayPosition) {
case 0:
cout << studentID;
break;
case 1:
cout << firstName;
break;
case 2:
cout << lastName;
break;
case 3:
cout << emailAddress;
break;
case 4:
cout << age;
break;
case 5:
cout << daysInCourse[0];
break;
case 6:
cout << daysInCourse[1];
break;
case 7:
cout << daysInCourse[2];
break;
case 8:
cout << degree;
break;
default:
cout << "NULL";
break;
}
} | [
"[email protected]"
] | |
7cc49edbcd5c2be8b65ede6b93676e5b6ddcc3f5 | 9f0c41bb41e9ec9d4c1e9e15d2d6d09f0a40fefc | /extern/partio/src/lib/io/NEW_BGEO.cpp | a5ee38c050411096859064e1a08ac5dbcd205560 | [
"MIT"
] | permissive | ttnghia/SPlisHSPlasH | 92a7eb7f39b3a4eaa41abf7962180198b0043e68 | ba9ee401844c43b554018b484decf897df544753 | refs/heads/master | 2021-01-17T17:00:57.121154 | 2017-04-24T16:35:22 | 2017-04-24T16:35:22 | 84,127,190 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 16,776 | cpp | /*
Copyright Disney Enterprises, Inc. All rights reserved.
This license governs use of the accompanying software. If you use the software, you
accept this license. If you do not accept the license, do not use the software.
1. Definitions
The terms "reproduce," "reproduction," "derivative works," and "distribution" have
the same meaning here as under U.S. copyright law. A "contribution" is the original
software, or any additions or changes to the software. A "contributor" is any person
that distributes its contribution under this license. "Licensed patents" are a
contributor's patent claims that read directly on its contribution.
2. Grant of Rights
(A) Copyright Grant- Subject to the terms of this license, including the license
conditions and limitations in section 3, each contributor grants you a non-exclusive,
worldwide, royalty-free copyright license to reproduce its contribution, prepare
derivative works of its contribution, and distribute its contribution or any derivative
works that you create.
(B) Patent Grant- Subject to the terms of this license, including the license
conditions and limitations in section 3, each contributor grants you a non-exclusive,
worldwide, royalty-free license under its licensed patents to make, have made,
use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the
software or derivative works of the contribution in the software.
3. Conditions and Limitations
(A) No Trademark License- This license does not grant you rights to use any
contributors' name, logo, or trademarks.
(B) If you bring a patent claim against any contributor over patents that you claim
are infringed by the software, your patent license from such contributor to the
software ends automatically.
(C) If you distribute any portion of the software, you must retain all copyright,
patent, trademark, and attribution notices that are present in the software.
(D) If you distribute any portion of the software in source code form, you may do
so only under this license by including a complete copy of this license with your
distribution. If you distribute any portion of the software in compiled or object code
form, you may only do so under a license that complies with this license.
(E) The software is licensed "as-is." You bear the risk of using it. The contributors
give no express warranties, guarantees or conditions. You may have additional
consumer rights under your local laws which this license cannot change.
To the extent permitted under your local laws, the contributors exclude the
implied warranties of merchantability, fitness for a particular purpose and non-
infringement.
*/
#include "PartioBinaryJson.h"
#include <fstream>
#include <cstdlib>
#include <cstring>
#include "../Partio.h"
ENTER_PARTIO_NAMESPACE
struct BGEOAttributeType:public JSONParser<BGEOAttributeType>
{
std::string attrName;
BGEOAttributeType(JSONParserState& state)
:JSONParser<BGEOAttributeType>(state)
{}
bool arrayBegin(const char* key){
throw JSONParseError("unexpected array begin",state);
}
void string(const char* key,const std::string& s){
//std::cerr<<"key "<<keyString(key)<<" string "<<s<<std::endl;
if(strcmp(key,"name")==0){
attrName=s;
}
}
template<class T> void numberData(const char* key,T x){
throw JSONParseError("unexpected number data",state);
}
void boolData(const char* key,bool x){
throw JSONParseError("unexpected number data",state);
}
bool mapBegin(const char* key){
//std::cerr<<"map "<<key<<std::endl;
return false;}
void mapEnd(){
//std::cerr<<"mapend"<<std::endl;
}
void arrayEnd(){
}
template<class T> bool uniformArray(const char* currKey,int length){
return false;
}
};
struct BGEOAttributeValues:public JSONParser<BGEOAttributeValues>
{
const char* attrName;
std::string storage;
int size;
Partio::ParticlesDataMutable* particles;
std::vector<int> packing;
BGEOAttributeValues(JSONParserState& state,Partio::ParticlesDataMutable* particles,const char* attrName)
:JSONParser<BGEOAttributeValues>(state),attrName(attrName),storage(""),size(0),particles(particles)
{
std::cerr<<"BGEOAttributeValues"<<std::endl;
}
void string(const char* key,const std::string& s){
if(strcmp(key,"storage")==0){
storage=s;
}
std::cerr<<"key "<<keyString(key)<<" string "<<s<<std::endl;
}
template<class T> bool uniformArray(const char* key,int length){
std::cerr<<"uniform array starting with "<<keyString(key)<<" lenght "<<length<<std::endl;
//for(int64 i=0;i<length;i++){
// T val=((JSONParser<BGEOAttributeValues>*)this)->numberData<T>();
// std::cerr<<" key "<<keyString(key)<<" "<<val<<std::endl;
//}
//return true;
if(strcmp(key,"rawpagedata")==0){
// TODO: check for size and storage
int nparts=particles->numParticles();
std::cerr<<"attr "<<attrName<<" reading raw page data with packing ";
for(size_t k=0;k<packing.size();k++) std::cerr<<" "<<packing[k];
std::cerr<<" storage "<<storage<<" length "<<length<<std::endl;
if(strcmp(attrName,"P")==0) attrName="position";
if(storage.substr(0,2)=="fp"){
Partio::ParticleAttribute attrH=particles->addAttribute(attrName,Partio::FLOAT,size);
int num=length/size;
int offset=0;
if(packing.size()==0) packing.push_back(size); // if no packing then full
for(size_t pack=0;pack<packing.size();pack++){
int packsize=packing[pack];
for(int i=0;i<num;i++){
float* partioVal=particles->dataWrite<float>(attrH,i);
for(int k=0;k<packsize;k++){
T val=((JSONParser<BGEOAttributeValues>*)this)->numberData<T>();
partioVal[offset+k]=val;
}
}
offset+=packing[pack];
}
}else if(storage.substr(0,3)=="int" || storage.substr(0,4)=="uint"){
Partio::ParticleAttribute attrH=particles->addAttribute(attrName,Partio::INT,size);
int num=length/size;
int offset=0;
if(packing.size()==0) packing.push_back(size); // if no packing then full
for(size_t pack=0;pack<packing.size();pack++){
int packsize=packing[pack];
for(int i=0;i<num;i++){
float* partioVal=particles->dataWrite<float>(attrH,i);
for(int k=0;k<packsize;k++){
T val=((JSONParser<BGEOAttributeValues>*)this)->numberData<T>();
partioVal[offset+k]=val;
}
}
offset+=packing[pack];
}
}else{
throw JSONParseError("Unexpected data storage "+storage,state);
}
return true;
}else if(strcmp(key,"packing")==0){
for(int i=0;i<length;i++){
T val=((JSONParser<BGEOAttributeValues>*)this)->numberData<T>();
packing.push_back(val);
}
return true;
}
return false;
}
template<class T> void numberData(const char* key,T x){
std::cerr<<"key "<<keyString(key)<<" "<<int64(x)<<std::endl;
if(strcmp(key,"size")==0){size=x;}
}
void boolData(const char* key,bool x){
std::cerr<<"key "<<keyString(key)<<" "<<x<<std::endl;
}
bool mapBegin(const char* key){
throw JSONParseError("Got unknown map begin with key "+keyString(key),state);
return false;}
void mapEnd(){
std::cerr<<"mapend"<<std::endl;
}
bool arrayBegin(const char* key){
throw JSONParseError("Got unknown key in values block in attribute"+keyString(key),state);
return false;
//std::cerr<<"arraybegin "<<key<<std::endl;
}
void arrayEnd(){}
};
struct BGEOAttributeValue:public JSONParser<BGEOAttributeValue>
{
Partio::ParticlesDataMutable* particles;
const char* attrName;
BGEOAttributeValue(JSONParserState& state,Partio::ParticlesDataMutable* particles,const char* attrName)
:JSONParser<BGEOAttributeValue>(state),particles(particles),attrName(attrName)
{
std::cerr<<"BGEOAttributeValue attr="<<attrName<<std::endl;
}
void string(const char* key,const std::string& s){
std::cerr<<"key "<<keyString(key)<<" string "<<s<<std::endl;
}
template<class T> void numberData(const char* key,T x){
std::cerr<<"key "<<keyString(key)<<" "<<int64(x)<<std::endl;
}
void boolData(const char* key,bool x){
std::cerr<<"key "<<keyString(key)<<" "<<x<<std::endl;
}
bool mapBegin(const char* key){
std::cerr<<"map "<<key<<std::endl;
return false;}
void mapEnd(){
std::cerr<<"mapend"<<std::endl;
}
bool arrayBegin(const char* key){
if(strcmp(key,"defaults")==0){
NULLParser(state).arrayMap();
return true;
}else if(strcmp(key,"values")==0){
//NULLParser(state).arrayMap();
BGEOAttributeValues(state,particles,attrName).arrayMap();
return true;
}
throw JSONParseError("Got unknown key in values block in attribute"+keyString(key),state);
return false;
//std::cerr<<"arraybegin "<<key<<std::endl;
}
void arrayEnd(){
std::cerr<<"arrayend"<<std::endl;
}
template<class T> bool uniformArray(const char* currKey,int length){
return false;
}
};
struct BGEOAttributes:public JSONParser<BGEOAttributes>
{
Partio::ParticlesDataMutable* particles;
enum ATTRTYPE{NONE,POINT};
ATTRTYPE attrtype;
enum ATTRSTATE{TOP,ATTRS,MID,MID2,MID3};
ATTRSTATE attrstate;
std::string attrName;
BGEOAttributes(JSONParserState& state,Partio::ParticlesDataMutable* particles)
:JSONParser<BGEOAttributes>(state),particles(particles),attrtype(NONE),attrstate(TOP)
{}
template<class T> bool uniformArray(const char* currKey,int length){
return false;
}
bool arrayBegin(const char* key){
if(attrstate==TOP){
if(attrtype==NONE){
if(strcmp(key,"pointattributes")==0){
std::cerr<<"parsing "<<key<<std::endl;
attrtype=POINT;
attrstate=ATTRS;
return false;
}else{
std::cerr<<"ignoring "<<key<<std::endl;
NULLParser(state).array();
return true;
}
}
}else if(attrstate==ATTRS){
attrstate=MID;
return false;
}else if(attrstate==MID){
BGEOAttributeType attrType(state);
attrType.arrayMap();
attrName=attrType.attrName;
attrstate=MID2;
return true;
}else if(attrstate==MID2){
BGEOAttributeValue(state,particles,attrName.c_str()).arrayMap();
attrstate=MID3;
return true;
}
std::stringstream ss;
ss<<"unknown key "<<keyString(key)<<" at type "<<attrtype<<" attrstate "<<attrstate;
throw JSONParseError(ss.str(),state);
}
void arrayEnd()
{
if(attrstate==MID){
throw JSONParseError("Trying to exit array in MID state",state);
}else if(attrstate==MID2){
throw JSONParseError("Trying to exit array in MID2 state",state);
}else if(attrstate==MID3){
attrstate=ATTRS;
}else if(attrstate==ATTRS){
attrtype=NONE;
attrstate=TOP;
}
}
void string(const char* key,const std::string& s){
throw JSONParseError("unexpected string data",state);
}
template<class T> void numberData(const char* key,T x){
throw JSONParseError("unexpected number data",state);
}
void boolData(const char* key,bool x){
throw JSONParseError("unexpected number data",state);
}
bool mapBegin(const char* key){return false;}
void mapEnd(){}
};
struct BGEOMainParser:public JSONParser<BGEOMainParser>
{
int64 pointcount,vertexcount,primitivecount;
Partio::ParticlesDataMutable* particles;
BGEOMainParser(JSONParserState& state, ParticlesDataMutable* particles)
:JSONParser<BGEOMainParser>(state),particles(particles)
{}
~BGEOMainParser(){
std::cerr<<"pt count "<<pointcount<<" vert "<<vertexcount<<" prim count "<<primitivecount<<std::endl;
}
void string(const char* key,const std::string& s){
//if(strcmp(key,"fileversion")==0) std::cerr<<"saw file version "<<s<<std::endl;
}
template<class T> void numberData(const char* key,T x){
if(strcmp(key,"primitivecount")==0) primitivecount=x;
else if(strcmp(key,"vertexcount")==0) vertexcount=x;
else if(strcmp(key,"pointcount")==0){
pointcount=x;
particles->addParticles(pointcount);
}else{
std::cerr<<"WARNING unknown number data ignored in key "<<keyString(key)<<std::endl;
}
}
void boolData(const char* key,bool x){
std::cerr<<"WARNING ignoring boolData with key="<<keyString(key)<<" value="<<x<<std::endl;
}
bool mapBegin(const char* key){
if(strcmp(key,"info")==0){
NULLParser parser(state);
parser.map();
return true;
}else{
std::cerr<<"WARNING unknown key "<<keyString(key)<<" with type array"<<std::endl;
}
std::cerr<<"WARNING found mapbegin with key "<<key<<std::endl;
return false;
}
void mapEnd(){throw JSONParseError("logic error",state);}
bool arrayBegin(const char* key){
if(strcmp(key,"topology")==0){
NULLParser parser(state);
parser.arrayMap();
return true;
}else if(strcmp(key,"attributes")==0){
BGEOAttributes(state,particles).arrayMap();
return true;
}else if(strcmp(key,"primitives")==0){
NULLParser parser(state);
parser.array();
return true;
}else if(strcmp(key,"pointgroups")==0){
NULLParser parser(state);
parser.array();
return true;
}
std::cerr<<"WARNING found arraybegin with key "<<key<<std::endl;
return false;
}
void arrayEnd(){}
template<class T> bool uniformArray(const char* currKey,int length){
return false;
}
};
/// This parser ignores everything it sees
struct BGEOParser:public JSONParser<BGEOParser>
{
Partio::ParticlesDataMutable* particles;
BGEOParser(JSONParserState& state,Partio::ParticlesDataMutable* particles)
:JSONParser<BGEOParser>(state),particles(particles)
{}
void string(const char* key,const std::string& s){throw JSONParseError("invalid string at top level",state);}
template<class T> void numberData(const char* key,T x){throw JSONParseError("invalid numberData at top level",state);}
void boolData(const char* key,bool x){throw JSONParseError("invalid boolData at top level",state);}
bool mapBegin(const char* key){throw JSONParseError("invalid mapBegin at top level",state);return false;}
void mapEnd(){throw JSONParseError("invalid mapEnd at top level",state);}
bool arrayBegin(const char* key){
std::cerr<<"starting array"<<std::endl;
BGEOMainParser main(state,particles);
main.arrayMap();
return true;
}
void arrayEnd(){throw JSONParseError("invalid arrayEnd at top level",state);}
template<class T> bool uniformArray(const char* currKey,int length){
return false;
}
};
ParticlesDataMutable* testRead(const char* filename)
{
std::ifstream fp(filename,std::ios::in);
if(!fp){
std::cerr<<"Error opening file"<<std::endl;
exit(1);
}
Partio::JSONParserState state(fp);
//Partio::GEOParser parser(state);
Partio::ParticlesDataMutable* particles=Partio::create();
Partio::BGEOParser parser(state,particles);
//Partio::PrintParser parser(state);
//PrintDelegate delegate;
//Partio::JSONParser<PrintDelegate> json(delegate,fp);
parser.parse();
std::cerr<<"particle count "<<particles->numParticles()<<std::endl;
std::cerr<<"attr count "<<particles->numAttributes()<<std::endl;
return particles;
}
EXIT_PARTIO_NAMESPACE
| [
"[email protected]"
] | |
32d733e4bc9bf9529ec6d541827edc6f3abb0358 | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function13975/function13975_schedule_41/function13975_schedule_41_wrapper.cpp | c96749f478eafe17ba4a21efb35221507732de95 | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,552 | cpp | #include "Halide.h"
#include "function13975_schedule_41_wrapper.h"
#include "tiramisu/utils.h"
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <fstream>
#include <chrono>
#define MAX_RAND 200
int main(int, char **){
Halide::Buffer<int32_t> buf00(512, 512);
Halide::Buffer<int32_t> buf01(512, 512);
Halide::Buffer<int32_t> buf02(256, 512);
Halide::Buffer<int32_t> buf03(256);
Halide::Buffer<int32_t> buf04(512, 512);
Halide::Buffer<int32_t> buf05(512, 512);
Halide::Buffer<int32_t> buf06(512);
Halide::Buffer<int32_t> buf07(256, 512);
Halide::Buffer<int32_t> buf08(256, 512);
Halide::Buffer<int32_t> buf09(512);
Halide::Buffer<int32_t> buf0(256, 512, 512);
init_buffer(buf0, (int32_t)0);
auto t1 = std::chrono::high_resolution_clock::now();
function13975_schedule_41(buf00.raw_buffer(), buf01.raw_buffer(), buf02.raw_buffer(), buf03.raw_buffer(), buf04.raw_buffer(), buf05.raw_buffer(), buf06.raw_buffer(), buf07.raw_buffer(), buf08.raw_buffer(), buf09.raw_buffer(), buf0.raw_buffer());
auto t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = t2 - t1;
std::ofstream exec_times_file;
exec_times_file.open("../data/programs/function13975/function13975_schedule_41/exec_times.txt", std::ios_base::app);
if (exec_times_file.is_open()){
exec_times_file << diff.count() * 1000000 << "us" <<std::endl;
exec_times_file.close();
}
return 0;
} | [
"[email protected]"
] | |
4bcf8d8a677edd21433d51d2ff879378e7f2daa9 | 9e4b45b1765473d099825613c272b7a5bde12504 | /include/tagslam/bag_sync.h | 3330de54acd73750ac7fb364322969da549f2bdf | [] | no_license | lnspection/tagslam | d3d2e306e12af3b3812cbf1a40bd3f5d044b502c | 3021a6d59fc997cd17563d69caba1ec7181cb0a7 | refs/heads/master | 2020-03-24T15:48:03.949042 | 2018-07-26T15:44:01 | 2018-07-26T15:44:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,955 | h | /* -*-c++-*--------------------------------------------------------------------
* 2018 Bernd Pfrommer [email protected]
*/
#ifndef TAGSLAM_BAG_SYNC_H
#define TAGSLAM_BAG_SYNC_H
#include <ros/ros.h>
#include <rosbag/bag.h>
#include <memory>
#include <string>
#include <vector>
#include <map>
#include <string>
namespace tagslam {
template <class T>
/*
bag synchronizing class for a single message type
*/
class BagSync {
typedef boost::shared_ptr<T const> ConstPtr;
public:
BagSync(const std::vector<std::string> &topics,
const std::function<void(const std::vector<ConstPtr> &)> &callback)
: topics_(topics),
callback_(callback)
{
}
bool process(const rosbag::MessageInstance &m) {
boost::shared_ptr<T> msg = m.instantiate<T>();
if (msg) {
if (msg->header.stamp > currentTime_) {
if (msgMap_.size() == topics_.size()) {
std::vector<ConstPtr> msgVec;
for (const auto &m: msgMap_) {
msgVec.push_back(m.second);
}
callback_(msgVec);
}
msgMap_.clear();
currentTime_ = msg->header.stamp;
}
msgMap_[m.getTopic()] = msg;
return (true);
}
return (false);
}
const ros::Time &getCurrentTime() { return (currentTime_); }
private:
ros::Time currentTime_{0.0};
std::map<std::string, ConstPtr> msgMap_;
std::vector<std::string> topics_;
std::function<void(const std::vector<ConstPtr> &)> callback_;
};
/*
bag synchronizing class for two different message types
*/
template <typename T1, typename T2>
class BagSync2 {
typedef boost::shared_ptr<T1 const> ConstPtr1;
typedef boost::shared_ptr<T2 const> ConstPtr2;
typedef std::map<std::string, std::map<ros::Time,ConstPtr1>> MsgMap1;
typedef std::map<std::string, std::map<ros::Time,ConstPtr2>> MsgMap2;
public:
BagSync2(const std::vector<std::string> &topics1,
const std::vector<std::string> &topics2,
const std::function<void(const std::vector<ConstPtr1> &, const std::vector<ConstPtr2>&)> &callback)
: topics1_(topics1), topics2_(topics2), callback_(callback)
{
for (const auto &topic: topics1_) {
msgMap1_[topic] = std::map<ros::Time, ConstPtr1>();
}
for (const auto &topic: topics2_) {
msgMap2_[topic] = std::map<ros::Time, ConstPtr2>();
}
}
const ros::Time &getCurrentTime() { return (currentTime_); }
template<typename T>
static std::vector<boost::shared_ptr<T const>> makeVec(const ros::Time &t,
std::map<std::string, std::map<ros::Time, boost::shared_ptr<T const> >> *topicToQueue) {
std::vector<boost::shared_ptr<T const>> mvec;
for (auto &queue: *topicToQueue) { // iterate over all topics
auto &t2m = queue.second; // time to message
while (t2m.begin()->first < t) {
t2m.erase(t2m.begin());
}
mvec.push_back(t2m.begin()->second);
t2m.erase(t2m.begin());
}
return (mvec);
}
void publishMessages(const ros::Time &t) {
std::vector<boost::shared_ptr<T1 const>> mvec1 = makeVec(t, &msgMap1_);
std::vector<boost::shared_ptr<T2 const>> mvec2 = makeVec(t, &msgMap2_);
callback_(mvec1, mvec2);
}
// have per-topic queue
// have time-to-count map
// if new message comes in, put it at head of its queue,
// and bump the time-to-count-map entry.
// if time-to-count-map entry is equal to number of topics:
// - erase all time-to-count-map entries that are older
// - erase all per-topic-queue entries that are older
// - deliver callback
bool process(const rosbag::MessageInstance &m) {
boost::shared_ptr<T1> msg1 = m.instantiate<T1>();
boost::shared_ptr<T2> msg2 = m.instantiate<T2>();
if (!msg1 && !msg2) {
return (false);
}
const ros::Time t = msg1 ? msg1->header.stamp : msg2->header.stamp;
if (msg1) {
msgMap1_[m.getTopic()][t] = msg1;
} else {
msgMap2_[m.getTopic()][t] = msg2;
}
auto it = msgCount_.find(t);
if (it == msgCount_.end()) {
msgCount_.insert(CountMap::value_type(t, 1));
it = msgCount_.find(t);
} else {
it->second++;
}
if (it->second == (int) (topics1_.size() + topics2_.size())) {
currentTime_ = t;
publishMessages(t); // also cleans out queues
it++;
msgCount_.erase(msgCount_.begin(), it);
}
return (true);
}
private:
typedef std::map<ros::Time, int> CountMap;
ros::Time currentTime_{0.0};
CountMap msgCount_;
MsgMap1 msgMap1_;
MsgMap2 msgMap2_;
std::vector<std::string> topics1_, topics2_;
std::function<void(const std::vector<ConstPtr1> &,
const std::vector<ConstPtr2> &)> callback_;
};
}
#endif
| [
"[email protected]"
] | |
c07062a1349d168ccaa4adc10ea6330b445c9abf | d077e40e376f16c9420f32001decf946a34a6e71 | /FEBioFluid/FEIdealGasIsothermal.cpp | b32b290e3996d528973933caccacfc2dba40de2b | [
"MIT"
] | permissive | jnbrunet/febio2 | 43196e79f8c54a5c92f3f592aa7437fd3b3fe842 | fdbedae97c7d2ecad3dc89d25c8343cfbdeb195a | refs/heads/master | 2021-07-21T01:04:58.828864 | 2020-05-19T06:47:31 | 2020-05-19T06:47:31 | 203,228,954 | 0 | 0 | null | 2019-08-19T18:38:29 | 2019-08-19T18:38:28 | null | UTF-8 | C++ | false | false | 4,430 | cpp | /*This file is part of the FEBio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio.txt for details.
Copyright (c) 2019 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
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 "stdafx.h"
#include "FEIdealGasIsothermal.h"
#include <FECore/FEModel.h>
#include <FECore/FECoreKernel.h>
// define the material parameters
BEGIN_PARAMETER_LIST(FEIdealGasIsothermal, FEMaterial)
ADD_PARAMETER2(m_M , FE_PARAM_DOUBLE, FE_RANGE_GREATER(0.0), "M" );
END_PARAMETER_LIST();
//============================================================================
// FEIdealGasIsothermal
//============================================================================
//-----------------------------------------------------------------------------
//! FEIdealGasIsothermal constructor
FEIdealGasIsothermal::FEIdealGasIsothermal(FEModel* pfem) : FEFluid(pfem)
{
m_rhor = 0;
m_k = 0;
m_M = 0;
}
//-----------------------------------------------------------------------------
//! initialization
bool FEIdealGasIsothermal::Init()
{
m_R = GetFEModel()->GetGlobalConstant("R");
m_Tr = GetFEModel()->GetGlobalConstant("T");
m_pr = GetFEModel()->GetGlobalConstant("p");
if (m_R <= 0) return fecore_error("A positive universal gas constant R must be defined in Globals section");
// if (m_Tr <= 0) return fecore_error("A positive ambient absolute temperature T must be defined in Globals section");
if (m_pr <= 0) return fecore_error("A positive ambient absolute pressure p must be defined in Globals section");
m_rhor = m_M*m_pr/(m_R*m_Tr);
return true;
}
//-----------------------------------------------------------------------------
//! elastic pressure from dilatation
double FEIdealGasIsothermal::Pressure(const double e)
{
double J = 1 + e;
return m_pr*(1./J - 1);
}
//-----------------------------------------------------------------------------
//! tangent of elastic pressure with respect to strain J
double FEIdealGasIsothermal::Tangent_Pressure_Strain(FEMaterialPoint& mp)
{
FEFluidMaterialPoint& fp = *mp.ExtractData<FEFluidMaterialPoint>();
double J = fp.m_Jf;
double dp = -m_pr/J;
return dp;
}
//-----------------------------------------------------------------------------
//! 2nd tangent of elastic pressure with respect to strain J
double FEIdealGasIsothermal::Tangent_Pressure_Strain_Strain(FEMaterialPoint& mp)
{
FEFluidMaterialPoint& fp = *mp.ExtractData<FEFluidMaterialPoint>();
double J = fp.m_Jf;
double d2p = 2*m_pr/(J*J);
return d2p;
}
//-----------------------------------------------------------------------------
//! evaluate temperature
double FEIdealGasIsothermal::Temperature(FEMaterialPoint& mp)
{
return m_Tr;
}
//-----------------------------------------------------------------------------
//! calculate free energy density (per reference volume)
double FEIdealGasIsothermal::StrainEnergyDensity(FEMaterialPoint& mp)
{
FEFluidMaterialPoint& fp = *mp.ExtractData<FEFluidMaterialPoint>();
double J = fp.m_Jf;
double sed = m_pr*(J-1-log(J));
return sed;
}
//-----------------------------------------------------------------------------
//! invert pressure-dilatation relation
double FEIdealGasIsothermal::Dilatation(const double p)
{
double J = m_pr/(p+m_pr);
return J - 1;
}
| [
"[email protected]"
] | |
08a0aa0ac108c19f992b2b38718ecf6cac65ec85 | 01a42b69633daf62a2eb3bb70c5b1b6e2639aa5f | /SCUM_UI_ActionProgress_parameters.hpp | c1110e897f41d327f8196ab12535211569d7f07c | [] | no_license | Kehczar/scum_sdk | 45db80e46dac736cc7370912ed671fa77fcb95cf | 8d1770b44321a9d0b277e4029551f39b11f15111 | refs/heads/master | 2022-07-25T10:06:20.892750 | 2020-05-21T11:45:36 | 2020-05-21T11:45:36 | 265,826,541 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,521 | hpp | #pragma once
// Scum 3.79.22573 (UE 4.24)
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace Classes
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function UI_ActionProgress.UI_ActionProgress_C.OnMouseButtonDown
struct UUI_ActionProgress_C_OnMouseButtonDown_Params
{
struct FGeometry* MyGeometry; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData)
struct FPointerEvent* MouseEvent; // (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm)
struct FEventReply ReturnValue; // (Parm, OutParm, ReturnParm)
};
// Function UI_ActionProgress.UI_ActionProgress_C.Get_PercentageText_Text_1
struct UUI_ActionProgress_C_Get_PercentageText_Text_1_Params
{
struct FText ReturnValue; // (Parm, OutParm, ReturnParm)
};
// Function UI_ActionProgress.UI_ActionProgress_C.Construct
struct UUI_ActionProgress_C_Construct_Params
{
};
// Function UI_ActionProgress.UI_ActionProgress_C.OnMouseEnter
struct UUI_ActionProgress_C_OnMouseEnter_Params
{
struct FGeometry* MyGeometry; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData)
struct FPointerEvent* MouseEvent; // (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm)
};
// Function UI_ActionProgress.UI_ActionProgress_C.OnMouseLeave
struct UUI_ActionProgress_C_OnMouseLeave_Params
{
struct FPointerEvent* MouseEvent; // (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm)
};
// Function UI_ActionProgress.UI_ActionProgress_C.ExecuteUbergraph_UI_ActionProgress
struct UUI_ActionProgress_C_ExecuteUbergraph_UI_ActionProgress_Params
{
int* EntryPoint; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
33ea7d3c0892219cd41f47b4ad7c71e2b7c69187 | 712ef829d66a20748303fd187987c606e2f6c692 | /Source/PPP/AActors/ATileManager.cpp | b5252c3d636ed5cdb4fdf30f487e4456a9a8b213 | [] | no_license | kimFrost/PPP | fac52e7c8ca37b88ea1bbe56d2d42d8b1652f3ba | ccf4bcf96db17ae83224488823db2b3b8a7f0547 | refs/heads/master | 2021-05-11T20:49:15.451516 | 2018-05-02T19:20:49 | 2018-05-02T19:20:49 | 117,448,450 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,238 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "ATileManager.h"
#include "UObjects/UTile.h"
#include "UObjects/UGridManager.h"
#include "Components/HierarchicalInstancedStaticMeshComponent.h"
#include "Components/InstancedStaticMeshComponent.h"
#include "Runtime/CoreUObject/Public/UObject/ConstructorHelpers.h"
#include "DrawDebugHelpers.h"
#include "Kismet/KismetSystemLibrary.h"
// Sets default values
ATileManager::ATileManager()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
PrimaryActorTick.bStartWithTickEnabled = true;
//PrimaryActorTick.bTickEvenWhenPaused = true;
//bAllowTickBeforeBeginPlay = true;
bUpdateTiles = false;
bDrawDebugLine = true;
RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("RootComponent"));
RootComponent->SetMobility(EComponentMobility::Static);
//AddOwnedComponent(RootScene);
HISMComp = CreateDefaultSubobject<UInstancedStaticMeshComponent>(TEXT("HISMComp"));
HISMComp->SetupAttachment(RootComponent);
//HISMComp->RegisterComponent();
//AddOwnedComponent(HISMComp);
//AddInstanceComponent(HISMComp);
//HISMComp->AttachTo()
HISMComp->SetMobility(EComponentMobility::Static);
HISMComp->SetCollisionEnabled(ECollisionEnabled::NoCollision);
HISMComp->SetFlags(RF_Transactional);
static ConstructorHelpers::FObjectFinder<UStaticMesh>BaseMeshObj(TEXT("StaticMesh'/Game/PPP/Meshes/Shapes/SM_Block-50.SM_Block-50'"));
if (BaseMeshObj.Succeeded())
{
HISMComp->SetStaticMesh(BaseMeshObj.Object);
}
GridManager = CreateDefaultSubobject<UGridManager>(TEXT("GridManager"));
//Mesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh"));
//GridManager = NewObject<UGridManager>();
/*
// FOr components
PrimaryComponentTick.bCanEverTick = true;
PrimaryComponentTick.bStartWithTickEnabled = true;
RegisterAllComponentTickFunctions(true);
bTickInEditor = true;
bAutoActivate = true;
bAutoRegister = true;
SetComponentTickEnabled(true);
PrimaryComponentTick.TickGroup = TG_PrePhysics;
*/
}
void ATileManager::CreateBlocks()
{
if (HISMComp)
{
HISMComp->ClearInstances();
if (GridManager)
{
for (auto& Tile : GridManager->GridTiles)
{
if (Tile)
{
FRotator Rotation = FRotator(0, 0, 0);
FVector Location = Tile->WorldLocation;
FTransform Transform = FTransform(Rotation, Location);
int32 Index = HISMComp->AddInstance(Transform);
}
}
}
}
}
void ATileManager::UpdateBlocks()
{
if (HISMComp && GridManager)
{
for (auto& Tile : GridManager->GridTiles)
{
if (Tile)
{
if (Tile->StructureOnTile || Tile->RoadOnTile)
{
FTransform Transform;
if (HISMComp->GetInstanceTransform(Tile->Index, Transform, true))
{
FVector WorldLocation = Transform.GetLocation();
WorldLocation.Z = -50;
Transform.SetLocation(WorldLocation);
HISMComp->UpdateInstanceTransform(Tile->Index, Transform, true, true, true);
}
//HISMComp->SelectInstance
}
else
{
}
}
}
}
}
void ATileManager::BeginPlay()
{
if (GridManager)
{
//GridManager->CreateTiles();
//CreateBlocks();
if (bDrawDebugLine)
{
if (GridManager)
{
for (auto& Tile : GridManager->GridTiles)
{
if (Tile && Tile->bHasSurface)
{
DrawDebugBox(
GetWorld(),
Tile->WorldLocation,
FVector(GridManager->TileSize / 2, GridManager->TileSize / 2, 0),
GetRootComponent()->GetComponentToWorld().GetRotation(),
FColor::Red,
true,
-1.f,
0
);
}
}
}
}
}
Super::BeginPlay();
}
void ATileManager::Tick(float DeltaTime)
{
/*
if (bDrawDebugLine)
{
if (GridManager)
{
for (auto& Tile : GridManager->GridTiles)
{
if (Tile)
{
DrawDebugBox(
GetWorld(),
Tile->WorldLocation,
FVector(GridManager->TileSize / 2, GridManager->TileSize / 2, 0),
GetRootComponent()->GetComponentToWorld().GetRotation(),
FColor::Red,
false,
0.f,
0
);
}
}
}
}
*/
Super::Tick(DeltaTime);
}
void ATileManager::OnConstruction(const FTransform& Transform)
{
Super::OnConstruction(Transform);
//RegisterAllComponents();
if (bUpdateTiles)
{
bUpdateTiles = false;
if (GridManager)
{
GridManager->CreateTiles(GetWorld());
//CreateBlocks();
}
}
if (bDrawDebugLine)
{
if (GridManager)
{
// Draw debug outline out grid
for (auto& Tile : GridManager->GridTiles)
{
if (Tile)
{
/*
DrawDebugSolidPlane(
GetWorld(),
FPlane(),
Tile->WorldLocation,
FVector2D(1, 1),
FColor::Red,
true,
10.0f,
0
);
*/
DrawDebugBox(
GetWorld(),
Tile->WorldLocation,
FVector(GridManager->TileSize / 2, GridManager->TileSize / 2, 0),
GetRootComponent()->GetComponentToWorld().GetRotation(),
FColor::Red,
true,
-1.f,
0
);
/*
DrawDebugSphere(
GetWorld(),
Tile->WorldLocation,
25.f,
3,
FColor::Red,
false,
10.f,
0
);
*/
}
}
}
}
else
{
UKismetSystemLibrary::FlushPersistentDebugLines(GetWorld());
}
}
/*
bool ATileManager::ShouldTickIfViewportsOnly() const
{
return true;
}
*/
// UGridManager
// ATileManager
// ABuilder
// Loop place buildings
//https://answers.unrealengine.com/questions/292074/spawn-actor-with-expose-on-spawn-variables-in-c.html
//https://answers.unrealengine.com/questions/252259/onconstruction-c-best-practice.html
//https://docs.unrealengine.com/en-us/Programming/UnrealArchitecture/Actors/ActorLifecycle
//https://docs.unrealengine.com/en-us/Programming/Tutorials/Components/1
//https://docs.unrealengine.com/en-us/Programming/Tutorials/Components/1
//https://forums.unrealengine.com/development-discussion/c-gameplay-programming/40085-proper-use-of-uscenecomponents-and-registercomponent
//https://answers.unrealengine.com/questions/183439/instantiating.html?sort=oldest
//https://answers.unrealengine.com/questions/658240/c-create-a-hierarchical-instanced-static-mesh-for.html?sort=oldest | [
"[email protected]"
] | |
2a5136e3cc2272383f78de00de86b9e2ce4084e3 | 48985260e44088055144db308d79d48b2a5ec4f7 | /igstkNeedleObjectRepresentation.cpp | 5eb5fce0149d7d6d90733dd694c746d73fa92202 | [] | no_license | FubuFabian/SkinSegmentation | ab0a4656b3d311720ead9e5a6a50d05bc824fb60 | bea23c882b3453ea70e4ca62daf927946984a0b3 | refs/heads/master | 2016-09-06T01:24:17.429916 | 2014-06-30T17:02:48 | 2014-06-30T17:02:48 | 20,535,601 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,077 | cpp | /*=========================================================================
Program: Image Guided Surgery Software Toolkit
Module: igstkNeedleObjectRepresentation.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) ISC Insight Software Consortium. All rights reserved.
See IGSTKCopyright.txt or http://www.igstk.org/copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "igstkNeedleObjectRepresentation.h"
#include <vtkPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkImplicitBoolean.h>
#include <vtkSampleFunction.h>
#include <vtkMarchingContourFilter.h>
#include <vtkCylinderSource.h>
#include <vtkSphereSource.h>
#include <vtkCubeSource.h>
namespace igstk
{
/** Constructor */
NeedleObjectRepresentation
::NeedleObjectRepresentation():m_StateMachine(this)
{
// We create the ellipse spatial object
m_NeedleSpatialObject = NULL;
this->RequestSetSpatialObject( m_NeedleSpatialObject );
igstkAddInputMacro( ValidNeedleObject );
igstkAddInputMacro( NullNeedleObject );
igstkAddStateMacro( NullNeedleObject );
igstkAddStateMacro( ValidNeedleObject );
igstkAddTransitionMacro( NullNeedleObject,
NullNeedleObject,
NullNeedleObject, No );
igstkAddTransitionMacro( NullNeedleObject,
ValidNeedleObject,
ValidNeedleObject,
SetNeedleObject );
igstkAddTransitionMacro( ValidNeedleObject,
NullNeedleObject,
NullNeedleObject, No );
igstkAddTransitionMacro( ValidNeedleObject,
ValidNeedleObject,
ValidNeedleObject, No );
igstkSetInitialStateMacro( NullNeedleObject );
m_StateMachine.SetReadyToRun();
}
/** Destructor */
NeedleObjectRepresentation::~NeedleObjectRepresentation()
{
this->DeleteActors();
}
/** Set the Needleal Spatial Object */
void NeedleObjectRepresentation
::RequestSetNeedleObject( const NeedleSpatialObjectType *
Needle )
{
m_NeedleObjectToAdd = Needle;
if( !m_NeedleObjectToAdd )
{
m_StateMachine.PushInput( m_NullNeedleObjectInput );
m_StateMachine.ProcessInputs();
}
else
{
m_StateMachine.PushInput( m_ValidNeedleObjectInput );
m_StateMachine.ProcessInputs();
}
}
/** Set the Needle Spatial Object */
void NeedleObjectRepresentation::NoProcessing()
{
}
/** Set the Needle Spatial Object */
void NeedleObjectRepresentation::SetNeedleObjectProcessing()
{
m_NeedleSpatialObject = m_NeedleObjectToAdd;
this->RequestSetSpatialObject( m_NeedleSpatialObject );
}
/** Print Self function */
void NeedleObjectRepresentation
::PrintSelf( std::ostream& os, itk::Indent indent ) const
{
Superclass::PrintSelf(os, indent);
}
/** Update the visual representation in response to changes in the geometric
* object */
void NeedleObjectRepresentation::UpdateRepresentationProcessing()
{
igstkLogMacro( DEBUG, "UpdateRepresentationProcessing called ....\n");
}
/** Create the vtk Actors */
void NeedleObjectRepresentation::CreateActors()
{
this->DeleteActors();
//Create the tip of the needle
vtkPolyDataMapper* tipSphereMapper = vtkPolyDataMapper::New();
vtkActor* tipSphereActor = vtkActor::New();
vtkSphereSource* tipSphere = vtkSphereSource::New();
tipSphere->SetRadius(1.0);
tipSphere->SetCenter(0,0,0);
tipSphereActor->GetProperty()->SetColor(0.0,1.0,0.0);
tipSphereActor->GetProperty()->SetOpacity(this->GetOpacity());
tipSphereMapper->SetInputConnection(tipSphere->GetOutputPort());
tipSphereActor->SetMapper( tipSphereMapper );
this->AddActor( tipSphereActor );
tipSphereMapper->Delete();
tipSphere->Delete();
vtkPolyDataMapper* trajectoryCylinderMapper = vtkPolyDataMapper::New();
trajectoryCylinderActor = vtkActor::New();
vtkCylinderSource* trajectoryCylinder = vtkCylinderSource::New();
trajectoryCylinder->SetRadius(0.5);
trajectoryCylinder->SetHeight(100000);
trajectoryCylinder->SetCenter(0,0,0);
trajectoryCylinderActor->GetProperty()->SetColor(1.0,0.0,0.0);
trajectoryCylinderActor->GetProperty()->SetOpacity(0.0);
trajectoryCylinderMapper->SetInputConnection(trajectoryCylinder->GetOutputPort());
trajectoryCylinderActor->SetMapper( trajectoryCylinderMapper );
this->AddActor( trajectoryCylinderActor );
trajectoryCylinderMapper->Delete();
trajectoryCylinder->Delete();
vtkPolyDataMapper* tipCylinderMapper = vtkPolyDataMapper::New();
vtkActor* tipCylinderActor = vtkActor::New();
vtkCylinderSource* tipCylinder = vtkCylinderSource::New();
tipCylinder->SetRadius(0.6);
tipCylinder->SetHeight(45);
tipCylinder->SetCenter(0,23,0);
tipCylinderActor->GetProperty()->SetColor(0.8,0.8,0.8);
tipCylinderActor->GetProperty()->SetOpacity(this->GetOpacity());
tipCylinderMapper->SetInputConnection(tipCylinder->GetOutputPort());
tipCylinderActor->SetMapper( tipCylinderMapper );
this->AddActor( tipCylinderActor );
tipCylinderMapper->Delete();
tipCylinder->Delete();
//Create the body of the needle
vtkPolyDataMapper* bodyCylinder1Mapper = vtkPolyDataMapper::New();
vtkActor* bodyCylinder1Actor = vtkActor::New();
vtkCylinderSource* bodyCylinder1 = vtkCylinderSource::New();
bodyCylinder1->SetRadius(4.5);
bodyCylinder1->SetHeight(8);
bodyCylinder1->SetCenter(0,49,0);
bodyCylinder1Actor->GetProperty()->SetColor(0.325,0.658,0.584);
bodyCylinder1Actor->GetProperty()->SetOpacity(this->GetOpacity());
bodyCylinder1Mapper->SetInputConnection(bodyCylinder1->GetOutputPort());
bodyCylinder1Actor->SetMapper( bodyCylinder1Mapper );
this->AddActor( bodyCylinder1Actor );
bodyCylinder1Mapper->Delete();
bodyCylinder1->Delete();
vtkPolyDataMapper* bodyCylinder2Mapper = vtkPolyDataMapper::New();
vtkActor* bodyCylinder2Actor = vtkActor::New();
vtkCylinderSource* bodyCylinder2 = vtkCylinderSource::New();
bodyCylinder2->SetRadius(8);
bodyCylinder2->SetHeight(87);
bodyCylinder2->SetCenter(0,96.5,0);
bodyCylinder2Actor->GetProperty()->SetColor(0.490,0.701,0.768);
bodyCylinder2Actor->GetProperty()->SetOpacity(this->GetOpacity());
bodyCylinder2Mapper->SetInputConnection(bodyCylinder2->GetOutputPort());
bodyCylinder2Actor->SetMapper( bodyCylinder2Mapper );
this->AddActor( bodyCylinder2Actor );
bodyCylinder2Mapper->Delete();
bodyCylinder2->Delete();
vtkPolyDataMapper* bodyCubeMapper = vtkPolyDataMapper::New();
vtkActor* bodyCubeActor = vtkActor::New();
vtkCubeSource* bodyCube = vtkCubeSource::New();
bodyCube->SetCenter(0,142,0);
bodyCube->SetYLength(2);
bodyCube->SetXLength(32);
bodyCube->SetZLength(18);
bodyCubeActor->GetProperty()->SetColor(0.247,0.462,0.545);
bodyCubeActor->GetProperty()->SetOpacity(this->GetOpacity());
bodyCubeMapper->SetInputConnection(bodyCube->GetOutputPort());
bodyCubeActor->SetMapper( bodyCubeMapper );
this->AddActor( bodyCubeActor );
bodyCubeMapper->Delete();
bodyCube->Delete();
}
/** Create a copy of the current object representation */
NeedleObjectRepresentation::Pointer
NeedleObjectRepresentation::Copy() const
{
Pointer newOR = NeedleObjectRepresentation::New();
newOR->SetColor(this->GetRed(),this->GetGreen(),this->GetBlue());
newOR->SetOpacity(this->GetOpacity());
newOR->RequestSetNeedleObject(m_NeedleSpatialObject);
return newOR;
}
void NeedleObjectRepresentation::putTrajectory()
{
trajectoryCylinderActor->GetProperty()->SetOpacity(this->GetOpacity());
}
void NeedleObjectRepresentation::removeTrajectory()
{
trajectoryCylinderActor->GetProperty()->SetOpacity(0.0);
}
} // end namespace igstk
| [
"[email protected]"
] | |
4dc8d37a67518208f11ee703792e00f1c568ed19 | 7358678d3d80ca41e8eeabd289f1af9ce3e0e68d | /ttk/core/vtk/ttkContinuousScatterPlot/ttkContinuousScatterPlot.h | d5a27a8e79ca17c29ab5589cc7e831edfb28b66f | [
"BSD-3-Clause"
] | permissive | JonasLukasczyk/lts-sample-code | 1cda416f2db7a3aedbc8703de7b54290449991f5 | 257fbe51743a65652264751bb6471eca151132dd | refs/heads/master | 2022-12-08T13:20:59.925025 | 2020-09-02T08:11:11 | 2020-09-02T08:11:11 | 291,699,607 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,164 | h | /// \ingroup vtk
/// \class ttkContinuousScatterPlot
/// \author Guillaume Favelier <[email protected]>
/// \author Julien Tierny <[email protected]>
/// \date March 2016
///
/// \brief TTK VTK-filter that computes the continuous scatterplot of bivariate
/// volumetric data.
///
/// This filter produces a 2D vtkUnstructuredGrid with a scalar field (named
/// "Density") representing the continuous scatter plot (attached to the
/// 2D geometry as point data). A point mask is also attached to the 2D
/// geometry as point data.
///
/// The components of the input bivariate data must be specified as independent
/// scalar fields attached to the input geometry as point data.
///
/// \param Input Input bivariate volumetric data-set, either regular grids or
/// tetrahedral meshes (vtkDataSet)
/// \param Output Output 2D continuous scatter plot (vtkUnstructuredGrid)
///
/// This filter can be used as any other VTK filter (for instance, by using the
/// sequence of calls SetInputData(), Update(), GetOutput()).
///
/// See the related ParaView example state files for usage examples within a
/// VTK pipeline.
///
/// \b Related \b publication \n
/// "Continuous Scatterplots" \n
/// Sven Bachthaler, Daniel Weiskopf \n
/// Proc. of IEEE VIS 2008.\n
/// IEEE Transactions on Visualization and Computer Graphics, 2008.
///
/// \sa ttk::ContinuousScatterPlot
#ifndef _TTK_CONTINUOUSSCATTERPLOT_H
#define _TTK_CONTINUOUSSCATTERPLOT_H
// VTK includes
#include <vtkCharArray.h>
#include <vtkDataArray.h>
#include <vtkDataSet.h>
#include <vtkDataSetAlgorithm.h>
#include <vtkDoubleArray.h>
#include <vtkFiltersCoreModule.h>
#include <vtkInformation.h>
#include <vtkObjectFactory.h>
#include <vtkPointData.h>
#include <vtkPoints.h>
#include <vtkSmartPointer.h>
#include <vtkUnstructuredGrid.h>
// VTK Module
#include <ttkContinuousScatterPlotModule.h>
// ttk baseCode includes
#include <ContinuousScatterPlot.h>
#include <ttkTriangulationAlgorithm.h>
class TTKCONTINUOUSSCATTERPLOT_EXPORT ttkContinuousScatterPlot
: public vtkDataSetAlgorithm,
public ttk::Wrapper {
public:
static ttkContinuousScatterPlot *New();
vtkTypeMacro(ttkContinuousScatterPlot, vtkDataSetAlgorithm);
vtkSetMacro(debugLevel_, int);
void SetThreadNumber(int threadNumber) {
ThreadNumber = threadNumber;
SetThreads();
}
void SetUseAllCores(bool onOff) {
UseAllCores = onOff;
SetThreads();
}
vtkSetMacro(ScalarField1, std::string);
vtkGetMacro(ScalarField1, std::string);
vtkSetMacro(ScalarField2, std::string);
vtkGetMacro(ScalarField2, std::string);
vtkSetMacro(UcomponentId, int);
vtkGetMacro(UcomponentId, int);
vtkSetMacro(VcomponentId, int);
vtkGetMacro(VcomponentId, int);
vtkSetMacro(WithVaryingConnectivity, int);
vtkGetMacro(WithVaryingConnectivity, int);
vtkSetMacro(WithDummyValue, int);
vtkGetMacro(WithDummyValue, int);
vtkSetMacro(DummyValue, double);
vtkGetMacro(DummyValue, double);
vtkSetMacro(ProjectImageSupport, bool);
vtkGetMacro(ProjectImageSupport, bool);
void SetScatterplotResolution(int N, int M) {
ScatterplotResolution[0] = N;
ScatterplotResolution[1] = M;
ScatterplotResolution[2] = 1;
Modified();
}
int getScalars(vtkDataSet *input);
int getTriangulation(vtkDataSet *input);
protected:
ttkContinuousScatterPlot();
~ttkContinuousScatterPlot() override;
TTK_SETUP();
int FillInputPortInformation(int port, vtkInformation *info) override;
int FillOutputPortInformation(int port, vtkInformation *info) override;
private:
bool WithVaryingConnectivity;
bool WithDummyValue;
double DummyValue;
bool ProjectImageSupport;
int ScatterplotResolution[3];
int UcomponentId, VcomponentId;
std::string ScalarField1;
std::string ScalarField2;
vtkDataArray *inputScalars1_;
vtkDataArray *inputScalars2_;
double scalarMin_[2];
double scalarMax_[2];
std::vector<std::vector<double>> density_;
std::vector<std::vector<char>> validPointMask_;
ttk::Triangulation *triangulation_;
// output
vtkSmartPointer<vtkUnstructuredGrid> vtu_;
vtkSmartPointer<vtkPoints> pts_;
};
#endif // _TTK_CONTINUOUSSCATTERPLOT_H
| [
"[email protected]"
] | |
d55e8177b13badf7c33682be39a7af07c728c030 | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /gpu/skia_bindings/grcontext_for_gles2_interface.cc | c6115fb8c5f36723d92a65c4108bf08ffa3bc3b6 | [
"BSD-3-Clause"
] | permissive | Samsung/Castanets | 240d9338e097b75b3f669604315b06f7cf129d64 | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | refs/heads/castanets_76_dev | 2023-08-31T09:01:04.744346 | 2021-07-30T04:56:25 | 2021-08-11T05:45:21 | 125,484,161 | 58 | 49 | BSD-3-Clause | 2022-10-16T19:31:26 | 2018-03-16T08:07:37 | null | UTF-8 | C++ | false | false | 2,726 | cc | // Copyright (c) 2013 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 "gpu/skia_bindings/grcontext_for_gles2_interface.h"
#include <stddef.h>
#include <string.h>
#include <utility>
#include "base/lazy_instance.h"
#include "base/macros.h"
#include "base/system/sys_info.h"
#include "base/trace_event/trace_event.h"
#include "gpu/command_buffer/client/gles2_interface.h"
#include "gpu/command_buffer/common/capabilities.h"
#include "gpu/skia_bindings/gl_bindings_skia_cmd_buffer.h"
#include "gpu/skia_bindings/gles2_implementation_with_grcontext_support.h"
#include "third_party/skia/include/gpu/GrContext.h"
#include "third_party/skia/include/gpu/GrContextOptions.h"
#include "third_party/skia/include/gpu/gl/GrGLInterface.h"
namespace skia_bindings {
GrContextForGLES2Interface::GrContextForGLES2Interface(
gpu::gles2::GLES2Interface* gl,
gpu::ContextSupport* context_support,
const gpu::Capabilities& capabilities,
size_t max_resource_cache_bytes,
size_t max_glyph_cache_texture_bytes)
: context_support_(context_support) {
// The limit of the number of GPU resources we hold in the GrContext's
// GPU cache.
static const int kMaxGaneshResourceCacheCount = 16384;
GrContextOptions options;
options.fGlyphCacheTextureMaximumBytes = max_glyph_cache_texture_bytes;
options.fAvoidStencilBuffers = capabilities.avoid_stencil_buffers;
options.fAllowPathMaskCaching = false;
options.fSharpenMipmappedTextures = true;
sk_sp<GrGLInterface> interface(
skia_bindings::CreateGLES2InterfaceBindings(gl, context_support));
gr_context_ = GrContext::MakeGL(std::move(interface), options);
if (gr_context_) {
gr_context_->setResourceCacheLimits(kMaxGaneshResourceCacheCount,
max_resource_cache_bytes);
context_support_->SetGrContext(gr_context_.get());
}
}
GrContextForGLES2Interface::~GrContextForGLES2Interface() {
// At this point the GLES2Interface is going to be destroyed, so have
// the GrContext clean up and not try to use it anymore.
if (gr_context_) {
gr_context_->releaseResourcesAndAbandonContext();
context_support_->SetGrContext(nullptr);
}
}
void GrContextForGLES2Interface::OnLostContext() {
if (gr_context_)
gr_context_->abandonContext();
}
void GrContextForGLES2Interface::FreeGpuResources() {
if (gr_context_) {
TRACE_EVENT_INSTANT0("gpu", "GrContext::freeGpuResources",
TRACE_EVENT_SCOPE_THREAD);
gr_context_->freeGpuResources();
}
}
GrContext* GrContextForGLES2Interface::get() {
return gr_context_.get();
}
} // namespace skia_bindings
| [
"[email protected]"
] | |
b8e0ffa4b009b74ff3fd786f6756e8196d929531 | 0589cbbee2fb123d2c71cd30a5d3d743717f9154 | /TilSys/DlgThreshold.cpp | 5403542cf7b6fe37eee07f7d4c15ab8449fb3b64 | [] | no_license | bruce-leng/CrackInspection | fd5ec18264e1f76aad75677fbfb2430001a563a0 | f9caf6762bcd0deb5d176387345e880ef9ece8fd | refs/heads/master | 2021-01-13T12:18:41.022833 | 2016-09-29T07:59:14 | 2016-09-29T07:59:14 | 69,544,583 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 5,125 | cpp | // DlgThreshold.cpp : implementation file
//
#include "stdafx.h"
#include "TilSys.h"
#include "DlgThreshold.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// DlgThreshold dialog
DlgThreshold::DlgThreshold(CWnd* pParent /*=NULL*/)
: CDialog(DlgThreshold::IDD, pParent)
{
//{{AFX_DATA_INIT(DlgThreshold)
m_level = 128;
m_bPreview = FALSE;
//}}AFX_DATA_INIT
}
void DlgThreshold::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(DlgThreshold)
DDX_Control(pDX, IDOK, m_ok);
DDX_Control(pDX, IDCANCEL, m_canc);
DDX_Text(pDX, IDC_EDIT1, m_level);
DDV_MinMaxByte(pDX, m_level, 0, 255);
DDX_Check(pDX, IDC_CHECK1, m_bPreview);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(DlgThreshold, CDialog)
//{{AFX_MSG_MAP(DlgThreshold)
ON_WM_PAINT()
ON_BN_CLICKED(IDC_THRESHOLD_MINUS, OnThresholdMinus)
ON_BN_CLICKED(IDC_THRESHOLD_PLUS, OnThresholdPlus)
ON_NOTIFY(NM_RELEASEDCAPTURE, IDC_SLIDER2, OnReleasedcaptureSlider2)
ON_NOTIFY(NM_CUSTOMDRAW, IDC_SLIDER2, OnCustomdrawSlider2)
ON_BN_CLICKED(IDC_CHECK1, OnCheck1)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// DlgThreshold message handlers
BOOL DlgThreshold::OnInitDialog()
{
CDialog::OnInitDialog();
CSliderCtrl* pSlider = (CSliderCtrl*)GetDlgItem(IDC_SLIDER2);
pSlider->SetRange(0, 255);
pSlider->SetPos(128);
m_pCurImage = new CImage(*GetCanvasMgr()->GetCurCanvas()->GetCurImage());
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void DlgThreshold::OnPaint()
{
CPaintDC dc(this); // device context for painting
// TODO: Add your message handler code here
// Do not call CDialog::OnPaint() for painting messages
}
void DlgThreshold::OnThresholdMinus()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
m_level --;
if (m_level == 254)
GetDlgItem(IDC_THRESHOLD_PLUS)->EnableWindow(TRUE);
else if (m_level <= 0)
GetDlgItem(IDC_THRESHOLD_MINUS)->EnableWindow(FALSE);
UpdateData(FALSE);
if (m_bPreview)
{
// 更新主视图中的显示
CImage* pImage = GetCanvasMgr()->GetCurCanvas()->GetCurImage();
pImage->Copy(*m_pCurImage);
pImage->ThresholdRGB(m_level);
m_pDoc->SetModifiedFlag(TRUE);
m_pDoc->UpdateAllViews(NULL);
}
}
void DlgThreshold::OnThresholdPlus()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
m_level ++;
if (m_level == 1)
GetDlgItem(IDC_THRESHOLD_MINUS)->EnableWindow(TRUE);
else if (m_level >= 255)
GetDlgItem(IDC_THRESHOLD_PLUS)->EnableWindow(FALSE);
UpdateData(FALSE);
if (m_bPreview)
{
// 更新主视图中的显示
CImage* pImage = GetCanvasMgr()->GetCurCanvas()->GetCurImage();
pImage->Copy(*m_pCurImage);
pImage->ThresholdRGB(m_level);
m_pDoc->SetModifiedFlag(TRUE);
m_pDoc->UpdateAllViews(NULL);
}
}
void DlgThreshold::OnOK()
{
CTilCanvas* pCanvas = GetCanvasMgr()->GetCurCanvas();
pCanvas->SetModifiedFlag(TRUE);
// 更新主视图中的显示
if (!m_bPreview)
{
CImage* pImage = pCanvas->GetCurImage();
pImage->ThresholdRGB(m_level);
m_pDoc->SetModifiedFlag(TRUE);
m_pDoc->UpdateAllViews(NULL);
}
delete m_pCurImage;
CDialog::OnOK();
}
void DlgThreshold::OnCancel()
{
// TODO: Add extra cleanup here
CImage* pImage = GetCanvasMgr()->GetCurCanvas()->GetCurImage();
pImage->Copy(*m_pCurImage);
// m_pDoc->SetModifiedFlag(FALSE);
m_pDoc->UpdateAllViews(NULL);
delete m_pCurImage;
CDialog::OnCancel();
}
void DlgThreshold::OnReleasedcaptureSlider2(NMHDR* pNMHDR, LRESULT* pResult)
{
// TODO: Add your control notification handler code here
CSliderCtrl* pSlider = (CSliderCtrl*)GetDlgItem(IDC_SLIDER2);
m_level = pSlider->GetPos();
// if (m_bPreview)
// {
// // 更新主视图中的显示
// CImage* pImage = GetCanvasMgr()->GetCurCanvas()->GetCurImage();
// pImage->Copy(*m_pCurImage);
// pImage->ThresholdRGB(m_level);
//
// m_pDoc->SetModifiedFlag(TRUE);
// m_pDoc->UpdateAllViews(FALSE);
// }
*pResult = 0;
}
void DlgThreshold::OnCustomdrawSlider2(NMHDR* pNMHDR, LRESULT* pResult)
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
CSliderCtrl* pSlider = (CSliderCtrl*)GetDlgItem(IDC_SLIDER2);
m_level = pSlider->GetPos();
UpdateData(FALSE);
if (m_bPreview)
{
// 更新主视图中的显示
CImage* pImage = GetCanvasMgr()->GetCurCanvas()->GetCurImage();
pImage->Copy(*m_pCurImage);
pImage->ThresholdRGB(m_level);
m_pDoc->SetModifiedFlag(TRUE);
m_pDoc->UpdateAllViews(NULL);
}
*pResult = 0;
}
void DlgThreshold::OnCheck1()
{
// TODO: Add your control notification handler code here
UpdateData(TRUE);
CImage* pImage = GetCanvasMgr()->GetCurCanvas()->GetCurImage();
pImage->Copy(*m_pCurImage);
if (m_bPreview)
{
// 更新主视图中的显示
pImage->ThresholdRGB(m_level);
}
m_pDoc->SetModifiedFlag(TRUE);
m_pDoc->UpdateAllViews(NULL);
}
| [
"[email protected]"
] | |
5a06fab3511d1ccaf75cc544f57913d192d2d412 | d0fb46aecc3b69983e7f6244331a81dff42d9595 | /sae/include/alibabacloud/sae/model/RestartInstancesRequest.h | d41da1461c747b59f2df5670daa0126ea0e92ef0 | [
"Apache-2.0"
] | permissive | aliyun/aliyun-openapi-cpp-sdk | 3d8d051d44ad00753a429817dd03957614c0c66a | e862bd03c844bcb7ccaa90571bceaa2802c7f135 | refs/heads/master | 2023-08-29T11:54:00.525102 | 2023-08-29T03:32:48 | 2023-08-29T03:32:48 | 115,379,460 | 104 | 82 | NOASSERTION | 2023-09-14T06:13:33 | 2017-12-26T02:53:27 | C++ | UTF-8 | C++ | false | false | 1,475 | h | /*
* Copyright 2009-2017 Alibaba Cloud 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 ALIBABACLOUD_SAE_MODEL_RESTARTINSTANCESREQUEST_H_
#define ALIBABACLOUD_SAE_MODEL_RESTARTINSTANCESREQUEST_H_
#include <alibabacloud/sae/SaeExport.h>
#include <alibabacloud/core/RoaServiceRequest.h>
#include <string>
#include <vector>
#include <map>
namespace AlibabaCloud {
namespace Sae {
namespace Model {
class ALIBABACLOUD_SAE_EXPORT RestartInstancesRequest : public RoaServiceRequest {
public:
RestartInstancesRequest();
~RestartInstancesRequest();
std::string getInstanceIds() const;
void setInstanceIds(const std::string &instanceIds);
std::string getAppId() const;
void setAppId(const std::string &appId);
private:
std::string instanceIds_;
std::string appId_;
};
} // namespace Model
} // namespace Sae
} // namespace AlibabaCloud
#endif // !ALIBABACLOUD_SAE_MODEL_RESTARTINSTANCESREQUEST_H_
| [
"[email protected]"
] | |
b546f618e3f72a60b91cb51341e3f0ef0dca9135 | 10081dbec33e55b2cfe5910161366626a1f3ca81 | /monitor/ocn/base/facility/ErrorMsg.h | dd8fe219dd645e7aca79fd0d8c9e6161c5c8d485 | [] | no_license | duyouhua/hlsEncoder | 4e00e3068eb01112f82fe574c821dbd2ccfb6d59 | 6e0f45ad5bf5465486b7f134c76126e33cf782dc | refs/heads/master | 2021-01-20T13:10:27.380648 | 2016-03-11T09:46:28 | 2016-03-11T09:46:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 222 | h | #ifndef ERRORMSG_FACILITY_BASE_OCN_H
#define ERRORMSG_FACILITY_BASE_OCN_H
#include <string>
namespace ocn
{
namespace base
{
namespace facility
{
std::string getErrorMsg();
}
}
}
#endif // ERRORMSG_FACILITY_BASE_OCN_H
| [
"[email protected]"
] | |
0607f8ff3472c289b6639d7c1e5e81e9253c2106 | af0ecafb5428bd556d49575da2a72f6f80d3d14b | /CodeJamCrawler/dataset/12_8135_60.cpp | 6fa677ad22355d39ebfcbbcf654d4764eb888968 | [] | no_license | gbrlas/AVSP | 0a2a08be5661c1b4a2238e875b6cdc88b4ee0997 | e259090bf282694676b2568023745f9ffb6d73fd | refs/heads/master | 2021-06-16T22:25:41.585830 | 2017-06-09T06:32:01 | 2017-06-09T06:32:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,419 | cpp | #include "cmath"
#include "cstdio"
#include "algorithm"
#include "map"
#include "numeric"
#include "queue"
#include "set"
#include "string"
#include "utility"
#include "vector"
using namespace std;
int T,t,A,B,a,b;
int sol;
set <int> R;
string flip_str(string x) {
string y = "";
for(int i = x.size()-1;i>=0;i--) {
y += x[i];
}
return y;
}
string int_to_string(int x) {
string s = "";
while(x>0) {
s += ('0'+x%10);
x/=10;
}
return flip_str(s);
}
int string_to_int(string s) {
int x = 0;
for(int i=0;i<(int)s.length();i++) {
x*=10;
x+=s[i]-'0';
}
return x;
}
string shift(string x, int o) {
string y = "";
int s = x.size();
for(int i=0;i<s;i++) {
y+=x[(i+o)%s];
}
return y;
}
int ispair(int xa, int xb) {
string sa = int_to_string(xa);
string sb = int_to_string(xb);
fflush(stdout);
for(int o=0;o<(int)sa.size();o++) {
if(shift(sa,o)==sb) {
//printf("%s %s\n", sa.c_str(), sb.c_str());
return 1;
}
}
return 0;
}
int count(int xa) {
R.clear();
string sa = int_to_string(xa);
int res = 0;
for(int o=1;o<(int)sa.size();o++) {
int xb = string_to_int(shift(sa,o));
if(xa<xb && xb<=B) {
//printf("%d %d\n",xa,xb);
R.insert(xb);
}
}
return res = R.size();
}
void testc() {
sol = 0;
scanf("%d %d",&A, &B);
for(a=A;a<=B;a++) {
sol+=count(a);
}
printf("Case #%d: %d\n",t,sol);
}
int main() {
scanf("%d",&T);
for(t=1;t<=T;t++) {
testc();
}
return 0;
} | [
"[email protected]"
] | |
08260f1e14f81acf3efea9bd961c08523e792f0b | 73120b54a6a7a08e3a7140fb53a0b018c38b499d | /hphp/util/vixl/a64/simulator-a64.h | 9ad6f5e84a4f89c7175e36925710b7cd70b27652 | [
"Zend-2.0",
"LicenseRef-scancode-unknown-license-reference",
"PHP-3.01"
] | permissive | mrotec/hiphop-php | 58705a281ff6759cf1acd9735a312c486a18a594 | 132241f5e5b7c5f1873dbec54c5bc691c6e75f28 | refs/heads/master | 2021-01-18T10:10:43.051362 | 2013-07-31T19:11:55 | 2013-07-31T19:25:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,354 | h | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2013 Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
// Copyright 2013, ARM Limited
// 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 ARM Limited 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 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.
#ifndef VIXL_A64_SIMULATOR_A64_H_
#define VIXL_A64_SIMULATOR_A64_H_
#include "hphp/util/vixl/globals.h"
#include "hphp/util/vixl/utils.h"
#include "hphp/util/vixl/a64/instructions-a64.h"
#include "hphp/util/vixl/a64/assembler-a64.h"
#include "hphp/util/vixl/a64/disasm-a64.h"
namespace vixl {
enum ReverseByteMode {
Reverse16 = 0,
Reverse32 = 1,
Reverse64 = 2
};
// Printf. See debugger-a64.h for more information on pseudo instructions.
// - type: CPURegister::RegisterType stored as a uint32_t.
//
// Simulate a call to printf.
//
// Floating-point and integer arguments are passed in separate sets of
// registers in AAPCS64 (even for varargs functions), so it is not possible to
// determine the type of location of each argument without some information
// about the values that were passed in. This information could be retrieved
// from the printf format string, but the format string is not trivial to
// parse so we encode the relevant information with the HLT instruction under
// the type argument. Therefore the interface is:
// x0: The format string
// x1-x7: Optional arguments, if type == CPURegister::kRegister
// d0-d7: Optional arguments, if type == CPURegister::kFPRegister
const Instr kPrintfOpcode = 0xdeb1;
const unsigned kPrintfTypeOffset = 1 * kInstructionSize;
const unsigned kPrintfLength = 2 * kInstructionSize;
class Simulator : public DecoderVisitor {
public:
explicit Simulator(Decoder* decoder, FILE* stream = stdout);
~Simulator();
void ResetState();
// TODO: We assume little endianness, and the way in which the members of this
// union overlay. Add tests to ensure this, or fix accessors to no longer
// require this assumption.
union SimRegister {
int64_t x;
int32_t w;
};
union SimFPRegister {
double d;
float s;
};
// Run the simulator.
virtual void Run();
void RunFrom(Instruction* first);
// Simulation helpers.
inline Instruction* pc() { return pc_; }
inline void set_pc(Instruction* new_pc) {
pc_ = new_pc;
pc_modified_ = true;
}
inline void increment_pc() {
if (!pc_modified_) {
pc_ = pc_->NextInstruction();
}
pc_modified_ = false;
}
inline void ExecuteInstruction() {
// The program counter should always be aligned.
ASSERT(IsWordAligned(pc_));
decoder_->Decode(pc_);
increment_pc();
}
// Declare all Visitor functions.
#define DECLARE(A) void Visit##A(Instruction* instr);
VISITOR_LIST(DECLARE)
#undef DECLARE
// Register accessors.
inline int32_t wreg(unsigned code,
Reg31Mode r31mode = Reg31IsZeroRegister) const {
ASSERT(code < kNumberOfRegisters);
if ((code == 31) && (r31mode == Reg31IsZeroRegister)) {
return 0;
}
return registers_[code].w;
}
inline int64_t xreg(unsigned code,
Reg31Mode r31mode = Reg31IsZeroRegister) const {
ASSERT(code < kNumberOfRegisters);
if ((code == 31) && (r31mode == Reg31IsZeroRegister)) {
return 0;
}
return registers_[code].x;
}
inline int64_t reg(unsigned size,
unsigned code,
Reg31Mode r31mode = Reg31IsZeroRegister) const {
switch (size) {
case kWRegSize: return wreg(code, r31mode) & kWRegMask;
case kXRegSize: return xreg(code, r31mode);
default:
UNREACHABLE();
return 0;
}
}
inline void set_wreg(unsigned code, int32_t value,
Reg31Mode r31mode = Reg31IsZeroRegister) {
ASSERT(code < kNumberOfRegisters);
if ((code == kZeroRegCode) && (r31mode == Reg31IsZeroRegister)) {
return;
}
registers_[code].x = 0; // First clear the register top bits.
registers_[code].w = value;
}
inline void set_xreg(unsigned code, int64_t value,
Reg31Mode r31mode = Reg31IsZeroRegister) {
ASSERT(code < kNumberOfRegisters);
if ((code == kZeroRegCode) && (r31mode == Reg31IsZeroRegister)) {
return;
}
registers_[code].x = value;
}
inline void set_reg(unsigned size, unsigned code, int64_t value,
Reg31Mode r31mode = Reg31IsZeroRegister) {
switch (size) {
case kWRegSize:
return set_wreg(code, static_cast<int32_t>(value & 0xffffffff),
r31mode);
case kXRegSize:
return set_xreg(code, value, r31mode);
default:
UNREACHABLE();
break;
}
}
#define REG_ACCESSORS(N) \
inline int32_t w##N() { return wreg(N); } \
inline int64_t x##N() { return xreg(N); } \
inline void set_w##N(int32_t val) { set_wreg(N, val); } \
inline void set_x##N(int64_t val) { set_xreg(N, val); }
REGISTER_CODE_LIST(REG_ACCESSORS)
#undef REG_ACCESSORS
// Aliases.
#define REG_ALIAS_ACCESSORS(N, wname, xname) \
inline int32_t wname() { return wreg(N); } \
inline int64_t xname() { return xreg(N); } \
inline void set_##wname(int32_t val) { set_wreg(N, val); } \
inline void set_##xname(int64_t val) { set_xreg(N, val); }
REG_ALIAS_ACCESSORS(30, wlr, lr);
#undef REG_ALIAS_ACCESSORS
// The stack is a special case in aarch64.
inline int32_t wsp() { return wreg(31, Reg31IsStackPointer); }
inline int64_t sp() { return xreg(31, Reg31IsStackPointer); }
inline void set_wsp(int32_t val) {
set_wreg(31, val, Reg31IsStackPointer);
}
inline void set_sp(int64_t val) {
set_xreg(31, val, Reg31IsStackPointer);
}
// FPRegister accessors.
inline float sreg(unsigned code) const {
ASSERT(code < kNumberOfFPRegisters);
return fpregisters_[code].s;
}
inline uint32_t sreg_bits(unsigned code) const {
return float_to_rawbits(sreg(code));
}
inline double dreg(unsigned code) const {
ASSERT(code < kNumberOfFPRegisters);
return fpregisters_[code].d;
}
inline uint64_t dreg_bits(unsigned code) const {
return double_to_rawbits(dreg(code));
}
inline double fpreg(unsigned size, unsigned code) const {
switch (size) {
case kSRegSize: return sreg(code);
case kDRegSize: return dreg(code);
default: {
UNREACHABLE();
return 0.0;
}
}
}
inline void set_sreg(unsigned code, float val) {
ASSERT(code < kNumberOfFPRegisters);
// Ensure that the upper word is set to 0.
set_dreg_bits(code, 0);
fpregisters_[code].s = val;
}
inline void set_sreg_bits(unsigned code, uint32_t rawbits) {
ASSERT(code < kNumberOfFPRegisters);
// Ensure that the upper word is set to 0.
set_dreg_bits(code, 0);
set_sreg(code, rawbits_to_float(rawbits));
}
inline void set_dreg(unsigned code, double val) {
ASSERT(code < kNumberOfFPRegisters);
fpregisters_[code].d = val;
}
inline void set_dreg_bits(unsigned code, uint64_t rawbits) {
ASSERT(code < kNumberOfFPRegisters);
set_dreg(code, rawbits_to_double(rawbits));
}
inline void set_fpreg(unsigned size, unsigned code, double value) {
switch (size) {
case kSRegSize:
return set_sreg(code, value);
case kDRegSize:
return set_dreg(code, value);
default:
UNREACHABLE();
break;
}
}
#define FPREG_ACCESSORS(N) \
inline float s##N() { return sreg(N); } \
inline double d##N() { return dreg(N); } \
inline void set_s##N(float val) { set_sreg(N, val); } \
inline void set_d##N(double val) { set_dreg(N, val); }
REGISTER_CODE_LIST(FPREG_ACCESSORS)
#undef FPREG_ACCESSORS
bool N() { return (psr_ & NFlag) != 0; }
bool Z() { return (psr_ & ZFlag) != 0; }
bool C() { return (psr_ & CFlag) != 0; }
bool V() { return (psr_ & VFlag) != 0; }
uint32_t nzcv() { return psr_ & (NFlag | ZFlag | CFlag | VFlag); }
// Debug helpers
void PrintFlags(bool print_all = false);
void PrintRegisters(bool print_all_regs = false);
void PrintFPRegisters(bool print_all_regs = false);
void PrintProcessorState();
static const char* WRegNameForCode(unsigned code,
Reg31Mode mode = Reg31IsZeroRegister);
static const char* XRegNameForCode(unsigned code,
Reg31Mode mode = Reg31IsZeroRegister);
static const char* SRegNameForCode(unsigned code);
static const char* DRegNameForCode(unsigned code);
static const char* VRegNameForCode(unsigned code);
inline bool coloured_trace() { return coloured_trace_; }
inline void set_coloured_trace(bool value) { coloured_trace_ = value; }
inline bool disasm_trace() { return disasm_trace_; }
inline void set_disasm_trace(bool value) {
if (value != disasm_trace_) {
if (value) {
decoder_->InsertVisitorBefore(print_disasm_, this);
} else {
decoder_->RemoveVisitor(print_disasm_);
}
disasm_trace_ = value;
}
}
protected:
// Simulation helpers ------------------------------------
bool ConditionPassed(Condition cond) {
switch (cond) {
case eq:
return Z();
case ne:
return !Z();
case hs:
return C();
case lo:
return !C();
case mi:
return N();
case pl:
return !N();
case vs:
return V();
case vc:
return !V();
case hi:
return C() && !Z();
case ls:
return !(C() && !Z());
case ge:
return N() == V();
case lt:
return N() != V();
case gt:
return !Z() && (N() == V());
case le:
return !(!Z() && (N() == V()));
case al:
return true;
default:
UNREACHABLE();
return false;
}
}
bool ConditionFailed(Condition cond) {
return !ConditionPassed(cond);
}
void AddSubHelper(Instruction* instr, int64_t op2);
int64_t AddWithCarry(unsigned reg_size,
bool set_flags,
int64_t src1,
int64_t src2,
int64_t carry_in = 0);
void LogicalHelper(Instruction* instr, int64_t op2);
void ConditionalCompareHelper(Instruction* instr, int64_t op2);
void LoadStoreHelper(Instruction* instr,
int64_t offset,
AddrMode addrmode);
void LoadStorePairHelper(Instruction* instr, AddrMode addrmode);
uint8_t* AddressModeHelper(unsigned addr_reg,
int64_t offset,
AddrMode addrmode);
uint64_t MemoryRead(const uint8_t* address, unsigned num_bytes);
uint8_t MemoryRead8(uint8_t* address);
uint16_t MemoryRead16(uint8_t* address);
uint32_t MemoryRead32(uint8_t* address);
float MemoryReadFP32(uint8_t* address);
uint64_t MemoryRead64(uint8_t* address);
double MemoryReadFP64(uint8_t* address);
void MemoryWrite(uint8_t* address, uint64_t value, unsigned num_bytes);
void MemoryWrite32(uint8_t* address, uint32_t value);
void MemoryWriteFP32(uint8_t* address, float value);
void MemoryWrite64(uint8_t* address, uint64_t value);
void MemoryWriteFP64(uint8_t* address, double value);
int64_t ShiftOperand(unsigned reg_size,
int64_t value,
Shift shift_type,
unsigned amount);
int64_t Rotate(unsigned reg_width,
int64_t value,
Shift shift_type,
unsigned amount);
int64_t ExtendValue(unsigned reg_width,
int64_t value,
Extend extend_type,
unsigned left_shift = 0);
uint64_t ReverseBits(uint64_t value, unsigned num_bits);
uint64_t ReverseBytes(uint64_t value, ReverseByteMode mode);
void FPCompare(double val0, double val1);
double FPRoundInt(double value, FPRounding round_mode);
int32_t FPToInt32(double value, FPRounding rmode);
int64_t FPToInt64(double value, FPRounding rmode);
uint32_t FPToUInt32(double value, FPRounding rmode);
uint64_t FPToUInt64(double value, FPRounding rmode);
double FPMax(double a, double b);
double FPMin(double a, double b);
// Pseudo Printf instruction
void DoPrintf(Instruction* instr);
// Processor state ---------------------------------------
// Output stream.
FILE* stream_;
PrintDisassembler* print_disasm_;
// General purpose registers. Register 31 is the stack pointer.
SimRegister registers_[kNumberOfRegisters];
// Floating point registers
SimFPRegister fpregisters_[kNumberOfFPRegisters];
// Program Status Register.
// bits[31, 27]: Condition flags N, Z, C, and V.
// (Negative, Zero, Carry, Overflow)
uint32_t psr_;
// Condition flags.
void SetFlags(uint32_t new_flags);
static inline uint32_t CalcNFlag(int64_t result, unsigned reg_size) {
return ((result >> (reg_size - 1)) & 1) * NFlag;
}
static inline uint32_t CalcZFlag(int64_t result) {
return (result == 0) ? static_cast<uint32_t>(ZFlag) : 0;
}
static const uint32_t kConditionFlagsMask = 0xf0000000;
// Stack
byte* stack_;
static const int stack_protection_size_ = 256;
// 2 KB stack.
static const int stack_size_ = 2 * 1024 + 2 * stack_protection_size_;
byte* stack_limit_;
Decoder* decoder_;
// Indicates if the pc has been modified by the instruction and should not be
// automatically incremented.
bool pc_modified_;
Instruction* pc_;
static const char* xreg_names[];
static const char* wreg_names[];
static const char* sreg_names[];
static const char* dreg_names[];
static const char* vreg_names[];
static const Instruction* kEndOfSimAddress;
private:
bool coloured_trace_;
// Indicates whether the disassembly trace is active.
bool disasm_trace_;
};
} // namespace vixl
#endif // VIXL_A64_SIMULATOR_A64_H_
| [
"[email protected]"
] | |
16d30ce59836ad9bc43ebfbc49e2dba853b7c57a | 9acc8899b66713c475e0504807fa70dffde8a71b | /Algorithms/Greedy Algo/Seats.cpp | 6d320c55c6b5fddfa12345ae990a9d6f5d67d15d | [
"MIT"
] | permissive | pratikshakj/HacktoberFest2020-Contributions | 05b9d080bffb5921f8bb10d3ef52618021656a25 | a925218708c0739554d6f34ce9e4104541b27a3f | refs/heads/master | 2022-12-30T14:23:49.539114 | 2020-10-24T16:33:43 | 2020-10-24T16:33:43 | 306,925,378 | 3 | 0 | MIT | 2020-10-24T16:33:44 | 2020-10-24T16:31:36 | null | UTF-8 | C++ | false | false | 3,503 | cpp | /*
There is a row of seats. Assume that it contains N seats adjacent to each other.
There is a group of people who are already seated in that row randomly. i.e. some are sitting together & some are scattered.
An occupied seat is marked with a character 'x' and an unoccupied seat is marked with a dot ('.')
Now your target is to make the whole group sit together i.e. next to each other,
without having any vacant seat between them in such a way that the total number of hops or jumps to move them should be minimum.
Return minimum value % MOD where MOD = 10000003
Example
Here is the row having 15 seats represented by the String (0, 1, 2, 3, ......... , 14) -
. . . . x . . x x . . . x . .
Now to make them sit together one of approaches is -
. . . . . . x x x x . . . . .
Following are the steps to achieve this -
1 - Move the person sitting at 4th index to 6th index -
Number of jumps by him = (6 - 4) = 2
2 - Bring the person sitting at 12th index to 9th index -
Number of jumps by him = (12 - 9) = 3
So now the total number of jumps made =
( 2 + 3 ) % MOD =
5 which is the minimum possible jumps to make them seat together.
There are also other ways to make them sit together but the number of jumps will exceed 5 and that will not be minimum.
For example bring them all towards the starting of the row i.e. start placing them from index 0.
In that case the total number of jumps will be
( 4 + 6 + 6 + 9 )%MOD
= 25 which is very costly and not an optimized way to do this movement
https://www.interviewbit.com/problems/seats/
*/
#define MOD 10000003
int Solution::seats(string A) {
auto n = A.length();
// Median approach
vector<int> pos;
for (auto i = 0; i<n; ++i)
if (A[i] == 'x')
pos.emplace_back(i);
auto psize = pos.size();
if (psize == 0)
return 0;
int mid = psize/2;
int median = psize & 1 ? pos[mid] : (pos[mid-1] + pos[mid])/2;
int hops = 0;
int empty = A[median] == 'x' ? median - 1 : median;
for (auto s = median-1; s>=0; --s)
if (A[s] == 'x')
{
hops += empty - s;
hops %= MOD;
--empty;
}
empty = median + 1;
for (auto e = median+1; e<n; ++e)
if (A[e] == 'x')
{
hops += e - empty;
hops %= MOD;
++empty;
}
return hops % MOD;
// My attempt of pushing it near max x count - failed for corner cases
/*int maxCount = INT_MIN, startIndex = 0, endIndex = 0;
int hops = 0;
for (auto i = 0; i < n; ++i)
{
int count = 0, index = i;
while (A[i] == 'x' && i < n)
{
++count;
++i;
}
if (count > maxCount)
{
maxCount = count;
startIndex = index;
endIndex = i - 1;
}
}
cout << maxCount << " " << startIndex << endIndex << endl;
auto f1 = startIndex, f2 = endIndex;
for (auto j = 0; j < n; ++j)
{
if (A[j] == 'x' && !(j >= f1 && j <= f2))
{
int d1 = abs(startIndex - 1 - j);
int d2 = abs(endIndex + 1 - j);
if (d1<=d2)
if (startIndex > 0)
--startIndex;
else
if (endIndex < n-1)
++endIndex;
hops += min (d1, d2);
}
}
return hops % 10000003;*/
}
| [
"[email protected]"
] | |
049b290a40774f60fa3f0765420d0ecdd3692863 | 8dbfa7dd87ff1531190202621494aa0342377368 | /gui/maintabwidget.cpp | 5ef744a4219be1e573380655b267ea7f534d2580 | [] | no_license | dazzle50/QPlanner | ea7d7b4668133c89c5dd326581723abec80068a4 | d6eab19e00e01cfc456ad2fa17d4abd1a227b747 | refs/heads/master | 2021-01-10T11:54:46.820915 | 2015-06-06T21:58:05 | 2015-06-06T21:58:05 | 36,996,654 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,718 | cpp | /***************************************************************************
* Copyright (C) 2014 by Richard Crook *
* http://code.google.com/p/projectplanner *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include <QMessageBox>
#include <QUndoStack>
#include <QXmlStreamWriter>
#include "maintabwidget.h"
#include "ui_maintabwidget.h"
#include "model/plan.h"
#include "model/daysmodel.h"
#include "model/day.h"
#include "model/calendarsmodel.h"
#include "model/calendar.h"
#include "model/resourcesmodel.h"
#include "model/resource.h"
#include "model/tasksmodel.h"
#include "model/task.h"
#include "command/commandpropertieschange.h"
#include "delegate/daysdelegate.h"
#include "delegate/calendarsdelegate.h"
#include "delegate/resourcesdelegate.h"
#include "delegate/tasksdelegate.h"
/*************************************************************************************************/
/***************************** Tabbed widget containing main screens *****************************/
/*************************************************************************************************/
QTableView* MainTabWidget::tasksTable() { return ui->tasksView; }
QTableView* MainTabWidget::resourcesTable() { return ui->resourcesView; }
QTableView* MainTabWidget::calendarsTable() { return ui->calendarsView; }
QTableView* MainTabWidget::daysTable() { return ui->daysView; }
/****************************************** constructor ******************************************/
MainTabWidget::MainTabWidget( QWidget* parent ) : QTabWidget( parent ), ui( new Ui::MainTabWidget )
{
// setup palette & ui for main tab widget
QPalette pal = palette();
pal.setBrush( QPalette::Inactive, QPalette::Highlight, QColor("#E0E0E0") );
setPalette( pal );
ui->setupUi( this );
// set models & delegates for table views
setModels();
DaysDelegate* dd = new DaysDelegate();
CalendarsDelegate* cd = new CalendarsDelegate();
ResourcesDelegate* rd = new ResourcesDelegate();
TasksDelegate* td = new TasksDelegate();
ui->daysView->setItemDelegate( dd );
ui->calendarsView->setItemDelegate( cd );
ui->resourcesView->setItemDelegate( rd );
ui->tasksView->setItemDelegate( td );
// connect delegate edit cell to slot, queued so any earlier edit is finished and closed
connect( dd, SIGNAL(editCell(QModelIndex,QString)),
this, SLOT(slotEditDayCell(QModelIndex,QString)), Qt::QueuedConnection );
connect( cd, SIGNAL(editCell(QModelIndex,QString)),
this, SLOT(slotEditCalendarCell(QModelIndex,QString)), Qt::QueuedConnection );
connect( rd, SIGNAL(editCell(QModelIndex,QString)),
this, SLOT(slotEditResourceCell(QModelIndex,QString)), Qt::QueuedConnection );
connect( td, SIGNAL(editCell(QModelIndex,QString)),
this, SLOT(slotEditTaskCell(QModelIndex,QString)), Qt::QueuedConnection );
// hide task 0 'plan summary' and resource 0 'unassigned'
ui->tasksView->verticalHeader()->hideSection( 0 );
ui->resourcesView->verticalHeader()->hideSection( 0 );
// setup tasks gantt
ui->ganttView->createGantt( ui->ganttWidget );
ui->ganttView->setTable( ui->tasksView );
ui->tasksView->setHeaderHeight( ui->ganttView->scaleHeight() );
// create new palette for read-only edit widgets with different Base colour
QPalette* palette = new QPalette( ui->propertiesWidget->palette() );
palette->setColor( QPalette::Base, palette->window().color() );
// setup plan tab
ui->planBeginning->setPalette( *palette );
ui->planEnd->setPalette( *palette );
ui->fileName->setPalette( *palette );
ui->fileLocation->setPalette( *palette );
ui->savedBy->setPalette( *palette );
ui->savedWhen->setPalette( *palette );
slotUpdatePlanTab();
// set initial column widths for tasks table view
ui->tasksView->horizontalHeader()->setDefaultSectionSize( 140 );
ui->tasksView->setColumnWidth( Task::SECTION_TITLE, 150 );
ui->tasksView->setColumnWidth( Task::SECTION_DURATION, 60 );
ui->tasksView->setColumnWidth( Task::SECTION_WORK, 50 );
ui->tasksView->setColumnWidth( Task::SECTION_PREDS, 80 );
ui->tasksView->setColumnWidth( Task::SECTION_RES, 80 );
ui->tasksView->setColumnWidth( Task::SECTION_TYPE, 150 );
ui->tasksView->setColumnWidth( Task::SECTION_PRIORITY, 50 );
ui->tasksView->setColumnWidth( Task::SECTION_COST, 50 );
ui->tasksView->setColumnWidth( Task::SECTION_COMMENT, 200 );
// set initial column widths for reources table view
ui->resourcesView->setColumnWidth( Resource::SECTION_INITIALS, 60 );
ui->resourcesView->setColumnWidth( Resource::SECTION_NAME, 150 );
ui->resourcesView->setColumnWidth( Resource::SECTION_ORG, 150 );
ui->resourcesView->setColumnWidth( Resource::SECTION_GROUP, 150 );
ui->resourcesView->setColumnWidth( Resource::SECTION_AVAIL, 65 );
ui->resourcesView->setColumnWidth( Resource::SECTION_COST, 65 );
ui->resourcesView->setColumnWidth( Resource::SECTION_COMMENT, 250 );
// set initial column widths for calendars table view
ui->calendarsView->horizontalHeader()->setDefaultSectionSize( 150 );
// set initial column widths for day types table view
ui->daysView->horizontalHeader()->setDefaultSectionSize( 60 );
ui->daysView->setColumnWidth( Day::SECTION_NAME, 150 );
ui->daysView->setColumnWidth( Day::SECTION_WORK, 50 );
ui->daysView->setColumnWidth( Day::SECTION_PERIODS, 50 );
// set tasks view splitter behaviour & default position
ui->tasksGanttSplitter->setStretchFactor( 1, 1 );
QList<int> sizes = ui->tasksGanttSplitter->sizes();
sizes[0] = ui->tasksView->horizontalHeader()->sectionSize( 0 ) +
ui->tasksView->horizontalHeader()->sectionSize( 1 ) +
ui->tasksView->horizontalHeader()->sectionSize( 2 ) +
ui->tasksView->horizontalHeader()->sectionSize( 3 ) +
ui->tasksView->horizontalHeader()->sectionSize( 4 ) +
ui->tasksView->verticalHeader()->width();
sizes[1] = sizes[0];
ui->tasksGanttSplitter->setSizes( sizes );
}
/****************************************** destructor *******************************************/
MainTabWidget::~MainTabWidget()
{
// free up memory used by the ui
delete ui;
}
/****************************************** setModels ********************************************/
void MainTabWidget::setModels()
{
// ensure table views are connected to correct models
ui->tasksView->setModel( plan->tasks() );
ui->resourcesView->setModel( plan->resources() );
ui->calendarsView->setModel( plan->calendars() );
ui->daysView->setModel( plan->days() );
ui->ganttView->setTable( ui->tasksView );
}
/****************************************** endEdits *********************************************/
void MainTabWidget::endEdits()
{
// end any task/resource/calendar/day edits in progress
ui->tasksView->endEdit();
ui->resourcesView->endEdit();
ui->calendarsView->endEdit();
ui->daysView->endEdit();
// check whether plan needs update
updatePlan();
}
/*************************************** slotEditDayCell *****************************************/
void MainTabWidget::slotEditDayCell( const QModelIndex& index, const QString& warning )
{
// slot to enable day type cell edit to be automatically re-started after validation failure
setCurrentWidget( ui->daysTab );
ui->daysView->setCurrentIndex( index );
QMessageBox::warning( ui->daysView, "Project Planner", warning, QMessageBox::Retry );
ui->daysView->edit( index );
// clear override
plan->days()->setOverride( QModelIndex(), QString() );
}
/************************************* slotEditCalendarCell **************************************/
void MainTabWidget::slotEditCalendarCell( const QModelIndex& index, const QString& warning )
{
// slot to enable calendar cell edit to be automatically re-started after validation failure
setCurrentWidget( ui->calendarsTab );
ui->calendarsView->setCurrentIndex( index );
QMessageBox::warning( ui->calendarsView, "Project Planner", warning, QMessageBox::Retry );
ui->calendarsView->edit( index );
// clear override
plan->calendars()->setOverride( QModelIndex(), QString() );
}
/************************************* slotEditResourceCell **************************************/
void MainTabWidget::slotEditResourceCell( const QModelIndex& index, const QString& warning )
{
// slot to enable resource cell edit to be automatically re-started after validation failure
setCurrentWidget( ui->resourcesTab );
ui->resourcesView->setCurrentIndex( index );
QMessageBox::warning( ui->resourcesView, "Project Planner", warning, QMessageBox::Retry );
ui->resourcesView->edit( index );
// clear override
plan->resources()->setOverride( QModelIndex(), QString() );
}
/*************************************** slotEditTaskCell ****************************************/
void MainTabWidget::slotEditTaskCell( const QModelIndex& index, const QString& warning )
{
// slot to enable task cell edit to be automatically re-started after validation failure
setCurrentWidget( ui->tasksGanttTab );
ui->tasksView->setCurrentIndex( index );
QMessageBox::warning( ui->tasksView, "Project Planner", warning, QMessageBox::Retry );
ui->tasksView->edit( index );
// clear override
plan->tasks()->setOverride( QModelIndex(), QString() );
}
/****************************************** updateGantt ******************************************/
void MainTabWidget::updateGantt()
{
// trigger gantt widget redraw
ui->ganttWidget->update();
}
/**************************************** indexOfTasksTab ****************************************/
int MainTabWidget::indexOfTasksTab()
{
// return index of tasks tab
return indexOf( ui->tasksGanttTab );
}
/**************************************** removePlanTab ******************************************/
void MainTabWidget::removePlanTab()
{
// remove 'Plan' tab (for example of new windows)
removeTab( this->indexOf( ui->planTab ) );
}
/***************************************** saveToStream ******************************************/
void MainTabWidget::saveToStream( QXmlStreamWriter* stream )
{
// write display data to xml stream
stream->writeStartElement( "display-data" );
saveTasksGanttToStream( stream );
saveResourcesTabToStream( stream );
saveCalendarsTabToStream( stream );
saveDaysTabToStream( stream );
stream->writeEndElement(); // display-data
}
/************************************ saveTasksGanttToStream *************************************/
void MainTabWidget::saveTasksGanttToStream( QXmlStreamWriter* stream )
{
// write tasks-gantt data to xml stream
stream->writeStartElement( "tasks-gantt" );
stream->writeAttribute( "start", XDateTime::toString( ui->ganttView->start(), "yyyy-MM-ddThh:mm" ) );
stream->writeAttribute( "end", XDateTime::toString( ui->ganttView->end(), "yyyy-MM-ddThh:mm" ) );
stream->writeAttribute( "minspp", QString::number( ui->ganttView->minsPP() ) );
stream->writeAttribute( "nonworking", "TODO" );
stream->writeAttribute( "current", "TODO" );
stream->writeAttribute( "upper", "TODO" );
stream->writeAttribute( "lower", "TODO" );
stream->writeAttribute( "splitter", QString::number( ui->tasksGanttSplitter->sizes().at(0) ) );
stream->writeStartElement( "upper-scale" );
stream->writeAttribute( "interval", ui->ganttView->upperInterval() );
stream->writeAttribute( "format", ui->ganttView->upperFormat() );
stream->writeEndElement(); // upper-scale
stream->writeStartElement( "lower-scale" );
stream->writeAttribute( "interval", ui->ganttView->lowerInterval() );
stream->writeAttribute( "format", ui->ganttView->lowerFormat() );
stream->writeEndElement(); // lower-scale
saveColumnsRowsToStream( ui->tasksView, stream );
stream->writeEndElement(); // tasks-gantt
}
/*********************************** saveResourcesTabToStream ************************************/
void MainTabWidget::saveResourcesTabToStream( QXmlStreamWriter* stream )
{
// write resources-tab data to xml stream
stream->writeStartElement( "resources-tab" );
saveColumnsRowsToStream( ui->resourcesView, stream );
stream->writeEndElement(); // resources-tab
}
/*********************************** saveCalendarsTabToStream ************************************/
void MainTabWidget::saveCalendarsTabToStream( QXmlStreamWriter* stream )
{
// write calendars-tab data to xml stream
stream->writeStartElement( "calendars-tab" );
saveColumnsRowsToStream( ui->calendarsView, stream );
stream->writeEndElement(); // calendars-tab
}
/*********************************** saveDaysTabToStream ************************************/
void MainTabWidget::saveDaysTabToStream( QXmlStreamWriter* stream )
{
// write days-tab data to xml stream
stream->writeStartElement( "days-tab" );
saveColumnsRowsToStream( ui->daysView, stream );
stream->writeEndElement(); // days-tab
}
/************************************** columnsRowsToStream **************************************/
void MainTabWidget::saveColumnsRowsToStream( QTableView* table, QXmlStreamWriter* stream )
{
// write tableview column position and size to xml stream
stream->writeStartElement( "columns" );
for( int i = 0 ; i < table->model()->columnCount() ; i++ )
{
stream->writeStartElement( "column" );
stream->writeAttribute( "id", QString::number(i) );
stream->writeAttribute( "position", QString::number( table->horizontalHeader()->visualIndex(i) ) );
stream->writeAttribute( "size", QString::number( table->horizontalHeader()->sectionSize(i) ) );
stream->writeEndElement(); // column
}
stream->writeEndElement(); // columns
// write tableview row size to xml stream
stream->writeStartElement( "rows" );
for( int i = 0 ; i < table->model()->rowCount() ; i++ )
{
stream->writeStartElement( "row" );
stream->writeAttribute( "id", QString::number(i) );
stream->writeAttribute( "size", QString::number( table->rowHeight(i) ) );
stream->writeEndElement(); // row
}
stream->writeEndElement(); // rows
}
/************************************** getGanttAttributes ***************************************/
void MainTabWidget::getGanttAttributes( DateTime& start, DateTime& end, double& minspp )
{
// get gantt attributes start/end/minsPP
start = ui->ganttView->start();
end = ui->ganttView->end();
minspp = ui->ganttView->minsPP();
}
/************************************** setGanttAttributes ***************************************/
void MainTabWidget::setGanttAttributes( DateTime start, DateTime end, double minspp )
{
// set gantt attributes start/end/minsPP
ui->ganttView->setStart( start );
ui->ganttView->setEnd( end );
ui->ganttView->setMinsPP( minspp );
ui->ganttView->setWidth();
}
/***************************************** updatePlan ********************************************/
void MainTabWidget::updatePlan()
{
// check if we need to update plan from 'Plan' tab widgets
if ( ui->title->text() != plan->title() ||
XDateTime::datetime( ui->planStart->dateTime() ) != plan->start() ||
ui->defaultCalendar->currentIndex() != plan->index( plan->calendar() ) ||
ui->dateTimeFormat->text() != plan->datetimeFormat() ||
ui->notesEdit->toPlainText() != plan->notes() )
{
plan->undostack()->push( new CommandPropertiesChange(
ui->title->text(), plan->title(),
XDateTime::datetime( ui->planStart->dateTime() ), plan->start(),
ui->defaultCalendar->currentIndex(), plan->index( plan->calendar() ),
ui->dateTimeFormat->text(), plan->datetimeFormat(),
ui->notesEdit->toPlainText(), plan->notes()) );
}
}
/************************************** slotUpdatePlanTab ****************************************/
void MainTabWidget::slotUpdatePlanTab()
{
// ensure 'Plan' tab widgets are up-to-date with what is in plan
ui->title->setText( plan->title() );
ui->title->setCursorPosition( 0 );
ui->planBeginning->setText( XDateTime::toString( plan->beginning(), "dd/MM/yyyy hh:mm" ) );
ui->planBeginning->setCursorPosition( 0 );
ui->planBeginning->setToolTip( XDateTime::toString( plan->beginning(), plan->datetimeFormat() ) );
ui->planStart->setTimeSpec( Qt::UTC );
ui->planStart->setDateTimeRange( XDateTime::MIN_QDATETIME, XDateTime::MAX_QDATETIME );
ui->planStart->setDateTime( XDateTime::qdatetime( plan->start() ) );
ui->planStart->setToolTip( XDateTime::toString( plan->start(), plan->datetimeFormat() ) );
ui->planEnd->setText( XDateTime::toString( plan->end(), "dd/MM/yyyy hh:mm") );
ui->planEnd->setCursorPosition( 0 );
ui->planEnd->setToolTip( XDateTime::toString( plan->end(), plan->datetimeFormat() ) );
ui->defaultCalendar->clear();
ui->defaultCalendar->addItems( plan->calendars()->namesList() );
ui->defaultCalendar->setCurrentIndex( plan->index( plan->calendar() ) );
ui->dateTimeFormat->setText( plan->datetimeFormat() );
ui->dateTimeFormat->setCursorPosition( 0 );
ui->dateTimeFormat->setToolTip( QDateTime::currentDateTime().toString( plan->datetimeFormat() ));
ui->fileName->setText( plan->filename() );
ui->fileName->setCursorPosition( 0 );
ui->fileLocation->setToolTip( plan->filename() );
ui->fileLocation->setText( plan->fileLocation() );
ui->fileLocation->setCursorPosition( 0 );
ui->fileLocation->setToolTip( plan->fileLocation() );
ui->savedBy->setText( plan->savedBy() );
ui->savedBy->setCursorPosition( 0 );
ui->savedBy->setToolTip( plan->savedBy() );
ui->savedWhen->setText( plan->savedWhen().toString("dd/MM/yyyy hh:mm") );
ui->savedWhen->setCursorPosition( 0 );
ui->savedWhen->setToolTip( plan->savedWhen().toString( plan->datetimeFormat() ) );
ui->numTasks->setText( QString(": %1").arg( plan->numTasks() ) );
ui->numResources->setText( QString(": %1").arg( plan->numResources() ) );
ui->numCalendars->setText( QString(": %1").arg( plan->numCalendars() ) );
ui->numDays->setText( QString(": %1").arg( plan->numDays() ) );
ui->notesEdit->setPlainText( plan->notes() );
// also update tasks table start/end/deadline columns in case datetimeFormat changed
plan->tasks()->emitDataChangedColumn( Task::SECTION_START );
plan->tasks()->emitDataChangedColumn( Task::SECTION_END );
plan->tasks()->emitDataChangedColumn( Task::SECTION_DEADLINE );
}
/************************************** tasksSelectionModel **************************************/
QItemSelectionModel* MainTabWidget::tasksSelectionModel()
{
// return selection model for tasks table view
return ui->tasksView->selectionModel();
}
/************************************* tasksSelectionIndexes *************************************/
QModelIndexList MainTabWidget::tasksSelectionIndexes()
{
// return selected indexes on tasks table view
return ui->tasksView->selectionModel()->selection().indexes();
}
| [
"[email protected]"
] | |
e819eacf75c090acc05f2bf0c8c75c97b4ceb1c4 | dd80a584130ef1a0333429ba76c1cee0eb40df73 | /external/chromium/chrome/browser/ui/gtk/bookmarks/bookmark_bar_gtk.h | 119a0164a68cb8ec41383d726de0d327439f7966 | [
"MIT",
"BSD-3-Clause"
] | permissive | karunmatharu/Android-4.4-Pay-by-Data | 466f4e169ede13c5835424c78e8c30ce58f885c1 | fcb778e92d4aad525ef7a995660580f948d40bc9 | refs/heads/master | 2021-03-24T13:33:01.721868 | 2017-02-18T17:48:49 | 2017-02-18T17:48:49 | 81,847,777 | 0 | 2 | MIT | 2020-03-09T00:02:12 | 2017-02-13T16:47:00 | null | UTF-8 | C++ | false | false | 16,086 | h | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_UI_GTK_BOOKMARKS_BOOKMARK_BAR_GTK_H_
#define CHROME_BROWSER_UI_GTK_BOOKMARKS_BOOKMARK_BAR_GTK_H_
#pragma once
#include <gtk/gtk.h>
#include <vector>
#include "base/gtest_prod_util.h"
#include "base/memory/scoped_ptr.h"
#include "chrome/browser/bookmarks/bookmark_context_menu_controller.h"
#include "chrome/browser/bookmarks/bookmark_model_observer.h"
#include "chrome/browser/prefs/pref_member.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/ui/gtk/bookmarks/bookmark_bar_instructions_gtk.h"
#include "chrome/browser/ui/gtk/menu_bar_helper.h"
#include "chrome/browser/ui/gtk/owned_widget_gtk.h"
#include "chrome/browser/ui/gtk/view_id_util.h"
#include "content/common/notification_observer.h"
#include "content/common/notification_registrar.h"
#include "ui/base/animation/animation.h"
#include "ui/base/animation/animation_delegate.h"
#include "ui/base/animation/slide_animation.h"
#include "ui/base/gtk/gtk_signal.h"
#include "ui/gfx/point.h"
#include "ui/gfx/size.h"
class BookmarkMenuController;
class Browser;
class BrowserWindowGtk;
class CustomContainerButton;
class GtkThemeService;
class MenuGtk;
class PageNavigator;
class Profile;
class TabstripOriginProvider;
class BookmarkBarGtk : public ui::AnimationDelegate,
public ProfileSyncServiceObserver,
public BookmarkModelObserver,
public MenuBarHelper::Delegate,
public NotificationObserver,
public BookmarkBarInstructionsGtk::Delegate,
public BookmarkContextMenuControllerDelegate {
public:
BookmarkBarGtk(BrowserWindowGtk* window,
Profile* profile,
Browser* browser,
TabstripOriginProvider* tabstrip_origin_provider);
virtual ~BookmarkBarGtk();
// Resets the profile. This removes any buttons for the current profile and
// recreates the models.
void SetProfile(Profile* profile);
// Returns the current profile.
Profile* GetProfile() { return profile_; }
// Returns the current browser.
Browser* browser() const { return browser_; }
// Returns the top level widget.
GtkWidget* widget() const { return event_box_.get(); }
// Sets the PageNavigator that is used when the user selects an entry on
// the bookmark bar.
void SetPageNavigator(PageNavigator* navigator);
// Create the contents of the bookmark bar.
void Init(Profile* profile);
// Whether the current page is the New Tag Page (which requires different
// rendering).
bool OnNewTabPage();
// Change the visibility of the bookmarks bar. (Starts out hidden, per GTK's
// default behaviour). There are three visiblity states:
//
// Showing - bookmark bar is fully visible.
// Hidden - bookmark bar is hidden except for a few pixels that give
// extra padding to the bottom of the toolbar. Buttons are not
// clickable.
// Fullscreen - bookmark bar is fully hidden.
void Show(bool animate);
void Hide(bool animate);
void EnterFullscreen();
// Get the current height of the bookmark bar.
int GetHeight();
// Returns true if the bookmark bar is showing an animation.
bool IsAnimating();
// Returns true if the bookmarks bar preference is set to 'always show'.
bool IsAlwaysShown();
// ui::AnimationDelegate implementation --------------------------------------
virtual void AnimationProgressed(const ui::Animation* animation);
virtual void AnimationEnded(const ui::Animation* animation);
// MenuBarHelper::Delegate implementation ------------------------------------
virtual void PopupForButton(GtkWidget* button);
virtual void PopupForButtonNextTo(GtkWidget* button,
GtkMenuDirectionType dir);
// The NTP needs to have access to this.
static const int kBookmarkBarNTPHeight;
// BookmarkContextMenuController::Delegate implementation --------------------
virtual void CloseMenu();
const ui::Animation* animation() { return &slide_animation_; }
private:
FRIEND_TEST_ALL_PREFIXES(BookmarkBarGtkUnittest, DisplaysHelpMessageOnEmpty);
FRIEND_TEST_ALL_PREFIXES(BookmarkBarGtkUnittest,
HidesHelpMessageWithBookmark);
FRIEND_TEST_ALL_PREFIXES(BookmarkBarGtkUnittest, BuildsButtons);
// Helper function which generates GtkToolItems for |bookmark_toolbar_|.
void CreateAllBookmarkButtons();
// Sets the visibility of the instructional text based on whether there are
// any bookmarks in the bookmark bar node.
void SetInstructionState();
// Sets the visibility of the overflow chevron.
void SetChevronState();
// Helper function which destroys all the bookmark buttons in the GtkToolbar.
void RemoveAllBookmarkButtons();
// Returns the number of buttons corresponding to starred urls/folders. This
// is equivalent to the number of children the bookmark bar node from the
// bookmark bar model has.
int GetBookmarkButtonCount();
// Set the appearance of the overflow button appropriately (either chromium
// style or GTK style).
void SetOverflowButtonAppearance();
// Returns the index of the first bookmark that is not visible on the bar.
// Returns -1 if they are all visible.
// |extra_space| is how much extra space to give the toolbar during the
// calculation (for the purposes of determining if ditching the chevron
// would be a good idea).
// If non-NULL, |showing_folders| will be packed with all the folders that are
// showing on the bar.
int GetFirstHiddenBookmark(int extra_space,
std::vector<GtkWidget*>* showing_folders);
// Returns true if the bookmark bar should be floating on the page (for
// NTP).
bool ShouldBeFloating();
// Update the floating state (either enable or disable it, or do nothing).
void UpdateFloatingState();
// Turns on or off the app_paintable flag on |event_box_|, depending on our
// state.
void UpdateEventBoxPaintability();
// Queue a paint on the event box.
void PaintEventBox();
// Finds the size of the current tab contents, if it exists and sets |size|
// to the correct value. Returns false if there isn't a TabContents, a
// condition that can happen during testing.
bool GetTabContentsSize(gfx::Size* size);
// Connects to the "size-allocate" signal on the given widget, and causes it
// to throb after allocation. This is called when a new item is added to the
// bar. We can't call StartThrobbing directly because we don't know if it's
// visible or not until after the widget is allocated.
void StartThrobbingAfterAllocation(GtkWidget* item);
// Used by StartThrobbingAfterAllocation.
CHROMEGTK_CALLBACK_1(BookmarkBarGtk, void, OnItemAllocate, GtkAllocation*);
// Makes the appropriate widget on the bookmark bar stop throbbing
// (a folder, the overflow chevron, or nothing).
void StartThrobbing(const BookmarkNode* node);
// Set |throbbing_widget_| to |widget|. Also makes sure that
// |throbbing_widget_| doesn't become stale.
void SetThrobbingWidget(GtkWidget* widget);
// An item has been dragged over the toolbar, update the drag context
// and toolbar UI appropriately.
gboolean ItemDraggedOverToolbar(
GdkDragContext* context, int index, guint time);
// When dragging in the middle of a folder, assume the user wants to drop
// on the folder. Towards the edges, assume the user wants to drop on the
// toolbar. This makes it possible to drop between two folders. This function
// returns the index on the toolbar the drag should target, or -1 if the
// drag should hit the folder.
int GetToolbarIndexForDragOverFolder(GtkWidget* button, gint x);
void ClearToolbarDropHighlighting();
// Overridden from BookmarkModelObserver:
// Invoked when the bookmark model has finished loading. Creates a button
// for each of the children of the root node from the model.
virtual void Loaded(BookmarkModel* model);
// Invoked when the model is being deleted.
virtual void BookmarkModelBeingDeleted(BookmarkModel* model);
// Invoked when a node has moved.
virtual void BookmarkNodeMoved(BookmarkModel* model,
const BookmarkNode* old_parent,
int old_index,
const BookmarkNode* new_parent,
int new_index);
virtual void BookmarkNodeAdded(BookmarkModel* model,
const BookmarkNode* parent,
int index);
virtual void BookmarkNodeRemoved(BookmarkModel* model,
const BookmarkNode* parent,
int old_index,
const BookmarkNode* node);
virtual void BookmarkNodeChanged(BookmarkModel* model,
const BookmarkNode* node);
// Invoked when a favicon has finished loading.
virtual void BookmarkNodeFaviconLoaded(BookmarkModel* model,
const BookmarkNode* node);
virtual void BookmarkNodeChildrenReordered(BookmarkModel* model,
const BookmarkNode* node);
// Overridden from NotificationObserver:
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details);
GtkWidget* CreateBookmarkButton(const BookmarkNode* node);
GtkToolItem* CreateBookmarkToolItem(const BookmarkNode* node);
void ConnectFolderButtonEvents(GtkWidget* widget, bool is_tool_item);
// Finds the BookmarkNode from the model associated with |button|.
const BookmarkNode* GetNodeForToolButton(GtkWidget* button);
// Creates and displays a popup menu for BookmarkNode |node|.
void PopupMenuForNode(GtkWidget* sender, const BookmarkNode* node,
GdkEventButton* event);
// GtkButton callbacks.
CHROMEGTK_CALLBACK_1(BookmarkBarGtk, gboolean, OnButtonPressed,
GdkEventButton*);
CHROMEGTK_CALLBACK_1(BookmarkBarGtk, gboolean, OnSyncErrorButtonPressed,
GdkEventButton*);
CHROMEGTK_CALLBACK_0(BookmarkBarGtk, void, OnClicked);
CHROMEGTK_CALLBACK_1(BookmarkBarGtk, void, OnButtonDragBegin,
GdkDragContext*);
CHROMEGTK_CALLBACK_1(BookmarkBarGtk, void, OnButtonDragEnd, GdkDragContext*);
CHROMEGTK_CALLBACK_4(BookmarkBarGtk, void, OnButtonDragGet,
GdkDragContext*, GtkSelectionData*, guint, guint);
// GtkButton callbacks for folder buttons.
CHROMEGTK_CALLBACK_0(BookmarkBarGtk, void, OnFolderClicked);
// GtkToolbar callbacks.
CHROMEGTK_CALLBACK_4(BookmarkBarGtk, gboolean, OnToolbarDragMotion,
GdkDragContext*, gint, gint, guint);
CHROMEGTK_CALLBACK_1(BookmarkBarGtk, void, OnToolbarSizeAllocate,
GtkAllocation*);
// Used for both folder buttons and the toolbar.
CHROMEGTK_CALLBACK_6(BookmarkBarGtk, void, OnDragReceived,
GdkDragContext*, gint, gint, GtkSelectionData*,
guint, guint);
CHROMEGTK_CALLBACK_2(BookmarkBarGtk, void, OnDragLeave,
GdkDragContext*, guint);
// Used for folder buttons.
CHROMEGTK_CALLBACK_4(BookmarkBarGtk, gboolean, OnFolderDragMotion,
GdkDragContext*, gint, gint, guint);
// GtkEventBox callbacks.
CHROMEGTK_CALLBACK_1(BookmarkBarGtk, gboolean, OnEventBoxExpose,
GdkEventExpose*);
CHROMEGTK_CALLBACK_0(BookmarkBarGtk, void, OnEventBoxDestroy);
// Callbacks on our parent widget.
CHROMEGTK_CALLBACK_1(BookmarkBarGtk, void, OnParentSizeAllocate,
GtkAllocation*);
// |throbbing_widget_| callback.
CHROMEGTK_CALLBACK_0(BookmarkBarGtk, void, OnThrobbingWidgetDestroy);
// ProfileSyncServiceObserver method.
virtual void OnStateChanged();
// Overriden from BookmarkBarInstructionsGtk::Delegate.
virtual void ShowImportDialog();
// Updates the drag&drop state when |edit_bookmarks_enabled_| changes.
void OnEditBookmarksEnabledChanged();
Profile* profile_;
// Used for opening urls.
PageNavigator* page_navigator_;
Browser* browser_;
BrowserWindowGtk* window_;
// Provides us with the offset into the background theme image.
TabstripOriginProvider* tabstrip_origin_provider_;
// Model providing details as to the starred entries/folders that should be
// shown. This is owned by the Profile.
BookmarkModel* model_;
// Contains |bookmark_hbox_|. Event box exists to prevent leakage of
// background color from the toplevel application window's GDK window.
OwnedWidgetGtk event_box_;
// Used to float the bookmark bar when on the NTP.
GtkWidget* ntp_padding_box_;
// Used to paint the background of the bookmark bar when in floating mode.
GtkWidget* paint_box_;
// Used to position all children.
GtkWidget* bookmark_hbox_;
// Alignment widget that is visible if there are no bookmarks on
// the bookmar bar.
GtkWidget* instructions_;
// BookmarkBarInstructionsGtk that holds the label and the link for importing
// bookmarks when there are no bookmarks on the bookmark bar.
scoped_ptr<BookmarkBarInstructionsGtk> instructions_gtk_;
// GtkToolbar which contains all the bookmark buttons.
OwnedWidgetGtk bookmark_toolbar_;
// The button that shows extra bookmarks that don't fit on the bookmark
// bar.
GtkWidget* overflow_button_;
// The other bookmarks button.
GtkWidget* other_bookmarks_button_;
// The sync error button.
GtkWidget* sync_error_button_;
// A pointer to the ProfileSyncService instance if one exists.
ProfileSyncService* sync_service_;
// The BookmarkNode from the model being dragged. NULL when we aren't
// dragging.
const BookmarkNode* dragged_node_;
// The visual representation that follows the cursor during drags.
GtkWidget* drag_icon_;
// We create a GtkToolbarItem from |dragged_node_| ;or display.
GtkToolItem* toolbar_drop_item_;
// Theme provider for building buttons.
GtkThemeService* theme_service_;
// Whether we should show the instructional text in the bookmark bar.
bool show_instructions_;
MenuBarHelper menu_bar_helper_;
// The last displayed right click menu, or NULL if no menus have been
// displayed yet.
// The controller.
scoped_ptr<BookmarkContextMenuController> current_context_menu_controller_;
// The view.
scoped_ptr<MenuGtk> current_context_menu_;
// The last displayed left click menu, or NULL if no menus have been
// displayed yet.
scoped_ptr<BookmarkMenuController> current_menu_;
ui::SlideAnimation slide_animation_;
// Whether we are currently configured as floating (detached from the
// toolbar). This reflects our actual state, and can be out of sync with
// what ShouldShowFloating() returns.
bool floating_;
// Used to optimize out |bookmark_toolbar_| size-allocate events we don't
// need to respond to.
int last_allocation_width_;
NotificationRegistrar registrar_;
// The size of the tab contents last time we forced a paint. We keep track
// of this so we don't force too many paints.
gfx::Size last_tab_contents_size_;
// The last coordinates recorded by OnButtonPress; used to line up the
// drag icon during bookmark drags.
gfx::Point last_pressed_coordinates_;
// The currently throbbing widget. This is NULL if no widget is throbbing.
// We track it because we only want to allow one widget to throb at a time.
GtkWidget* throbbing_widget_;
// Tracks whether bookmarks can be modified.
BooleanPrefMember edit_bookmarks_enabled_;
ScopedRunnableMethodFactory<BookmarkBarGtk> method_factory_;
};
#endif // CHROME_BROWSER_UI_GTK_BOOKMARKS_BOOKMARK_BAR_GTK_H_
| [
"[email protected]"
] | |
37921940b08461278e5994385f6435a7a3c6947e | 35c9a440d2ab4bbdbce9eef077b266b90ca57e6a | /gulab/spoj/BYTESM2.cpp | 6d9910ddbacd0683faff89fd33eb80429868be1f | [] | no_license | kushkgp/CompetitiveCode | b6b934f49077d05658fdb8aa100d53b0e8ee62b2 | 2742d9d85374887fee2faddf4a10c51b3d3a2582 | refs/heads/master | 2021-03-30T16:12:49.161891 | 2018-12-26T07:58:15 | 2018-12-26T07:58:15 | 112,836,990 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 792 | cpp | #include <bits/stdc++.h>
#define tr(c,i) for(typeof((c).begin() i = (c).begin(); i != (c).end(); i++)
using namespace std;
typedef vector<int> vi;
typedef vector< vi > vvi;
int ans(const vvi v, int h, int w){
int dp[h][w];
for (int i = 0; i < h; ++i)
{
for (int j = 0; j < w; ++j)
{
dp[i][j] = 0;
if(i){
dp[i][j] = max(dp[i][j],dp[i-1][j]);
if(j)
dp[i][j] = max(dp[i][j],dp[i-1][j-1]);
if(j<w-1)
dp[i][j] = max(dp[i][j],dp[i-1][j+1]);
}
dp[i][j] += v[i][j];
}
}
int retmax = 0;
for (int i = 0; i < w; ++i)
{
retmax=max(retmax,dp[h-1][i]);
}
return retmax;
}
int main(){
int t;
cin>>t;
while(t--){
int h,w;
cin>>h>>w;
vvi v;
v.resize(h,vi(w,0));
tr(v,it)
tr(*it,it1)
cin>>*it1;
cout<<ans(v,h,w)<<endl;
}
return 0;
} | [
"[email protected]"
] | |
e54f6922e6ed3612ca54fc361936ce6ea523f026 | efb87e4ac44f9cc98eab0dc162266fa1b99b7e5a | /Facebook Hacker Cup/FbHkrCup 20-R1-A1.cpp | d1251dfbbb5611bb843cd50a3e1e78b1e6249a35 | [] | no_license | farmerboy95/CompetitiveProgramming | fe4eef85540d3e91c42ff6ec265a3262e5b97d1f | 1998d5ae764d47293f2cd71020bec1dbf5b470aa | refs/heads/master | 2023-08-29T16:42:28.109183 | 2023-08-24T07:00:19 | 2023-08-24T07:00:19 | 206,353,615 | 12 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,188 | cpp | /*
Author: Nguyen Tan Bao
Statement: https://www.facebook.com/codingcompetitions/hacker-cup/2020/round-1/problems/A1
Status: AC
Idea:
- We notice that the width of rooms is the same and small (W <= 20). So we can maintain
an array "height" of W+1 (i from 0 to W) contains the height at x = i.
- Define latestX as the max x-coordinate that has been occupied by a room, we can use this
because L1 < L2 < ... < Ln
- If latestX < L[i], the new room does not overlap with the ones before, so we add 2 * (h[i] + w)
to p and update "height".
- Otherwise, the current one overlaps with some rooms before, first we move the array "height"
forward to the point L[i].
- For the width, only need to add 2 * (l[i] + w - latestX), the rest of width does not change
in value, only be moved higher.
- For the height, only need to add 2 * (h[i] - height[0]) (if h[i] > height[0])
- Complexity O(NW)
*/
#include <bits/stdc++.h>
#define FI first
#define SE second
#define EPS 1e-9
#define ALL(a) a.begin(),a.end()
#define SZ(a) int((a).size())
#define MS(s, n) memset(s, n, sizeof(s))
#define FOR(i,a,b) for (int i = (a); i <= (b); i++)
#define FORE(i,a,b) for (int i = (a); i >= (b); i--)
#define FORALL(it, a) for (__typeof((a).begin()) it = (a).begin(); it != (a).end(); it++)
//__builtin_ffs(x) return 1 + index of least significant 1-bit of x
//__builtin_clz(x) return number of leading zeros of x
//__builtin_ctz(x) return number of trailing zeros of x
using namespace std;
using ll = long long;
using ld = double;
typedef pair<int, int> II;
typedef pair<II, int> III;
typedef complex<ld> cd;
typedef vector<cd> vcd;
const ll MODBASE = 1000000007LL;
const int MAXN = 1000010;
const int MAXM = 1000;
const int MAXK = 16;
const int MAXQ = 200010;
int n, k, w;
ll l[MAXN], h[MAXN], height[25];
void init() {
}
void input() {
ll A, B, C, D;
cin >> n >> k >> w;
FOR(i,1,k) cin >> l[i];
cin >> A >> B >> C >> D;
FOR(i,k+1,n) l[i] = (A * l[i-2] + B * l[i-1] + C) % D + 1;
FOR(i,1,k) cin >> h[i];
cin >> A >> B >> C >> D;
FOR(i,k+1,n) h[i] = (A * h[i-2] + B * h[i-1] + C) % D + 1;
}
ll handle() {
ll res = 1;
FOR(i,0,w) height[i] = 0;
ll latestX = 0;
ll p = 0;
FOR(i,1,n) {
if (latestX < l[i]) {
p = (p + 2 * w + 2 * h[i]) % MODBASE;
FOR(j,0,w) height[j] = h[i];
} else {
ll pos = w - (latestX - l[i]);
FOR(j,0,w)
if (j + pos > w) height[j] = 0;
else height[j] = height[j + pos];
p = (p + 2 * (l[i] + w - latestX)) % MODBASE;
if (height[0] < h[i]) p = (p + 2 * (h[i] - height[0])) % MODBASE;
FOR(j,0,w) height[j] = max(height[j], h[i]);
}
latestX = l[i] + w;
res = res * p % MODBASE;
}
return res;
}
ll solve() {
input();
init();
return handle();
}
int main() {
ios::sync_with_stdio(0);
cin.tie(nullptr);
int te;
cin >> te;
FOR(o,1,te) {
cout << "Case #" << o << ": ";
cout << solve() << "\n";
}
return 0;
}
| [
"[email protected]"
] | |
5a0f1150ba0d30baa841aaa0acf4a49a05c85125 | a091d500abbda0a3e36898b23075744c5a36433d | /ecs/src/component_test.cpp | f2c3d961a7eec6f55c34767c37e2691d65d2cdb4 | [
"MIT"
] | permissive | FabianHahn/shoveler | e996a50dd9d9e40442bd5e562fdbc45b1760b06c | 2f602fe2edc4bb99f74e570115fc733ecc80503c | refs/heads/master | 2023-08-31T00:52:54.630367 | 2023-08-28T12:45:01 | 2023-08-28T13:28:42 | 60,905,873 | 34 | 1 | MIT | 2022-12-14T16:43:36 | 2016-06-11T12:23:16 | C | UTF-8 | C++ | false | false | 28,208 | cpp | #include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <string>
extern "C" {
#include "shoveler/component.h"
#include "shoveler/component_type.h"
#include "shoveler/log.h"
#include "test_component_types.h"
}
#include "component_field_value_wrapper.h"
using ::testing::ElementsAre;
using ::testing::IsEmpty;
using ::testing::SizeIs;
const long long int entityId1 = 1;
const long long int entityId2 = 2;
// world adapter methods
static ShovelerComponent* getComponent(
ShovelerComponent* component,
long long int entityId,
const char* componentTypeId,
void* userData);
static void onUpdateComponentField(
ShovelerComponent* component,
int fieldId,
const ShovelerComponentField* field,
const ShovelerComponentFieldValue* value,
bool isCanonical,
void* testPointer);
static void onActivateComponent(ShovelerComponent* component, void* userData);
static void onDeactivateComponent(ShovelerComponent* component, void* userData);
static void addDependency(
ShovelerComponent* component,
long long int targetEntityId,
const char* targetComponentTypeId,
void* userData);
static bool removeDependency(
ShovelerComponent* component,
long long int targetEntityId,
const char* targetComponentTypeId,
void* userData);
static void forEachReverseDependency(
ShovelerComponent* component,
ShovelerComponentWorldAdapterForEachReverseDependencyCallbackFunction* callbackFunction,
void* callbackUserData,
void* adapterUserData);
// system adapter methods
static bool requiresAuthority(ShovelerComponent* component, void* userData);
static bool canLiveUpdateField(
ShovelerComponent* component, int fieldId, const ShovelerComponentField* field, void* userData);
static bool canLiveUpdateDependencyField(
ShovelerComponent* component, int fieldId, const ShovelerComponentField* field, void* userData);
static bool liveUpdateField(
ShovelerComponent* component,
int fieldId,
const ShovelerComponentField* field,
ShovelerComponentFieldValue* fieldValue,
void* userData);
static bool liveUpdateDependencyField(
ShovelerComponent* component,
int fieldId,
const ShovelerComponentField* field,
ShovelerComponent* dependencyComponent,
void* userData);
static void* activateComponent(ShovelerComponent* component, void* userData);
static bool updateComponent(ShovelerComponent* component, double dt, void* userData);
static void deactivateComponent(ShovelerComponent* component, void* userData);
class ShovelerComponentTest : public ::testing::Test {
public:
virtual void SetUp() {
worldAdapter.getComponent = getComponent;
worldAdapter.forEachReverseDependency = forEachReverseDependency;
worldAdapter.addDependency = addDependency;
worldAdapter.removeDependency = removeDependency;
worldAdapter.onUpdateComponentField = onUpdateComponentField;
worldAdapter.onActivateComponent = onActivateComponent;
worldAdapter.onDeactivateComponent = onDeactivateComponent;
worldAdapter.userData = this;
systemAdapter.requiresAuthority = requiresAuthority;
systemAdapter.canLiveUpdateField = canLiveUpdateField;
systemAdapter.canLiveUpdateDependencyField = canLiveUpdateDependencyField;
systemAdapter.liveUpdateField = liveUpdateField;
systemAdapter.liveUpdateDependencyField = liveUpdateDependencyField;
systemAdapter.activateComponent = activateComponent;
systemAdapter.updateComponent = updateComponent;
systemAdapter.deactivateComponent = deactivateComponent;
systemAdapter.userData = this;
componentType1 = shovelerCreateTestComponentType1();
componentType2 = shovelerCreateTestComponentType2();
componentType3 = shovelerCreateTestComponentType3();
component1 = shovelerComponentCreate(&worldAdapter, &systemAdapter, entityId1, componentType1);
component2 = shovelerComponentCreate(&worldAdapter, &systemAdapter, entityId2, componentType2);
component3 = shovelerComponentCreate(&worldAdapter, &systemAdapter, entityId1, componentType3);
ASSERT_TRUE(component1 != nullptr);
ASSERT_TRUE(component2 != nullptr);
ASSERT_TRUE(component3 != nullptr);
}
virtual void TearDown() {
shovelerLogTrace("Tearing down test case.");
shovelerComponentFree(component3);
shovelerComponentFree(component2);
shovelerComponentFree(component1);
shovelerComponentTypeFree(componentType3);
shovelerComponentTypeFree(componentType2);
shovelerComponentTypeFree(componentType1);
}
ShovelerComponentWorldAdapter worldAdapter;
ShovelerComponentSystemAdapter systemAdapter;
ShovelerComponentType* componentType1;
ShovelerComponentType* componentType2;
ShovelerComponentType* componentType3;
ShovelerComponent* component1;
ShovelerComponent* component2;
ShovelerComponent* component3;
struct OnUpdateComponentFieldCall {
ShovelerComponent* component;
int fieldId;
const ShovelerComponentField* field;
ShovelerComponentFieldValueWrapper value;
bool isAuthoritative;
};
std::vector<OnUpdateComponentFieldCall> onUpdateComponentFieldCalls;
std::vector<ShovelerComponent*> onActivateComponentCalls;
std::vector<ShovelerComponent*> onDeactivateComponentCalls;
std::map<std::pair<long long int, std::string>, std::set<ShovelerComponent*>> reverseDependencies;
bool propagateNextLiveUpdate = false;
struct LiveUpdateCall {
ShovelerComponent* component;
int fieldId;
const ShovelerComponentField* field;
ShovelerComponentFieldValueWrapper value;
};
std::vector<LiveUpdateCall> liveUpdateCalls;
bool propagateNextLiveUpdateDependency = false;
struct LiveUpdateDependencyCall {
ShovelerComponent* component;
int fieldId;
const ShovelerComponentField* field;
ShovelerComponent* dependencyComponent;
bool operator==(const LiveUpdateDependencyCall& other) const {
return component == other.component && fieldId == other.fieldId && field == other.field &&
dependencyComponent == other.dependencyComponent;
}
};
std::vector<LiveUpdateDependencyCall> liveUpdateDependencyCalls;
bool failNextActivate = false;
std::vector<ShovelerComponent*> activateCalls;
bool propagateNextUpdate = false;
std::vector<std::pair<ShovelerComponent*, double>> updateCalls;
std::vector<ShovelerComponent*> deactivateCalls;
};
MATCHER_P5(
IsWorldUpdateComponentIntValueCall, component, fieldId, field, intValue, isAuthoritative, "") {
const ShovelerComponentTest::OnUpdateComponentFieldCall& call = arg;
return call.component == component && call.fieldId == fieldId && call.field == field &&
call.value->type == SHOVELER_COMPONENT_FIELD_TYPE_INT && call.value->isSet &&
call.value->intValue == intValue && call.isAuthoritative == isAuthoritative;
}
MATCHER_P4(IsLiveUpdateStringValueCall, component, fieldId, field, stringValue, "") {
const ShovelerComponentTest::LiveUpdateCall& call = arg;
return call.component == component && call.fieldId == fieldId && call.field == field &&
call.value->type == SHOVELER_COMPONENT_FIELD_TYPE_STRING && call.value->isSet &&
std::string(call.value->stringValue) == stringValue;
}
TEST_F(ShovelerComponentTest, activateDeactivate) {
ASSERT_FALSE(shovelerComponentIsActive(component1));
bool activated = shovelerComponentActivate(component1);
ASSERT_TRUE(activated);
ASSERT_TRUE(shovelerComponentIsActive(component1));
ASSERT_THAT(activateCalls, ElementsAre(component1));
ASSERT_THAT(onActivateComponentCalls, ElementsAre(component1));
shovelerComponentDeactivate(component1);
ASSERT_FALSE(shovelerComponentIsActive(component1));
ASSERT_THAT(onDeactivateComponentCalls, ElementsAre(component1));
}
TEST_F(ShovelerComponentTest, activateThroughDependencyActivation) {
shovelerComponentUpdateCanonicalFieldEntityId(
component1, COMPONENT_TYPE_1_FIELD_DEPENDENCY_REACTIVATE, entityId2);
bool activated = shovelerComponentActivate(component1);
ASSERT_FALSE(activated);
ASSERT_FALSE(shovelerComponentIsActive(component1));
bool dependencyActivatedBeforeDelegation = shovelerComponentActivate(component2);
ASSERT_FALSE(dependencyActivatedBeforeDelegation);
shovelerComponentDelegate(component2);
bool dependencyActivated = shovelerComponentActivate(component2);
ASSERT_TRUE(dependencyActivated);
ASSERT_TRUE(shovelerComponentIsActive(component2));
ASSERT_TRUE(shovelerComponentIsActive(component1))
<< "component 1 has also been activated after activating its dependency";
ASSERT_THAT(activateCalls, ElementsAre(component2, component1));
ASSERT_THAT(onActivateComponentCalls, ElementsAre(component2, component1));
}
TEST_F(ShovelerComponentTest, deactivateWhenAddingUnsatisfiedDependency) {
bool activated = shovelerComponentActivate(component1);
ASSERT_TRUE(activated);
ASSERT_TRUE(shovelerComponentIsActive(component1));
ASSERT_THAT(activateCalls, ElementsAre(component1));
ASSERT_THAT(onActivateComponentCalls, ElementsAre(component1));
shovelerComponentUpdateCanonicalFieldEntityId(
component1, COMPONENT_TYPE_1_FIELD_DEPENDENCY_REACTIVATE, entityId2);
ASSERT_THAT(deactivateCalls, ElementsAre(component1))
<< "component 1 should be deactivated after adding unsatisfied dependency";
ASSERT_THAT(onDeactivateComponentCalls, ElementsAre(component1));
ASSERT_FALSE(shovelerComponentIsActive(component1));
}
TEST_F(ShovelerComponentTest, deactivateReverseDependencies) {
shovelerComponentActivate(component1);
shovelerComponentDelegate(component2);
shovelerComponentActivate(component2);
shovelerComponentUpdateCanonicalFieldEntityId(
component1, COMPONENT_TYPE_1_FIELD_DEPENDENCY_REACTIVATE, entityId2);
shovelerComponentDeactivate(component2);
ASSERT_THAT(deactivateCalls, ElementsAre(component1, component2))
<< "component 1 has also been deactivated after deactivating its dependency";
ASSERT_THAT(onDeactivateComponentCalls, ElementsAre(component1, component2));
ASSERT_FALSE(shovelerComponentIsActive(component1));
}
TEST_F(ShovelerComponentTest, deactivateFreedComponent) {
shovelerComponentActivate(component1);
shovelerComponentFree(component1);
ASSERT_THAT(deactivateCalls, ElementsAre(component1));
ASSERT_THAT(onDeactivateComponentCalls, ElementsAre(component1));
component1 = nullptr;
}
TEST_F(ShovelerComponentTest, updateField) {
const int newFieldValue = 27;
int firstValue = shovelerComponentGetFieldValueInt(component1, COMPONENT_TYPE_1_FIELD_PRIMITIVE);
ASSERT_EQ(firstValue, 0);
bool updated = shovelerComponentUpdateCanonicalFieldInt(
component1, COMPONENT_TYPE_1_FIELD_PRIMITIVE, newFieldValue);
ASSERT_TRUE(updated);
ASSERT_THAT(
onUpdateComponentFieldCalls,
ElementsAre(IsWorldUpdateComponentIntValueCall(
component1,
COMPONENT_TYPE_1_FIELD_PRIMITIVE,
&componentType1->fields[COMPONENT_TYPE_1_FIELD_PRIMITIVE],
newFieldValue,
/* isAuthoritative */ false)));
int secondValue = shovelerComponentGetFieldValueInt(component1, COMPONENT_TYPE_1_FIELD_PRIMITIVE);
ASSERT_EQ(secondValue, newFieldValue);
}
TEST_F(ShovelerComponentTest, updateFieldWithReactivation) {
const int newFieldValue = 27;
shovelerComponentActivate(component1);
activateCalls.clear();
onActivateComponentCalls.clear();
bool updated = shovelerComponentUpdateCanonicalFieldInt(
component1, COMPONENT_TYPE_1_FIELD_PRIMITIVE, newFieldValue);
ASSERT_TRUE(updated);
ASSERT_THAT(onUpdateComponentFieldCalls, SizeIs(1));
ASSERT_THAT(liveUpdateCalls, IsEmpty());
ASSERT_THAT(deactivateCalls, ElementsAre(component1));
ASSERT_THAT(onDeactivateComponentCalls, ElementsAre(component1));
ASSERT_THAT(activateCalls, ElementsAre(component1));
ASSERT_THAT(onActivateComponentCalls, ElementsAre(component1));
}
TEST_F(ShovelerComponentTest, updateConfigurationLive) {
const char* newFieldValue = "new value";
shovelerComponentDelegate(component2);
shovelerComponentActivate(component2);
ASSERT_THAT(activateCalls, ElementsAre(component2));
ASSERT_THAT(onActivateComponentCalls, ElementsAre(component2));
activateCalls.clear();
onActivateComponentCalls.clear();
bool updated = shovelerComponentUpdateCanonicalFieldString(
component2, COMPONENT_TYPE_2_FIELD_PRIMITIVE_LIVE_UPDATE, newFieldValue);
ASSERT_TRUE(updated);
ASSERT_THAT(onUpdateComponentFieldCalls, SizeIs(1));
ASSERT_THAT(
liveUpdateCalls,
ElementsAre(IsLiveUpdateStringValueCall(
component2,
COMPONENT_TYPE_2_FIELD_PRIMITIVE_LIVE_UPDATE,
&component2->type->fields[COMPONENT_TYPE_2_FIELD_PRIMITIVE_LIVE_UPDATE],
newFieldValue)));
ASSERT_THAT(activateCalls, IsEmpty());
ASSERT_THAT(onActivateComponentCalls, IsEmpty());
ASSERT_THAT(deactivateCalls, IsEmpty());
ASSERT_THAT(onDeactivateComponentCalls, IsEmpty());
const char* newValue = shovelerComponentGetFieldValueString(
component2, COMPONENT_TYPE_2_FIELD_PRIMITIVE_LIVE_UPDATE);
ASSERT_STREQ(newValue, newFieldValue);
}
TEST_F(ShovelerComponentTest, updateConfigurationLiveUpdatesReverseDependency) {
const char* newConfigurationValue = "new value";
shovelerComponentUpdateCanonicalFieldEntityId(
component1, COMPONENT_TYPE_1_FIELD_DEPENDENCY_LIVE_UPDATE, entityId2);
shovelerComponentDelegate(component2);
bool dependencyActivated = shovelerComponentActivate(component2);
ASSERT_TRUE(dependencyActivated);
bool activated = shovelerComponentActivate(component1);
ASSERT_TRUE(activated);
activateCalls.clear();
onActivateComponentCalls.clear();
propagateNextLiveUpdate = true;
bool updated = shovelerComponentUpdateCanonicalFieldString(
component2, COMPONENT_TYPE_2_FIELD_PRIMITIVE_LIVE_UPDATE, newConfigurationValue);
ASSERT_TRUE(updated);
ASSERT_THAT(onUpdateComponentFieldCalls, SizeIs(2));
ASSERT_THAT(
liveUpdateDependencyCalls,
ElementsAre(LiveUpdateDependencyCall{
component1,
COMPONENT_TYPE_1_FIELD_DEPENDENCY_LIVE_UPDATE,
&component1->type->fields[COMPONENT_TYPE_1_FIELD_DEPENDENCY_LIVE_UPDATE],
component2}));
ASSERT_THAT(activateCalls, IsEmpty());
ASSERT_THAT(onActivateComponentCalls, IsEmpty());
ASSERT_THAT(deactivateCalls, IsEmpty());
ASSERT_THAT(onDeactivateComponentCalls, IsEmpty());
}
TEST_F(ShovelerComponentTest, updateConfigurationLiveWithoutPropagation) {
const char* newConfigurationValue = "new value";
shovelerComponentUpdateCanonicalFieldEntityId(
component1, COMPONENT_TYPE_1_FIELD_DEPENDENCY_LIVE_UPDATE, entityId2);
shovelerComponentDelegate(component2);
bool dependencyActivated = shovelerComponentActivate(component2);
ASSERT_TRUE(dependencyActivated);
bool activated = shovelerComponentActivate(component1);
ASSERT_TRUE(activated);
activateCalls.clear();
onActivateComponentCalls.clear();
propagateNextLiveUpdate = false;
bool updated = shovelerComponentUpdateCanonicalFieldString(
component2, COMPONENT_TYPE_2_FIELD_PRIMITIVE_LIVE_UPDATE, newConfigurationValue);
ASSERT_TRUE(updated);
ASSERT_THAT(onUpdateComponentFieldCalls, SizeIs(2));
ASSERT_THAT(liveUpdateDependencyCalls, IsEmpty());
ASSERT_THAT(activateCalls, IsEmpty());
ASSERT_THAT(onActivateComponentCalls, IsEmpty());
ASSERT_THAT(deactivateCalls, IsEmpty());
ASSERT_THAT(onDeactivateComponentCalls, IsEmpty());
}
TEST_F(ShovelerComponentTest, updateComponentUpdatesReverseDependency) {
double dt = 1234.5;
shovelerComponentUpdateCanonicalFieldEntityId(
component1, COMPONENT_TYPE_1_FIELD_DEPENDENCY_LIVE_UPDATE, entityId2);
shovelerComponentDelegate(component2);
bool dependencyActivated = shovelerComponentActivate(component2);
ASSERT_TRUE(dependencyActivated);
bool activated = shovelerComponentActivate(component1);
ASSERT_TRUE(activated);
activateCalls.clear();
onActivateComponentCalls.clear();
propagateNextUpdate = true;
bool updatePropagated = shovelerComponentUpdate(component2, dt);
ASSERT_TRUE(updatePropagated);
ASSERT_THAT(updateCalls, ElementsAre(std::make_pair(component2, dt)));
ASSERT_THAT(onUpdateComponentFieldCalls, SizeIs(1));
ASSERT_THAT(
liveUpdateDependencyCalls,
ElementsAre(LiveUpdateDependencyCall{
component1,
COMPONENT_TYPE_1_FIELD_DEPENDENCY_LIVE_UPDATE,
&component1->type->fields[COMPONENT_TYPE_1_FIELD_DEPENDENCY_LIVE_UPDATE],
component2}));
ASSERT_THAT(activateCalls, IsEmpty());
ASSERT_THAT(onActivateComponentCalls, IsEmpty());
ASSERT_THAT(deactivateCalls, IsEmpty());
ASSERT_THAT(onDeactivateComponentCalls, IsEmpty());
}
TEST_F(ShovelerComponentTest, updateConfigurationLiveReactivatesReverseDependency) {
const char* newConfigurationValue = "new value";
shovelerComponentUpdateCanonicalFieldEntityId(
component1, COMPONENT_TYPE_1_FIELD_DEPENDENCY_REACTIVATE, entityId2);
shovelerComponentDelegate(component2);
bool dependencyActivated = shovelerComponentActivate(component2);
ASSERT_TRUE(dependencyActivated);
bool activated = shovelerComponentActivate(component1);
ASSERT_TRUE(activated);
activateCalls.clear();
onActivateComponentCalls.clear();
propagateNextLiveUpdate = true;
bool updated = shovelerComponentUpdateCanonicalFieldString(
component2, COMPONENT_TYPE_2_FIELD_PRIMITIVE_LIVE_UPDATE, newConfigurationValue);
ASSERT_TRUE(updated);
ASSERT_THAT(onUpdateComponentFieldCalls, SizeIs(2));
ASSERT_THAT(liveUpdateDependencyCalls, IsEmpty());
ASSERT_THAT(deactivateCalls, ElementsAre(component1));
ASSERT_THAT(onDeactivateComponentCalls, ElementsAre(component1));
ASSERT_THAT(activateCalls, ElementsAre(component1));
ASSERT_THAT(onActivateComponentCalls, ElementsAre(component1));
}
TEST_F(ShovelerComponentTest, updateComponentReactivatesReverseDependency) {
double dt = 1234.5;
shovelerComponentUpdateCanonicalFieldEntityId(
component1, COMPONENT_TYPE_1_FIELD_DEPENDENCY_REACTIVATE, entityId2);
shovelerComponentDelegate(component2);
bool dependencyActivated = shovelerComponentActivate(component2);
ASSERT_TRUE(dependencyActivated);
bool activated = shovelerComponentActivate(component1);
ASSERT_TRUE(activated);
activateCalls.clear();
onActivateComponentCalls.clear();
propagateNextUpdate = true;
bool updatePropagated = shovelerComponentUpdate(component2, dt);
ASSERT_TRUE(updatePropagated);
ASSERT_THAT(onUpdateComponentFieldCalls, SizeIs(1));
ASSERT_THAT(liveUpdateDependencyCalls, IsEmpty());
ASSERT_THAT(deactivateCalls, ElementsAre(component1));
ASSERT_THAT(onDeactivateComponentCalls, ElementsAre(component1));
ASSERT_THAT(activateCalls, ElementsAre(component1));
ASSERT_THAT(onActivateComponentCalls, ElementsAre(component1));
}
TEST_F(ShovelerComponentTest, nonPropagatingUpdateComponentDoesntAffectReverseDependency) {
double dt = 1234.5;
shovelerComponentUpdateCanonicalFieldEntityId(
component1, COMPONENT_TYPE_1_FIELD_DEPENDENCY_LIVE_UPDATE, entityId2);
shovelerComponentUpdateCanonicalFieldEntityId(
component1, COMPONENT_TYPE_1_FIELD_DEPENDENCY_REACTIVATE, entityId2);
shovelerComponentDelegate(component2);
bool dependencyActivated = shovelerComponentActivate(component2);
ASSERT_TRUE(dependencyActivated);
bool activated = shovelerComponentActivate(component1);
ASSERT_TRUE(activated);
activateCalls.clear();
onActivateComponentCalls.clear();
propagateNextUpdate = false;
bool updatePropagated = shovelerComponentUpdate(component2, dt);
ASSERT_FALSE(updatePropagated);
ASSERT_THAT(updateCalls, ElementsAre(std::make_pair(component2, dt)));
ASSERT_THAT(onUpdateComponentFieldCalls, SizeIs(2));
ASSERT_THAT(liveUpdateDependencyCalls, IsEmpty());
ASSERT_THAT(activateCalls, IsEmpty());
ASSERT_THAT(onActivateComponentCalls, IsEmpty());
ASSERT_THAT(deactivateCalls, IsEmpty());
ASSERT_THAT(onDeactivateComponentCalls, IsEmpty());
}
TEST_F(ShovelerComponentTest, doublePropagateUpdate) {
double dt = 1234.5;
shovelerComponentUpdateCanonicalFieldEntityId(
component1, COMPONENT_TYPE_1_FIELD_DEPENDENCY_LIVE_UPDATE, entityId2);
shovelerComponentDelegate(component2);
bool dependencyActivated = shovelerComponentActivate(component2);
ASSERT_TRUE(dependencyActivated);
bool activated = shovelerComponentActivate(component1);
ASSERT_TRUE(activated);
shovelerComponentUpdateCanonicalFieldEntityId(
component3, COMPONENT_TYPE_3_FIELD_DEPENDENCY, entityId1);
bool secondDependencyActivated = shovelerComponentActivate(component3);
ASSERT_TRUE(secondDependencyActivated);
activateCalls.clear();
onActivateComponentCalls.clear();
propagateNextUpdate = true;
propagateNextLiveUpdateDependency = true;
bool updatePropagated = shovelerComponentUpdate(component2, dt);
ASSERT_TRUE(updatePropagated);
ASSERT_THAT(onUpdateComponentFieldCalls, SizeIs(2));
ASSERT_THAT(
liveUpdateDependencyCalls,
ElementsAre(LiveUpdateDependencyCall{
component1,
COMPONENT_TYPE_1_FIELD_DEPENDENCY_LIVE_UPDATE,
&component1->type->fields[COMPONENT_TYPE_1_FIELD_DEPENDENCY_LIVE_UPDATE],
component2}));
ASSERT_THAT(deactivateCalls, ElementsAre(component3));
ASSERT_THAT(onDeactivateComponentCalls, ElementsAre(component3));
ASSERT_THAT(activateCalls, ElementsAre(component3));
ASSERT_THAT(onActivateComponentCalls, ElementsAre(component3));
}
TEST_F(ShovelerComponentTest, dontPropagateLiveDependencyUpdate) {
double dt = 1234.5;
shovelerComponentUpdateCanonicalFieldEntityId(
component1, COMPONENT_TYPE_1_FIELD_DEPENDENCY_LIVE_UPDATE, entityId2);
shovelerComponentDelegate(component2);
bool dependencyActivated = shovelerComponentActivate(component2);
ASSERT_TRUE(dependencyActivated);
bool activated = shovelerComponentActivate(component1);
ASSERT_TRUE(activated);
shovelerComponentUpdateCanonicalFieldEntityId(
component3, COMPONENT_TYPE_3_FIELD_DEPENDENCY, entityId1);
bool secondDependencyActivated = shovelerComponentActivate(component3);
ASSERT_TRUE(secondDependencyActivated);
activateCalls.clear();
onActivateComponentCalls.clear();
propagateNextUpdate = true;
propagateNextLiveUpdateDependency = false;
bool updatePropagated = shovelerComponentUpdate(component2, dt);
ASSERT_TRUE(updatePropagated);
ASSERT_THAT(onUpdateComponentFieldCalls, SizeIs(2));
ASSERT_THAT(
liveUpdateDependencyCalls,
ElementsAre(LiveUpdateDependencyCall{
component1,
COMPONENT_TYPE_1_FIELD_DEPENDENCY_LIVE_UPDATE,
&component1->type->fields[COMPONENT_TYPE_1_FIELD_DEPENDENCY_LIVE_UPDATE],
component2}));
ASSERT_THAT(activateCalls, IsEmpty());
ASSERT_THAT(onActivateComponentCalls, IsEmpty());
ASSERT_THAT(deactivateCalls, IsEmpty());
ASSERT_THAT(onDeactivateComponentCalls, IsEmpty());
}
static ShovelerComponent* getComponent(
ShovelerComponent* component,
long long int entityId,
const char* componentTypeId,
void* testPointer) {
auto* test = static_cast<ShovelerComponentTest*>(testPointer);
if (entityId == entityId1 && componentTypeId == componentType1Id) {
return test->component1;
}
if (entityId == entityId2 && componentTypeId == componentType2Id) {
return test->component2;
}
if (entityId == entityId1 && componentTypeId == componentType3Id) {
return test->component3;
}
return nullptr;
}
static void onUpdateComponentField(
ShovelerComponent* component,
int fieldId,
const ShovelerComponentField* field,
const ShovelerComponentFieldValue* value,
bool isCanonical,
void* testPointer) {
auto* test = static_cast<ShovelerComponentTest*>(testPointer);
test->onUpdateComponentFieldCalls.push_back(ShovelerComponentTest::OnUpdateComponentFieldCall{
component, fieldId, field, value, isCanonical});
}
static void onActivateComponent(ShovelerComponent* component, void* testPointer) {
auto* test = static_cast<ShovelerComponentTest*>(testPointer);
test->onActivateComponentCalls.emplace_back(component);
}
static void onDeactivateComponent(ShovelerComponent* component, void* testPointer) {
auto* test = static_cast<ShovelerComponentTest*>(testPointer);
test->onDeactivateComponentCalls.emplace_back(component);
}
static void addDependency(
ShovelerComponent* component,
long long int targetEntityId,
const char* targetComponentTypeId,
void* testPointer) {
auto* test = static_cast<ShovelerComponentTest*>(testPointer);
auto dependencyTarget = std::make_pair(targetEntityId, targetComponentTypeId);
test->reverseDependencies[dependencyTarget].insert(component);
}
static bool removeDependency(
ShovelerComponent* component,
long long int targetEntityId,
const char* targetComponentTypeId,
void* testPointer) {
auto* test = static_cast<ShovelerComponentTest*>(testPointer);
auto dependencyTarget = std::make_pair(targetEntityId, targetComponentTypeId);
test->reverseDependencies[dependencyTarget].erase(component);
return true;
}
static void forEachReverseDependency(
ShovelerComponent* component,
ShovelerComponentWorldAdapterForEachReverseDependencyCallbackFunction* callbackFunction,
void* callbackUserData,
void* testPointer) {
auto* test = static_cast<ShovelerComponentTest*>(testPointer);
auto dependencyTarget = std::make_pair(component->entityId, component->type->id);
for (ShovelerComponent* sourceComponent : test->reverseDependencies[dependencyTarget]) {
if (sourceComponent != nullptr) {
callbackFunction(sourceComponent, component, callbackUserData);
}
}
}
static bool requiresAuthority(ShovelerComponent* component, void* testPointer) {
auto* test = static_cast<ShovelerComponentTest*>(testPointer);
if (component->type == test->componentType2) {
return true;
}
return false;
}
static bool canLiveUpdateField(
ShovelerComponent* component,
int fieldId,
const ShovelerComponentField* field,
void* testPointer) {
auto* test = static_cast<ShovelerComponentTest*>(testPointer);
if (component->type == test->componentType2 &&
field->name == componentType2FieldPrimitiveLiveUpdate) {
return true;
}
return false;
}
static bool canLiveUpdateDependencyField(
ShovelerComponent* component,
int fieldId,
const ShovelerComponentField* field,
void* testPointer) {
auto* test = static_cast<ShovelerComponentTest*>(testPointer);
if (component->type == test->componentType1 &&
field->name == componentType1FieldDependencyLiveUpdate) {
return true;
}
return false;
}
static bool liveUpdateField(
ShovelerComponent* component,
int fieldId,
const ShovelerComponentField* field,
ShovelerComponentFieldValue* fieldValue,
void* testPointer) {
auto* test = static_cast<ShovelerComponentTest*>(testPointer);
test->liveUpdateCalls.push_back(
ShovelerComponentTest::LiveUpdateCall{component, fieldId, field, fieldValue});
return test->propagateNextLiveUpdate;
}
static bool liveUpdateDependencyField(
ShovelerComponent* component,
int fieldId,
const ShovelerComponentField* field,
ShovelerComponent* dependencyComponent,
void* testPointer) {
auto* test = static_cast<ShovelerComponentTest*>(testPointer);
test->liveUpdateDependencyCalls.emplace_back(ShovelerComponentTest::LiveUpdateDependencyCall{
component, fieldId, field, dependencyComponent});
return test->propagateNextLiveUpdateDependency;
}
static void* activateComponent(ShovelerComponent* component, void* testPointer) {
auto* test = static_cast<ShovelerComponentTest*>(testPointer);
test->activateCalls.emplace_back(component);
if (test->failNextActivate) {
return nullptr;
}
return test;
}
static bool updateComponent(ShovelerComponent* component, double dt, void* testPointer) {
auto* test = static_cast<ShovelerComponentTest*>(testPointer);
test->updateCalls.emplace_back(component, dt);
return test->propagateNextUpdate;
}
static void deactivateComponent(ShovelerComponent* component, void* testPointer) {
auto* test = static_cast<ShovelerComponentTest*>(testPointer);
test->deactivateCalls.emplace_back(component);
}
| [
"[email protected]"
] | |
531788c33827bf687470a0209136923ff9891d88 | 7db9caf5123c9d4a559f5f555d856bb1eae1fb8e | /chap6/factorial.cpp | 4cd979c5fa301c3d2f6a47e186f969d7e4495911 | [] | no_license | PhillipSalazar/Programming-one | cde9d2b021c402a7e1de758a45b2258626cec6f0 | ef95def973791b02f6135e79c1caf24be761b2b6 | refs/heads/master | 2020-03-09T00:28:21.611114 | 2018-05-04T20:56:28 | 2018-05-04T20:56:28 | 128,489,003 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 337 | cpp | #include <iostream>
using namespace std;
long FACT(long n);
int main(){
int numIn = 0;
cout << "\nPlease enter an integer";
cin >> numIn;
cout << "factorial of " << numIn << " is " << FACT(numIn) << endl;
return 0;
}
long FACT(long num){
if (num == 0){
return 1;
} else {
return(num * FACT(num -1));
}
} | [
"[email protected]"
] | |
c7adf86d6c4b08162abfec5f74229f4e300329d7 | cd98b19a5066877a6de84ed3015a3d1bad7ab3cc | /reader_funnel_m0_feather/reader_funnel_m0_feather.ino | ffc8f266a9cc4bdf1988bc0d1651c5073a04b6c2 | [
"BSD-2-Clause"
] | permissive | tstellanova/senselog | 5cb22af3a72bb0fea735b2c3be7203f28d3407b8 | 72b8da8f567fe9a05e75f98fcb1a7929ff157a34 | refs/heads/master | 2021-01-17T13:00:09.304481 | 2016-07-29T21:02:55 | 2016-07-29T21:02:55 | 59,036,813 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,470 | ino | /**
*
*
*/
#include <OpenBMP280.h>
` #include <SD.h>
// base SPI pins
#define BMP_MOSI 13
#define BMP_MISO 12
#define BMP_SCK 11
// SPI chip select pins
#define BMP_CS0 20
#define BMP_CS1 21
#define BMP_CS2 5
#define BMP_CS3 6
#define BMP_CS4 9
#define BMP_CS5 10
const int kErrorLED = 13;
// SD card constants
const int kSDChipSelect = 4;
const int kSDStatusLED = 8;
const int kSDCardDetect = 7;
const int kSDFileFlush_ms = 2000;
// main user serial output port
#define USERIAL Serial1
// debug serial output port
#define DSERIAL Serial
#define FIELD_SEPARATOR "\t"
// time at which we start this app
unsigned long _startTime;
// sensors
const int kNumSensors = 6;
const int _select_pins[kNumSensors] = { BMP_CS0, BMP_CS1, BMP_CS2, BMP_CS3, BMP_CS4, BMP_CS5 };
OpenBMP280* _sensor[kNumSensors];
// logging
File _logFile;
unsigned long _lastFlushTime;
void flashErrorLED() {
digitalWrite(kErrorLED, HIGH);
delay(100);
digitalWrite(kErrorLED, LOW);
delay(100);
digitalWrite(kErrorLED, HIGH);
delay(100);
digitalWrite(kErrorLED, LOW);
delay(100);
digitalWrite(kErrorLED, HIGH);
delay(100);
digitalWrite(kErrorLED, LOW);
delay(750);
}
void failError(String msg) {
DSERIAL.println(msg);
DSERIAL.println(msg);
DSERIAL.println(msg);
DSERIAL.flush();
while(true) {
flashErrorLED();
}
}
void openSDLog() {
//determine whether SD card is present
if(digitalRead(kSDCardDetect)) {
if (!SD.begin(kSDChipSelect)){
failError(F("Couldn't SD.begin"));
}
_logFile = SD.open("LOGGER.TXT", FILE_WRITE);
if (!_logFile) {
failError(F("Couldn't open file"));
}
}
else {
failError(F("No SD card detected"));
}
_lastFlushTime = _startTime;
}
void setupPinMap() {
//config SD pins
pinMode(kSDCardDetect, INPUT); // SD card presence detector
pinMode(kSDStatusLED, OUTPUT); // Status LED
//config base SPI pins
pinMode(BMP_SCK, OUTPUT);
pinMode(BMP_MOSI, OUTPUT);
pinMode(BMP_MISO, INPUT);
//setup all the SPI sensor select pins
for (int i = 0; i < kNumSensors ; i++) {
pinMode(_select_pins[i], OUTPUT);
digitalWrite(_select_pins[i], HIGH);
}
}
// Start a single BMP sensor
bool startOneSensor(OpenBMP280& sensor) {
int startupCount = 0;
bool started = false;
while(!started && (startupCount < 10)) {
startupCount++;
started = sensor.begin();
delay(10);
}
return started;
}
void setupSerialPorts() {
DSERIAL.begin(9600);
for (int i = 0; i < 10; i++) {
if (!DSERIAL) {
digitalWrite(kErrorLED, HIGH);
// wait for serial port to connect. Needed for native USB port only
delay(100);
digitalWrite(kErrorLED, LOW);
}
}
if (DSERIAL) {
DSERIAL.println("hello DSERIAL");
}
USERIAL.begin(9600);
for (int i = 0; i < 10; i++) {
if (!USERIAL) {
digitalWrite(kErrorLED, HIGH);
// wait for serial port to connect.
delay(100);
digitalWrite(kErrorLED, LOW);
}
}
if (USERIAL) {
USERIAL.println("hello USERIAL");
}
}
void setup() {
_startTime = millis();
setupSerialPorts();
setupPinMap();
for (int i = 0; i < kNumSensors ; i++) {
const int select = _select_pins[i];
_sensor[i] = new OpenBMP280(select, BMP_MOSI, BMP_MISO, BMP_SCK);
if (!startOneSensor(*_sensor[i])) {
char errBuf[40];
sprintf(errBuf, "Sensor %d is not responding",i);
failError(errBuf);
}
pinMode(_select_pins[i], OUTPUT);
digitalWrite(_select_pins[i], HIGH);
}
openSDLog();
}
void outputVector(float* points)
{
char outBuf[80];
long currentTime = millis();
long dTime = currentTime - _startTime;
sprintf(outBuf,"%8d\t%7.2f\t%7.2f\t%7.2f",dTime,points[0],points[1],points[2]);
if (DSERIAL) {
DSERIAL.println(outBuf);
}
if (USERIAL) {
USERIAL.println(outBuf);
}
if (_logFile) {
_logFile.println(outBuf);
if(currentTime >= (_lastFlushTime + kSDFileFlush_ms)) {
_logFile.flush();
_lastFlushTime = currentTime;
}
}
}
void loop() {
float points[3] = {};
digitalWrite(kSDStatusLED, HIGH); // started read
for (int i = 0, j = 0; i < kNumSensors ; i+=2, j++) {
float p0 = _sensor[i]->readPressure();
float p1 = _sensor[i+1]->readPressure();
points[j] = p0 - p1;
}
outputVector(points);
digitalWrite(kSDStatusLED, LOW); // done
delay(10);
}
| [
"[email protected]"
] | |
07598283b5ff8b914b7769b4153ab2075333fd3a | 1d3a8bc0d855e61ba1975300fc14b991ccaba18b | /PyLoops/include/PyLoops/MapMatching/FastMapMatching.h | 95527a9af7c06e7ea0defc2c11afcd41566d3a6d | [] | no_license | tue-alga/RouteReconstruction | 0c448da15b33a5efa3b2e510fe5343f06e727fe5 | 9d71a9b14bb4e46e270e52c47983b4c2c9b691f9 | refs/heads/main | 2023-01-21T09:37:47.884107 | 2020-12-03T00:00:47 | 2020-12-03T00:00:47 | 318,003,592 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 592 | h | #ifndef PYLOOPS_MAPMATCHING_FASTMAPMATCHING
#define PYLOOPS_MAPMATCHING_FASTMAPMATCHING
#include <PyLoops/PyLoops.inc.h>
namespace LoopsAlgs::MapMatching
{
class FastMapMatching;
}
namespace PyLoops::MapMatching{
class FastMapMatching{
void multithreadedMapmatchSet(const LoopsLib::MovetkGeometryKernel::TimestampedTrajectorySet& input,
const LoopsAlgs::MapMatching::FastMapMatching& mapMatcher,
int threadNum,
const std::string& outputFile
);
public:
static void registerPy(pybind11::module& mod);
};
}
#endif | [
"[email protected]"
] | |
20804243152250ee952011717e8550611b1e4321 | 1f4ce808663ce88821e1ac0539ab5db07f64b545 | /include/tsar/Analysis/Memory/Passes.h | 3491a55423e6151224263741e478cf7c99e0521a | [
"Apache-2.0",
"NCSA"
] | permissive | v-makeev/tsar | 759f7af2ef98334bc35f02872606b334a9438b9c | a6f95cdaeb117ccd5fcb775b471b1aa17c45f4e8 | refs/heads/master | 2021-06-20T22:05:48.637920 | 2021-02-20T16:24:24 | 2021-02-20T16:24:24 | 215,977,391 | 0 | 0 | Apache-2.0 | 2019-10-18T08:28:26 | 2019-10-18T08:28:26 | null | UTF-8 | C++ | false | false | 8,389 | h | //===- Passes.h - Create and Initialize Memory Analysis Passes -*- C++ -*-===//
//
// Traits Static Analyzer (SAPFOR)
//
// Copyright 2018 DVM System Group
//
// 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.
//
//===----------------------------------------------------------------------===//
//
// It contains declarations of functions that initialize and create an instances
// of TSAR passes which are necessary for analysis of memory accesses.
// Declarations of appropriate methods for an each new pass should
// be added to this file.
//
//===----------------------------------------------------------------------===//
#ifndef TSAR_MEMORY_ANALYSIS_PASSES_H
#define TSAR_MEMORY_ANALYSIS_PASSES_H
#include <functional>
namespace tsar {
class DIMemoryTrait;
}
namespace llvm {
class Pass;
class PassRegistry;
class FunctionPass;
class ImmutablePass;
class ModulePass;
/// Initialize all passes to perform analysis of memory accesses.
void initializeMemoryAnalysis(PassRegistry &Registry);
/// Initialize a pass to find defined locations for each data-flow region.
void initializeDefinedMemoryPassPass(PassRegistry &Registry);
/// Create a pass to find defined locations for each data-flow region.
FunctionPass * createDefinedMemoryPass();
/// Initialize a pass to find live locations for each data-flow region.
void initializeLiveMemoryPassPass(PassRegistry &Registry);
/// Create a pass to find live locations for each data-flow region.
FunctionPass * createLiveMemoryPass();
/// Initialize a pass to build hierarchy of accessed memory.
void initializeEstimateMemoryPassPass(PassRegistry &Registry);
/// Create a pass to build hierarchy of accessed memory.
FunctionPass * createEstimateMemoryPass();
/// Initialize a pass to build hierarchy of accessed memory.
void initializeDIEstimateMemoryPassPass(PassRegistry &Registry);
/// Create a pass to build hierarchy of accessed memory.
FunctionPass * createDIEstimateMemoryPass();
/// Initializes storage of debug-level memory environment.
void initializeDIMemoryEnvironmentStoragePass(PassRegistry &Registry);
/// Create storage of debug-level memory environment.
ImmutablePass * createDIMemoryEnvironmentStorage();
/// Initialize wrapper to access debug-level memory environment.
void initializeDIMemoryEnvironmentWrapperPass(PassRegistry &Registry);
/// Initialize a pass to display alias tree.
void initializeAliasTreeViewerPass(PassRegistry &Registry);
/// Create a pass to display alias tree.
FunctionPass * createAliasTreeViewerPass();
/// Initialize a pass to display alias tree (alias summary only).
void initializeAliasTreeOnlyViewerPass(PassRegistry &Registry);
/// Create a pass to display alias tree (alias summary only).
FunctionPass * createAliasTreeOnlyViewerPass();
/// Initialize a pass to display alias tree.
void initializeDIAliasTreeViewerPass(PassRegistry &Registry);
/// Create a pass to display alias tree.
FunctionPass * createDIAliasTreeViewerPass();
/// Initialize a pass to print alias tree to 'dot' file.
void initializeAliasTreePrinterPass(PassRegistry &Registry);
/// Create a pass to print alias tree to 'dot' file.
FunctionPass * createAliasTreePrinterPass();
/// Initialize a pass to print alias tree to 'dot' file (alias summary only).
void initializeAliasTreeOnlyPrinterPass(PassRegistry &Registry);
/// Create a pass to print alias tree to 'dot' file (alias summary only).
FunctionPass * createAliasTreeOnlyPrinterPass();
/// Initialize a pass to print alias tree to 'dot' file.
void initializeDIAliasTreePrinterPass(PassRegistry &Registry);
/// Create a pass to print alias tree to 'dot' file.
FunctionPass * createDIAliasTreePrinterPass();
/// Initialize storage of metadata-level pool of memory traits.
void initializeDIMemoryTraitPoolStoragePass(PassRegistry &Registry);
/// Create storage of metadata-level pool of memory traits.
ImmutablePass * createDIMemoryTraitPoolStorage();
/// Initialize wrapper to access metadata-level pool of memory traits.
void initializeDIMemoryTraitPoolWrapperPass(PassRegistry &Registry);
/// Initialize a pass to determine privatizable variables.
void initializePrivateRecognitionPassPass(PassRegistry &Registry);
/// Create a pass to determine privatizable variables.
FunctionPass * createPrivateRecognitionPass();
/// Initializes a pass to analyze private variables (at metadata level).
void initializeDIDependencyAnalysisPassPass(PassRegistry &Registry);
/// Create a pass to classify data dependency at metadata level.
///
/// This includes privatization, reduction and induction variable recognition
/// and flow/anti/output dependencies exploration.
FunctionPass * createDIDependencyAnalysisPass();
/// Initialize a pass to process traits in a region.
void initializeProcessDIMemoryTraitPassPass(PassRegistry &Registry);
/// Create a pass to process traits in a region.
Pass * createProcessDIMemoryTraitPass(
const std::function<void(tsar::DIMemoryTrait &)> &Lock);
/// Initialized a pass to look for not initialized memory locations.
void initializeNotInitializedMemoryAnalysisPass(PassRegistry &Registry);
/// Create a pass to look for not initialized memory locations.
FunctionPass * createNotInitializedMemoryAnalysis(PassRegistry &Registry);
/// Initialize a pass to delinearize array accesses.
void initializeDelinearizationPassPass(PassRegistry &Registry);
/// Create a pass to delinearize array accesses.
FunctionPass * createDelinearizationPass();
/// Initialize a pass to perform iterprocedural live memory analysis.
void initializeGlobalLiveMemoryPass(PassRegistry& Registry);
/// Create a pass to perform iterprocedural live memory analysis.
ModulePass * createGlobalLiveMemoryPass();
/// Initialize a pass to store results of interprocedural live memory analysis.
void initializeGlobalLiveMemoryStoragePass(PassRegistry &Registry);
/// Create a pass to store results of interprocedural live memory analysis.
ImmutablePass *createGlobalLiveMemoryStorage();
/// Initialize a pass to access results of interprocedural live memory analysis.
void initializeGlobalLiveMemoryWrapperPass(PassRegistry &Registry);
/// Initialize a pass to perform iterprocedural analysis of defined memory
/// locations.
void initializeGlobalDefinedMemoryPass(PassRegistry &Registry);
/// Create a pass to perform iterprocedural analysis of defined memory
/// locations.
ModulePass * createGlobalDefinedMemoryPass();
/// Initialize a pass to store results of interprocedural reaching definition
/// analysis.
void initializeGlobalDefinedMemoryStoragePass(PassRegistry &Registry);
/// Create a pass to store results of interprocedural reaching definition
/// analysis.
ImmutablePass *createGlobalDefinedMemoryStorage();
/// Initialize a pass to access results of interprocedural reaching definition
/// analysis.
void initializeGlobalDefinedMemoryWrapperPass(PassRegistry &Registry);
/// Create analysis server.
ModulePass *createDIMemoryAnalysisServer();
/// Initialize analysis server.
void initializeDIMemoryAnalysisServerPass(PassRegistry &Registry);
/// Initialize a pass to store list of array accesses.
void initializeDIArrayAccessStoragePass(PassRegistry &Registry);
/// Create a pass to store list of array accesses.
ImmutablePass *createDIArrayAccessStorage();
/// Initialize a pass to access information about array accesses in the program.
void initializeDIArrayAccessWrapperPass(PassRegistry &Registry);
/// Initialize a pass to collect array accesses.
void initializeDIArrayAccessCollectorPass(PassRegistry &Registry);
/// Create a pass to collect array accesses.
ModulePass *createDIArrayAccessCollector();
/// Initialize a pass to access alias results for allocas.
void initializeAllocasAAWrapperPassPass(PassRegistry &Regitsry);
/// Create a pass to access alias results for allocas.
ImmutablePass *createAllocasAAWrapperPass();
}
#endif//TSAR_MEMORY_ANALYSIS_PASSES_H
| [
"[email protected]"
] | |
13ac7cec18d75b816c4ea69ce520fcbc3b2ba5a7 | 31ac07ecd9225639bee0d08d00f037bd511e9552 | /externals/OCCTLib/inc/TPrsStd_GeometryDriver.hxx | 32fc706d09d9dac1eb20a5c8a7b2b74a9f9f9f7a | [] | no_license | litao1009/SimpleRoom | 4520e0034e4f90b81b922657b27f201842e68e8e | 287de738c10b86ff8f61b15e3b8afdfedbcb2211 | refs/heads/master | 2021-01-20T19:56:39.507899 | 2016-07-29T08:01:57 | 2016-07-29T08:01:57 | 64,462,604 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,628 | hxx | // This file is generated by WOK (CPPExt).
// Please do not edit this file; modify original file instead.
// The copyright and license terms as defined for the original file apply to
// this header file considered to be the "object code" form of the original source.
#ifndef _TPrsStd_GeometryDriver_HeaderFile
#define _TPrsStd_GeometryDriver_HeaderFile
#ifndef _Standard_HeaderFile
#include <Standard.hxx>
#endif
#ifndef _Standard_DefineHandle_HeaderFile
#include <Standard_DefineHandle.hxx>
#endif
#ifndef _Handle_TPrsStd_GeometryDriver_HeaderFile
#include <Handle_TPrsStd_GeometryDriver.hxx>
#endif
#ifndef _TPrsStd_Driver_HeaderFile
#include <TPrsStd_Driver.hxx>
#endif
#ifndef _Standard_Boolean_HeaderFile
#include <Standard_Boolean.hxx>
#endif
#ifndef _Handle_AIS_InteractiveObject_HeaderFile
#include <Handle_AIS_InteractiveObject.hxx>
#endif
class TDF_Label;
class AIS_InteractiveObject;
//! This method is an implementation of TPrsStd_Driver for geometries. <br>
class TPrsStd_GeometryDriver : public TPrsStd_Driver {
public:
//! Constructs an empty geometry driver. <br>
Standard_EXPORT TPrsStd_GeometryDriver();
//! Build the AISObject (if null) or update it. <br>
//! No compute is done. <br>
//! Returns <True> if informations was found <br>
//! and AISObject updated. <br>
Standard_EXPORT virtual Standard_Boolean Update(const TDF_Label& aLabel,Handle(AIS_InteractiveObject)& anAISObject) ;
DEFINE_STANDARD_RTTI(TPrsStd_GeometryDriver)
protected:
private:
};
// other Inline functions and methods (like "C++: function call" methods)
#endif
| [
"[email protected]"
] | |
f5f7e9a95d8a4ea92a37d065170cf9a15b9863fb | 14fdf908cbf7199479a02a941f84f9b63cc3a6f1 | /is_subtree/main.cpp | 015f8ac266d1f5437dfa582a1bb391798727baff | [] | no_license | gbertuol/codechef | 2305086c4b257aa8180fb69e23886c1ba68ddb6d | 3ae8dd0d753057df27e1986d6420b0193975631c | refs/heads/master | 2021-01-22T12:08:19.016276 | 2013-12-28T20:55:13 | 2013-12-28T20:55:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,165 | cpp | #include <Tree.h>
template <typename T>
bool matchTree(Node<T> *a, Node<T> *b)
{
if (!a && !b)
return true;
if (!a || !b)
return false;
if (a->data != b->data)
return false;
return matchTree(a->left, b->left) && matchTree(a->right, b->right);
}
template <typename T>
bool subtree(Node<T> *a, Node<T> *b)
{
if (!a)
return false;
if (a->data == b->data)
{
if (matchTree(a, b))
return true;
}
return subtree(a->left, b) || subtree(a->right, b);
}
template <typename T>
bool isSubtree(Tree<T> &a, Tree<T> &b)
{
if (!b.root)
return true;
return subtree(a.root, b.root);
}
int main()
{
Tree<int> tree;
tree.insert(50);
tree.insert(17);
tree.insert(12);
tree.insert(9);
tree.insert(14);
tree.insert(23);
tree.insert(19);
tree.insert(72);
tree.insert(54);
tree.insert(67);
tree.insert(76);
Tree<int> subtree;
subtree.insert(12);
subtree.insert(9);
subtree.insert(14);
std::cout << isSubtree(tree, subtree);
return 0;
} | [
"[email protected]"
] | |
47f5d3d74618625e33ab544c6af7d8bd94cbabe5 | dd2cc8a83c96b45eb5f7e1ad72ddeebd39b12ad9 | /include/boost/url/static_pool.hpp | 23cc94e859dc81932f64c7126a65487193b3da29 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | dendisuhubdy/url | 9a0307029198c5f37dacdb2cf5ea82e7b78140a7 | cb186dc5fa650a5dceb820915f975ef0c1a899cb | refs/heads/master | 2022-04-13T11:21:50.305706 | 2020-01-24T03:20:39 | 2020-01-24T03:55:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,634 | hpp | //
// Copyright (c) 2019 Vinnie Falco ([email protected])
//
// 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)
//
// Official repository: https://github.com/vinniefalco/url
//
#ifndef BOOST_URL_STATIC_POOL_HPP
#define BOOST_URL_STATIC_POOL_HPP
#include <boost/url/config.hpp>
#include <cstdlib>
namespace boost {
namespace url {
class basic_static_pool
{
char* const base_;
std::size_t const capacity_;
char* top_;
template<class T>
friend class allocator_type;
void*
allocate(
std::size_t bytes,
std::size_t align)
{
auto const u0 = std::uintptr_t(top_);
auto const u = align * (
(u0 + align - 1) / align);
auto const p =
reinterpret_cast<char*>(u);
if( u < u0 || bytes >
capacity_ - (p - base_))
BOOST_THROW_EXCEPTION(
std::bad_alloc());
top_ = reinterpret_cast<
char*>(p + bytes);
return p;
}
void
deallocate(
void* p,
std::size_t bytes,
std::size_t align) noexcept
{
(void)p;
(void)bytes;
(void)align;
}
public:
template<class T>
class allocator_type
{
basic_static_pool* pool_ = nullptr;
template<class U>
friend class allocator_type;
public:
using is_always_equal = std::false_type;
using value_type = T;
using pointer = T*;
using reference = T&;
using const_pointer = T const*;
using const_reference = T const&;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
template<class U>
struct rebind
{
using other = allocator_type<U>;
};
#ifndef BOOST_URL_NO_GCC_4_2_WORKAROUND
// libg++ basic_string requires Allocator to be DefaultConstructible
// https://code.woboq.org/firebird/include/c++/4.8.2/bits/basic_string.tcc.html#82
allocator_type() = default;
#endif
template<class U>
allocator_type(
allocator_type<U> const& other) noexcept
: pool_(other.pool_)
{
}
explicit
allocator_type(
basic_static_pool& pool)
: pool_(&pool)
{
}
pointer
allocate(size_type n)
{
return reinterpret_cast<T*>(
pool_->allocate(
n * sizeof(T),
alignof(T)));
}
void
deallocate(
pointer p,
size_type n) noexcept
{
pool_->deallocate(p,
n * sizeof(T),
alignof(T));
}
template<class U>
bool
operator==(allocator_type<U> const& other) const noexcept
{
return pool_ == other.pool_;
}
template<class U>
bool
operator!=(allocator_type<U> const& other) const noexcept
{
return pool_ != other.pool_;
}
};
basic_static_pool(
char* buffer,
std::size_t size)
: base_(buffer)
, capacity_(size)
, top_(buffer)
{
}
allocator_type<char>
allocator() noexcept
{
return allocator_type<char>(*this);
}
};
template<std::size_t N>
class static_pool : public basic_static_pool
{
char buf_[N];
public:
static_pool()
: basic_static_pool(buf_, N)
{
}
};
} // url
} // boost
#endif
| [
"[email protected]"
] | |
de5181291152c6c0a38ae7ec57dda5d023bd362b | a1d0ba29f9b0036a9d777d1137466d7f95be932e | /src/DuiLib/Control/UISlider.cpp | 94f3f8ded06d2df1d9302bf3ae787e791d496eb9 | [] | no_license | starsoverflow/videoplayer | 90d5a2a8724de25d145bc4739aa01cb1a9c62c5b | 75bf43ac3cf14e2c0aa7f35cd780ae074facf14f | refs/heads/master | 2021-06-28T03:02:24.033917 | 2020-11-15T14:45:42 | 2020-11-15T14:45:42 | 84,651,936 | 5 | 1 | null | null | null | null | GB18030 | C++ | false | false | 11,153 | cpp | #include "StdAfx.h"
#include "UISlider.h"
namespace DuiLib
{
CSliderUI::CSliderUI() : m_uButtonState(0), m_nStep(1),m_bSendMove(false)
{
m_uTextStyle = DT_SINGLELINE | DT_CENTER;
m_szThumb.cx = m_szThumb.cy = 10;
}
LPCTSTR CSliderUI::GetClass() const
{
return _T("SliderUI");
}
UINT CSliderUI::GetControlFlags() const
{
if( IsEnabled() ) return UIFLAG_SETCURSOR;
else return 0;
}
LPVOID CSliderUI::GetInterface(LPCTSTR pstrName)
{
if( _tcscmp(pstrName, DUI_CTR_SLIDER) == 0 ) return static_cast<CSliderUI*>(this);
return CProgressUI::GetInterface(pstrName);
}
void CSliderUI::SetEnabled(bool bEnable)
{
CControlUI::SetEnabled(bEnable);
if( !IsEnabled() ) {
m_uButtonState = 0;
}
}
int CSliderUI::GetChangeStep()
{
return m_nStep;
}
void CSliderUI::SetChangeStep(int step)
{
m_nStep = step;
}
void CSliderUI::SetThumbSize(SIZE szXY)
{
m_szThumb = szXY;
}
RECT CSliderUI::GetThumbRect() const
{
if( m_bHorizontal ) {
int left = m_rcItem.left + (m_rcItem.right - m_rcItem.left - m_szThumb.cx) * (m_nValue - m_nMin) / (m_nMax - m_nMin);
int top = (m_rcItem.bottom + m_rcItem.top - m_szThumb.cy) / 2;
return CDuiRect(left, top, left + m_szThumb.cx, top + m_szThumb.cy);
}
else {
int left = (m_rcItem.right + m_rcItem.left - m_szThumb.cx) / 2;
int top = m_rcItem.bottom - m_szThumb.cy - (m_rcItem.bottom - m_rcItem.top - m_szThumb.cy) * (m_nValue - m_nMin) / (m_nMax - m_nMin);
return CDuiRect(left, top, left + m_szThumb.cx, top + m_szThumb.cy);
}
}
LPCTSTR CSliderUI::GetThumbImage() const
{
return m_sThumbImage;
}
void CSliderUI::SetThumbImage(LPCTSTR pStrImage)
{
m_sThumbImage = pStrImage;
Invalidate();
}
LPCTSTR CSliderUI::GetThumbHotImage() const
{
return m_sThumbHotImage;
}
void CSliderUI::SetThumbHotImage(LPCTSTR pStrImage)
{
m_sThumbHotImage = pStrImage;
Invalidate();
}
LPCTSTR CSliderUI::GetThumbPushedImage() const
{
return m_sThumbPushedImage;
}
void CSliderUI::SetThumbPushedImage(LPCTSTR pStrImage)
{
m_sThumbPushedImage = pStrImage;
Invalidate();
}
void CSliderUI::SetValue(int nValue) //2014.7.28 redrain 当鼠标正在滑动滑块时不会收到SetValue的影响,比如滑动改变音乐的进度,不会因为外部一直调用SetValue而让我们无法滑动滑块
{
if( (m_uButtonState & UISTATE_CAPTURED) != 0 )
return;
CProgressUI::SetValue(nValue);
}
void CSliderUI::DoEvent(TEventUI& event)
{
if( !IsMouseEnabled() && event.Type > UIEVENT__MOUSEBEGIN && event.Type < UIEVENT__MOUSEEND ) {
if( m_pParent != NULL ) m_pParent->DoEvent(event);
else CProgressUI::DoEvent(event);
return;
}
if( event.Type == UIEVENT_BUTTONDOWN || event.Type == UIEVENT_DBLCLICK )
{
if( IsEnabled() ) {//2014.7.28 redrain 注释掉原来的代码,加上这些代码后可以让Slider不是在鼠标弹起时才改变滑块的位置
m_uButtonState |= UISTATE_CAPTURED;
int nValue;
if( m_bHorizontal ) {
if( event.ptMouse.x >= m_rcItem.right - m_szThumb.cx / 2 ) nValue = m_nMax;
else if( event.ptMouse.x <= m_rcItem.left + m_szThumb.cx / 2 ) nValue = m_nMin;
else nValue = m_nMin + (m_nMax - m_nMin) * (event.ptMouse.x - m_rcItem.left - m_szThumb.cx / 2 ) / (m_rcItem.right - m_rcItem.left - m_szThumb.cx);
}
else {
if( event.ptMouse.y >= m_rcItem.bottom - m_szThumb.cy / 2 ) nValue = m_nMin;
else if( event.ptMouse.y <= m_rcItem.top + m_szThumb.cy / 2 ) nValue = m_nMax;
else nValue = m_nMin + (m_nMax - m_nMin) * (m_rcItem.bottom - event.ptMouse.y - m_szThumb.cy / 2 ) / (m_rcItem.bottom - m_rcItem.top - m_szThumb.cy);
}
if(m_nValue !=nValue && nValue>=m_nMin && nValue<=m_nMax)
{
m_nValue = nValue;
Invalidate();
m_pManager->SendNotify(this, _T("buttondownandposchanged"));
}
}
return;
}
// if( event.Type == UIEVENT_BUTTONDOWN || event.Type == UIEVENT_DBLCLICK )
// {
// if( IsEnabled() ) {
// RECT rcThumb = GetThumbRect();
// if( ::PtInRect(&rcThumb, event.ptMouse) ) {
// m_uButtonState |= UISTATE_CAPTURED;
// }
// }
// return;
// }
if( event.Type == UIEVENT_BUTTONUP)
{
int nValue;
if( (m_uButtonState & UISTATE_CAPTURED) != 0 ) {
m_uButtonState &= ~UISTATE_CAPTURED;
}
if( m_bHorizontal ) {
if( event.ptMouse.x >= m_rcItem.right - m_szThumb.cx / 2 ) nValue = m_nMax;
else if( event.ptMouse.x <= m_rcItem.left + m_szThumb.cx / 2 ) nValue = m_nMin;
else nValue = m_nMin + (m_nMax - m_nMin) * (event.ptMouse.x - m_rcItem.left - m_szThumb.cx / 2 ) / (m_rcItem.right - m_rcItem.left - m_szThumb.cx);
}
else {
if( event.ptMouse.y >= m_rcItem.bottom - m_szThumb.cy / 2 ) nValue = m_nMin;
else if( event.ptMouse.y <= m_rcItem.top + m_szThumb.cy / 2 ) nValue = m_nMax;
else nValue = m_nMin + (m_nMax - m_nMin) * (m_rcItem.bottom - event.ptMouse.y - m_szThumb.cy / 2 ) / (m_rcItem.bottom - m_rcItem.top - m_szThumb.cy);
}
if(/*m_nValue != nValue && 2014.7.28 redrain 这个注释很关键,是他导致了鼠标拖动滑块无法发出DUI_MSGTYPE_VALUECHANGED消息*/nValue>=m_nMin && nValue<=m_nMax)
{
m_nValue = nValue;
m_pManager->SendNotify(this, DUI_MSGTYPE_VALUECHANGED);
Invalidate();
}
return;
}
if( event.Type == UIEVENT_CONTEXTMENU )
{
return;
}
if( event.Type == UIEVENT_SCROLLWHEEL )
{
switch( LOWORD(event.wParam) ) {
case SB_LINEUP:
SetValue(GetValue() + GetChangeStep());
m_pManager->SendNotify(this, DUI_MSGTYPE_VALUECHANGED);
return;
case SB_LINEDOWN:
SetValue(GetValue() - GetChangeStep());
m_pManager->SendNotify(this, DUI_MSGTYPE_VALUECHANGED);
return;
}
}
if( event.Type == UIEVENT_MOUSEMOVE )
{
if( (m_uButtonState & UISTATE_CAPTURED) != 0 ) {//2014.7.28 redrain 重写这个消息判断让Slider发出DUI_MSGTYPE_VALUECHANGED_MOVE消息,让他在滑动过程也发出消息,比如用在改变音量时,一边滑动就可以一边改变音量
if( m_bHorizontal ) {
if( event.ptMouse.x >= m_rcItem.right - m_szThumb.cx / 2 ) m_nValue = m_nMax;
else if( event.ptMouse.x <= m_rcItem.left + m_szThumb.cx / 2 ) m_nValue = m_nMin;
else m_nValue = m_nMin + (m_nMax - m_nMin) * (event.ptMouse.x - m_rcItem.left - m_szThumb.cx / 2 ) / (m_rcItem.right - m_rcItem.left - m_szThumb.cx);
}
else {
if( event.ptMouse.y >= m_rcItem.bottom - m_szThumb.cy / 2 ) m_nValue = m_nMin;
else if( event.ptMouse.y <= m_rcItem.top + m_szThumb.cy / 2 ) m_nValue = m_nMax;
else m_nValue = m_nMin + (m_nMax - m_nMin) * (m_rcItem.bottom - event.ptMouse.y - m_szThumb.cy / 2 ) / (m_rcItem.bottom - m_rcItem.top - m_szThumb.cy);
}
if (m_bSendMove)
m_pManager->SendNotify(this, DUI_MSGTYPE_VALUECHANGED_MOVE);
Invalidate();
}
// Generate the appropriate mouse messages
POINT pt = event.ptMouse;
RECT rcThumb = GetThumbRect();
if( IsEnabled() && ::PtInRect(&rcThumb, event.ptMouse) ) {
m_uButtonState |= UISTATE_HOT;
Invalidate();
}else
{
m_uButtonState &= ~UISTATE_HOT;
Invalidate();
}
return;
}
// if( event.Type == UIEVENT_MOUSEMOVE )
// {
// if( (m_uButtonState & UISTATE_CAPTURED) != 0 ) {
// if( m_bHorizontal ) {
// if( event.ptMouse.x >= m_rcItem.right - m_szThumb.cx / 2 ) m_nValue = m_nMax;
// else if( event.ptMouse.x <= m_rcItem.left + m_szThumb.cx / 2 ) m_nValue = m_nMin;
// else m_nValue = m_nMin + (m_nMax - m_nMin) * (event.ptMouse.x - m_rcItem.left - m_szThumb.cx / 2 ) / (m_rcItem.right - m_rcItem.left - m_szThumb.cx);
// }
// else {
// if( event.ptMouse.y >= m_rcItem.bottom - m_szThumb.cy / 2 ) m_nValue = m_nMin;
// else if( event.ptMouse.y <= m_rcItem.top + m_szThumb.cy / 2 ) m_nValue = m_nMax;
// else m_nValue = m_nMin + (m_nMax - m_nMin) * (m_rcItem.bottom - event.ptMouse.y - m_szThumb.cy / 2 ) / (m_rcItem.bottom - m_rcItem.top - m_szThumb.cy);
// }
// Invalidate();
// }
// return;
// }
if( event.Type == UIEVENT_SETCURSOR )
{
RECT rcThumb = GetThumbRect();
if( IsEnabled()) {
::SetCursor(::LoadCursor(NULL, IDC_HAND));
return;
}
}
// if( event.Type == UIEVENT_SETCURSOR )
// {
// RECT rcThumb = GetThumbRect();
// if( IsEnabled() && ::PtInRect(&rcThumb, event.ptMouse) ) {
// ::SetCursor(::LoadCursor(NULL, MAKEINTRESOURCE(IDC_HAND)));
// return;
// }
// }
if( event.Type == UIEVENT_MOUSEENTER )
{//2014.7.28 redrain 只有鼠标在滑块的范围内才变为UISTATE_HOT
// if( IsEnabled() ) {
// m_uButtonState |= UISTATE_HOT;
// Invalidate();
// }
// return;
}
if( event.Type == UIEVENT_MOUSELEAVE )
{
if( IsEnabled() ) {
m_uButtonState &= ~UISTATE_HOT;
Invalidate();
}
return;
}
CControlUI::DoEvent(event);
}
void CSliderUI::SetCanSendMove(bool bCanSend) //2014.7.28 redrain
{
m_bSendMove = bCanSend;
}
bool CSliderUI::GetCanSendMove() const //2014.7.28 redrain
{
return m_bSendMove;
}
void CSliderUI::SetAttribute(LPCTSTR pstrName, LPCTSTR pstrValue)
{
if( _tcscmp(pstrName, _T("thumbimage")) == 0 ) SetThumbImage(pstrValue);
else if( _tcscmp(pstrName, _T("thumbhotimage")) == 0 ) SetThumbHotImage(pstrValue);
else if( _tcscmp(pstrName, _T("thumbpushedimage")) == 0 ) SetThumbPushedImage(pstrValue);
else if( _tcscmp(pstrName, _T("thumbsize")) == 0 ) {
SIZE szXY = {0};
LPTSTR pstr = NULL;
szXY.cx = _tcstol(pstrValue, &pstr, 10); ASSERT(pstr);
szXY.cy = _tcstol(pstr + 1, &pstr, 10); ASSERT(pstr);
SetThumbSize(szXY);
}
else if( _tcscmp(pstrName, _T("step")) == 0 ) {
SetChangeStep(_ttoi(pstrValue));
}
else if( _tcscmp(pstrName, _T("sendmove")) == 0 ) {
SetCanSendMove(_tcscmp(pstrValue, _T("true")) == 0);
}
else CProgressUI::SetAttribute(pstrName, pstrValue);
}
void CSliderUI::PaintStatusImage(HDC hDC)
{
CProgressUI::PaintStatusImage(hDC);
RECT rcThumb = GetThumbRect();
rcThumb.left -= m_rcItem.left;
rcThumb.top -= m_rcItem.top;
rcThumb.right -= m_rcItem.left;
rcThumb.bottom -= m_rcItem.top;
if( (m_uButtonState & UISTATE_CAPTURED) != 0 ) {
if( !m_sThumbPushedImage.IsEmpty() ) {
m_sImageModify.Empty();
m_sImageModify.SmallFormat(_T("dest='%d,%d,%d,%d'"), rcThumb.left, rcThumb.top, rcThumb.right, rcThumb.bottom);
if( !DrawImage(hDC, (LPCTSTR)m_sThumbPushedImage, (LPCTSTR)m_sImageModify) ) m_sThumbPushedImage.Empty();
else return;
}
}
else if( (m_uButtonState & UISTATE_HOT) != 0 ) {
if( !m_sThumbHotImage.IsEmpty() ) {
m_sImageModify.Empty();
m_sImageModify.SmallFormat(_T("dest='%d,%d,%d,%d'"), rcThumb.left, rcThumb.top, rcThumb.right, rcThumb.bottom);
if( !DrawImage(hDC, (LPCTSTR)m_sThumbHotImage, (LPCTSTR)m_sImageModify) ) m_sThumbHotImage.Empty();
else return;
}
}
if( !m_sThumbImage.IsEmpty() ) {
m_sImageModify.Empty();
m_sImageModify.SmallFormat(_T("dest='%d,%d,%d,%d'"), rcThumb.left, rcThumb.top, rcThumb.right, rcThumb.bottom);
if( !DrawImage(hDC, (LPCTSTR)m_sThumbImage, (LPCTSTR)m_sImageModify) ) m_sThumbImage.Empty();
else return;
}
}
}
| [
"[email protected]"
] | |
7241f6eb1c9d2ff216e5f29b3d3cf6cf22fe55b4 | 3e5aac2f8338e65c51ea312c1190fe674ce8f9f7 | /Engine/Source/Runtime/Core/Public/HAL/Event.h | de0613695ae3ab0c92503f69a0b798a3acbb487a | [] | no_license | blueness9527/SolidAngle | b48fa9562776f24fc9f165b53048ff6982d9570b | c1c329cd8f0dcd97387ea962f4f00c0b67ccffdf | refs/heads/master | 2021-04-09T13:22:03.333409 | 2017-07-25T02:34:39 | 2017-07-25T02:34:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,974 | h | #pragma once
#include "CoreTypes.h"
#include "Math/NumericLimits.h"
#include "Misc/Timespan.h"
/**
* Interface for waitable events.
*
* This interface has platform-specific implementations that are used to wait for another
* thread to signal that it is ready for the waiting thread to do some work. It can also
* be used for telling groups of threads to exit.
*/
class FEvent
{
public:
/**
* Creates the event.
*
* Manually reset events stay triggered until reset.
* Named events share the same underlying event.
*
* @param bIsManualReset Whether the event requires manual reseting or not.
* @return true if the event was created, false otherwise.
*/
virtual bool Create(bool bIsManualReset = false) = 0;
/**
* Whether the signaled state of this event needs to be reset manually.
*
* @return true if the state requires manual resetting, false otherwise.
* @see Reset
*/
virtual bool IsManualReset() = 0;
/**
* Triggers the event so any waiting threads are activated.
*
* @see IsManualReset, Reset
*/
virtual void Trigger() = 0;
/**
* Resets the event to an untriggered (waitable) state.
*
* @see IsManualReset, Trigger
*/
virtual void Reset() = 0;
/**
* Waits the specified amount of time for the event to be triggered.
*
* A wait time of MAX_uint32 is treated as infinite wait.
*
* @param WaitTime The time to wait (in milliseconds).
* @param bIgnoreThreadIdleStats If true, ignores ThreadIdleStats
* @return true if the event was triggered, false if the wait timed out.
*/
virtual bool Wait(uint32 WaitTime, const bool bIgnoreThreadIdleStats = false) = 0;
/**
* Waits an infinite amount of time for the event to be triggered.
*
* @return true if the event was triggered.
*/
bool Wait()
{
return Wait(MAX_uint32);
}
/**
* Waits the specified amount of time for the event to be triggered.
*
* @param WaitTime The time to wait.
* @param bIgnoreThreadIdleStats If true, ignores ThreadIdleStats
* @return true if the event was triggered, false if the wait timed out.
*/
bool Wait(const YTimespan& WaitTime, const bool bIgnoreThreadIdleStats = false)
{
return Wait(WaitTime.GetTotalMilliseconds(), bIgnoreThreadIdleStats);
}
/** Default constructor. */
FEvent()
: EventId(0)
, EventStartCycles(0)
{}
/** Virtual destructor. */
virtual ~FEvent()
{}
// DO NOT MODIFY THESE
/** Advances stats associated with this event. Used to monitor wait->trigger history. */
void AdvanceStats();
protected:
/** Sends to the stats a special messages which encodes a wait for the event. */
void WaitForStats();
/** Send to the stats a special message which encodes a trigger for the event. */
void TriggerForStats();
/** Resets start cycles to 0. */
void ResetForStats();
/** Counter used to generate an unique id for the events. */
static uint32 EventUniqueId;
/** An unique id of this event. */
uint32 EventId;
/** Greater than 0, if the event called wait. */
uint32 EventStartCycles;
};
| [
"[email protected]"
] | |
543318a137d23b601cc9df2d62b1fce32bab2b96 | bea80db60ffab92429a371411256d5dd975a6ad0 | /stackusingqueues.cpp | e0783a87cc239ac1d41e8afa098f53fba971d8cb | [] | no_license | ananddeb23/cppsolutions | 7339efb4ccf9771cd00479dfaf04fa40583cfd3b | 93b61b4a1db2fd53d2c8e1f73c04293937e8e65e | refs/heads/master | 2021-01-01T16:27:45.165076 | 2017-07-20T13:33:04 | 2017-07-20T13:33:04 | 97,837,281 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,029 | cpp | #include<iostream>
#include<queue>
using namespace std;
queue<int> s1;
queue<int> s2;
void psh(int n){
s1.push(n);
}
void transfr1(){
if(!s1.empty()){
int t=s1.front();
s1.pop();
transfr1();
s2.push(t);
}
else{
return ;
}
}
void transfr2(){
if(!s2.empty()){
int t=s2.front();
s2.pop();
//s3.push(t);
transfr2();
transfr1();
s2.push(t);
//s3.pop();
}
else{
return;
}
}
int pop1(){
if(s1.empty()&& s2.empty()){
return -9999;// Both queue empty meaning underflow;
}
if(!s1.empty()){
if(s2.empty()){
transfr1();}
else{
transfr2();
}
}
int t=s2.front();
s2.pop();
return t;
}
int main(){
psh(1);
psh(2);
cout<<pop1()<<endl;
cout<<pop1()<<endl;
psh(3);
psh(4);
psh(5);
cout<<pop1()<<endl;
cout<<pop1()<<endl;
psh(6);
psh(7);
psh(8);
cout<<pop1()<<endl;
cout<<pop1()<<endl;
psh(61);
psh(72);
psh(83);
cout<<pop1()<<endl;
cout<<pop1()<<endl;
cout<<pop1()<<endl;
cout<<pop1()<<endl;
cout<<pop1()<<endl;
cout<<pop1()<<endl;
}
| [
"[email protected]"
] | |
d814f73792c62a010b0148ca224ef92cd729f7ad | d4d313a195839fdb360dea0d18f5432b355b8acd | /NetworkInterface.h | 6fd26523564e05a41ff7048c1748cdb58e4f04d6 | [] | no_license | nakkaya/makeWay | 6b8434e3b9804be0f5a0855ef4a714fe65cff6fd | 792fd28864f7234ebf43dc84ee2ef05ac3f6f6e9 | refs/heads/master | 2021-01-20T05:08:28.180139 | 2013-12-07T08:37:36 | 2013-12-07T08:37:36 | 210,124 | 3 | 1 | null | 2013-12-07T08:37:39 | 2009-05-26T01:01:48 | C++ | UTF-8 | C++ | false | false | 1,312 | h | // Copyright 2011 Nurullah Akkaya
// makeWay 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.
// makeWay is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
// for more details.
// You should have received a copy of the GNU General Public License
// along with makeWay. If not, see http://www.gnu.org/licenses/.
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>
#include <vector>
#include <math.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <sys/sysctl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "util.h"
#include <string.h>
#ifdef OS_DARWIN
#include <net/if_dl.h>
#include <stdlib.h>
#include <sys/sysctl.h>
#include <sys/socket.h>
#include <net/route.h>
#endif
class NetworkInterface{
private:
const char* dev;
public:
NetworkInterface(const char* dv);
std::string getLocalGateway();
std::string getLocalIP();
std::string getLocalMAC();
};
| [
"[email protected]"
] | |
7012d75a66af16b444f0b6135cd86aaf862c9102 | f5c1518f067ba1baf4168ad8cd58264cba0f4037 | /AtomTraceCL/BVHTriMesh.cpp | 3b6711d74e980e8fc9b89db88ab35b418a0439f2 | [] | no_license | owuntu/AtomTraceCL | 09893d017dc469162ad5f8978ee6e38a112e9468 | 2623de466f3759b5dbf7510c0c175a64c07ee41c | refs/heads/master | 2022-03-02T19:41:37.069458 | 2022-02-25T12:49:22 | 2022-02-25T12:49:22 | 110,912,084 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,288 | cpp | #include "TriMesh.h"
#include "BVHTriMesh.h"
namespace AtomTraceCL
{
void BVHTriMesh::SetMesh(const TriMesh *m, unsigned int maxElementsPerNode /* = CY_BVH_MAX_ELEMENT_COUNT */)
{
mesh = m;
Clear();
Build(mesh->m_faces.size(), maxElementsPerNode);
}
void BVHTriMesh::GetElementBounds(unsigned int i, float box[6]) const
{
using namespace AtomMathCL;
const TriMesh::TriFace& f = mesh->m_faces[i];
const Vector3& p = mesh->m_vertices[f.v[0]];
box[0] = box[3] = p.X();
box[1] = box[4] = p.Y();
box[2] = box[5] = p.Z();
for (int i = 1; i < 3; ++i) // for each vertex
{
const Vector3& pi = mesh->m_vertices[f.v[i]];
for (int d = 0; d < 3; ++d) // for each dimension
{
if (box[d] > pi[d]) box[d] = pi[d]; // update min
if (box[d + 3] < pi[d]) box[d + 3] = pi[d]; // update max
}
}
}
float BVHTriMesh::GetElementCenter(unsigned int i, int dim) const
{
const TriMesh::TriFace& f = mesh->m_faces[i];
const std::vector<AtomMathCL::Vector3>& v = mesh->m_vertices;
return (v[f.v[0]][dim] + v[f.v[1]][dim] + v[f.v[2]][dim]) / 3.0f;
}
} // namespace AtomTraceCL
| [
"[email protected]"
] | |
a764da78cf39ff109e82de4be45786096608b548 | 400b5408cec60d4bf3c4885220285d671d3fa0ee | /pathplan.h | 51572b9bd0c875f5dfc3c33d174156cceb15c4a9 | [] | no_license | msnh2012/OCCT_KUKAwsts | 8386af9605373bd2f46354f5abf92d8a3b038e5f | 5e385fdc718835b064715e97c6862680ac858774 | refs/heads/master | 2023-03-19T02:39:56.812872 | 2021-01-28T00:05:36 | 2021-01-28T00:05:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,252 | h | #ifndef PATHPLAN_H
#define PATHPLAN_H
#include <QObject>
#include <QVector3D>
#include "globalvar.h"
#include <QTimer>
#include "kinematics.h"
enum MOVEMENT_MODE{
COMMON_MODE,
LINE_MODE,
ARC_MODE
};
typedef struct _FiveOrderPolyCoefficients
{
float data[6];
} FiveOrderPolyCoefficients;
typedef struct _StrajectoryParameter
{
float v,a,omega;
float t1,t2,T;
float s1,s2;
}STrajectoryParameter;
typedef struct _AxisAngle
{
float axis[3];
float angle;
}AxisAngle;
typedef struct _OrientationGeometry
{
float R0[3][3];
AxisAngle AA;
}OrientationGeometry;
typedef struct _LineGeometry
{
float startpoint[3];
float direction[3];
float length;
}LineGeometry;
float polynomialvalue(const unsigned int order,const float *coefficients,const float t)
{
float value=coefficients[0];
for(unsigned int i=0;i<order;++i)
{
value=value*t+coefficients[i+1];
}
return value;
}
bool isgreaterthanzero(const float value)
{
return value>0?true:false;
}
class PathPlan:public QObject
{
Q_OBJECT
public:
PathPlan();
~PathPlan();
public slots:
void setpathpoint(QVector<QVector3D> point);
void setpathpoint(float width,float height,float length);
void setpathpoint(QVector3D start,QVector3D end);
void sendVirtualJointPosition();
private:
void getcommonmodeposition();
void atendpoint();
float cal_position(const FiveOrderPolyCoefficients *coefficients,const float t);
void calculat_next_lq_point(const LineGeometry *line,const OrientationGeometry *oritentation,const STrajectoryParameter *linetrajp,\
const float orientationtrajp[6],const float time,const float currentq[6],float result[6]);
signals:
void currentcommandsignal();
private:
QTimer* simulationTimer;
int movement_mode;
float currenttimepoint;
float speedrate;
float time_step;
float tmax;
bool isatendpoint;
unsigned int waypointsnum;
float *timepoints;
FiveOrderPolyCoefficients** allcoefficients;
QVector<float> parame;
STrajectoryParameter *linetrajp;
OrientationGeometry *orientation;
LineGeometry *line;
float orientationtrajp[6];
};
#endif // PATHPLAN_H
| [
"[email protected]"
] | |
aca6ea7b79b180d1526906aa3b9484a2ddd27d46 | e286931190b2fe2cd3b342a6359efb840d7ee025 | /11/part1.cpp | 118408246dd95238496b616410f95590a6182688 | [] | no_license | JohanSmet/aoc_2019 | 2a72ad1cec4e2888edeffb0d74df04ba55cce32e | 53d9f705f9d637e25d5a2807cbef0749dc6a2dd8 | refs/heads/master | 2021-07-10T23:13:51.585565 | 2020-12-05T14:35:22 | 2020-12-05T14:35:22 | 225,716,170 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,436 | cpp | #include <cassert>
#include <initializer_list>
#include <iostream>
#include <queue>
#include <vector>
#include <unordered_map>
using namespace std;
using base_t = int64_t;
using program_t = vector<base_t>;
class Computer {
public:
// functions
Computer(const program_t &prog) : program(prog) {
}
void add_input(initializer_list<base_t> in);
void run_until_output();
void run(vector<base_t> &output);
// data
program_t program;
base_t ip = 0; // instruction pointer
base_t bp = 0; // relative base
queue<base_t> input;
base_t output = 0;
bool finished = false;
bool error = false;
};
program_t read_program_source() {
program_t result;
base_t v;
char delim;
while (cin >> v) {
result.push_back(v);
cin >> delim;
}
return result;
}
void Computer::add_input(initializer_list<base_t> in) {
for (auto i : in) {
input.push(i);
}
}
void Computer::run_until_output() {
auto opcode = [](int v) -> int {return v % 100;};
auto check_memsize = [&](int min) {
if (program.size() <= min) {
program.resize(min + 1, 0);
}
};
auto memory_ref = [&](base_t i) -> base_t & {
assert(i >= 1 && i <= 3);
static const int factor[] = {1, 100, 1000, 10000};
auto mode = (program[ip] / factor[i]) % 10;
base_t pos = 0;
switch (mode) {
case 0 : // indirect
pos = program[ip+i];
break;
case 1 : // direct
pos = ip+i;
break;
case 2 : // relative
pos = bp+program[ip+i];
break;
default:
error = true;
finished = true;
cerr << "invalid parameter mode" << endl;
return program[0];
};
check_memsize(pos);
return program[pos];
};
auto get_data = [&](base_t i) -> base_t {
auto result = memory_ref(i);
return result;
};
auto set_data = [&](base_t i, base_t v) {
auto &ref = memory_ref(i);
ref = v;
};
while (ip < program.size()) {
switch (opcode(program[ip])) {
case 1: { // addition
auto result = get_data(1) + get_data(2);
set_data(3, result);
ip += 4;
break;
}
case 2: { // multiplication
auto result = get_data(1) * get_data(2);
set_data(3, result);
ip += 4;
break;
}
case 3: // input
set_data(1, input.front());
input.pop();
ip += 2;
break;
case 4: // output
output = get_data(1);
ip += 2;
return;
case 5: { // jump-if-true
auto cond = get_data(1);
if (cond != 0) {
ip = get_data(2);
} else {
ip += 3;
}
break;
}
case 6: { // jump-if-false
auto cond = get_data(1);
if (cond == 0) {
ip = get_data(2);
} else {
ip += 3;
}
break;
}
case 7: // less than
set_data(3, get_data(1) < get_data(2) ? 1 : 0);
ip += 4;
break;
case 8: // equals
set_data(3, get_data(1) == get_data(2) ? 1 : 0);
ip += 4;
break;
case 9: // set relative base
bp += get_data(1);
ip += 2;
break;
case 99:
finished = true;
return;
default:
cerr << "Invalid opcode: " << opcode(program[ip]) << endl;
finished = true;
error = true;
return;
}
}
}
void Computer::run(vector<base_t> &out) {
if (!finished) {
run_until_output();
}
while (!finished) {
out.push_back(output);
run_until_output();
}
}
union Pos {
struct {
int32_t x;
int32_t y;
};
uint64_t key;
};
int main() {
// load program
auto program = read_program_source();
Computer comp(program);
// run
static const int move_delta[4][2] = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}};
static const int turn_delta[2] = {-1, 1};
static const int black = 0;
static const int white = 1;
int direction = 0;
Pos position = {0, 0};
unordered_map<uint64_t, int> painted_panels;
auto panel_color = [&](const Pos &pos) -> int {
auto found = painted_panels.find(pos.key);
return (found != end(painted_panels)) ? found->second : black;
};
while (!comp.finished) {
// provide current color as input
comp.add_input({panel_color(position)});
// get the color to paint this panel
comp.run_until_output();
if (comp.finished) break;
painted_panels[position.key] = comp.output;
// get the turn direction
comp.run_until_output();
if (comp.finished) break;
// turn
direction = (direction + turn_delta[comp.output] + 4) % 4;
// move
position.x += move_delta[direction][0];
position.y += move_delta[direction][1];
}
cout << "Robot painted " << painted_panels.size() << " panels." << endl;
return 0;
}
| [
"[email protected]"
] | |
71956e7a6f3253af51a4d63c0a9bac1835662e9d | 6232a242f9d08f5079bdd8b953a3406a43022908 | /mapnavi/src/mapdocument.cpp | 2a0bbad34f1fff2fc2b01f10dfd6cd5174607134 | [] | no_license | flaithbheartaigh/symbianmapnavi | f7ee81f810d1bfabd6f7d50d60e290bbb9f13816 | de3d4ec353d9bdca1833c47afef13eb5acc4e6c2 | refs/heads/master | 2021-01-10T11:29:49.395196 | 2009-02-21T18:45:33 | 2009-02-21T18:45:33 | 50,259,266 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,442 | cpp | // INCLUDE FILES
#include "MapAppUi.h"
#include "MapDocument.h"
// ============================ MEMBER FUNCTIONS ===============================
// -----------------------------------------------------------------------------
// CMapDocument::NewL()
// Two-phased constructor.
// -----------------------------------------------------------------------------
//
CMapDocument* CMapDocument::NewL( CEikApplication& aApp )
{
CMapDocument* self = NewLC( aApp );
CleanupStack::Pop( self );
return self;
}
// -----------------------------------------------------------------------------
// CMapDocument::NewLC()
// Two-phased constructor.
// -----------------------------------------------------------------------------
//
CMapDocument* CMapDocument::NewLC( CEikApplication& aApp )
{
CMapDocument* self =
new ( ELeave ) CMapDocument( aApp );
CleanupStack::PushL( self );
self->ConstructL();
return self;
}
// -----------------------------------------------------------------------------
// CMapDocument::ConstructL()
// Symbian 2nd phase constructor can leave.
// -----------------------------------------------------------------------------
//
void CMapDocument::ConstructL()
{
// No implementation required
}
// -----------------------------------------------------------------------------
// CMapDocument::CMapDocument()
// C++ default constructor can NOT contain any code, that might leave.
// -----------------------------------------------------------------------------
//
CMapDocument::CMapDocument( CEikApplication& aApp )
: CAknDocument( aApp )
{
// No implementation required
}
// ---------------------------------------------------------------------------
// CMapDocument::~CMapDocument()
// Destructor.
// ---------------------------------------------------------------------------
//
CMapDocument::~CMapDocument()
{
// No implementation required
}
// ---------------------------------------------------------------------------
// CMapDocument::CreateAppUiL()
// Constructs CreateAppUi.
// ---------------------------------------------------------------------------
//
CEikAppUi* CMapDocument::CreateAppUiL()
{
// Create the application user interface, and return a pointer to it;
// the framework takes ownership of this object
return ( static_cast <CEikAppUi*> ( new ( ELeave )
CMapAppUi ) );
}
// End of File
| [
"gzhangsymbian@4f307c46-000b-11de-88c7-29a3b14d5316"
] | gzhangsymbian@4f307c46-000b-11de-88c7-29a3b14d5316 |
b70c254f1a164504f164623cd5acf47a5924be8e | bb7645bab64acc5bc93429a6cdf43e1638237980 | /Official Windows Platform Sample/Windows 8 app samples/[C++]-Windows 8 app samples/C++/Windows 8 app samples/Hilo C++ sample (Windows 8)/C++/Hilo/IPhoto.h | ba761d2ba8086260a0ce3f6efb402786acdcb3d2 | [
"MIT"
] | permissive | Violet26/msdn-code-gallery-microsoft | 3b1d9cfb494dc06b0bd3d509b6b4762eae2e2312 | df0f5129fa839a6de8f0f7f7397a8b290c60ffbb | refs/heads/master | 2020-12-02T02:00:48.716941 | 2020-01-05T22:39:02 | 2020-01-05T22:39:02 | 230,851,047 | 1 | 0 | MIT | 2019-12-30T05:06:00 | 2019-12-30T05:05:59 | null | UTF-8 | C++ | false | false | 2,234 | h | // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved
#pragma once
namespace Hilo
{
interface class IPhotoGroup;
// The IPhoto class defines the signature of data used by XAML image controls.
[Windows::Foundation::Metadata::WebHostHidden]
public interface class IPhoto
{
property IPhotoGroup^ Group
{
IPhotoGroup^ get();
}
property Platform::String^ Name { Platform::String^ get(); }
property Platform::String^ Path
{
Platform::String^ get();
}
property Platform::String^ FormattedPath
{
Platform::String^ get();
}
property Platform::String^ FileType
{
Platform::String^ get();
}
property Windows::Foundation::DateTime DateTaken
{
Windows::Foundation::DateTime get();
}
property Platform::String^ FormattedDateTaken
{
Platform::String^ get();
}
property Platform::String^ FormattedTimeTaken
{
Platform::String^ get();
}
property Platform::String^ Resolution
{
Platform::String^ get();
}
property uint64 FileSize
{
uint64 get();
}
property Platform::String^ DisplayType
{
Platform::String^ get();
}
property Windows::UI::Xaml::Media::Imaging::BitmapImage^ Thumbnail
{
Windows::UI::Xaml::Media::Imaging::BitmapImage^ get();
}
property Windows::UI::Xaml::Media::Imaging::BitmapImage^ Image
{
Windows::UI::Xaml::Media::Imaging::BitmapImage^ get();
}
property bool IsInvalidThumbnail
{
bool get();
}
void ClearImageData();
Windows::Foundation::IAsyncOperation<Windows::Storage::Streams::IRandomAccessStreamWithContentType^>^ OpenReadAsync();
};
} | [
"[email protected]"
] | |
4d400da382a74ec92bcd26e052cfdb7cefedebf6 | bd18edfafeec1470d9776f5a696780cbd8c2e978 | /SlimDX/source/directinput/PeriodicForce.cpp | a94cd1f6b0e4c64b45f17ce2edaab94ca3a21f03 | [
"MIT"
] | permissive | MogreBindings/EngineDeps | 1e37db6cd2aad791dfbdfec452111c860f635349 | 7d1b8ecaa2cbd8e8e21ec47b3ce3a5ab979bdde7 | refs/heads/master | 2023-03-30T00:45:53.489795 | 2020-06-30T10:48:12 | 2020-06-30T10:48:12 | 276,069,149 | 0 | 1 | null | 2021-04-05T16:05:53 | 2020-06-30T10:33:46 | C++ | UTF-8 | C++ | false | false | 2,536 | cpp | /*
* Copyright (c) 2007-2010 SlimDX Group
*
* 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 "stdafx.h"
#include <dinput.h>
#include "PeriodicForce.h"
using namespace System;
namespace SlimDX
{
namespace DirectInput
{
PeriodicForce::PeriodicForce()
{
}
PeriodicForce^ PeriodicForce::FromData( void *data, int size )
{
if( size != sizeof( DIPERIODIC ) )
return nullptr;
PeriodicForce^ force = gcnew PeriodicForce();
DIPERIODIC *ptr = reinterpret_cast<DIPERIODIC*>( data );
force->Magnitude = ptr->dwMagnitude;
force->Offset = ptr->lOffset;
force->Phase = ptr->dwPhase;
force->Period = ptr->dwPeriod;
return force;
}
int PeriodicForce::Size::get()
{
return sizeof( DIPERIODIC );
}
void *PeriodicForce::ToUnmanaged()
{
// Manual Allocation: released in Release function
DIPERIODIC *result = new DIPERIODIC();
result->dwMagnitude = Magnitude;
result->dwPeriod = Period;
result->dwPhase = Phase;
result->lOffset = Offset;
return result;
}
void PeriodicForce::Release( void* data )
{
delete data;
}
ConstantForce^ PeriodicForce::AsConstantForce()
{
return nullptr;
}
CustomForce^ PeriodicForce::AsCustomForce()
{
return nullptr;
}
PeriodicForce^ PeriodicForce::AsPeriodicForce()
{
return this;
}
RampForce^ PeriodicForce::AsRampForce()
{
return nullptr;
}
ConditionSet^ PeriodicForce::AsConditionSet()
{
return nullptr;
}
}
} | [
"Michael@localhost"
] | Michael@localhost |
a4a7356facbcaf42485c7fb4e4a1b1032d81d9d2 | cead62b219e80196b8fadab134169b649fce5ca7 | /cpp/CompositeOperation.cpp | ef4cf3f4dafcae67e5f27c2764fb0ca63d78dd3f | [] | no_license | samoluka/Projekat-fotoedit | fc74e599db8155378ac53d549ac61be60a764b15 | cf55121585f5a947564706d6b8ec337918458721 | refs/heads/master | 2022-11-16T05:05:29.560668 | 2020-07-01T15:19:21 | 2020-07-01T15:19:21 | 260,755,582 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,100 | cpp | #include "CompositeOperation.h"
#include <regex>
#include <fstream>
#include <vector>
std::map<std::string, Operation*> CompositeOperation::getOperation = {
{"plus",new OperationPlus()},{"minus",new OperationMinus()},{"iminus",new OperationMinusInvers()}
,{"mul",new OperationMul()},{"div",new OperationDiv()},{"idiv",new OperationDivInvers()},
{"pow",new OperationPower()},{"log",new OperationLogarithm()},{"min",new OperationMin()},{"max",new OperationMax()},
{"invers",new OperationInvers()},{"greyscale",new OperationGreyScale()},{"blackwhite",new OperationBlackWhite()},
{"<>",new CompositeOperation()},{"setA",new OperationSetAlpha()}
};
/*
Izgled fajla:
kod_Operacije (proizvoljno razmaka) operand(*ako je potrebno);
....
" Putanja do druge kompozitne operacije"
...
...
END
*/
CompositeOperation::CompositeOperation(const std::string file){
std::ifstream f(file);
if (!f) {
std::cout << "Nema fajla " + file + "\n";
return;
}
Operation* o;
std::string op;
std::string line;
std::smatch res;
std::regex opt1("([a-z]+)[ ]*([0-9.]*);.*");
std::regex opt2("<(.*)>;.*");
std::getline(f, line);
while (line!="END") {
if (line[0] == '\\' && line[1] == '\\') {
std::getline(f, line);
continue;
}
if (line[0] != '<') {
std::regex_match(line, res, opt1);
o = getOperation[res[1]];
if (!o) {
std::getline(f, line);
continue;
}
if (o->GetNumOfOperand()) {
if (res[2] == "") throw GCompose_Operation_Fail();
operand.push_back(o->GetParam(res[2]).getRef());
}
F.push_back(o);
}
else {
std::regex_match(line, res, opt2);
o = new CompositeOperation(res[1]);
F.push_back(o);
}
std::getline(f, line);
}
f.close();
}
int CompositeOperation::GetNumOfOperand() const{
return 0;
}
IntPixel & CompositeOperation::operator()(IntPixel & p, void *) {
Operation* o;
void* v;
auto x = operand.begin();
for (auto& o : F) {
v = nullptr;
if (o->GetNumOfOperand()) {
v = *x++;
}
o->operator()(p, v);
}
return p;
}
ParamNull& CompositeOperation::GetParam(const std::string&)const { return *new ParamNull(); } | [
"[email protected]"
] | |
c1a39fbb173183500676c10f264831994be3f41f | 8a0546301a42c00850314965612c2dffaee8884f | /include/GameAudio.h | 0c20220132660203a6c47dd8efc14ef7660a78a4 | [] | no_license | bagidea/SampleGameEngine | 32b12616b47f2f55dfe81e4a7414938d3ec349bf | 384908408b712903a9c379bc8fb12ca9c794db9b | refs/heads/master | 2021-01-17T18:29:41.627378 | 2015-07-06T03:43:36 | 2015-07-06T03:43:36 | 37,573,367 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 498 | h | #ifndef GAMEAUDIO_INCLUDE_H
#define GAMEAUDIO_INCLUDE_H
#include <iostream>
#include <string>
#include <SDL.h>
#include <SDL_mixer.h>
using namespace std;
//AudioBackground
class AudioBackground
{
public:
AudioBackground();
~AudioBackground();
bool Load(string path);
void Play();
void Pause();
void Stop();
private:
Mix_Music* audio;
};
//AudioClip
class AudioClip
{
public:
AudioClip();
~AudioClip();
bool Load(string path);
void Play();
private:
Mix_Chunk* audio;
};
#endif | [
"[email protected]"
] | |
2305639a72fbbc29ab49e27b49de3ab2e7756eb6 | a83983e32ff37d22435e2d4d032b7941c7d801b0 | /suma de Digitos de un Numero.cpp | df9ee23dd2c1a80b4701e11fc16528284b6b7df4 | [] | no_license | Hidel57/Programacion-basica | 5b6ce21e4c10b5472e386e5f76c11fdd1d07bbb7 | c45b5523dbac0771f162194eec6e7344952583e3 | refs/heads/master | 2023-04-14T07:18:34.829415 | 2021-04-19T18:09:19 | 2021-04-19T18:09:19 | 135,869,618 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 474 | cpp | /*
Suma de digitos de un numero
*/
#include <iostream>
using namespace std;
int n,c,ct,sum;
int leer()
{
cout<<"introducir numero largo: ";
cin>>n;
return n;
}
int serie(int c,int n)
{
c=n%10;
n=n/10;
if(n==0)
{
cout<<c<<" = ";
return c;
}
else
{
cout<<c<<" + ";
return(c+serie(c,n));
}
}
void imprimir(int sum)
{
cout<<"\nla suma de digitos es: "<<sum;
}
int main(int argc, char *argv[])
{
n=leer();
sum=serie(c,n);
imprimir(sum);
return 0;
}
| [
"[email protected]"
] | |
3209b7600e7aaf4246348337466edbfa69a53655 | f4b4cdaa458248f15278a2bc88f1b764a56b118b | /AssoRule.cpp | 90197457c1c65be2082aa0c1dd3512a7efd627b2 | [] | no_license | gsm1011/data-mining-algorithms | d8c94dd32694e12583e79e3e297ea2a6e0ad4bcb | 3bddfd8fec6061040b7824acb55f1c6d8735cfce | refs/heads/master | 2020-05-16T20:46:21.984802 | 2015-03-16T15:11:47 | 2015-03-16T15:11:47 | 32,333,238 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 746 | cpp | #include "AssoRule.h"
// Constructor.
AssoRule::AssoRule(Itemset an, Itemset co, float sptxy, float sptx)
:ante(an),cons(co),suptxy(sptxy),suptx(sptx) {}
bool AssoRule::operator<(const AssoRule& rule) const {
return getSupXY() * getConf() < rule.getSupXY() * rule.getConf();
}
bool operator>(const AssoRule& rule1, const AssoRule& rule2){
return rule1.getSupXY() * rule1.getConf() >
rule2.getSupXY() * rule2.getConf();
}
// output the Association rule.
ostream& operator<<(ostream& out, AssoRule& rule) {
out << rule.getAnte() << "-->" << rule.getCons()
<< " " << rule.getSupXY()
<< " " << rule.getSupX()
<< " " << rule.getConf()
<< " " << rule.getSupXY() * rule.getConf()
<< endl;
return out;
}
| [
"gsmsteve@bd8dc0af-94fc-5d16-9929-21567a77942c"
] | gsmsteve@bd8dc0af-94fc-5d16-9929-21567a77942c |
137a3eddea70b2ddb3dfc0ff6774066148fc3a20 | d85b246096c9eb6177d8964efa4e9223b0d30d62 | /src/random.cc | fe0b1ff70aa19e9298da8b21d4335c9801594c7a | [] | no_license | alibenD/vslam_tutorial | a61c6e5c1a9a3fa7cf2edff14bec72522c67c271 | 5e497481446586fa14d3faa06ac0125955b35b37 | refs/heads/master | 2020-06-26T21:30:00.633830 | 2019-08-15T07:05:57 | 2019-08-15T07:05:57 | 199,762,779 | 1 | 0 | null | 2019-08-15T07:05:58 | 2019-07-31T02:28:33 | C | UTF-8 | C++ | false | false | 504 | cc | /**
* @Copyright (C) 2019 All rights reserved.
* @date: 2019
* @file: random.cc
* @version: v0.0.1
* @author: [email protected]
* @create_date: 2019-02-03 10:38:36
* @last_modified_date: 2019-02-03 11:31:24
* @brief: TODO
* @details: TODO
*/
//INCLUDE
#include <visual_slam/utils/random.hh>
//CODE
void setRandomSeed(int seed)
{
srand(seed);
}
int randomInt(int min, int max)
{
int d = max - min + 1;
return int(((double)rand()/((double)RAND_MAX + 1.0)) * d) + min;
}
| [
"[email protected]"
] | |
2408f3ad17f164e630a1f5e3a589e45c46ed3632 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5634697451274240_1/C++/KevinLiu/pancake.cpp | a95057ad9aa302ffd0176a56bd49039c910d6d6b | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 761 | cpp | #include <stdio.h>
#include <string>
using namespace std;
int flipPlus(string S);
int flipMinus(string S);
int flipPlus(string S)
{
if (S.find_first_of('-')==string::npos) {
return 0;
}
if (S[S.length()-1]=='+')
return flipPlus(S.substr(0, S.length()-1));
else
return flipMinus(S.substr(0, S.length()-1))+1;
}
int flipMinus(string S)
{
if (S.find_first_of('+')==string::npos) {
return 0;
}
if (S[S.length()-1]=='-')
return flipMinus(S.substr(0, S.length()-1));
else
return flipPlus(S.substr(0, S.length()-1))+1;
}
int main()
{
int T;
scanf("%d", &T);
for (int i=0;i<T;i++) {
char line[1000];
scanf("%s", line);
printf("Case #%d: %d\n", i+1, flipPlus(string(line)));
}
return 0;
}
| [
"[email protected]"
] | |
cf42c08190f65830c682fae9933bc752d6007577 | 43a2fbc77f5cea2487c05c7679a30e15db9a3a50 | /Cpp/External (Offsets Only)/SDK/BP_hair_col_red_05_under_Desc_functions.cpp | 21e27a543099d38f251428ced1e3108024f5f3ee | [] | no_license | zH4x/SoT-Insider-SDK | 57e2e05ede34ca1fd90fc5904cf7a79f0259085c | 6bff738a1b701c34656546e333b7e59c98c63ad7 | refs/heads/main | 2023-06-09T23:10:32.929216 | 2021-07-07T01:34:27 | 2021-07-07T01:34:27 | 383,638,719 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 583 | cpp | // Name: SoT-Insider, Version: 1.102.2382.0
#include "../pch.h"
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
void UBP_hair_col_red_05_under_Desc_C::AfterRead()
{
UClothingDesc::AfterRead();
}
void UBP_hair_col_red_05_under_Desc_C::BeforeDelete()
{
UClothingDesc::BeforeDelete();
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
32055a886851651592083946cf7e8b62fa01489a | fc347406b479605236f5d49a13ab27a922e7f3e9 | /Easy/0415-add-strings.cpp | 95e26ef016ca60c80b0346eb012e47454e143310 | [
"MIT"
] | permissive | sandychn/LeetCode-Solutions | 0ebec09f977e15c10f3708796f63e6ef2495b50f | d0dd55d62b099c5b7db947822ab2111a4ecdc941 | refs/heads/main | 2023-08-10T22:30:21.399891 | 2021-10-07T16:31:49 | 2021-10-07T16:31:49 | 274,187,518 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 526 | cpp | class Solution {
public:
string addStrings(string num1, string num2) {
string res;
int carry = 0;
for (int p = (int)num1.size() - 1, q = (int)num2.size() - 1; p >= 0 || q >= 0; --p, --q) {
int now = carry;
now += (p >= 0 ? num1[p] - '0' : 0) + (q >= 0 ? num2[q] - '0' : 0);
carry = now / 10;
res.push_back(now % 10 + '0');
}
if (carry) res.push_back(carry + '0');
reverse(res.begin(), res.end());
return res;
}
};
| [
"[email protected]"
] | |
5053a1f0ef253fbe12a868998c0536995aeb6197 | 93a89acb8dfc02de05837556132b27628abde83c | /vpu-hal2/dl/inference-engine/src/mkldnn_plugin/config.cpp | 35de626b44d59318388aa9bb821750f039c801b7 | [
"Intel",
"Apache-2.0"
] | permissive | leon1205/nn-hal | ef1b8c3fd5b2e0cbc96df44cb6206b7917c59d53 | f6c23e001c690cb32ce8392825e000ae631cf5fc | refs/heads/master | 2020-03-24T10:03:32.377936 | 2018-07-06T15:45:19 | 2018-07-06T15:45:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,737 | cpp | //
// INTEL CONFIDENTIAL
// Copyright 2016 Intel Corporation.
//
// The source code contained or described herein and all documents
// related to the source code ("Material") are owned by Intel Corporation
// or its suppliers or licensors. Title to the Material remains with
// Intel Corporation or its suppliers and licensors. The Material may
// contain trade secrets and proprietary and confidential information
// of Intel Corporation and its suppliers and licensors, and is protected
// by worldwide copyright and trade secret laws and treaty provisions.
// No part of the Material may be used, copied, reproduced, modified,
// published, uploaded, posted, transmitted, distributed, or disclosed
// in any way without Intel's prior express written permission.
//
// No license under any patent, copyright, trade secret or other
// intellectual property right is granted to or conferred upon you by
// disclosure or delivery of the Materials, either expressly, by implication,
// inducement, estoppel or otherwise. Any license under such intellectual
// property rights must be express and approved by Intel in writing.
//
// Include any supplier copyright notices as supplier requires Intel to use.
//
// Include supplier trademarks or logos as supplier requires Intel to use,
// preceded by an asterisk. An asterisked footnote can be added as follows:
// *Third Party trademarks are the property of their respective owners.
//
// Unless otherwise agreed by Intel in writing, you may not remove or alter
// this notice or any other notice embedded in Materials by Intel or Intel's
// suppliers or licensors in any way.
//
#include "config.h"
#include "ie_plugin_config.hpp"
#include "ie_common.h"
#include <string>
#include <map>
#include <algorithm>
#include <cpp_interfaces/exception2status.hpp>
namespace MKLDNNPlugin {
using namespace InferenceEngine;
void Config::readProperties(const std::map<std::string, std::string> &prop) {
for (auto& kvp : prop) {
std::string key = kvp.first;
std::string val = kvp.second;
if (key == PluginConfigParams::KEY_CPU_BIND_THREAD) {
if (val == PluginConfigParams::YES) useThreadBinding = true;
else if (val == PluginConfigParams::NO) useThreadBinding = false;
else
THROW_IE_EXCEPTION << "Wrong value for property key " << PluginConfigParams::KEY_CPU_BIND_THREAD
<< ". Expected only YES/NO";
} else if (key == PluginConfigParams::KEY_DYN_BATCH_LIMIT) {
int val_i = std::stoi(val);
// zero and any negative value will be treated
// as default batch size
batchLimit = std::max(val_i, 0);
} else if (key == PluginConfigParams::KEY_PERF_COUNT) {
if (val == PluginConfigParams::YES) collectPerfCounters = true;
else if (val == PluginConfigParams::NO) collectPerfCounters = false;
else
THROW_IE_EXCEPTION << "Wrong value for property key " << PluginConfigParams::KEY_PERF_COUNT
<< ". Expected only YES/NO";
} else if (key == PluginConfigParams::KEY_EXCLUSIVE_ASYNC_REQUESTS) {
if (val == PluginConfigParams::YES) exclusiveAsyncRequests = true;
else if (val == PluginConfigParams::NO) exclusiveAsyncRequests = false;
else
THROW_IE_EXCEPTION << "Wrong value for property key " << PluginConfigParams::KEY_EXCLUSIVE_ASYNC_REQUESTS
<< ". Expected only YES/NO";
} else {
THROW_IE_EXCEPTION << NOT_FOUND_str << "Unsupported property key [" << key << "] by CPU plugin";
}
}
}
} // namespace MKLDNNPlugin
| [
"[email protected]"
] | |
49501c74853d0e6d1dabd589e3dbcafbba91730f | ff15e11d8acd817a6bb69cdb5df55a22f3eb5d9e | /Source/BattleTank/Private/TankMovementComponent.cpp | 01be03e3279e5c5030bb2e56c59b8da4c47c3f5b | [] | no_license | teobaranga/BattleTank | 4ea15082290ed729c9b6562562c08a213d491b6f | 778bfe1c0a87df8097874cccb642420a186177f3 | refs/heads/master | 2021-03-16T07:37:36.091237 | 2019-02-23T03:14:16 | 2019-02-23T03:14:16 | 115,683,808 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,476 | cpp | // Copyright (c) 2018 Teo Baranga
#include "TankMovementComponent.h"
#include "Components/StaticMeshComponent.h"
#include "Engine/World.h"
#include "GameFramework/Actor.h"
const FName UTankMovementComponent::TrackForceSocketName = FName("Force");
void UTankMovementComponent::Initialize(UStaticMeshComponent* Tank,
UStaticMeshComponent* LeftTrack, UStaticMeshComponent* RightTrack)
{
this->Tank = Tank;
this->LeftTrack = LeftTrack;
this->RightTrack = RightTrack;
if (!Tank || !LeftTrack || !RightTrack)
{
UE_LOG(LogTemp, Error, TEXT("Missing tank or tracks, movement component will not work"));
return;
}
this->LeftTrack->OnComponentHit.AddDynamic(this, &UTankMovementComponent::OnHit);
this->RightTrack->OnComponentHit.AddDynamic(this, &UTankMovementComponent::OnHit);
}
void UTankMovementComponent::MoveForwardIntent(float Throw)
{
CurrentThrottle = FMath::Clamp(Throw, -1.f, 1.f);
}
void UTankMovementComponent::TurnRightIntent(float Throw)
{
if (!Tank || !LeftTrack || !RightTrack)
{
UE_LOG(LogTemp, Error, TEXT("Missing tank or tracks, cannot turn"));
return;
}
FVector ForceApplied = LeftTrack->GetRightVector() * Throw * MaxDrivingForce;
FVector ForceLocation = LeftTrack->GetSocketLocation(TrackForceSocketName);
Tank->AddForceAtLocation(ForceApplied, ForceLocation);
ForceApplied = RightTrack->GetRightVector() * -Throw * MaxDrivingForce;
ForceLocation = RightTrack->GetSocketLocation(TrackForceSocketName);
Tank->AddForceAtLocation(ForceApplied, ForceLocation);
}
void UTankMovementComponent::RequestDirectMove(const FVector& MoveVelocity, bool bForceMaxSpeed)
{
FVector TankForward = GetOwner()->GetActorRightVector().GetSafeNormal();
FVector TankMoveDirection = MoveVelocity.GetSafeNormal();
/// Move forward towards the player
MoveForwardIntent(FVector::DotProduct(TankForward, TankMoveDirection));
/// Rotate towards the player
TurnRightIntent(FVector::CrossProduct(TankForward, TankMoveDirection).Z);
}
void UTankMovementComponent::DriveTracks()
{
if (!Tank || !LeftTrack || !RightTrack)
{
UE_LOG(LogTemp, Error, TEXT("Missing tank or tracks, cannot move forward"));
return;
}
/// Forwards force
FVector ForceApplied = Tank->GetRightVector() * CurrentThrottle * MaxDrivingForce;
FVector ForceLocation = LeftTrack->GetSocketLocation(TrackForceSocketName);
Tank->AddForceAtLocation(ForceApplied, ForceLocation);
ForceLocation = RightTrack->GetSocketLocation(TrackForceSocketName);
Tank->AddForceAtLocation(ForceApplied, ForceLocation);
}
void UTankMovementComponent::ApplySidewaysForce()
{
// Compute the velocity sideways
float SlipVelocity = FVector::DotProduct(Tank->GetComponentVelocity(), Tank->GetForwardVector());
float DeltaTime = GetWorld()->GetDeltaSeconds();
FVector CorrectionAcceleration = -SlipVelocity / DeltaTime * Tank->GetForwardVector();
FVector CorrectionForce = Tank->GetMass() * CorrectionAcceleration;
Tank->AddForce(CorrectionForce);
}
void UTankMovementComponent::OnHit(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherComponent, FVector NormalImpulse, const FHitResult& Hit)
{
// Drive the tracks
DriveTracks();
// Apply the correction sideways force
ApplySidewaysForce();
// Reset throttle
CurrentThrottle = 0.f;
}
| [
"[email protected]"
] | |
b3e5d1735c076eff5d88af6eb0c1d1e6bf8123c9 | 8f84b92a84c5a2f5a640ca0a7cbba3cfa957154d | /mediatek/frameworks-ext/av/media/libstagefright/LivePhotoSource.cpp | 13bc61e1592690e410e973c555a6c7a65fe506f9 | [] | no_license | Al3XKOoL/MT65x2_kernel_lk | c7a23c2d41fb4c593d1bb9054a15d3b51ffaa224 | 51fe3f27e90e42dbdebae928e6b787f82bee4ddc | refs/heads/master | 2021-01-18T10:25:35.483668 | 2015-03-25T07:17:37 | 2015-03-25T07:17:37 | 32,857,246 | 0 | 4 | null | 2015-03-25T10:16:26 | 2015-03-25T10:16:26 | null | UTF-8 | C++ | false | false | 10,827 | cpp |
#define LOG_TAG "LivePhotoSource"
#include <utils/Log.h>
#include <cutils/xlog.h>
#include <linux/rtpm_prio.h>
#include <sys/prctl.h>
#include <media/stagefright/foundation/ADebug.h>
#include <media/stagefright/MetaData.h>
#include <media/stagefright/OMXCodec.h>
#include <LivePhotoSource.h>
#define ALOGV(fmt, arg...) XLOGV("[%s] "fmt, __FUNCTION__, ##arg)
#define ALOGD(fmt, arg...) XLOGD("[%s] "fmt, __FUNCTION__, ##arg)
#define ALOGI(fmt, arg...) XLOGI("[%s] "fmt, __FUNCTION__, ##arg)
#define ALOGW(fmt, arg...) XLOGW("[%s] "fmt, __FUNCTION__, ##arg)
#define ALOGE(fmt, arg...) XLOGE("[%s] "fmt, __FUNCTION__, ##arg)
#define DEFAULT_KEEP_TIMEUS 3000000 // 3S
namespace android {
/******************************************************************************
*
*******************************************************************************/
LivePhotoSource::LivePhotoSource(const sp<MediaSource> &source)
:mSource(source)
,mKeepTimeUs(DEFAULT_KEEP_TIMEUS)
,mCodecConfigBuffer(NULL)
,mMediaBufferPool() // Sample data
,mSourceStarted(false)
,mLivePhotoStarted(false)
,mLock()
,mFrameAvailableCond()
,mWriterReadEndCond()
,mThreadExitCond()
,mIsThreadExit(false)
{
}
/******************************************************************************
*
*******************************************************************************/
LivePhotoSource::~LivePhotoSource() {
ALOGD("+");
stop();
if(mSource != NULL)
mSource.clear();
if(mCodecConfigBuffer != NULL) {
mCodecConfigBuffer->release();
mCodecConfigBuffer = NULL;
}
while (!mMediaBufferPool.empty()) {
List<MediaBuffer*>::iterator it = mMediaBufferPool.begin();
(*it)->release();
(*it) = NULL;
mMediaBufferPool.erase(it);
}
mMediaBufferPool.clear();
ALOGD("-");
}
/******************************************************************************
*
*******************************************************************************/
status_t LivePhotoSource::start(MetaData *params) {
ALOGD("+");
Mutex::Autolock _lock(mLock);
if(mSource == NULL) {
ALOGE("Failed: mSource is NULL");
return UNKNOWN_ERROR;
}
status_t err = mSource->start(params);
if (err != OK) {
ALOGE("Failed: source start err(%d)", err);
return err;
}
mSourceStarted = true;
run();
ALOGD("-");
return err;
}
/******************************************************************************
*
*******************************************************************************/
status_t LivePhotoSource::stop()
{
ALOGD("+");
bool bStopSource = false;
{
Mutex::Autolock _lock(mLock);
if(mSourceStarted && !mLivePhotoStarted) {
bStopSource = true;
mSourceStarted = false;
ALOGD("signal to stop writer read");
mFrameAvailableCond.signal();
//mWriterReadEndCond.wait(mLock);
}
else if(mLivePhotoStarted) {
ALOGD("wait writer read end");
mWriterReadEndCond.wait(mLock);
}
}
status_t err = OK;
if(bStopSource) {
{
Mutex::Autolock _lock(mLock);
if(mIsThreadExit) {
ALOGD("thread exited, no need wait");
}
else {
ALOGD("wait thread exit");
mThreadExitCond.wait(mLock);
}
}
requestExit();
requestExitAndWait();
if(mSource != NULL) {
ALOGD("mSource stop()");
err = mSource->stop();
}
}
ALOGD("-");
return err;
}
/******************************************************************************
*
*******************************************************************************/
status_t LivePhotoSource::read(MediaBuffer **buffer, const ReadOptions *options) {
ALOGD("+");
*buffer = NULL;
if(options != NULL) {
ALOGE("Failed: LivePhotoSource dose not support read options");
return ERROR_UNSUPPORTED;
}
{
Mutex::Autolock _lock(mLock);
if( (mSourceStarted && !mLivePhotoStarted) || (mSourceStarted && mLivePhotoStarted && (mMediaBufferPool.empty() && mCodecConfigBuffer==NULL))) {
status_t status = mFrameAvailableCond.wait(mLock);
if ( NO_ERROR != status ) {
ALOGE("wait status(%d) err", status);
return UNKNOWN_ERROR;
}
}
if(mLivePhotoStarted && (mMediaBufferPool.empty() && mCodecConfigBuffer==NULL))
mLivePhotoStarted = false;
if( !mSourceStarted && !mLivePhotoStarted ) {
mWriterReadEndCond.signal();
ALOGD("- Live photo stoped, return ERROR_END_OF_STREAM");
return ERROR_END_OF_STREAM;
}
if( mCodecConfigBuffer != NULL) {
ALOGD("codec config buffer");
*buffer = mCodecConfigBuffer;
mCodecConfigBuffer = NULL;
}
else if(!(mMediaBufferPool.empty())) {
List<MediaBuffer *>::iterator it = mMediaBufferPool.begin();
*buffer = (*it);
mMediaBufferPool.erase(it);
}
ALOGD("-");
return OK;
}
}
/******************************************************************************
*
*******************************************************************************/
sp<MetaData> LivePhotoSource::getFormat() {
if(mSource == NULL) {
ALOGE("Failed: mSource is NULL");
return NULL;
}
return mSource->getFormat();
}
status_t LivePhotoSource::startLivePhoto() {
ALOGD("+");
bool bStopSource = false;
{
Mutex::Autolock _lock(mLock);
if(mSourceStarted && !mLivePhotoStarted) {
bStopSource = true;
mLivePhotoStarted = true;
//mSourceStarted = false; // move before source stop()??
ALOGD("wait read source end");
}
else if(mLivePhotoStarted) {
ALOGD("live photo has been started");
return OK;
}
else
return UNKNOWN_ERROR;
}
status_t err = OK;
if(bStopSource) {
{
Mutex::Autolock _lock(mLock);
ALOGD("wait thread exit");
mThreadExitCond.wait(mLock);
}
requestExit();
requestExitAndWait();
if(mSource != NULL) {
ALOGD("mSource stop()");
err = mSource->stop();
}
}
ALOGD("-");
return err;
}
/******************************************************************************
*
*******************************************************************************/
void LivePhotoSource::setLPKeepTimeUs(int64_t timeUs) {
ALOGD("%lldus +", timeUs);
Mutex::Autolock _lock(mLock);
if(!mLivePhotoStarted) {
ALOGD("real set keep time: %lldus", timeUs);
mKeepTimeUs = timeUs;
updateBufferPool(); // how to update the lastext time -1??
}
ALOGD("-");
}
/******************************************************************************
*
*******************************************************************************/
void LivePhotoSource::updateBufferPool()
{ // must be protected by mLock
ALOGD("+");
if(!mMediaBufferPool.empty())
{ // only check mStarted
List<MediaBuffer *>::iterator newBegin = mMediaBufferPool.begin();
int64_t timestampUs;
int64_t latestTimestampUs;
List<MediaBuffer *>::iterator latest = mMediaBufferPool.end(); // this will be null, there alse need a wait
latest--;
CHECK((*latest)->meta_data()->findInt64(kKeyTime, &latestTimestampUs));
for (List<MediaBuffer *>::iterator it = mMediaBufferPool.begin();
it != mMediaBufferPool.end(); ++it)
{
CHECK((*it)->meta_data()->findInt64(kKeyTime, ×tampUs));
ALOGI("check timestamp is %lldus, latestTimestampUs=%lld", timestampUs, latestTimestampUs);
if(latestTimestampUs - timestampUs < mKeepTimeUs)
break;
int32_t isSync = false;
(*it)->meta_data()->findInt32(kKeyIsSyncFrame, &isSync);
if(isSync)
{
newBegin = it;
}
}
for (List<MediaBuffer *>::iterator it = mMediaBufferPool.begin();
it != newBegin; )
{
(*it)->release();
(*it) = NULL;
it = mMediaBufferPool.erase(it);
}
}
ALOGD(" -");
}
/******************************************************************************
*
*******************************************************************************/
// Good place to do one-time initializations
status_t LivePhotoSource::readyToRun() {
ALOGD("+");
::prctl(PR_SET_NAME,"LivePhotoThread", 0, 0, 0);
// thread policy & priority
// Notes:
// Even if pthread_create() with SCHED_OTHER policy, a newly-created thread
// may inherit the non-SCHED_OTHER policy & priority of the thread creator.
// And thus, we must set the expected policy & priority after a thread creation.
int const policy = SCHED_RR;
int const priority = RTPM_PRIO_VIDEO_BS_BUFFER;
//
struct sched_param sched_p;
::sched_getparam(0, &sched_p);
//
// set
sched_p.sched_priority = priority; // Note: "priority" is real-time priority.
::sched_setscheduler(0, policy, &sched_p);
//
// get
::sched_getparam(0, &sched_p);
//
ALOGD("policy:(expect, result)=(%d, %d), priority:(expect, result)=(%d, %d) -",
policy, ::sched_getscheduler(0), priority, sched_p.sched_priority);
return NO_ERROR;
}
/******************************************************************************
*
*******************************************************************************/
bool LivePhotoSource:: threadLoop() {
ALOGD("+");
status_t err = OK;
MediaBuffer *buffer = NULL;
int32_t isSync = false;
while(mSourceStarted && !exitPending() && ((err = mSource->read(&buffer)) == OK)) {
MediaBuffer* copy = new MediaBuffer(buffer->range_length(), buffer->meta_data());
memcpy( copy->data(), (uint8_t *)buffer->data() + buffer->range_offset(), buffer->range_length() );
copy->set_range(0, buffer->range_length());
int64_t latestTimestampUs;
CHECK(copy->meta_data()->findInt64(kKeyTime, &latestTimestampUs));
ALOGI("cur timestamp is %lldus", latestTimestampUs);
{
Mutex::Autolock _lock(mLock);
int32_t isCodecConfig;
if(copy->meta_data()->findInt32(kKeyIsCodecConfig, &isCodecConfig) && isCodecConfig ) {
if(mCodecConfigBuffer != NULL) {
mCodecConfigBuffer->release();
mCodecConfigBuffer = NULL;
}
ALOGD("keep codec config buffer");
mCodecConfigBuffer = copy;
}
else {
mMediaBufferPool.push_back(copy);
if(mLivePhotoStarted) {
mFrameAvailableCond.signal();
copy->meta_data()->findInt32(kKeyIsSyncFrame, &isSync);
if (!isSync) {
if (reinterpret_cast<OMXCodec *>(mSource.get())->
vEncSetForceIframe(true) != OK)
ALOGW("Send force I cmd fail");
}
else {
mSourceStarted = false;
buffer->release();
buffer = NULL;
break; //
}
}
else {
updateBufferPool();
}
}
}
buffer->release();
buffer = NULL;
}
{
Mutex::Autolock _lock(mLock);
if(err != OK) {
ALOGE("read source err(%d) . this is a bad livephoto", err);
}
if(mSourceStarted && mLivePhotoStarted) {
mLivePhotoStarted = false;
mSourceStarted = false;
ALOGE("there is an error with exiting while when livephoto started");
mFrameAvailableCond.signal();
}
ALOGD("Thread exit signal");
mThreadExitCond.signal();
mIsThreadExit = true;
}
ALOGD("-");
return false;
}
}
| [
"[email protected]"
] | |
63badd51460eec0d351531e779551369e691cdfb | 287072b999b3221210071237b1d67d02855cdae5 | /Lab_2/src_A/pipeline.cpp | 43884afd044ce9ba82ffdd65e959e4faa80e0b8e | [] | no_license | bbruen3/ECE6100 | c66689bfb6f639079b45dca0b4848960150b7207 | 1dbd5308bf56615de238b303d87ccf1cf4f0a79a | refs/heads/master | 2023-08-13T18:17:37.505101 | 2021-10-07T03:59:00 | 2021-10-07T03:59:00 | 414,451,885 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31,878 | cpp | // --------------------------------------------------------------------- //
// You will need to modify this file. //
// You may add any code you need, as long as you correctly implement the //
// required pipe_cycle_*() functions already listed in this file. //
// In part B, you will also need to implement pipe_check_bpred(). //
// --------------------------------------------------------------------- //
// pipeline.cpp
// Implements functions to simulate a pipelined processor.
#include "pipeline.h"
#include <cstdlib>
#include <stdio.h>
#include <unistd.h>
#include <iostream>
/**
* Read a single trace record from the trace file and use it to populate the
* given fetch_op.
*
* You should not modify this function.
*
* @param p the pipeline whose trace file should be read
* @param fetch_op the PipelineLatch struct to populate
*/
void pipe_get_fetch_op(Pipeline *p, PipelineLatch *fetch_op)
{
TraceRec *trace_rec = &fetch_op->trace_rec;
uint8_t *trace_rec_buf = (uint8_t *)trace_rec;
size_t bytes_read_total = 0;
ssize_t bytes_read_last = 0;
size_t bytes_left = sizeof(*trace_rec);
// Read a total of sizeof(TraceRec) bytes from the trace file.
while (bytes_left > 0)
{
bytes_read_last = read(p->trace_fd, trace_rec_buf, bytes_left);
if (bytes_read_last <= 0)
{
// EOF or error
break;
}
trace_rec_buf += bytes_read_last;
bytes_read_total += bytes_read_last;
bytes_left -= bytes_read_last;
}
// Check for error conditions.
if (bytes_left > 0 || trace_rec->op_type >= NUM_OP_TYPES)
{
fetch_op->valid = false;
p->halt_op_id = p->last_op_id;
if (p->last_op_id == 0)
{
p->halt = true;
}
if (bytes_read_last == -1)
{
fprintf(stderr, "\n");
perror("Couldn't read from pipe");
return;
}
if (bytes_read_total == 0)
{
// No more trace records to read
return;
}
// Too few bytes read or invalid op_type
fprintf(stderr, "\n");
fprintf(stderr, "Error: Invalid trace file\n");
return;
}
// Got a valid trace record!
fetch_op->valid = true;
fetch_op->stall = false;
fetch_op->is_mispred_cbr = false;
fetch_op->op_id = ++p->last_op_id;
}
/**
* Allocate and initialize a new pipeline.
*
* You should not need to modify this function.
*
* @param trace_fd the file descriptor from which to read trace records
* @return a pointer to a newly allocated pipeline
*/
Pipeline *pipe_init(int trace_fd)
{
printf("\n** PIPELINE IS %d WIDE **\n\n", PIPE_WIDTH);
// Allocate pipeline.
Pipeline *p = (Pipeline *)calloc(1, sizeof(Pipeline));
// Initialize pipeline.
p->trace_fd = trace_fd;
p->halt_op_id = (uint64_t)(-1) - 3;
// Allocate and initialize a branch predictor if needed.
if (BPRED_POLICY != BPRED_PERFECT)
{
p->b_pred = new BPred(BPRED_POLICY);
}
return p;
}
/**
* Print out the state of the pipeline latches for debugging purposes.
*
* You may use this function to help debug your pipeline implementation, but
* please remove calls to this function before submitting the lab.
*
* @param p the pipeline
*/
void pipe_print_state(Pipeline *p)
{
printf("\n--------------------------------------------\n");
printf("Cycle count: %lu, retired instructions: %lu\n",
(unsigned long)p->stat_num_cycle,
(unsigned long)p->stat_retired_inst);
// Print table header
for (uint8_t latch_type = 0; latch_type < NUM_LATCH_TYPES; latch_type++)
{
switch (latch_type)
{
case IF_LATCH:
printf(" IF: ");
break;
case ID_LATCH:
printf(" ID: ");
break;
case EX_LATCH:
printf(" EX: ");
break;
case MA_LATCH:
printf(" MA: ");
break;
default:
printf(" ------ ");
}
}
printf("\n");
// Print row for each lane in pipeline width
for (uint8_t i = 0; i < PIPE_WIDTH; i++)
{
for (uint8_t latch_type = 0; latch_type < NUM_LATCH_TYPES;
latch_type++)
{
if (p->pipe_latch[latch_type][i].valid)
{
printf(" %6lu ",
(unsigned long)p->pipe_latch[latch_type][i].op_id);
}
else
{
printf(" ------ ");
}
}
printf("\n");
}
printf("\n");
}
/**
* Simulate one cycle of all stages of a pipeline.
*
* You should not need to modify this function except for debugging purposes.
* If you add code to print debug output in this function, remove it or comment
* it out before you submit the lab.
*
* @param p the pipeline to simulate
*/
void pipe_cycle(Pipeline *p)
{
p->stat_num_cycle++;
// In hardware, all pipeline stages execute in parallel, and each pipeline
// latch is populated at the start of the next clock cycle.
// In our simulator, we simulate the pipeline stages one at a time in
// reverse order, from the Write Back stage (WB) to the Fetch stage (IF).
// We do this so that each stage can read from the latch before it and
// write to the latch after it without needing to "double-buffer" the
// latches.
// Additionally, it means that earlier pipeline stages can know about
// stalls triggered in later pipeline stages in the same cycle, as would be
// the case with hardware stall signals asserted by combinational logic.
//std::cout << "BEGIN" << std::endl;
pipe_cycle_WB(p);
pipe_cycle_MA(p);
pipe_cycle_EX(p);
pipe_cycle_ID(p);
pipe_cycle_IF(p);
// You can uncomment the following line to print out the pipeline state
// after each clock cycle for debugging purposes.
// Make sure you comment it out or remove it before you submit the lab.
//pipe_print_state(p);
/*
for (unsigned int i = 0; i < PIPE_WIDTH; i++) {
std::cout << "valid: " << p->pipe_latch[IF_LATCH][i].valid << " " << p->pipe_latch[ID_LATCH][i].valid << " " << p->pipe_latch[EX_LATCH][i].valid << " "<< p->pipe_latch[MA_LATCH][i].valid << std::endl;
std::cout << "stall: " << p->pipe_latch[IF_LATCH][i].stall << " " << p->pipe_latch[ID_LATCH][i].stall << " " << p->pipe_latch[EX_LATCH][i].stall << " "<< p->pipe_latch[MA_LATCH][i].stall << std::endl;
}
std::cout << "END" << std::endl << std::endl; */
}
/**
* Simulate one cycle of the Write Back stage (WB) of a pipeline.
*
* Some skeleton code has been provided for you. You must implement anything
* else you need for the pipeline simulation to work properly.
*
* @param p the pipeline to simulate
*/
void pipe_cycle_WB(Pipeline *p)
{
for (unsigned int i = 0; i < PIPE_WIDTH; i++)
{
if (p->pipe_latch[MA_LATCH][i].valid)
{
p->stat_retired_inst++;
if (p->pipe_latch[MA_LATCH][i].op_id >= p->halt_op_id)
{
// Halt the pipeline if we've reached the end of the trace.
p->halt = true;
}
}
}
}
/**
* Simulate one cycle of the Memory Access stage (MA) of a pipeline.
*
* Some skeleton code has been provided for you. You must implement anything
* else you need for the pipeline simulation to work properly.
*
* @param p the pipeline to simulate
*/
void pipe_cycle_MA(Pipeline *p)
{
for (unsigned int i = 0; i < PIPE_WIDTH; i++)
{
// Copy each instruction from the EX latch to the MA latch.
p->pipe_latch[MA_LATCH][i] = p->pipe_latch[EX_LATCH][i];
p->pipe_latch[MA_LATCH][i].valid = p->pipe_latch[EX_LATCH][i].valid;
}
}
/**
* Simulate one cycle of the Execute stage (EX) of a pipeline.
*
* Some skeleton code has been provided for you. You must implement anything
* else you need for the pipeline simulation to work properly.
*
* @param p the pipeline to simulate
*/
void pipe_cycle_EX(Pipeline *p)
{
for (unsigned int i = 0; i < PIPE_WIDTH; i++)
{
// Copy each instruction from the ID latch to the EX latch.
p->pipe_latch[EX_LATCH][i] = p->pipe_latch[ID_LATCH][i];
p->pipe_latch[EX_LATCH][i].valid = p->pipe_latch[ID_LATCH][i].valid;
}
}
/**
* Simulate one cycle of the Instruction Decode stage (ID) of a pipeline.
*
* Some skeleton code has been provided for you. You must implement anything
* else you need for the pipeline simulation to work properly.
*
* @param p the pipeline to simulate
*/
void pipe_cycle_ID(Pipeline *p)
{
for (unsigned int i = 0; i < PIPE_WIDTH; i++)
{
// Copy each instruction from the IF latch to the ID latch.
p->pipe_latch[ID_LATCH][i] = p->pipe_latch[IF_LATCH][i];
p->pipe_latch[ID_LATCH][i].stall = false;
}
for (unsigned int i = 0; i < PIPE_WIDTH; i++)
{
//Track reasons for stalling
bool stall_src1_ma = false;
bool stall_src2_ma = false;
bool stall_cc_ma = false;
bool stall_src1_ex = false;
bool stall_src2_ex = false;
bool stall_cc_ex = false;
bool stall_cc_id = false;
bool stall_src1_id = false;
bool stall_src2_id = false;
for (unsigned int ii = 0; ii < PIPE_WIDTH; ii++) {
//Check for a colission between the EX dest reg and the first src reg for ID
if (p->pipe_latch[EX_LATCH][ii].trace_rec.dest_reg == p->pipe_latch[ID_LATCH][i].trace_rec.src1_reg && p->pipe_latch[ID_LATCH][i].trace_rec.src1_needed && p->pipe_latch[EX_LATCH][ii].trace_rec.dest_needed && p->pipe_latch[EX_LATCH][ii].valid) {
stall_src1_ex = true;
}
//Check for a colission between the EX dest reg and the second src reg for ID
if (p->pipe_latch[EX_LATCH][ii].trace_rec.dest_reg == p->pipe_latch[ID_LATCH][i].trace_rec.src2_reg && p->pipe_latch[ID_LATCH][i].trace_rec.src2_needed && p->pipe_latch[EX_LATCH][ii].trace_rec.dest_needed && p->pipe_latch[EX_LATCH][ii].valid) {
stall_src2_ex = true;
}
//Check for a colission between the EX cc_write reg and the cc_read ID
//if (p->pipe_latch[EX_LATCH][ii].trace_rec.cc_write == p->pipe_latch[ID_LATCH][i].trace_rec.cc_read && p->pipe_latch[EX_LATCH][ii].valid) {
if (p->pipe_latch[EX_LATCH][ii].trace_rec.cc_write && p->pipe_latch[ID_LATCH][i].trace_rec.cc_read && p->pipe_latch[EX_LATCH][ii].valid) {
stall_cc_ex = true;
}
//Check for a colission between the MA dest reg and the first src reg for ID
if (p->pipe_latch[MA_LATCH][ii].trace_rec.dest_reg == p->pipe_latch[ID_LATCH][i].trace_rec.src1_reg && p->pipe_latch[ID_LATCH][i].trace_rec.src1_needed && p->pipe_latch[MA_LATCH][ii].trace_rec.dest_needed && p->pipe_latch[MA_LATCH][ii].valid) {
stall_src1_ma = true;
}
//Check for a colission between the MA dest reg and the second src reg for ID
if (p->pipe_latch[MA_LATCH][ii].trace_rec.dest_reg == p->pipe_latch[ID_LATCH][i].trace_rec.src2_reg && p->pipe_latch[ID_LATCH][i].trace_rec.src2_needed && p->pipe_latch[MA_LATCH][ii].trace_rec.dest_needed && p->pipe_latch[MA_LATCH][ii].valid) {
stall_src2_ma = true;
}
//Check for a colission between the MA cc_write reg and the cc_read ID
//if (p->pipe_latch[MA_LATCH][ii].trace_rec.cc_write == p->pipe_latch[ID_LATCH][i].trace_rec.cc_read && p->pipe_latch[MA_LATCH][ii].valid) {
if (p->pipe_latch[MA_LATCH][ii].trace_rec.cc_write && p->pipe_latch[ID_LATCH][i].trace_rec.cc_read && p->pipe_latch[MA_LATCH][ii].valid) {
stall_cc_ma = true;
}
if (PIPE_WIDTH > 1) {
if (p->pipe_latch[ID_LATCH][ii].op_id < p->pipe_latch[ID_LATCH][i].op_id) {
if (p->pipe_latch[ID_LATCH][ii].trace_rec.cc_write && p->pipe_latch[ID_LATCH][i].trace_rec.cc_read) {
stall_cc_id = true;
}
if (p->pipe_latch[ID_LATCH][ii].trace_rec.dest_reg == p->pipe_latch[ID_LATCH][i].trace_rec.src1_reg && p->pipe_latch[ID_LATCH][i].trace_rec.src1_needed && p->pipe_latch[ID_LATCH][ii].trace_rec.dest_needed ) {
stall_src1_id = true;
}
if (p->pipe_latch[ID_LATCH][ii].trace_rec.dest_reg == p->pipe_latch[ID_LATCH][i].trace_rec.src2_reg && p->pipe_latch[ID_LATCH][i].trace_rec.src2_needed && p->pipe_latch[ID_LATCH][ii].trace_rec.dest_needed ) {
stall_src1_id = true;
}
}
}
}
if (ENABLE_MEM_FWD)
{
// TODO: Handle forwarding from the MA stage.
if (stall_src1_ma) {
unsigned int youngest = 256;
for (unsigned int j = 0; j < PIPE_WIDTH; j++) {
if (p->pipe_latch[MA_LATCH][j].trace_rec.dest_reg==p->pipe_latch[ID_LATCH][i].trace_rec.src1_reg && p->pipe_latch[MA_LATCH][j].trace_rec.dest_needed && p->pipe_latch[MA_LATCH][j].valid) {
if (youngest==256) {
youngest = j;
} else {
if (p->pipe_latch[MA_LATCH][j].op_id > p->pipe_latch[MA_LATCH][youngest].op_id) {
youngest = j;
}
}
}
}
if (youngest != 256) {
stall_src1_ma = false;
}
}
if (stall_src2_ma) {
unsigned int youngest = 256;
for (unsigned int j = 0; j < PIPE_WIDTH; j++) {
if (p->pipe_latch[MA_LATCH][j].trace_rec.dest_reg==p->pipe_latch[ID_LATCH][i].trace_rec.src2_reg && p->pipe_latch[MA_LATCH][j].trace_rec.dest_needed && p->pipe_latch[MA_LATCH][j].valid) {
if (youngest==256) {
youngest = j;
} else {
if (p->pipe_latch[MA_LATCH][j].op_id > p->pipe_latch[MA_LATCH][youngest].op_id) {
youngest = j;
}
}
}
}
if (youngest != 256) {
stall_src2_ma = false;
}
}
if (stall_cc_ma) {
unsigned int youngest = 256;
for (unsigned int j = 0; j < PIPE_WIDTH; j++) {
if (p->pipe_latch[MA_LATCH][j].trace_rec.cc_write && p->pipe_latch[ID_LATCH][i].trace_rec.cc_read && p->pipe_latch[MA_LATCH][j].valid) {
if (youngest==256) {
youngest = j;
} else {
if (p->pipe_latch[MA_LATCH][j].op_id > p->pipe_latch[MA_LATCH][youngest].op_id) {
youngest = j;
}
}
}
}
if (youngest != 256) {
stall_cc_ma = false;
}
}
/*
for (unsigned int ii = 0; ii < PIPE_WIDTH; ii++) {
if (stall_src1_ma) {
if (p->pipe_latch[ID_LATCH][i].trace_rec.src1_reg == p->pipe_latch[MA_LATCH][ii].trace_rec.dest_reg && p->pipe_latch[MA_LATCH][ii].valid && p->pipe_latch[MA_LATCH][ii].trace_rec.dest_needed && p->pipe_latch[ID_LATCH][i].trace_rec.src1_needed ) {
stall_src1_ma = false;
}
}
if (stall_src2_ma) {
if (p->pipe_latch[ID_LATCH][i].trace_rec.src2_reg == p->pipe_latch[MA_LATCH][ii].trace_rec.dest_reg && p->pipe_latch[MA_LATCH][ii].valid && p->pipe_latch[MA_LATCH][ii].trace_rec.dest_needed && p->pipe_latch[ID_LATCH][i].trace_rec.src2_needed ) {
stall_src2_ma = false;
}
}
if (stall_cc_ma) {
if (p->pipe_latch[ID_LATCH][i].trace_rec.cc_read && p->pipe_latch[MA_LATCH][ii].trace_rec.cc_write && p->pipe_latch[MA_LATCH][ii].valid) {
stall_cc_ma = false;
}
}
}*/
}
if (ENABLE_EXE_FWD)
{
// TODO: Handle forwarding from the EX stage.
// Rishov: New implementation based on youngest instruction in EX.
if (stall_src1_ex) {
unsigned int youngest = 256;
for (unsigned int j = 0; j < PIPE_WIDTH; j++) {
if (p->pipe_latch[EX_LATCH][j].trace_rec.dest_reg==p->pipe_latch[ID_LATCH][i].trace_rec.src1_reg && p->pipe_latch[EX_LATCH][j].trace_rec.dest_needed && p->pipe_latch[EX_LATCH][j].valid) {
if (youngest==256) {
youngest = j;
} else {
if (p->pipe_latch[EX_LATCH][j].op_id > p->pipe_latch[EX_LATCH][youngest].op_id) {
youngest = j;
}
}
}
}
if (youngest != 256) {
if (p->pipe_latch[EX_LATCH][youngest].trace_rec.op_type!=OP_LD) {
stall_src1_ex = false;
}
}
}
if (stall_src2_ex) {
unsigned int youngest = 256;
for (unsigned int j = 0; j < PIPE_WIDTH; j++) {
if (p->pipe_latch[EX_LATCH][j].trace_rec.dest_reg==p->pipe_latch[ID_LATCH][i].trace_rec.src2_reg && p->pipe_latch[EX_LATCH][j].trace_rec.dest_needed && p->pipe_latch[EX_LATCH][j].valid) {
if (youngest==256) {
youngest = j;
} else {
if (p->pipe_latch[EX_LATCH][j].op_id > p->pipe_latch[EX_LATCH][youngest].op_id) {
youngest = j;
}
}
}
}
if (youngest != 256) {
if (p->pipe_latch[EX_LATCH][youngest].trace_rec.op_type!=OP_LD) {
stall_src2_ex = false;
}
}
}
if (stall_cc_ex) {
unsigned int youngest = 256;
for (unsigned int j = 0; j < PIPE_WIDTH; j++) {
if (p->pipe_latch[EX_LATCH][j].trace_rec.cc_write && p->pipe_latch[ID_LATCH][i].trace_rec.cc_read && p->pipe_latch[EX_LATCH][j].valid) {
if (youngest==256) {
youngest = j;
} else {
if (p->pipe_latch[EX_LATCH][j].op_id > p->pipe_latch[EX_LATCH][youngest].op_id) {
youngest = j;
}
}
}
}
if (youngest != 256) {
if (p->pipe_latch[EX_LATCH][youngest].trace_rec.op_type!=OP_LD) {
stall_cc_ex = false;
}
}
}
/*
for (unsigned int ii = 0; ii < PIPE_WIDTH; ii++) {
if (!p->pipe_latch[EX_LATCH][ii].trace_rec.op_type==OP_LD) {
if (stall_src1_ex) {
if (p->pipe_latch[ID_LATCH][i].trace_rec.src1_reg == p->pipe_latch[EX_LATCH][ii].trace_rec.dest_reg && p->pipe_latch[EX_LATCH][ii].valid && p->pipe_latch[EX_LATCH][ii].trace_rec.dest_needed && p->pipe_latch[ID_LATCH][i].trace_rec.src1_needed) {
//if (p->pipe_latch[EX_LATCH][ii].trace_rec.dest_reg == p->pipe_latch[ID_LATCH][i].trace_rec.src1_reg && p->pipe_latch[ID_LATCH][i].trace_rec.src2_needed && p->pipe_latch[EX_LATCH][ii].valid) {
stall_src1_ex = false;
}
}
if (stall_src2_ex) {
if (p->pipe_latch[ID_LATCH][i].trace_rec.src2_reg == p->pipe_latch[EX_LATCH][ii].trace_rec.dest_reg && p->pipe_latch[EX_LATCH][ii].valid && p->pipe_latch[EX_LATCH][ii].trace_rec.dest_needed && p->pipe_latch[ID_LATCH][i].trace_rec.src2_needed) {
//if (p->pipe_latch[EX_LATCH][ii].trace_rec.dest_reg == p->pipe_latch[ID_LATCH][i].trace_rec.src2_reg && p->pipe_latch[ID_LATCH][i].trace_rec.src2_needed && p->pipe_latch[EX_LATCH][ii].valid) {
stall_src2_ex = false;
}
}
if (stall_cc_ex) {
if (p->pipe_latch[ID_LATCH][i].trace_rec.cc_read && p->pipe_latch[EX_LATCH][ii].trace_rec.cc_write && p->pipe_latch[EX_LATCH][ii].valid) {
stall_cc_ex = false;
}
}
} else {
for (unsigned int j = 0; j < PIPE_WIDTH; j++) {
if (p->pipe_latch[EX_LATCH][j].op_id < p->pipe_latch[EX_LATCH][ii].op_id && !p->pipe_latch[EX_LATCH][j].trace_rec.op_type==OP_LD) {
if (stall_src1_ex && p->pipe_latch[EX_LATCH][j].trace_rec.dest_reg==p->pipe_latch[EX_LATCH][ii].trace_rec.dest_reg && p->pipe_latch[EX_LATCH][j].trace_rec.dest_needed && p->pipe_latch[EX_LATCH][j].trace_rec.dest_reg == p->pipe_latch[ID_LATCH][i].trace_rec.src1_reg && p->pipe_latch[ID_LATCH][i].trace_rec.src1_needed && p->pipe_latch[EX_LATCH][j].valid)
}
}
}
}*/
}
if (stall_src1_ex || stall_src1_ma || stall_src2_ex || stall_src2_ma || stall_cc_ex || stall_cc_ma || stall_cc_id || stall_src1_id || stall_src2_id || !p->pipe_latch[ID_LATCH][i].op_id>1) {
p->pipe_latch[ID_LATCH][i].valid = false;
} else {
p->pipe_latch[ID_LATCH][i].valid = true;
}
if (!p->pipe_latch[IF_LATCH][i].valid) {
p->pipe_latch[ID_LATCH][i].valid = false;
}
/*
if (stall_src1_ex || stall_src2_ex) {
std::cout << "EX stall " << stall_src1_ex << " " << stall_src2_ex << std::endl;
if (p->pipe_latch[IF_LATCH][0].op_id==4689 && i==0) {
bool dest0 = false;
bool dest1 = false;
if (p->pipe_latch[ID_LATCH][0].trace_rec.src2_reg==p->pipe_latch[EX_LATCH][0].trace_rec.dest_reg) {
dest0 = true;
}
if (p->pipe_latch[ID_LATCH][0].trace_rec.src2_reg==p->pipe_latch[EX_LATCH][1].trace_rec.dest_reg) {
dest1 = true;
}
bool ld = false;
if (p->pipe_latch[EX_LATCH][1].trace_rec.op_type==OP_LD) {
ld = true;
}
bool src2_needed0 = p->pipe_latch[ID_LATCH][0].trace_rec.src2_needed;
bool dest_needed0 = p->pipe_latch[EX_LATCH][0].trace_rec.dest_needed;
bool src2_needed1 = p->pipe_latch[ID_LATCH][1].trace_rec.src2_needed;
bool dest_needed1 = p->pipe_latch[EX_LATCH][1].trace_rec.dest_needed;
bool younger = false;
if (p->pipe_latch[EX_LATCH][1].op_id > p->pipe_latch[EX_LATCH][0].op_id) {
younger = true;
}
std::cout << "src2: " << stall_src2_ex << " " << dest0 << " " << src2_needed0 << " " << dest_needed0 << " " << dest1 << " " << src2_needed1 << " " << dest_needed1 << " " << ld << " " << younger << std::endl;
}
//std::cout << p->pipe_latch[ID_LATCH][i].trace_rec.src1_reg << " " << p->pipe_latch[ID_LATCH][i].trace_rec.src2_reg << " " << p->pipe_latch[EX_LATCH][i].trace_rec.dest_reg <<std::endl;
}
bool ex_pipe0 = p->pipe_latch[EX_LATCH][0].trace_rec.cc_write;
bool ex_pipe1 = p->pipe_latch[EX_LATCH][1].trace_rec.cc_write;
bool ma_pipe0 = p->pipe_latch[MA_LATCH][0].trace_rec.cc_write;
bool ma_pipe1 = p->pipe_latch[MA_LATCH][1].trace_rec.cc_write;
if (stall_cc_ex) {
if (PIPE_WIDTH > 1) {
std::cout << "EX stall CC " << p->pipe_latch[ID_LATCH][i].op_id << " " << ex_pipe0 << " " << ex_pipe1 << std::endl;
} else {
std::cout << "EX stall CC " << p->pipe_latch[ID_LATCH][i].op_id << std::endl;
}
//std::cout << p->pipe_latch[ID_LATCH][i].trace_rec.cc_read << " " << p->pipe_latch[EX_LATCH][i].trace_rec.cc_write << std::endl;
}
if (stall_src1_ma || stall_src2_ma) {
std::cout << "MA stall" << stall_src1_ma << " " << stall_src2_ma << std::endl;
//std::cout << p->pipe_latch[ID_LATCH][i].trace_rec.src1_reg << " " << p->pipe_latch[ID_LATCH][i].trace_rec.src2_reg << " " << p->pipe_latch[MA_LATCH][i].trace_rec.dest_reg <<std::endl;
}
if (stall_cc_ma) {
if (PIPE_WIDTH > 1) {
std::cout << "MA stall CC " << p->pipe_latch[ID_LATCH][i].op_id << " " << ma_pipe0 << " " << ma_pipe1 << std::endl;
} else {
std::cout << "MA stall CC " << p->pipe_latch[ID_LATCH][i].op_id << std::endl;
}
//std::cout << p->pipe_latch[ID_LATCH][i].trace_rec.cc_read << " " << p->pipe_latch[MA_LATCH][i].trace_rec.cc_write << std::endl;
}*/
/*
if (p->pipe_latch[ID_LATCH][i].trace_rec.op_type==OP_CBR ) {
std::cout << "PIPE " << i << " ID OP_ID: " << p->pipe_latch[ID_LATCH][i].op_id << " " << "BRANCH" << " " << stall_src1_ex << " " << stall_src2_ex << " " << stall_cc_ex << " " << stall_src1_ma << " " << stall_src2_ma << " " << stall_cc_ma << " " << p->pipe_latch[ID_LATCH][i].valid << std::endl;
}*/
}
/*
for (unsigned int i = 0; i < PIPE_WIDTH; i++) {
//After all data stalls have been set, we can check to see if there are age related stalls that need to be implemented
for (unsigned int ii = 0; ii < PIPE_WIDTH; ii++) {
if (i != ii) {
if(p->pipe_latch[ID_LATCH][i].op_id < p->pipe_latch[ID_LATCH][ii].op_id && p->pipe_latch[ID_LATCH][ii].stall) {
//p->pipe_latch[ID_LATCH][i].stall = true;
p->pipe_latch[ID_LATCH][i].valid = false;
}
}
}
}*/
}
/**
* Simulate one cycle of the Instruction Fetch stage (IF) of a pipeline.
*
* Some skeleton code has been provided for you. You must implement anything
* else you need for the pipeline simulation to work properly.
*
* @param p the pipeline to simulate
*/
void pipe_cycle_IF(Pipeline *p)
{
for (unsigned int i = 0; i < PIPE_WIDTH; i++)
{
if (!p->pipe_latch[ID_LATCH][i].valid && !p->pipe_latch[EX_LATCH][i].valid && !p->pipe_latch[MA_LATCH][i].valid && p->pipe_latch[IF_LATCH][i].op_id < PIPE_WIDTH) {
//if (!p->pipe_latch[ID_LATCH][i].valid && !p->pipe_latch[EX_LATCH][i].valid) {
p->pipe_latch[IF_LATCH][i].stall = false;
} else if (!p->pipe_latch[ID_LATCH][i].valid) {
p->pipe_latch[IF_LATCH][i].stall = true;
} else {
p->pipe_latch[IF_LATCH][i].stall = false;
}
if (PIPE_WIDTH > 1) {
for (unsigned int j = 0; j < PIPE_WIDTH; j++) {
if (!p->pipe_latch[ID_LATCH][j].valid && p->pipe_latch[IF_LATCH][j].op_id < p->pipe_latch[IF_LATCH][i].op_id) {
p->pipe_latch[IF_LATCH][i].stall = true;
p->pipe_latch[ID_LATCH][i].valid = false;
//std::cout << "IF valid check " << p->pipe_latch[IF_LATCH][i].op_id << " " << j << " " << i << " " << p->pipe_latch[ID_LATCH][j].valid << " " << (p->pipe_latch[IF_LATCH][j].op_id < p->pipe_latch[IF_LATCH][i].op_id) << std::endl;
}
}
}
/*bool ma_cc = false;
bool ex_cc = false;
bool if_cc = false;
if (p->pipe_latch[MA_LATCH][i].trace_rec.cc_write && p->pipe_latch[MA_LATCH][i].valid ) {
ma_cc = true;
}
if (p->pipe_latch[EX_LATCH][i].trace_rec.cc_write && p->pipe_latch[EX_LATCH][i].valid ) {
ex_cc = true;
}
if (p->pipe_latch[IF_LATCH][i].trace_rec.cc_read ) {
if_cc = true;
}*/
/*
if (p->pipe_latch[IF_LATCH][i].trace_rec.op_type==OP_LD ) {
std::cout << "PIPE " << i << " OP_ID: " << p->pipe_latch[IF_LATCH][i].op_id << " " << "LOAD" << " " << if_cc << " " << ex_cc << " " << ma_cc << std::endl;
} else if (p->pipe_latch[IF_LATCH][i].trace_rec.op_type==OP_ST ) {
std::cout << "PIPE " << i << " OP_ID: " << p->pipe_latch[IF_LATCH][i].op_id << " " << "STORE" << " " << if_cc << " " << ex_cc << " " << ma_cc << std::endl;
} else if (p->pipe_latch[IF_LATCH][i].trace_rec.op_type==OP_ALU ) {
std::cout << "PIPE " << i << " OP_ID: " << p->pipe_latch[IF_LATCH][i].op_id << " " << "ALU" << " " << if_cc << " " << ex_cc << " " << ma_cc << std::endl;
} else if (p->pipe_latch[IF_LATCH][i].trace_rec.op_type==OP_CBR ) {
std::cout << "PIPE " << i << " OP_ID: " << p->pipe_latch[IF_LATCH][i].op_id << " " << "BRANCH" << " " << if_cc << " " << ex_cc << " " << ma_cc << std::endl;
} else if (p->pipe_latch[IF_LATCH][i].trace_rec.op_type==OP_OTHER ) {
std::cout << "PIPE " << i << " OP_ID: " << p->pipe_latch[IF_LATCH][i].op_id << " " << "OTHER" << " " << if_cc << " " << ex_cc << " " << ma_cc << std::endl;
}*/
//std::cout << "IF " << p->pipe_latch[ID_LATCH][i].valid << std::endl;
if (!p->pipe_latch[IF_LATCH][i].stall) {
// Read an instruction from the trace file.
PipelineLatch fetch_op;
pipe_get_fetch_op(p, &fetch_op);
// Handle branch (mis)prediction.
if (BPRED_POLICY != BPRED_PERFECT)
{
pipe_check_bpred(p, &fetch_op);
}
// Copy the instruction to the IF latch.
p->pipe_latch[IF_LATCH][i] = fetch_op;
if (p->pipe_latch[IF_LATCH][i].op_id == 1) {
p->pipe_latch[ID_LATCH][i].valid = false;
//std::cout << "IF valid 2" << std::endl;
}
}
//std::cout << "PIPE " << i << "IF end" << p->pipe_latch[ID_LATCH][i].valid << std::endl;
}
/*
for (unsigned int i = 0; i < PIPE_WIDTH; i++) {
std::cout << "PIPE " << i << "IF independent look" << p->pipe_latch[ID_LATCH][i].valid << std::endl;
}*/
}
/**
* If the instruction just fetched is a conditional branch, check for a branch
* misprediction, update the branch predictor, and set appropriate flags in the
* pipeline.
*
* You must implement this function in part B of the lab.
*
* @param p the pipeline
* @param fetch_op the pipeline latch containing the operation fetched
*/
void pipe_check_bpred(Pipeline *p, PipelineLatch *fetch_op)
{
// TODO: For a conditional branch instruction, get a prediction from the
// branch predictor.
// TODO: If the branch predictor mispredicted, mark the fetch_op
// accordingly.
// TODO: Immediately update the branch predictor.
// TODO: If needed, stall the IF stage by setting the flag
// p->fetch_cbr_stall.
}
| [
"[email protected]"
] | |
36799e6189178fd9b287c109be648a62d3dcf91e | 5f66493c991b076453e422ffafe66dc6412407cb | /Binary Trees/sumOfNodes.cpp | f05f91ede67e8982fc322b301c0162df0177eefc | [] | no_license | kanishka012/Data_Structure | 4ae24978e954c434617704177c7dc92de2699340 | 4da294d01317f4c18afc33e5be06b0f31f90500f | refs/heads/master | 2020-12-19T01:21:34.367012 | 2020-01-22T13:17:31 | 2020-01-22T13:17:31 | 235,576,824 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,614 | cpp | #include <iostream>
#include <queue>
template <typename T>
class BinaryTreeNode {
public :
T data;
BinaryTreeNode<T> *left;
BinaryTreeNode<T> *right;
BinaryTreeNode(T data) {
this -> data = data;
left = NULL;
right = NULL;
}
};
using namespace std;
int sumOfAllNodes(BinaryTreeNode<int>* root) {
// Write your code here
if(root==NULL)
return 0;
return root->data+sumOfAllNodes(root->left)+sumOfAllNodes(root->right);
}
BinaryTreeNode<int>* takeInput() {
int rootData;
//cout << "Enter root data : ";
cin >> rootData;
if(rootData == -1) {
return NULL;
}
BinaryTreeNode<int> *root = new BinaryTreeNode<int>(rootData);
queue<BinaryTreeNode<int>*> q;
q.push(root);
while(!q.empty()) {
BinaryTreeNode<int> *currentNode = q.front();
q.pop();
int leftChild, rightChild;
//cout << "Enter left child of " << currentNode -> data << " : ";
cin >> leftChild;
if(leftChild != -1) {
BinaryTreeNode<int>* leftNode = new BinaryTreeNode<int>(leftChild);
currentNode -> left =leftNode;
q.push(leftNode);
}
//cout << "Enter right child of " << currentNode -> data << " : ";
cin >> rightChild;
if(rightChild != -1) {
BinaryTreeNode<int>* rightNode = new BinaryTreeNode<int>(rightChild);
currentNode -> right =rightNode;
q.push(rightNode);
}
}
return root;
}
int main() {
BinaryTreeNode<int>* root = takeInput();
cout << sumOfAllNodes(root) << endl;
}
| [
"[email protected]"
] | |
9a341f7216c640c724ef8755ba4658c88a11001a | 492976adfdf031252c85de91a185bfd625738a0c | /src/Game/AI/AI/aiTargetHomePos.h | 8a27a7023d5285160c697866032e1449affcac6d | [] | no_license | zeldaret/botw | 50ccb72c6d3969c0b067168f6f9124665a7f7590 | fd527f92164b8efdb746cffcf23c4f033fbffa76 | refs/heads/master | 2023-07-21T13:12:24.107437 | 2023-07-01T20:29:40 | 2023-07-01T20:29:40 | 288,736,599 | 1,350 | 117 | null | 2023-09-03T14:45:38 | 2020-08-19T13:16:30 | C++ | UTF-8 | C++ | false | false | 514 | h | #pragma once
#include "Game/AI/AI/aiTargetPosAI.h"
#include "KingSystem/ActorSystem/actAiAi.h"
namespace uking::ai {
class TargetHomePos : public TargetPosAI {
SEAD_RTTI_OVERRIDE(TargetHomePos, TargetPosAI)
public:
explicit TargetHomePos(const InitArg& arg);
~TargetHomePos() override;
bool init_(sead::Heap* heap) override;
void enter_(ksys::act::ai::InlineParamPack* params) override;
void leave_() override;
void loadParams_() override;
protected:
};
} // namespace uking::ai
| [
"[email protected]"
] | |
f0421be3dd5043773cb66d8368d6dca1299d9936 | b92769dda6c8b7e9bf79c48df810a702bfdf872f | /6.BranchingStatements&LogicalOperators/6.3.ifelseif.cpp | d6b6502f398e2a114b15ea858a437c8f1f34aef6 | [
"MIT"
] | permissive | HuangStomach/Cpp-primer-plus | 4276e0a24887ef6d48f202107b7b4c448230cd20 | c8b2b90f10057e72da3ab570da7cc39220c88f70 | refs/heads/master | 2021-06-25T07:22:15.405581 | 2021-02-28T06:55:23 | 2021-02-28T06:55:23 | 209,192,905 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 418 | cpp | #include <iostream>
const int Fave = 27;
int main(int argc, char const *argv[]) {
using namespace std;
int n;
cout << "Enter a number in the range 1-100 to find ";
cout << "favourite number: ";
do {
cin >> n;
if (n < Fave) cout << "Too low: ";
else if (n > Fave) cout << "Too high: ";
else cout << Fave << " is right!";
} while (n != Fave);
return 0;
}
| [
"[email protected]"
] | |
8837b2540ed960c5163d7f2ad7dcffb495771ceb | a8f5ff4386c982e67dbe323a1b5057f21ed75339 | /Source/NeopleTestP_KJH/MyPlayerController.h | 1ffc1dc3718590979376b27fea4a62693a2f837d | [] | no_license | gabriloon/TestP_KJH | 573b197f6c8cb3318a7a5da96ace0e4e751aea25 | df352cab50c5ad94116570754ae695e209aede8c | refs/heads/master | 2023-06-18T18:35:14.869375 | 2021-07-09T06:17:41 | 2021-07-09T06:17:41 | 382,609,484 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 502 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/PlayerController.h"
#include "MyPlayerController.generated.h"
/**
*
*/
UCLASS()
class NEOPLETESTP_KJH_API AMyPlayerController : public APlayerController
{
GENERATED_BODY()
protected:
virtual void BeginPlay() override;
private:
UPROPERTY(EditAnywhere,Category="Widget")
TSubclassOf<class UUserWidget> UIWidget;
class UUserWidget* InfoScreen;
};
| [
"[email protected]"
] | |
3c1064307afeed562d69c2d896742bbfac5ab819 | 58355df22f3932239db4eef2c3eb7d6602013919 | /Code Jam/Kickstart-2017/Practice-Round/C.cpp | 9c8327530a3c16bf9bd5ea9c1f148dad71abf01d | [] | no_license | ma5terdrag0n/Competitive-Programming | fafd7eb0b8960f7c24f7eabd58675dafd91d679c | 9b1b2ab74ce8464ff9b824e5f55763521bb2961c | refs/heads/master | 2021-06-24T17:14:52.940955 | 2020-10-04T07:19:25 | 2020-10-04T07:19:25 | 131,677,687 | 2 | 2 | null | 2018-05-25T06:53:19 | 2018-05-01T04:53:00 | C++ | UTF-8 | C++ | false | false | 608 | cpp | /*
* Author : __daemon
*/
#include<bits/stdc++.h>
#define pb push_back
#define mkp make_pair
#define inf 1000000009
#define rep(i,n) for(int i=0;i<n;i++)
using namespace std;
typedef long long ll;
typedef vector<ll> vi;
typedef pair<ll,ll> ii;
typedef vector<ii> vii;
void clr(ll *a,ll val){
memset(a,val,sizeof(a));
}
void solve(){
freopen("a.txt","r",stdin);
freopen("out.txt","w",stdout);
ll t,cas=0;
cin>>t;
for(int iii=1;iii<=t;iii++){
ll n,m;
cin>>n>>m;
ll ans=0;
n = min(n,m);
ans = n*(n+1)/2LL;
printf("Case #%d: %lld\n", iii,ans);
}
}
int main(){
solve();
}
| [
"[email protected]"
] | |
f21de1bb6fe98353ef555ddcfdf557e33769071a | d7e8806194d9afcd03ce6d91bfb628988393e9fb | /Lib/GelTime/GelTime.cpp | e46a642b712fce1c131e7b05d1866d6d70dd3cbc | [] | no_license | mikekasprzak/gel3-lib | 2eac2ed89944bdcad094b9be2850b108c2d4721d | 6ca4f58b6bea8707face8bcdd1949658a1b7521b | refs/heads/master | 2020-03-23T22:59:53.772671 | 2018-07-24T20:41:21 | 2018-07-24T20:41:21 | 142,210,808 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 396 | cpp | // - ------------------------------------------------------------------------------------------ - //
#include <Lib/Lib.h>
// - ------------------------------------------------------------------------------------------ - //
//namespace Gel {
// GelTime StartTime;
//}; // namespace Gel //
// - ------------------------------------------------------------------------------------------ - //
| [
"[email protected]"
] | |
7b6c91038f156920ceff337c0494e5c8d0e07b59 | bcd06c8b088638714885c58def111cf2f744bd07 | /main_functions.h | f727b87e78300a580f00dbf6d6cc87118f4fa0b3 | [] | no_license | FabiowQuixada/NeuralNetworks | 97cbc601ce5dd0da72e82e7e2baf1b2cd0428f47 | a644da71a20835251d448951d99dd64179755048 | refs/heads/master | 2016-09-14T03:35:38.440768 | 2016-05-03T23:43:22 | 2016-05-03T23:43:22 | 58,008,378 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 755 | h | #ifndef MAIN_FUNCTIONS_H
#define MAIN_FUNCTIONS_H
#include "pattern.h"
#include "neuron.h"
#include "halfedge.h"
typedef std::vector<Pattern*> PatternList;
typedef std::vector<int> IntList;
typedef std::vector<Neuron*> NeuronList;
typedef std::vector<Neural_HalfEdge*> HalfEdgeList;
PatternList BIPOLAR_INPUT();
IntList AND();
IntList OR();
IntList XOR();
void wait();
IntList A();
IntList B();
IntList C();
IntList D();
IntList E();
IntList J();
IntList K();
Pattern input1();
Pattern input2();
Pattern input3();
Pattern input4();
IntList output1();
IntList output2();
IntList output3();
IntList output4();
float minusa(Pattern p, FloatList list);
#endif // MAIN_FUNCTIONS_H
| [
"[email protected]"
] | |
739ef4f603e1b2d90c81bfaf30d98b71e71dedf5 | d2928bcf96b425ee2964ac2fa8af124b491d57b1 | /dbase/devicedata.h | 29c8ba1e16fc90418eb9d339310cc8a5454f77b5 | [] | no_license | ruraomsk/rdu | aef69c77c4f8bfb2c86987fd8715519a0c4e824f | 3623d7419574a4434a11ca455c8fc675751d76d9 | refs/heads/main | 2023-03-21T09:26:50.956892 | 2021-03-19T04:06:06 | 2021-03-19T04:06:06 | 339,029,112 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 784 | h | #ifndef DEVICEDATA_H
#define DEVICEDATA_H
#include <QObject>
#include <QMap>
#include <QVariant>
#include "commanddata.h"
class DeviceData
{
public:
DeviceData();
DeviceData(QMap<QString,QVariant> map);
void AppendInfo(QMap<QString,QVariant> map);
static bool Compare (DeviceData &d1,DeviceData &d2);
QString getKey();
QString getStatus();
QString getCrossStatus();
bool isConnected();
bool isWorked(CommandData cmd);
bool isReadyToXT();
public:
int region ;
int area;
int subarea;
int id;
int idevice;
int status;
QString Status;
int ck;
int pk;
int nk;
QString name;
int techmode;
bool ispk=false;
bool isck=false;
bool isnk=false;
int edk=false;
};
#endif // DEVICEDATA_H
| [
"[email protected]"
] | |
4c2a091dca2dd2a55764aec578970f67c2407a2f | 57338e7af891aaee72cab07b4329d80a3bc358f5 | /sonic-sairedis/lib/src/sai_redis_policer.cpp | 56e4197af3eaa881240433b59112a41120f628e2 | [
"Apache-2.0"
] | permissive | tiglabs/sonic | 18ecb2364be2bf70d239dc30a9d006911391d4b0 | e10c5b82c4b1cdb439f7212579aca880aa9d7cd3 | refs/heads/master | 2021-07-10T18:38:28.814144 | 2017-10-12T03:36:51 | 2017-10-12T03:36:51 | 106,631,679 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 753 | cpp | #include "sai_redis.h"
sai_status_t redis_get_policer_stats(
_In_ sai_object_id_t policer_id,
_In_ uint32_t number_of_counters,
_In_ const sai_policer_stat_t *counter_ids,
_Out_ uint64_t *counters)
{
MUTEX();
SWSS_LOG_ENTER();
return SAI_STATUS_NOT_IMPLEMENTED;
}
sai_status_t redis_clear_policer_stats(
_In_ sai_object_id_t policer_id,
_In_ uint32_t number_of_counters,
_In_ const sai_policer_stat_t *counter_ids)
{
MUTEX();
SWSS_LOG_ENTER();
return SAI_STATUS_NOT_IMPLEMENTED;
}
REDIS_GENERIC_QUAD(POLICER,policer);
const sai_policer_api_t redis_policer_api = {
REDIS_GENERIC_QUAD_API(policer)
redis_get_policer_stats,
redis_clear_policer_stats,
};
| [
"[email protected]"
] | |
447e119585ea58750a96dc5ffd8dceb867927d5f | 33474998bd5b91e54981b95fb0c77a6961be932a | /cwmods/gfx/IndexBuffer.h | c99d15c556990fc05eb7dcfb9d53e6e17f5caee6 | [] | no_license | ParanormalVibe/Better-Progression | ac502b08ada13448090eaff04307c4921c85419e | 8c54574036ce618295a7a25affd646ea0a6295aa | refs/heads/master | 2020-08-28T05:25:27.330364 | 2019-11-10T09:02:39 | 2019-11-10T09:02:39 | 217,606,030 | 6 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 175 | h | #ifndef INDEXBUFFER_H
#define INDEXBUFFER_H
#include "../IDA/types.h"
namespace gfx {
class IndexBuffer {
public:
~IndexBuffer() {};
};
}
#endif // INDEXBUFFER_H
| [
"[email protected]"
] | |
9d7969a9a96437e1195968823c33f860dba88e43 | a7688edeb9d50c63dd9e6d388bd9b9323438e800 | /raceTest/Setup/Deep/w2f/system/topoSetDict6 | e93151e1f6f7f6eb949cbae0dea4832ed94df7ee | [] | no_license | christianwindt/WaveMakerAssessment | 6691edf71cda9173b972335206ee1fbd71df9c28 | 8dcd3d301eec04837c27db3f922658d53e5d39bd | refs/heads/master | 2020-04-11T21:28:43.155770 | 2018-12-19T16:16:03 | 2018-12-19T16:16:03 | 162,106,905 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 902 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 6
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class dictionary;
location "system";
object topoSetDict;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
actions
(
{
name box;
type cellSet;
action new;
source boxToCell;
sourceInfo
{
box (-1e6 -1e6 -70 ) (1e6 1e6 -68.8 );
}
}
);
// ************************************************************************* //
| [
"[email protected]"
] | ||
494860e350217fe8e2724d6f958ec0edc2752a30 | a2f49596b412213b40bd76a4a35acf9f6663a71e | /ParticleSystem.h | eacb93032e8db53a71f05c9238e508cc89557d20 | [
"Apache-2.0"
] | permissive | skylarbpayne/component-entity-system | c350b08a68cd38876f7211d6eed6708297405ec0 | afa8656d877ee829c702242185c91a0f67534bc7 | refs/heads/master | 2020-04-26T11:18:09.690805 | 2014-03-20T00:57:59 | 2014-03-20T00:57:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 383 | h | /**
* The ParticleSystem class handles all the updating
*
* Author: Skylar Payne
* Date: 03/16/2014
* File: ParticleSystem.h
**/
#pragma once
#include "ISystem.h"
class ParticleSystem : public ISystem
{
private:
public:
ParticleSystem() : ISystem("particle") { }
void Update(sf::Time dt) override;
bool ValidateEntity(unsigned int ID) override;
};
| [
"[email protected]"
] |
Subsets and Splits