hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
99f81cb6b13e3ca0fa728799fa64f8d61fa134d0 | 4,765 | cxx | C++ | com/oleutest/perform/cairole/tests/bm_qi.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | com/oleutest/perform/cairole/tests/bm_qi.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | com/oleutest/perform/cairole/tests/bm_qi.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //+------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1993.
//
// File: bm_qi.cxx
//
// Contents: Ole QueryInterface test
//
// Classes: CQueryInterfaceTest
//
// History: 1-July-93 t-martig Created
//
//--------------------------------------------------------------------------
#include <headers.cxx>
#pragma hdrstop
#include <bm_qi.hxx>
// this is just an array of random interface iids. The qi server object
// answers YES to any QI, although the only valid methods on each interface
// are the methods of IUnknown.
//
// the code will answer NO to the following IIDs in order to prevent
// custom marshalling problems...
//
// IID_IMarshal, IID_IStdMarshalInfo, IID_IStdIdentity,
// IID_IPersist, IID_IProxyManager
const IID *iid[] = {&IID_IAdviseSink, &IID_IDataObject,
&IID_IOleObject, &IID_IOleClientSite,
&IID_IParseDisplayName, &IID_IPersistStorage,
&IID_IPersistFile, &IID_IStorage,
&IID_IOleContainer, &IID_IOleItemContainer,
&IID_IOleInPlaceSite, &IID_IOleInPlaceActiveObject,
&IID_IOleInPlaceObject, &IID_IOleInPlaceUIWindow,
&IID_IOleInPlaceFrame, &IID_IOleWindow};
TCHAR *CQueryInterfaceTest::Name ()
{
return TEXT("QueryInterface");
}
SCODE CQueryInterfaceTest::Setup (CTestInput *pInput)
{
SCODE sc;
CTestBase::Setup(pInput);
// get iteration count
m_ulIterations = pInput->GetIterations(Name());
// initialize state
for (ULONG iCtx=0; iCtx<CNT_CLSCTX; iCtx++)
{
sc = pInput->GetGUID(&m_ClsID[iCtx], Name(), apszClsIDName[iCtx]);
if (FAILED(sc))
{
Log (TEXT("Setup - GetClassID failed."), sc);
return sc;
}
INIT_RESULTS(m_ulQueryInterfaceSameTime[iCtx]);
INIT_RESULTS(m_ulPunkReleaseSameTime[iCtx]);
INIT_RESULTS(m_ulQueryInterfaceNewTime[iCtx]);
INIT_RESULTS(m_ulPunkReleaseNewTime[iCtx]);
_pUnk[iCtx] = NULL;
}
sc = InitCOM();
if (FAILED(sc))
{
Log (TEXT("Setup - CoInitialize failed."), sc);
return sc;
}
// create an instance of each qi server object
for (iCtx=0; iCtx<CNT_CLSCTX; iCtx++)
{
sc = CoCreateInstance(m_ClsID[iCtx], NULL, dwaClsCtx[iCtx],
IID_IUnknown, (void **)&_pUnk[iCtx]);
if (FAILED(sc))
{
Log (TEXT("Setup - CoCreateInstance failed"), sc);
}
}
return S_OK;
}
SCODE CQueryInterfaceTest::Cleanup ()
{
for (ULONG iCtx=0; iCtx<CNT_CLSCTX; iCtx++)
{
if (_pUnk[iCtx])
{
_pUnk[iCtx]->Release();
}
}
UninitCOM();
return S_OK;
}
SCODE CQueryInterfaceTest::Run ()
{
CStopWatch sw;
IUnknown *pUnk = NULL;
for (ULONG iCtx=0; iCtx<CNT_CLSCTX; iCtx++)
{
if (!_pUnk[iCtx])
continue;
// same interface each time, releasing after each query
for (ULONG iIter=0; iIter<m_ulIterations; iIter++)
{
sw.Reset ();
SCODE sc = _pUnk[iCtx]->QueryInterface(IID_IStorage, (void **)&pUnk);
m_ulQueryInterfaceSameTime[iCtx][iIter] = sw.Read ();
Log (TEXT("QueryInterface"), sc);
if (SUCCEEDED(sc))
{
sw.Reset();
pUnk->Release ();
m_ulPunkReleaseSameTime[iCtx][iIter] = sw.Read();
}
else
{
m_ulPunkReleaseSameTime[iCtx][iIter] = NOTAVAIL;
}
}
// different interface each time, releasing after each query
for (iIter=0; iIter<m_ulIterations; iIter++)
{
sw.Reset ();
SCODE sc = _pUnk[iCtx]->QueryInterface(*(iid[iIter]), (void **)&pUnk);
m_ulQueryInterfaceNewTime[iCtx][iIter] = sw.Read ();
Log (TEXT("QueryInterface"), sc);
if (SUCCEEDED(sc))
{
sw.Reset();
pUnk->Release ();
m_ulPunkReleaseNewTime[iCtx][iIter] = sw.Read();
}
else
{
m_ulPunkReleaseNewTime[iCtx][iIter] = NOTAVAIL;
}
}
}
return S_OK;
}
SCODE CQueryInterfaceTest::Report (CTestOutput &output)
{
output.WriteSectionHeader (Name(), TEXT("QueryInterface"), *m_pInput);
for (ULONG iCtx=0; iCtx<CNT_CLSCTX; iCtx++)
{
output.WriteString(TEXT("\n"));
output.WriteClassID (&m_ClsID[iCtx]);
output.WriteString(apszClsCtx[iCtx]);
output.WriteString(TEXT("\n"));
output.WriteResults (TEXT("QuerySameInterface"), m_ulIterations,
m_ulQueryInterfaceSameTime[iCtx]);
output.WriteResults (TEXT("Release "), m_ulIterations,
m_ulPunkReleaseSameTime[iCtx]);
output.WriteResults (TEXT("QueryNewInterface "), m_ulIterations,
m_ulQueryInterfaceNewTime[iCtx]);
output.WriteResults (TEXT("Release "), m_ulIterations,
m_ulPunkReleaseNewTime[iCtx]);
}
return S_OK;
}
| 23.944724 | 77 | 0.613431 | npocmaka |
99f85fb50189a5b7b85ce0bd0752dbff255bf3f3 | 5,609 | cc | C++ | src/devices/i2c/drivers/i2c/i2c-child.cc | EnderNightLord-ChromeBook/fuchsia-pine64-pinephone | 05e2c059b57b6217089090a0315971d1735ecf57 | [
"BSD-3-Clause"
] | 14 | 2020-10-25T05:48:36.000Z | 2021-09-20T02:46:20.000Z | src/devices/i2c/drivers/i2c/i2c-child.cc | JokeZhang/fuchsia | d6e9dea8dca7a1c8fa89d03e131367e284b30d23 | [
"BSD-3-Clause"
] | null | null | null | src/devices/i2c/drivers/i2c/i2c-child.cc | JokeZhang/fuchsia | d6e9dea8dca7a1c8fa89d03e131367e284b30d23 | [
"BSD-3-Clause"
] | 2 | 2020-10-25T01:13:49.000Z | 2020-10-26T02:32:13.000Z | // Copyright 2019 The Fuchsia 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 "i2c-child.h"
#include <lib/sync/completion.h>
#include <threads.h>
#include <zircon/types.h>
#include <ddk/binding.h>
#include <ddk/debug.h>
#include <ddk/device.h>
#include <ddk/metadata.h>
#include <ddk/metadata/i2c.h>
#include <fbl/alloc_checker.h>
#include <fbl/mutex.h>
namespace i2c {
void I2cChild::Transfer(fidl::VectorView<bool> segments_is_write,
fidl::VectorView<fidl::VectorView<uint8_t>> write_segments_data,
fidl::VectorView<uint8_t> read_segments_length,
TransferCompleter::Sync& completer) {
if (segments_is_write.count() < 1) {
completer.ReplyError(ZX_ERR_INVALID_ARGS);
return;
}
auto op_list = std::make_unique<i2c_op_t[]>(segments_is_write.count());
size_t write_cnt = 0;
size_t read_cnt = 0;
for (size_t i = 0; i < segments_is_write.count(); ++i) {
if (segments_is_write[i]) {
if (write_cnt >= write_segments_data.count()) {
completer.ReplyError(ZX_ERR_INVALID_ARGS);
return;
}
op_list[i].data_buffer = write_segments_data[write_cnt].data();
op_list[i].data_size = write_segments_data[write_cnt].count();
op_list[i].is_read = false;
op_list[i].stop = false;
write_cnt++;
} else {
if (read_cnt >= read_segments_length.count()) {
completer.ReplyError(ZX_ERR_INVALID_ARGS);
return;
}
op_list[i].data_buffer = nullptr; // unused.
op_list[i].data_size = read_segments_length[read_cnt];
op_list[i].is_read = true;
op_list[i].stop = false;
read_cnt++;
}
}
op_list[segments_is_write.count() - 1].stop = true;
if (write_segments_data.count() != write_cnt) {
completer.ReplyError(ZX_ERR_INVALID_ARGS);
return;
}
if (read_segments_length.count() != read_cnt) {
completer.ReplyError(ZX_ERR_INVALID_ARGS);
return;
}
struct Ctx {
sync_completion_t done = {};
TransferCompleter::Sync* completer;
} ctx;
ctx.completer = &completer;
auto callback = [](void* ctx, zx_status_t status, const i2c_op_t* op_list, size_t op_count) {
auto ctx2 = static_cast<Ctx*>(ctx);
if (status == ZX_OK) {
auto reads = std::make_unique<fidl::VectorView<uint8_t>[]>(op_count);
for (size_t i = 0; i < op_count; ++i) {
reads[i].set_data(
fidl::unowned_ptr(static_cast<uint8_t*>(const_cast<void*>(op_list[i].data_buffer))));
reads[i].set_count(op_list[i].data_size);
}
fidl::VectorView<fidl::VectorView<uint8_t>> all_reads(fidl::unowned_ptr(reads.get()),
op_count);
ctx2->completer->ReplySuccess(std::move(all_reads));
} else {
ctx2->completer->ReplyError(status);
}
sync_completion_signal(&ctx2->done);
};
bus_->Transact(address_, op_list.get(), segments_is_write.count(), callback, &ctx);
sync_completion_wait(&ctx.done, zx::duration::infinite().get());
}
void I2cChild::I2cTransact(const i2c_op_t* op_list, size_t op_count, i2c_transact_callback callback,
void* cookie) {
bus_->Transact(address_, op_list, op_count, callback, cookie);
}
zx_status_t I2cChild::I2cGetMaxTransferSize(size_t* out_size) {
*out_size = bus_->max_transfer();
return ZX_OK;
}
zx_status_t I2cChild::I2cGetInterrupt(uint32_t flags, zx::interrupt* out_irq) {
// This is only used by the Intel I2C driver.
// TODO: Pass these interrupt numbers from intel-i2c.
if (address_ == 0xa) {
// Please do not use get_root_resource() in new code. See fxbug.dev/31358.
zx_status_t status = zx::interrupt::create(zx::resource(get_root_resource()), 0x1f,
ZX_INTERRUPT_MODE_LEVEL_LOW, out_irq);
if (status != ZX_OK) {
return status;
}
return ZX_OK;
} else if (address_ == 0x49) {
// Please do not use get_root_resource() in new code. See fxbug.dev/31358.
zx_status_t status = zx::interrupt::create(zx::resource(get_root_resource()), 0x33,
ZX_INTERRUPT_MODE_LEVEL_LOW, out_irq);
if (status != ZX_OK) {
return status;
}
return ZX_OK;
} else if (address_ == 0x10) {
// Acer12
// Please do not use get_root_resource() in new code. See fxbug.dev/31358.
zx_status_t status = zx::interrupt::create(zx::resource(get_root_resource()), 0x1f,
ZX_INTERRUPT_MODE_LEVEL_LOW, out_irq);
if (status != ZX_OK) {
return status;
}
return ZX_OK;
} else if (address_ == 0x50) {
// Please do not use get_root_resource() in new code. See fxbug.dev/31358.
zx_status_t status = zx::interrupt::create(zx::resource(get_root_resource()), 0x18,
ZX_INTERRUPT_MODE_EDGE_LOW, out_irq);
if (status != ZX_OK) {
return status;
}
return ZX_OK;
} else if (address_ == 0x15) {
// Please do not use get_root_resource() in new code. See fxbug.dev/31358.
zx_status_t status = zx::interrupt::create(zx::resource(get_root_resource()), 0x2b,
ZX_INTERRUPT_MODE_EDGE_LOW, out_irq);
if (status != ZX_OK) {
return status;
}
return ZX_OK;
}
return ZX_ERR_NOT_FOUND;
}
void I2cChild::DdkUnbind(ddk::UnbindTxn txn) { txn.Reply(); }
void I2cChild::DdkRelease() { delete this; }
} // namespace i2c
| 35.726115 | 100 | 0.633446 | EnderNightLord-ChromeBook |
99faccc599709f54020bcb9b3388e1c1380dfa74 | 6,744 | cpp | C++ | src/graphics/Primitives.cpp | PatrickDahlin/Untitled-Game | e12a0eb9b83d45727201fd47ca073e6c2530cb48 | [
"Zlib",
"MIT"
] | null | null | null | src/graphics/Primitives.cpp | PatrickDahlin/Untitled-Game | e12a0eb9b83d45727201fd47ca073e6c2530cb48 | [
"Zlib",
"MIT"
] | null | null | null | src/graphics/Primitives.cpp | PatrickDahlin/Untitled-Game | e12a0eb9b83d45727201fd47ca073e6c2530cb48 | [
"Zlib",
"MIT"
] | null | null | null | #include "graphics/Primitives.hpp"
#include <vector>
#include <glm/glm.hpp>
typedef glm::vec3 v3;
typedef glm::vec2 v2;
typedef glm::vec4 v4;
/*
p4 -- p3
| |
p1 -- p2
*/
void add_face(std::vector<v3>& v,
std::vector<v3>& n,
std::vector<v4>& c,
std::vector<v2>& t,
v3 p1,
v3 p2,
v3 p3,
v3 p4,
v3 n1,
v4 c1)
{
v.emplace_back(p1);
v.emplace_back(p2);
v.emplace_back(p3);
v.emplace_back(p1);
v.emplace_back(p3);
v.emplace_back(p4);
t.emplace_back(v2(0,0));
t.emplace_back(v2(1,0));
t.emplace_back(v2(1,1));
t.emplace_back(v2(0,0));
t.emplace_back(v2(1,1));
t.emplace_back(v2(0,1));
n.emplace_back(n1);
n.emplace_back(n1);
n.emplace_back(n1);
n.emplace_back(n1);
n.emplace_back(n1);
n.emplace_back(n1);
c.emplace_back(c1);
c.emplace_back(c1);
c.emplace_back(c1);
c.emplace_back(c1);
c.emplace_back(c1);
c.emplace_back(c1);
}
Model* Primitives::create_cube()
{
Model* model = new Model();
std::vector<v3> pos;
std::vector<v3> norm;
std::vector<v4> cols;
std::vector<v2> tex;
const float n = -0.5f;
const float p = 0.5f;
// FRONT
add_face(pos, norm, cols, tex,
v3(n,n,n),v3(p,n,n),
v3(p,p,n),v3(n,p,n),
v3(0,0,-1),v4(1,1,1,1));
// BACK
add_face(pos, norm, cols, tex,
v3(p,n,p),v3(n,n,p),
v3(n,p,p),v3(p,p,p),
v3(0,0,1),v4(1,1,1,1));
// TOP
add_face(pos, norm, cols, tex,
v3(n,p,n),v3(p,p,n),
v3(p,p,p),v3(n,p,p),
v3(0,1,0),v4(1,1,1,1));
// BOTTOM
add_face(pos, norm, cols, tex,
v3(n,n,p),v3(p,n,p),
v3(p,n,n),v3(n,n,n),
v3(0,-1,0),v4(1,1,1,1));
// LEFT
add_face(pos, norm, cols, tex,
v3(n,n,p),v3(n,n,n),
v3(n,p,n),v3(n,p,p),
v3(-1,0,0),v4(1,1,1,1));
// RIGHT
add_face(pos, norm, cols, tex,
v3(p,n,n),v3(p,n,p),
v3(p,p,p),v3(p,p,n),
v3(1,0,0),v4(1,1,1,1));
model->set_vertices(pos);
model->set_normals(norm);
model->set_colors(cols);
model->set_texcoords(tex);
return model;
}
Model* Primitives::create_quad(const float w, const float h)
{
Model* model = new Model();
std::vector<v3> pos;
std::vector<v3> norm;
std::vector<v4> cols;
std::vector<v2> tex;
add_face(pos, norm, cols, tex,
v3( -w/2.0f, -h/2.0f, 0),v3( w/2.0f, h/2.0f, 0),
v3( w/2.0f, h/2.0f, 0),v3(-w/2.0f, h/2.0f,0),
v3(0,0,-1),v4(1,1,1,1));
model->set_vertices(pos);
model->set_normals(norm);
model->set_colors(cols);
model->set_texcoords(tex);
return model;
}
/*
void make_cube(Model& model, glm::vec4 col, glm::vec3 pos, float scale)
{
float n = -0.5f;
float p = 0.5f;
std::vector<glm::vec3> verts;
std::vector<glm::vec4> colors;
std::vector<glm::vec2> texcoords;
// FRONT
verts.emplace_back(pos + glm::vec3(n,n,n) * scale);
verts.emplace_back(pos + glm::vec3(p,n,n) * scale);
verts.emplace_back(pos + glm::vec3(p,p,n) * scale);
verts.emplace_back(pos + glm::vec3(n,n,n) * scale);
verts.emplace_back(pos + glm::vec3(p,p,n) * scale);
verts.emplace_back(pos + glm::vec3(n,p,n) * scale);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,0); texcoords.emplace_back(1,1);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,1); texcoords.emplace_back(0,1);
// TOP
verts.emplace_back(pos + glm::vec3(n,p,n) * scale);
verts.emplace_back(pos + glm::vec3(p,p,p) * scale);
verts.emplace_back(pos + glm::vec3(p,p,n) * scale);
verts.emplace_back(pos + glm::vec3(n,p,n) * scale);
verts.emplace_back(pos + glm::vec3(p,p,p) * scale);
verts.emplace_back(pos + glm::vec3(n,p,p) * scale);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,0); texcoords.emplace_back(1,1);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,1); texcoords.emplace_back(0,1);
// LEFT
verts.emplace_back(pos + glm::vec3(n,n,p) * scale);
verts.emplace_back(pos + glm::vec3(n,p,n) * scale);
verts.emplace_back(pos + glm::vec3(n,n,n) * scale);
verts.emplace_back(pos + glm::vec3(n,n,p) * scale);
verts.emplace_back(pos + glm::vec3(n,p,n) * scale);
verts.emplace_back(pos + glm::vec3(n,p,p) * scale);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,0); texcoords.emplace_back(1,1);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,1); texcoords.emplace_back(0,1);
// RIGHT
verts.emplace_back(pos + glm::vec3(p,n,n) * scale);
verts.emplace_back(pos + glm::vec3(p,n,p) * scale);
verts.emplace_back(pos + glm::vec3(p,p,p) * scale);
verts.emplace_back(pos + glm::vec3(p,n,n) * scale);
verts.emplace_back(pos + glm::vec3(p,p,p) * scale);
verts.emplace_back(pos + glm::vec3(p,p,n) * scale);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,0); texcoords.emplace_back(1,1);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,1); texcoords.emplace_back(0,1);
// BOTTOM
verts.emplace_back(pos + glm::vec3(n,n,p) * scale);
verts.emplace_back(pos + glm::vec3(p,n,p) * scale);
verts.emplace_back(pos + glm::vec3(p,n,n) * scale);
verts.emplace_back(pos + glm::vec3(n,n,p) * scale);
verts.emplace_back(pos + glm::vec3(p,n,n) * scale);
verts.emplace_back(pos + glm::vec3(n,n,n) * scale);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,0); texcoords.emplace_back(1,1);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,1); texcoords.emplace_back(0,1);
// BACK
verts.emplace_back(pos + glm::vec3(n,n,p) * scale);
verts.emplace_back(pos + glm::vec3(p,p,p) * scale);
verts.emplace_back(pos + glm::vec3(p,n,p) * scale);
verts.emplace_back(pos + glm::vec3(n,n,p) * scale);
verts.emplace_back(pos + glm::vec3(n,p,p) * scale);
verts.emplace_back(pos + glm::vec3(p,p,p) * scale);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
colors.emplace_back(col); colors.emplace_back(col); colors.emplace_back(col);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,0); texcoords.emplace_back(1,1);
texcoords.emplace_back(0,0); texcoords.emplace_back(1,1); texcoords.emplace_back(0,1);
model.set_vertices(verts);
model.set_colors(colors);
model.set_texcoords(texcoords);
}
*/ | 27.867769 | 87 | 0.668298 | PatrickDahlin |
99fd76bb3603af515c1cebf7a7aa4e300efa562c | 17,006 | cpp | C++ | src/LevScene/LevSceneUtil.cpp | wakare/Leviathan | 8a488f014d6235c5c6e6422c9f53c82635b7ebf7 | [
"MIT"
] | 3 | 2019-03-05T13:05:30.000Z | 2019-12-16T05:56:21.000Z | src/LevScene/LevSceneUtil.cpp | wakare/Leviathan | 8a488f014d6235c5c6e6422c9f53c82635b7ebf7 | [
"MIT"
] | null | null | null | src/LevScene/LevSceneUtil.cpp | wakare/Leviathan | 8a488f014d6235c5c6e6422c9f53c82635b7ebf7 | [
"MIT"
] | null | null | null | #include "LevSceneUtil.h"
#include "LevMeshObject.h"
#include "LevSceneObject.h"
#include "LevRAttrRenderObjectAttributeBinder.h"
namespace Leviathan
{
namespace Scene
{
bool LevSceneUtil::InitSceneNodeWithMeshFile(const char * mesh_file, unsigned scene_object_mask, LSPtr<LevSceneNode>& out_scene_node)
{
LSPtr<LevMeshObject> mesh_object = new LevMeshObject;
EXIT_IF_FALSE(mesh_object->LoadMeshFile(mesh_file));
LSPtr<LevSceneObject> scene_object = new LevSceneObject(scene_object_mask);
EXIT_IF_FALSE(scene_object->SetObjectDesc(TryCast<LevMeshObject, LevSceneObjectDescription>(mesh_object)));
out_scene_node.Reset(new LevSceneNode(scene_object));
return true;
}
// TODO: Handle different bind_type
bool LevSceneUtil::BindMeshDataToRenderAttribute(LevSceneNode& node, int bind_type_mask)
{
const Scene::LevMeshObject* meshes = dynamic_cast<const Scene::LevMeshObject*>(&node.GetNodeData()->GetObjectDesc());
EXIT_IF_FALSE(meshes);
// Bind attributes
size_t primitive_vertex_count = 0;
size_t vertex_count = 0;
for (auto& mesh : meshes->GetMesh())
{
primitive_vertex_count += mesh->GetPrimitiveCount();
vertex_count += mesh->GetVertexCount();
}
LSPtr<RAIIBufferData> index_buffer = new RAIIBufferData(3 * sizeof(unsigned) * primitive_vertex_count);
LSPtr<RAIIBufferData> vertex_buffer = new RAIIBufferData(3 * sizeof(float) * vertex_count);
unsigned last_index = 0;
unsigned* index_buffer_pointer = static_cast<unsigned*>(index_buffer->GetArrayData());
float* vertex_buffer_pointer = static_cast<float*>(vertex_buffer->GetArrayData());
for (auto& mesh : meshes->GetMesh())
{
const auto sub_mesh_vertex_count = mesh->GetVertexCount();
const auto sub_mesh_index_count = mesh->GetPrimitiveCount();
const auto* vertex_array = mesh->GetVertex3DCoordArray();
memcpy(vertex_buffer_pointer, vertex_array, 3 * sizeof(float) * sub_mesh_vertex_count);
unsigned* index = mesh->GetPrimitiveIndexArray();
for (unsigned i = 0; i < 3 * sub_mesh_index_count; i++)
{
index_buffer_pointer[0] = index[i] + last_index;
index_buffer_pointer++;
}
last_index += sub_mesh_vertex_count;
vertex_buffer_pointer += 3 * sub_mesh_vertex_count;
}
LSPtr<Scene::LevRAttrRenderObjectAttributeBinder> attribute_binder = new Scene::LevRAttrRenderObjectAttributeBinder(vertex_count);
attribute_binder->BindAttribute(0, new LevRenderObjectAttribute(Scene::RenderObjectAttributeType::EROAT_FLOAT, 3 * sizeof(float), vertex_buffer));
attribute_binder->SetIndexAttribute(new LevRenderObjectAttribute(Scene::RenderObjectAttributeType::EROAT_UINT, sizeof(unsigned), index_buffer));
node.GetNodeData()->AddAttribute(TryCast<Scene::LevRAttrRenderObjectAttributeBinder, Scene::LevSceneObjectAttribute>(attribute_binder));
return true;
}
bool LevSceneUtil::GenerateEmptySceneNode(LSPtr<LevSceneNode>& out)
{
const LSPtr<LevSceneObject> empty_object = new LevSceneObject(ELSOT_EMPTY);
out.Reset(new LevSceneNode(empty_object));
return true;
}
bool LevSceneUtil::GenerateCube(const float* cube_center, float cube_length, LSPtr<LevSceneNode>& out_cube_node)
{
LSPtr<RAIIBufferData> vertices_buffer = new RAIIBufferData(8 * 3 * sizeof(float));
float* data = static_cast<float*>(vertices_buffer->GetArrayData());
LSPtr<RAIIBufferData> normal_buffer = new RAIIBufferData(8 * 3 * sizeof(float));
float* normal_data = static_cast<float*>(vertices_buffer->GetArrayData());
float _cube[] =
{
-cube_length, -cube_length, -cube_length,
-cube_length, -cube_length, cube_length,
-cube_length, cube_length, -cube_length,
-cube_length, cube_length, cube_length,
cube_length, -cube_length, -cube_length,
cube_length, -cube_length, cube_length,
cube_length, cube_length, -cube_length,
cube_length, cube_length, cube_length
};
for (unsigned i = 0; i < 8; i++)
{
_cube[3 * i] += cube_center[0];
_cube[3 * i + 1] += cube_center[1];
_cube[3 * i + 2] += cube_center[2];
}
memcpy(data, _cube, sizeof(_cube));
const float NORMAL_PART_VALUE = 0.57735f;
float _normal[] =
{
-NORMAL_PART_VALUE, -NORMAL_PART_VALUE, -NORMAL_PART_VALUE,
-NORMAL_PART_VALUE, -NORMAL_PART_VALUE, NORMAL_PART_VALUE,
-NORMAL_PART_VALUE, NORMAL_PART_VALUE, -NORMAL_PART_VALUE,
-NORMAL_PART_VALUE, NORMAL_PART_VALUE, NORMAL_PART_VALUE,
NORMAL_PART_VALUE, -NORMAL_PART_VALUE, -NORMAL_PART_VALUE,
NORMAL_PART_VALUE, -NORMAL_PART_VALUE, NORMAL_PART_VALUE,
NORMAL_PART_VALUE, NORMAL_PART_VALUE, -NORMAL_PART_VALUE,
NORMAL_PART_VALUE, NORMAL_PART_VALUE, NORMAL_PART_VALUE,
};
memcpy(normal_data, _normal, sizeof(_normal));
LSPtr<RAIIBufferData> indices_buffer = new RAIIBufferData(6 * 2 * 3 * sizeof(unsigned));
unsigned* indices_data = static_cast<unsigned*>(indices_buffer->GetArrayData());
unsigned indices[] =
{
0, 3, 1,
0, 2, 3,
0, 2, 6,
0, 6, 4,
0, 1, 5,
0, 5, 4,
7, 6, 4,
7, 4, 5,
7, 5, 1,
7, 1, 3,
7, 6, 2,
7, 2, 3
};
memcpy(indices_data, indices, sizeof(indices));
LSPtr<LevRAttrRenderObjectAttributeBinder> attribute_binder = new LevRAttrRenderObjectAttributeBinder(8);
LSPtr<LevRenderObjectAttribute> vertices_attribute = new LevRenderObjectAttribute(EROAT_FLOAT, 3 * sizeof(float), vertices_buffer);
attribute_binder->BindAttribute(0, vertices_attribute);
LSPtr<LevRenderObjectAttribute> normals_attribute = new LevRenderObjectAttribute(EROAT_FLOAT, 3 * sizeof(float), normal_buffer);
attribute_binder->BindAttribute(1, normals_attribute);
LSPtr<LevRenderObjectAttribute> index_attribute = new LevRenderObjectAttribute(EROAT_UINT, sizeof(unsigned), indices_buffer);
attribute_binder->SetIndexAttribute(index_attribute);
LSPtr<LevSceneObject> object = new LevSceneObject(ELSOT_DYNAMIC);
object->AddAttribute(TryCast<LevRAttrRenderObjectAttributeBinder, LevSceneObjectAttribute>(attribute_binder));
out_cube_node.Reset(new LevSceneNode(object));
return true;
}
bool LevSceneUtil::GenerateBallNode(const float* ball_center, float ball_radius, LSPtr<LevSceneNode>& out_ball_node)
{
constexpr float angle_delta = 15.0f * PI_FLOAT / 180.0f;
constexpr size_t step_count = 2 * PI_FLOAT / angle_delta;
Eigen::Vector3f current_scan_half_ball[step_count + 1];
// Init base scan line
for (size_t i = 0; i <= step_count; i++)
{
float coord[] = { sinf(angle_delta * i) , cosf(angle_delta * i) , 0.0f };
memcpy(current_scan_half_ball[i].data(), coord, 3 * sizeof(float));
}
// Generate step rotation matrix (Rotate with x axis)
Eigen::Matrix3f rotation_step;
float rotation[] =
{
1.0f, 0.0f, 0.0f,
0.0f, cosf(angle_delta), sinf(angle_delta),
0.0f, -sinf(angle_delta), cosf(angle_delta),
};
memcpy(rotation_step.data(), rotation, sizeof(rotation));
std::vector<Eigen::Vector3f> m_vertices;
std::vector<Eigen::Vector3f> m_normals;
std::vector<unsigned> m_indices;
unsigned current_index_offset = 0;
for (auto& vertex : current_scan_half_ball)
{
m_vertices.push_back(vertex);
}
/*
Current scan line: 0 - 1 - 2 - 3 - 4 - 5
| / | / | / | / | / |
Next scan line: 6 - 7 - 8 - 9 - 10- 11
*/
unsigned index_delta[2 * 3 * step_count];
for (size_t i = 0; i < step_count; i++)
{
unsigned* data = index_delta + 2 * 3 * i;
data[0] = i;
data[1] = i + 1;
data[2] = step_count + 1 + i;
data[3] = data[2];
data[4] = data[1];
data[5] = data[2] + 1;
}
for (size_t i = 0; i < step_count; i++)
{
Eigen::Vector3f next_scan_half_ball[step_count + 1];
for (size_t j = 0; j <= step_count; j++)
{
next_scan_half_ball[j] = rotation_step * current_scan_half_ball[j];
m_vertices.push_back(next_scan_half_ball[j]);
}
for (auto index : index_delta)
{
m_indices.push_back(index + current_index_offset);
}
memcpy(current_scan_half_ball->data(), next_scan_half_ball->data(), sizeof(next_scan_half_ball));
current_index_offset += (step_count + 1);
}
// calculate normals
size_t vertices_count = m_vertices.size();
for (size_t i = 0; i < vertices_count; i++)
{
m_normals.push_back(m_vertices[i].normalized());
}
// Do radius scale
Eigen::Vector3f ball_center_vector; memcpy(ball_center_vector.data(), ball_center, 3 * sizeof(float));
for (size_t i = 0; i < m_vertices.size(); i++)
{
auto& vertex = m_vertices[i];
vertex *= ball_radius;
vertex += ball_center_vector;
}
// Convert vertices data
LSPtr<RAIIBufferData> vertices_buffer_data = new RAIIBufferData(m_vertices.size() * 3 * sizeof(float));
float* coord_data = static_cast<float*>(vertices_buffer_data->GetArrayData());
for (size_t i = 0; i < m_vertices.size(); i++)
{
float* data = coord_data + 3 * i;
memcpy(data, m_vertices[i].data(), 3 * sizeof(float));
}
LSPtr<RAIIBufferData> normals_buffer_data = new RAIIBufferData(m_normals.size() * 3 * sizeof(float));
float* normal_data = static_cast<float*>(normals_buffer_data->GetArrayData());
for (size_t i = 0; i < m_normals.size(); i++)
{
float* data = normal_data + 3 * i;
memcpy(data, m_normals[i].data(), 3 * sizeof(float));
}
LSPtr<LevRAttrRenderObjectAttributeBinder> attribute_binder = new LevRAttrRenderObjectAttributeBinder(m_vertices.size());
LSPtr<LevRenderObjectAttribute> vertices_attribute = new LevRenderObjectAttribute(EROAT_FLOAT, 3 * sizeof(float), vertices_buffer_data);
attribute_binder->BindAttribute(0, vertices_attribute);
LSPtr<LevRenderObjectAttribute> normals_attribute = new LevRenderObjectAttribute(EROAT_FLOAT, 3 * sizeof(float), normals_buffer_data);
attribute_binder->BindAttribute(1, normals_attribute);
LSPtr<RAIIBufferData> indices_buffer_data = new RAIIBufferData(m_indices.size() * sizeof(unsigned));
unsigned* indices_data = static_cast<unsigned*>(indices_buffer_data->GetArrayData());
for (size_t i = 0; i < m_indices.size(); i++)
{
unsigned* data = indices_data + i;
*data = m_indices[i];
}
LSPtr<LevRenderObjectAttribute> index_attribute = new LevRenderObjectAttribute(EROAT_UINT, sizeof(unsigned), indices_buffer_data);
attribute_binder->SetIndexAttribute(index_attribute);
LSPtr<LevSceneObject> object = new LevSceneObject(ELSOT_DYNAMIC);
object->AddAttribute(TryCast<LevRAttrRenderObjectAttributeBinder, LevSceneObjectAttribute>(attribute_binder));
out_ball_node.Reset(new LevSceneNode(object));
return true;
}
bool LevSceneUtil::GeneratePlaneNode(const float* plane_node0, const float* plane_node1, const float* plane_node2, const float* plane_node3, LSPtr<LevSceneNode>& out_plane_node)
{
float vertices[12];
memcpy(vertices, plane_node0, 3 * sizeof(float));
memcpy(vertices + 3, plane_node1, 3 * sizeof(float));
memcpy(vertices + 6, plane_node2, 3 * sizeof(float));
memcpy(vertices + 9, plane_node3, 3 * sizeof(float));
LSPtr<RAIIBufferData> vertices_buffer_data = new RAIIBufferData(sizeof(vertices));
memcpy(vertices_buffer_data->GetArrayData(), vertices, sizeof(vertices));
/*
Calculate plane normal
*/
Eigen::Vector3f edge0;
edge0.x() = plane_node0[0] - plane_node1[0];
edge0.y() = plane_node0[1] - plane_node1[1];
edge0.z() = plane_node0[2] - plane_node1[2];
Eigen::Vector3f edge1;
edge1.x() = plane_node1[0] - plane_node2[0];
edge1.y() = plane_node1[1] - plane_node2[1];
edge1.z() = plane_node1[2] - plane_node2[2];
Eigen::Vector3f normal;
normal = edge0.cross(edge1);
normal.normalize();
LSPtr<RAIIBufferData> normals_buffer_data = new RAIIBufferData(sizeof(vertices));
float* normal_data = static_cast<float*>(normals_buffer_data->GetArrayData());
for (size_t i = 0; i < 4; i++)
{
memcpy(normal_data + 3 * i, normal.data(), 3 * sizeof(float));
}
LSPtr<LevRenderObjectAttribute> vertex_attibute = new LevRenderObjectAttribute(EROAT_FLOAT, 3 * sizeof(float), vertices_buffer_data);
LSPtr<LevRenderObjectAttribute> normal_attribute = new LevRenderObjectAttribute(EROAT_FLOAT, 3 * sizeof(float), normals_buffer_data);
unsigned indexs[6] =
{
0, 1, 2,
0, 2, 3
};
LSPtr<RAIIBufferData> index_buffer_data = new RAIIBufferData(sizeof(indexs));
memcpy(index_buffer_data->GetArrayData(), indexs, sizeof(indexs));
LSPtr<LevRenderObjectAttribute> index_attribute = new LevRenderObjectAttribute(EROAT_UINT, sizeof(unsigned), index_buffer_data);
LSPtr<LevRAttrRenderObjectAttributeBinder> attribute_binder = new LevRAttrRenderObjectAttributeBinder(4);
attribute_binder->BindAttribute(0, vertex_attibute);
attribute_binder->BindAttribute(1, normal_attribute);
attribute_binder->SetIndexAttribute(index_attribute);
LSPtr<LevSceneObject> plane_object = new LevSceneObject(ELSOT_DYNAMIC);
plane_object->AddAttribute(TryCast<LevRAttrRenderObjectAttributeBinder, LevSceneObjectAttribute>(attribute_binder));
out_plane_node.Reset(new LevSceneNode(plane_object));
return true;
}
bool LevSceneUtil::GeneratePoints(const float* vertices, const float* normals,
unsigned count, LSPtr<LevSceneNode>& out_points_node)
{
LSPtr<LevRAttrRenderObjectAttributeBinder> attribute_binder = new LevRAttrRenderObjectAttributeBinder(count);
LSPtr<RAIIBufferData> vertices_data = new RAIIBufferData(count * 3 * sizeof(float));
memcpy(vertices_data->GetArrayData(), vertices, 3 * count * sizeof(float));
LSPtr<LevRenderObjectAttribute> vertices_attribute = new LevRenderObjectAttribute(EROAT_FLOAT, 3 * sizeof(float), vertices_data);
attribute_binder->BindAttribute(0, vertices_attribute);
if (normals)
{
LSPtr<RAIIBufferData> normals_data = new RAIIBufferData(count * 3 * sizeof(float));
memcpy(normals_data->GetArrayData(), normals, 3 * count * sizeof(float));
LSPtr<LevRenderObjectAttribute> normals_attribute = new LevRenderObjectAttribute(EROAT_FLOAT, 3 * count * sizeof(float), normals_data);
attribute_binder->BindAttribute(1, normals_attribute);
}
attribute_binder->SetPrimitiveType(EROPT_POINTS);
LSPtr<LevSceneObject> point_object = new LevSceneObject(ELSOT_DYNAMIC);
point_object->AddAttribute(attribute_binder);
out_points_node.Reset(new LevSceneNode(point_object));
return true;
}
bool LevSceneUtil::GenerateIdentityMatrixUniform(const char* uniform_name, LSPtr<LevNumericalUniform>& out_uniform)
{
static float identity_matrix[] =
{
1.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f
};
out_uniform.Reset(new LevNumericalUniform(uniform_name, TYPE_FLOAT_MAT4));
LSPtr<RAIIBufferData> identity_matrix_buffer_data = new RAIIBufferData(sizeof(identity_matrix));
identity_matrix_buffer_data->SetArrayData(identity_matrix, sizeof(identity_matrix));
out_uniform->SetData(identity_matrix_buffer_data);
return true;
}
bool LevSceneUtil::GenerateLookAtMatrixUniform(const char* uniform_name, const float* eye, const float* target,
const float* up, LSPtr<LevNumericalUniform>& out_uniform)
{
Eigen::Vector3f N, U, V;
Eigen::Vector3f veye; memcpy(veye.data(), eye, 3 * sizeof(float));
Eigen::Vector3f vup; memcpy(vup.data(), up, 3 * sizeof(float));
Eigen::Vector3f vlookat; memcpy(vlookat.data(), target, 3 * sizeof(float));
N = vlookat - veye;
N.normalize();
U = vup.cross(N);
U.normalize();
V = N.cross(U);
V.normalize();
float data[16] =
{
U[0], U[1], U[2], 0.0f,
V[0], V[1], V[2], 0.0f,
N[0], N[1], N[2], 0.0f,
-U.dot(veye), -V.dot(veye), -N.dot(veye), 1.0f,
};
out_uniform.Reset(new LevNumericalUniform(uniform_name, TYPE_FLOAT_MAT4));
LSPtr<RAIIBufferData> identity_matrix_buffer_data = new RAIIBufferData(sizeof(data));
identity_matrix_buffer_data->SetArrayData(data, sizeof(data));
out_uniform->SetData(identity_matrix_buffer_data);
return true;
}
bool LevSceneUtil::GenerateProjectionMatrix(const char* uniform_name, float fov, float aspect, float near, float far, LSPtr<LevNumericalUniform>& out_uniform)
{
float T = tanf(fov / 2.0f);
float N = near - far;
float M = near + far;
float K = aspect * T;
float L = far * near;
float data[16] =
{
1.0f / K, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f / T, 0.0f, 0.0f,
0.0f, 0.0f, -M / N, 1.0f,
0.0f, 0.0f, 2 * L / N, 0.0f
};
out_uniform.Reset(new LevNumericalUniform(uniform_name, TYPE_FLOAT_MAT4));
LSPtr<RAIIBufferData> identity_matrix_buffer_data = new RAIIBufferData(sizeof(data));
identity_matrix_buffer_data->SetArrayData(data, sizeof(data));
out_uniform->SetData(identity_matrix_buffer_data);
return true;
}
}
} | 36.730022 | 179 | 0.711043 | wakare |
8200dabecfc445f3828d119c8d6f6b47f8c17d3d | 2,409 | cpp | C++ | TileServer und Tiles/filereader.cpp | andr1312e/Russia-Tiles-Server | c1d596b84e22c170ba0f795ed6e2bfb80167eeb6 | [
"Unlicense"
] | null | null | null | TileServer und Tiles/filereader.cpp | andr1312e/Russia-Tiles-Server | c1d596b84e22c170ba0f795ed6e2bfb80167eeb6 | [
"Unlicense"
] | null | null | null | TileServer und Tiles/filereader.cpp | andr1312e/Russia-Tiles-Server | c1d596b84e22c170ba0f795ed6e2bfb80167eeb6 | [
"Unlicense"
] | null | null | null | #include "filereader.h"
ImageRotator::ImageRotator(const QString *pathToSourceSvg, const QString *pathToRendedImage, const QString *fileType, const QString *slash, const QString *svgType, QObject *parent)
: QObject(parent)
, m_file(new QFile())
, m_pathToSourceSvgFolder(pathToSourceSvg)
, m_pathToRendedImageFolder(pathToRendedImage)
, m_fileType(fileType)
, m_slash(slash)
, m_svgType(svgType)
, m_image(new QImage(497, 279, QImage::Format_RGB32))
, m_renderer(new QSvgRenderer())
, m_painter(new QPainter(m_image))
, index(100)
, m_previousCharInArray(' ')
, m_array(Q_NULLPTR)
{
m_painter->setCompositionMode(QPainter::CompositionMode_SourceOver);
m_painter->setRenderHints(QPainter::Antialiasing, true);
m_renderer->setFramesPerSecond(0);
}
ImageRotator::~ImageRotator()
{
delete m_file;
delete m_image;
delete m_renderer;
delete m_painter;
}
void ImageRotator::setParams(QString &tile, QString &azm, QString &layer, char &firstNum, char &secondNum, char &thirdNum)
{
m_pathToSource.append(*m_pathToSourceSvgFolder).append(layer).append(*m_slash).append(tile).append(*m_svgType);
m_pathToRender.append(*m_pathToRendedImageFolder).append(layer).append(*m_slash).append(azm).append(*m_slash).append(tile).append(*m_fileType);
m_firstNum=firstNum;
m_secondNum=secondNum;
m_thirdNum=thirdNum;
}
void ImageRotator::doing()
{
m_file->setFileName(m_pathToSource);
m_file->open(QIODevice::ReadOnly);
m_array=m_file->readAll();
m_file->close();
for (index; index<m_array.size()-10; index=index+1)
{
if(m_previousCharInArray=='('&&m_array.at(index)==' '&&m_array.at(index+1)==' ')
{
m_array.operator[](index+2)=m_firstNum;
m_array.operator[](index+3)=m_secondNum;
m_array.operator[](index+4)=m_thirdNum;
index=index+60;
}
m_previousCharInArray=m_array.at(index);
}
m_renderer->load(m_array);
m_renderer->render(m_painter);
m_image->save(m_pathToRender);
index=40;
// m_file->setFileName(*m_pathToSourceSvg+m_layer+ "_1"+*m_slash+m_tileName+*m_svgType);
// m_file->open(QIODevice::WriteOnly);
// m_file->write(m_array);
// m_file->flush();
// m_file->close();
m_pathToSource.clear();
m_pathToRender.clear();
m_previousCharInArray=' ';
Q_EMIT finished();
}
| 34.913043 | 180 | 0.689913 | andr1312e |
8200f3e25afdf83ecf00d91a958e787e807a0aeb | 702 | cpp | C++ | dkcoro/utils.cpp | huahang/dkcoro | c1e8a69e07fd8cc80886fe1fc4a931d97ce3bc91 | [
"Apache-2.0"
] | null | null | null | dkcoro/utils.cpp | huahang/dkcoro | c1e8a69e07fd8cc80886fe1fc4a931d97ce3bc91 | [
"Apache-2.0"
] | null | null | null | dkcoro/utils.cpp | huahang/dkcoro | c1e8a69e07fd8cc80886fe1fc4a931d97ce3bc91 | [
"Apache-2.0"
] | null | null | null | /**
* @author hans@dkmt.io
* @date 2021-06-24
*/
#include "utils.h"
#include <chrono>
namespace dkcoro {
int64_t utils::current_time_millis() {
using std::chrono::duration_cast;
using std::chrono::milliseconds;
using std::chrono::system_clock;
auto now = system_clock::now();
return duration_cast<milliseconds>(now.time_since_epoch()).count();
}
int64_t utils::now() {
return current_time_millis();
}
int64_t utils::nano_time() {
using std::chrono::duration_cast;
using std::chrono::high_resolution_clock;
using std::chrono::nanoseconds;
auto now = high_resolution_clock::now();
return duration_cast<nanoseconds>(now.time_since_epoch()).count();
}
} // namespace dkcoro | 21.9375 | 69 | 0.717949 | huahang |
8201f063c0e7940d8b744a3f528d45a102d272c5 | 9,937 | cpp | C++ | Classes/stk-4.4.1/src/Mesh2D.cpp | jongwook/urMus | b3d22e8011253f137a3581e84db8e79accccc7a4 | [
"MIT",
"AML",
"BSD-3-Clause"
] | 1 | 2015-11-05T00:50:07.000Z | 2015-11-05T00:50:07.000Z | Classes/stk-4.4.1/src/Mesh2D.cpp | jongwook/urMus | b3d22e8011253f137a3581e84db8e79accccc7a4 | [
"MIT",
"AML",
"BSD-3-Clause"
] | null | null | null | Classes/stk-4.4.1/src/Mesh2D.cpp | jongwook/urMus | b3d22e8011253f137a3581e84db8e79accccc7a4 | [
"MIT",
"AML",
"BSD-3-Clause"
] | null | null | null | /***************************************************/
/*! \class Mesh2D
\brief Two-dimensional rectilinear waveguide mesh class.
This class implements a rectilinear,
two-dimensional digital waveguide mesh
structure. For details, see Van Duyne and
Smith, "Physical Modeling with the 2-D Digital
Waveguide Mesh", Proceedings of the 1993
International Computer Music Conference.
This is a digital waveguide model, making its
use possibly subject to patents held by Stanford
University, Yamaha, and others.
Control Change Numbers:
- X Dimension = 2
- Y Dimension = 4
- Mesh Decay = 11
- X-Y Input Position = 1
by Julius Smith, 2000 - 2002.
Revised by Gary Scavone for STK, 2002.
*/
/***************************************************/
#include "Mesh2D.h"
#include "SKINI-msg.h"
namespace stk {
Mesh2D :: Mesh2D( short nX, short nY )
{
this->setNX(nX);
this->setNY(nY);
StkFloat pole = 0.05;
short i;
for (i=0; i<NYMAX; i++) {
filterY_[i].setPole( pole );
filterY_[i].setGain( 0.99 );
}
for (i=0; i<NXMAX; i++) {
filterX_[i].setPole( pole );
filterX_[i].setGain( 0.99 );
}
this->clearMesh();
counter_=0;
xInput_ = 0;
yInput_ = 0;
}
Mesh2D :: ~Mesh2D( void )
{
}
void Mesh2D :: clear( void )
{
this->clearMesh();
short i;
for (i=0; i<NY_; i++)
filterY_[i].clear();
for (i=0; i<NX_; i++)
filterX_[i].clear();
counter_=0;
}
void Mesh2D :: clearMesh( void )
{
int x, y;
for (x=0; x<NXMAX-1; x++) {
for (y=0; y<NYMAX-1; y++) {
v_[x][y] = 0;
}
}
for (x=0; x<NXMAX; x++) {
for (y=0; y<NYMAX; y++) {
vxp_[x][y] = 0;
vxm_[x][y] = 0;
vyp_[x][y] = 0;
vym_[x][y] = 0;
vxp1_[x][y] = 0;
vxm1_[x][y] = 0;
vyp1_[x][y] = 0;
vym1_[x][y] = 0;
}
}
}
StkFloat Mesh2D :: energy( void )
{
// Return total energy contained in wave variables Note that some
// energy is also contained in any filter delay elements.
int x, y;
StkFloat t;
StkFloat e = 0;
if ( counter_ & 1 ) { // Ready for Mesh2D::tick1() to be called.
for (x=0; x<NX_; x++) {
for (y=0; y<NY_; y++) {
t = vxp1_[x][y];
e += t*t;
t = vxm1_[x][y];
e += t*t;
t = vyp1_[x][y];
e += t*t;
t = vym1_[x][y];
e += t*t;
}
}
}
else { // Ready for Mesh2D::tick0() to be called.
for (x=0; x<NX_; x++) {
for (y=0; y<NY_; y++) {
t = vxp_[x][y];
e += t*t;
t = vxm_[x][y];
e += t*t;
t = vyp_[x][y];
e += t*t;
t = vym_[x][y];
e += t*t;
}
}
}
return(e);
}
void Mesh2D :: setNX( short lenX )
{
NX_ = lenX;
if ( lenX < 2 ) {
errorString_ << "Mesh2D::setNX(" << lenX << "): Minimum length is 2!";
handleError( StkError::WARNING );
NX_ = 2;
}
else if ( lenX > NXMAX ) {
errorString_ << "Mesh2D::setNX(" << lenX << "): Maximum length is " << NXMAX << '!';;
handleError( StkError::WARNING );
NX_ = NXMAX;
}
}
void Mesh2D :: setNY( short lenY )
{
NY_ = lenY;
if ( lenY < 2 ) {
errorString_ << "Mesh2D::setNY(" << lenY << "): Minimum length is 2!";
handleError( StkError::WARNING );
NY_ = 2;
}
else if ( lenY > NYMAX ) {
errorString_ << "Mesh2D::setNY(" << lenY << "): Maximum length is " << NXMAX << '!';;
handleError( StkError::WARNING );
NY_ = NYMAX;
}
}
void Mesh2D :: setDecay( StkFloat decayFactor )
{
StkFloat gain = decayFactor;
if ( decayFactor < 0.0 ) {
errorString_ << "Mesh2D::setDecay: decayFactor value is less than 0.0!";
handleError( StkError::WARNING );
gain = 0.0;
}
else if ( decayFactor > 1.0 ) {
errorString_ << "Mesh2D::setDecay decayFactor value is greater than 1.0!";
handleError( StkError::WARNING );
gain = 1.0;
}
int i;
for (i=0; i<NYMAX; i++)
filterY_[i].setGain( gain );
for (i=0; i<NXMAX; i++)
filterX_[i].setGain( gain );
}
void Mesh2D :: setInputPosition( StkFloat xFactor, StkFloat yFactor )
{
if ( xFactor < 0.0 ) {
errorString_ << "Mesh2D::setInputPosition xFactor value is less than 0.0!";
handleError( StkError::WARNING );
xInput_ = 0;
}
else if ( xFactor > 1.0 ) {
errorString_ << "Mesh2D::setInputPosition xFactor value is greater than 1.0!";
handleError( StkError::WARNING );
xInput_ = NX_ - 1;
}
else
xInput_ = (short) (xFactor * (NX_ - 1));
if ( yFactor < 0.0 ) {
errorString_ << "Mesh2D::setInputPosition yFactor value is less than 0.0!";
handleError( StkError::WARNING );
yInput_ = 0;
}
else if ( yFactor > 1.0 ) {
errorString_ << "Mesh2D::setInputPosition yFactor value is greater than 1.0!";
handleError( StkError::WARNING );
yInput_ = NY_ - 1;
}
else
yInput_ = (short) (yFactor * (NY_ - 1));
}
void Mesh2D :: noteOn( StkFloat frequency, StkFloat amplitude )
{
// Input at corner.
if ( counter_ & 1 ) {
vxp1_[xInput_][yInput_] += amplitude;
vyp1_[xInput_][yInput_] += amplitude;
}
else {
vxp_[xInput_][yInput_] += amplitude;
vyp_[xInput_][yInput_] += amplitude;
}
#if defined(_STK_DEBUG_)
errorString_ << "Mesh2D::NoteOn: frequency = " << frequency << ", amplitude = " << amplitude << ".";
handleError( StkError::DEBUG_WARNING );
#endif
}
void Mesh2D :: noteOff( StkFloat amplitude )
{
#if defined(_STK_DEBUG_)
errorString_ << "Mesh2D::NoteOff: amplitude = " << amplitude << ".";
handleError( StkError::DEBUG_WARNING );
#endif
}
StkFloat Mesh2D :: inputTick( StkFloat input )
{
if ( counter_ & 1 ) {
vxp1_[xInput_][yInput_] += input;
vyp1_[xInput_][yInput_] += input;
lastFrame_[0] = tick1();
}
else {
vxp_[xInput_][yInput_] += input;
vyp_[xInput_][yInput_] += input;
lastFrame_[0] = tick0();
}
counter_++;
return lastFrame_[0];
}
StkFloat Mesh2D :: tick( unsigned int )
{
lastFrame_[0] = ((counter_ & 1) ? this->tick1() : this->tick0());
counter_++;
return lastFrame_[0];
}
const StkFloat VSCALE = 0.5;
StkFloat Mesh2D :: tick0( void )
{
int x, y;
StkFloat outsamp = 0;
// Update junction velocities.
for (x=0; x<NX_-1; x++) {
for (y=0; y<NY_-1; y++) {
v_[x][y] = ( vxp_[x][y] + vxm_[x+1][y] +
vyp_[x][y] + vym_[x][y+1] ) * VSCALE;
}
}
// Update junction outgoing waves, using alternate wave-variable buffers.
for (x=0; x<NX_-1; x++) {
for (y=0; y<NY_-1; y++) {
StkFloat vxy = v_[x][y];
// Update positive-going waves.
vxp1_[x+1][y] = vxy - vxm_[x+1][y];
vyp1_[x][y+1] = vxy - vym_[x][y+1];
// Update minus-going waves.
vxm1_[x][y] = vxy - vxp_[x][y];
vym1_[x][y] = vxy - vyp_[x][y];
}
}
// Loop over velocity-junction boundary faces, update edge
// reflections, with filtering. We're only filtering on one x and y
// edge here and even this could be made much sparser.
for (y=0; y<NY_-1; y++) {
vxp1_[0][y] = filterY_[y].tick(vxm_[0][y]);
vxm1_[NX_-1][y] = vxp_[NX_-1][y];
}
for (x=0; x<NX_-1; x++) {
vyp1_[x][0] = filterX_[x].tick(vym_[x][0]);
vym1_[x][NY_-1] = vyp_[x][NY_-1];
}
// Output = sum of outgoing waves at far corner. Note that the last
// index in each coordinate direction is used only with the other
// coordinate indices at their next-to-last values. This is because
// the "unit strings" attached to each velocity node to terminate
// the mesh are not themselves connected together.
outsamp = vxp_[NX_-1][NY_-2] + vyp_[NX_-2][NY_-1];
return outsamp;
}
StkFloat Mesh2D :: tick1( void )
{
int x, y;
StkFloat outsamp = 0;
// Update junction velocities.
for (x=0; x<NX_-1; x++) {
for (y=0; y<NY_-1; y++) {
v_[x][y] = ( vxp1_[x][y] + vxm1_[x+1][y] +
vyp1_[x][y] + vym1_[x][y+1] ) * VSCALE;
}
}
// Update junction outgoing waves,
// using alternate wave-variable buffers.
for (x=0; x<NX_-1; x++) {
for (y=0; y<NY_-1; y++) {
StkFloat vxy = v_[x][y];
// Update positive-going waves.
vxp_[x+1][y] = vxy - vxm1_[x+1][y];
vyp_[x][y+1] = vxy - vym1_[x][y+1];
// Update minus-going waves.
vxm_[x][y] = vxy - vxp1_[x][y];
vym_[x][y] = vxy - vyp1_[x][y];
}
}
// Loop over velocity-junction boundary faces, update edge
// reflections, with filtering. We're only filtering on one x and y
// edge here and even this could be made much sparser.
for (y=0; y<NY_-1; y++) {
vxp_[0][y] = filterY_[y].tick(vxm1_[0][y]);
vxm_[NX_-1][y] = vxp1_[NX_-1][y];
}
for (x=0; x<NX_-1; x++) {
vyp_[x][0] = filterX_[x].tick(vym1_[x][0]);
vym_[x][NY_-1] = vyp1_[x][NY_-1];
}
// Output = sum of outgoing waves at far corner.
outsamp = vxp1_[NX_-1][NY_-2] + vyp1_[NX_-2][NY_-1];
return outsamp;
}
void Mesh2D :: controlChange( int number, StkFloat value )
{
StkFloat norm = value * ONE_OVER_128;
if ( norm < 0 ) {
norm = 0.0;
errorString_ << "Mesh2D::controlChange: control value less than zero ... setting to zero!";
handleError( StkError::WARNING );
}
else if ( norm > 1.0 ) {
norm = 1.0;
errorString_ << "Mesh2D::controlChange: control value greater than 128.0 ... setting to 128.0!";
handleError( StkError::WARNING );
}
if (number == 2) // 2
this->setNX( (short) (norm * (NXMAX-2) + 2) );
else if (number == 4) // 4
this->setNY( (short) (norm * (NYMAX-2) + 2) );
else if (number == 11) // 11
this->setDecay( 0.9 + (norm * 0.1) );
else if (number == __SK_ModWheel_) // 1
this->setInputPosition( norm, norm );
else {
errorString_ << "Mesh2D::controlChange: undefined control number (" << number << ")!";
handleError( StkError::WARNING );
}
#if defined(_STK_DEBUG_)
errorString_ << "Mesh2D::controlChange: number = " << number << ", value = " << value << ".";
handleError( StkError::DEBUG_WARNING );
#endif
}
} // stk namespace
| 24.780549 | 102 | 0.564456 | jongwook |
8204c74eb1e8d078edeeeab4aa26129ea08b00d1 | 3,646 | cpp | C++ | UCF HSPT Documents/2007/Solutions/radio.cpp | p473lr/i-urge-mafia-gear | ae19efb1af2e85ed8bcbbcc3d12ae0f024f3565e | [
"Apache-2.0"
] | null | null | null | UCF HSPT Documents/2007/Solutions/radio.cpp | p473lr/i-urge-mafia-gear | ae19efb1af2e85ed8bcbbcc3d12ae0f024f3565e | [
"Apache-2.0"
] | null | null | null | UCF HSPT Documents/2007/Solutions/radio.cpp | p473lr/i-urge-mafia-gear | ae19efb1af2e85ed8bcbbcc3d12ae0f024f3565e | [
"Apache-2.0"
] | null | null | null |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// There are potenially several ways to solve this problem. This solution
// simply fills a two dimensional boolean array representing whether or
// not a commercial is on for each minute of each station's programming.
// Then, we traverse the array, checking each minute to see if two or more
// stations are playing commercials at that time.
//
// This is probably not the most efficient solution in terms of time or
// memory used, but it is a simple, straightforward way to solve the
// problem.
int main(void)
{
FILE *fp;
char line[256];
int numSessions, numStations;
bool commercials[16][384];
int i, j;
int commercialGap, commercialLength;
int minute;
int commercialCount;
int sessionNum;
int pureCramming;
// Open the input file
fp = fopen("radio.in", "r");
// Get the number of sessions to check
fgets(line, sizeof(line), fp);
sscanf(line, "%d", &numSessions);
// For each session...
for (sessionNum = 1; sessionNum <= numSessions; sessionNum++)
{
// Clear the commercials array to all zeroes (all false values)
memset(commercials, 0, sizeof(commercials));
// Get the number of stations
fgets(line, sizeof(line), fp);
sscanf(line, "%d", &numStations);
// For each station...
for (i = 0; i < numStations; i++)
{
// Read the station's schedule and set up the commercial
// schedule in our array
fgets(line, sizeof(line), fp);
commercialGap = atoi(strtok(line, " \n"));
commercialLength = atoi(strtok(NULL, " \n"));
// Start at minute zero (6:00 PM)
minute = 0;
// Update the schedule all the way through midnight
while (minute < 360)
{
// Skip the commercial gap (the amount of time between
// commercials)
minute += commercialGap;
// Now, iterate through the array for commercialLength
// minutes, and change the entries to true (there is a
// commercial on at this time). Keep track of the overall
// minute as we go, so we don't overrun our array.
j = 0;
while ((j < commercialLength) && (minute < 360))
{
// Change this minute's entry to true
commercials[i][minute] = true;
// Increment the commercial time counter as well as the
// overall minute counter
minute++;
j++;
}
}
}
// Now that the array is set up, scan it minute by minute to see
// how many minutes of pure cramming we have
pureCramming = 0;
for (minute = 0; minute < 360; minute++)
{
// Start with zero commercial on for this minute
commercialCount = 0;
// Check each station for commercials
for (i = 0; i < numStations; i++)
{
// If there's a commercial on this station, increment the
// commercial count
if (commercials[i][minute])
commercialCount++;
}
// If there are two or more commercials on at this time, the
// radio is off and pure cramming ensues
if (commercialCount >= 2)
pureCramming++;
}
// Now, we can print the output
printf("Study session #%d has %d minute(s) of pure cramming."
" Excellent!\n", sessionNum, pureCramming);
}
}
| 32.265487 | 75 | 0.566648 | p473lr |
820537e1be718f43d856f9bc9d230bb86b3198b4 | 77,729 | cc | C++ | src/Newick.cc | pgajer/MCclassifier | 5da58744a4cc58b6c854efff63534aae50c72258 | [
"Unlicense"
] | 6 | 2016-03-05T04:45:16.000Z | 2021-08-07T06:20:07.000Z | src/Newick.cc | pgajer/MCclassifier | 5da58744a4cc58b6c854efff63534aae50c72258 | [
"Unlicense"
] | 2 | 2016-09-20T18:30:27.000Z | 2016-11-08T17:35:11.000Z | src/Newick.cc | pgajer/MCclassifier | 5da58744a4cc58b6c854efff63534aae50c72258 | [
"Unlicense"
] | 2 | 2016-09-20T16:37:40.000Z | 2017-03-11T23:37:04.000Z | // Author: Adam Phillippy
/*
Copyright (C) 2016 Pawel Gajer (pgajer@gmail.com), Adam Phillippy and Jacques Ravel jravel@som.umaryland.edu
Permission to use, copy, modify, and distribute this software and its
documentation with or without modifications and for any purpose and
without fee is hereby granted, provided that any copyright notices
appear in all copies and that both those copyright notices and this
permission notice appear in supporting documentation, and that the
names of the contributors or copyright holders not be used in
advertising or publicity pertaining to distribution of the software
without specific prior permission.
THE CONTRIBUTORS AND COPYRIGHT HOLDERS OF THIS SOFTWARE DISCLAIM ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL THE
CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT
OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <queue>
#include <deque>
#include <string>
#include "IOCUtilities.h"
#include "IOCppUtilities.hh"
#include "Newick.hh"
using namespace std;
#define DEBUG 0
//--------------------------------------------- NewickNode_t() -----
NewickNode_t::NewickNode_t(NewickNode_t * parent)
: parent_m(parent)
{
#if DEBUG
fprintf(stderr,"in NewickTree_t(parent)\t(parent==NULL)=%d\n",(int)(parent==NULL));
#endif
if (parent==NULL)
{
#if DEBUG
fprintf(stderr,"in if(parent==NULL)\n");
#endif
depth_m = -1;
}
else
{
#if DEBUG
fprintf(stderr,"in else\n");
#endif
depth_m = parent->depth_m+1;
}
#if DEBUG
fprintf(stderr,"leaving NewickTree_t(parent)\tdepth_m: %d\n", depth_m);
#endif
}
//--------------------------------------------- ~NewickNode_t() -----
NewickNode_t::~NewickNode_t()
{
// for (unsigned int i = 0; i < children_m.size(); i++)
// {
// delete children_m[i];
// }
}
//--------------------------------------------- stitch -----
// make children on the input node the children of the current node
// the children of the input node have the current node as a parent
void NewickNode_t::stitch( NewickNode_t *node )
{
#if DEBUG
fprintf(stderr,"in NewickNode_t::stitch()\n");
#endif
children_m = node->children_m;
int nChildren = children_m.size();
for ( int i = 0; i < nChildren; i++ )
{
children_m[i]->parent_m = this;
}
#if DEBUG
fprintf(stderr,"leaving NewickNode_t::stitch()\n");
#endif
}
//--------------------------------------------- addChild -----
NewickNode_t * NewickNode_t::addChild()
{
#if DEBUG
fprintf(stderr,"in addChild()\n");
#endif
NewickNode_t * child = new NewickNode_t(this);
#if DEBUG
fprintf(stderr,"before children_m.size()\n");
//fprintf(stderr,"children_m.size()=%d\n",(int)children_m.size());
#endif
children_m.push_back(child);
#if DEBUG
fprintf(stderr,"leaving addChild()\n");
#endif
return child;
}
//--------------------------------------------- NewickTree_t -----
NewickTree_t::NewickTree_t()
: root_m(NULL), nLeaves_m(0), minIdx_m(-1)
{
#if DEBUG
fprintf(stderr,"in NewickTree_t()\n");
#endif
}
//--------------------------------------------- ~NewickTree_t -----
NewickTree_t::~NewickTree_t()
{
delete root_m;
}
//--------------------------------------------- rmLeaf -----
// remove leaf with label s
void NewickTree_t::rmLeaf( string &s )
{
queue<NewickNode_t *> bfs2;
bfs2.push(root_m);
int numChildren;
NewickNode_t *pnode;
NewickNode_t *node;
bool go = true;
while ( !bfs2.empty() && go )
{
node = bfs2.front();
bfs2.pop();
numChildren = node->children_m.size();
if ( numChildren )
{
for (int i = 0; i < numChildren; i++)
{
bfs2.push(node->children_m[i]);
}
}
else if ( node->label == s )
{
pnode = node->parent_m;
// identify which element of pnode->children_m vector is s
int n = pnode->children_m.size();
for ( int i = 0; i < n; ++i )
if ( pnode->children_m[i]->label == s )
{
pnode->children_m.erase ( pnode->children_m.begin() + i );
go = false;
break;
}
}
} // end of while() loop
}
//--------------------------------------------- rmNodesWith1child -----
// remove nodes with only one child
void NewickTree_t::rmNodesWith1child()
{
queue<NewickNode_t *> bfs2;
bfs2.push(root_m);
int numChildren;
NewickNode_t *pnode;
NewickNode_t *node;
while ( !bfs2.empty() )
{
node = bfs2.front();
bfs2.pop();
while ( node->children_m.size() == 1 )
{
// finding node in a children array of the parent node
pnode = node->parent_m;
numChildren = pnode->children_m.size();
#if DEBUG_LFTT
fprintf(stderr, "\n\nNode %s has only one child %s; %s's parent is %s with %d children\n",
node->label.c_str(), node->children_m[0]->label.c_str(), node->label.c_str(),
pnode->label.c_str(), numChildren);
#endif
int i;
for ( i = 0; i < numChildren; i++)
{
if ( pnode->children_m[i] == node )
break;
}
if ( i == numChildren )
{
fprintf(stderr, "ERROR in %s at line %d: node %s cannot be found in %s\n",
__FILE__, __LINE__,(node->label).c_str(), (pnode->label).c_str());
exit(1);
}
#if DEBUG_LFTT
fprintf(stderr, "%s is the %d-th child of %s\n",
node->label.c_str(), i, pnode->label.c_str());
fprintf(stderr, "%s children BEFORE change: ", pnode->label.c_str());
for ( int j = 0; j < numChildren; j++)
fprintf(stderr, "%s ", pnode->children_m[j]->label.c_str());
#endif
node = node->children_m[0];
pnode->children_m[i] = node;
node->parent_m = pnode;
#if DEBUG_LFTT
fprintf(stderr, "\n%s children AFTER change: ", pnode->label.c_str());
for ( int j = 0; j < numChildren; j++)
fprintf(stderr, "%s ", pnode->children_m[j]->label.c_str());
#endif
}
numChildren = node->children_m.size();
if ( numChildren )
{
for (int i = 0; i < numChildren; i++)
{
bfs2.push(node->children_m[i]);
}
}
}
}
//--------------------------------------------- loadTree -----
bool NewickTree_t::loadTree(const char *file)
{
#define DEBUGLT 0
#if DEBUGLT
fprintf(stderr, "in NewickTree_t::loadTree()\n");
#endif
FILE * fp = fOpen(file, "r");
char str[256];
NewickNode_t * cur = new NewickNode_t();
int LINE = 1;
char c;
bool DONE = false;
int leafIdx = 0;
int count = 0;
while ((c = fgetc(fp)) != EOF)
{
#if DEBUGLT
fprintf(stderr,"c=|%c|\tcount=%d\t(cur==NULL)=%d\n", c, count,(int)(cur==NULL));
#endif
count++;
if (c == ';') { DONE = true;}
else if (c == '\n') { LINE++; }
else if (c == ' ') { }
else if (DONE)
{
cerr << "ERROR: Unexpected data after ; on line " << LINE << endl;
return false;
}
else if (c == '(')
{
cur = cur->addChild();
if (root_m == NULL) { root_m = cur; }
}
else if (c == ')') // '):bl,' or '):bl' or ')lable:bl'
{
c = fgetc(fp);
#if DEBUGLT
fprintf(stderr,"in ) next c=%c\n", c);
fprintf(stderr,"in ) minIdx_m=%d\n", minIdx_m);
#endif
cur->idx = minIdx_m;
minIdx_m--;
if ( c == ';' )
{
DONE = 1;
break;
}
else if ( c == ':' )
{
fscanf(fp, "%lf", &cur->branch_length);
}
else if ( isdigit(c) )
{
double bootVal;
fscanf(fp, "%lf:%lf", &bootVal, &cur->branch_length);
}
else if ( isalpha(c) ) // label:digit
{
#if DEBUGLT
fprintf(stderr,"in )alpha=%c\n", c);
#endif
char *brkt;
ungetc(c, fp);
int i = 0;
while ( isalnum(c) || c==':' || c=='.' || c=='_' || c=='-' )
{
c = fgetc(fp);
str[i++] = c;
}
str[--i] = '\0';
if (c != ',') { ungetc(c, fp); }
strtok_r(str, ":", &brkt);
cur->label = string(str);
cur->branch_length = 0; //atof(str);
#if DEBUGLT
fprintf(stderr, "label=%s\tbranch_length=%.2f\n", cur->label.c_str(), cur->branch_length);
#endif
}
else //if (c != ':' && !isdigit(c) && c !=';')
{
fprintf(stderr, "ERROR in %s at %d: Unexpected data, %c, after ')' in %s on line %d\n",
__FILE__, __LINE__, c, file, LINE);
return 0;
}
cur = cur->parent_m;
c = fgetc(fp);
if (c != ',') { ungetc(c, fp); }
}
else // 'name:bl' or 'name:bl,' - leaf
{
#if DEBUGLT
fprintf(stderr,"in name:bl=%c\n", c);
#endif
cur = cur->addChild();
nLeaves_m++;
cur->label += c;
while ((c = fgetc(fp)) != ':')
{
cur->label += c;
}
#if DEBUGLT
fprintf(stderr,"in name:bl label=%s\n", cur->label.c_str());
#endif
fscanf(fp, "%lf", &cur->branch_length);
cur->idx = leafIdx;
leafIdx++;
cur = cur->parent_m;
c = fgetc(fp);
if (c != ',') { ungetc(c, fp); }
}
} // end of while()
minIdx_m++;
if (!root_m)
{
fprintf(stderr,"ERROR in %s at line %d: Newick root is null!\n",__FILE__,__LINE__);
exit(EXIT_FAILURE);
}
return true;
}
//--------------------------------------------- writeNewickNode -----
static void writeNewickNode(NewickNode_t * node,
FILE * fp,
int depth)
{
if (!node) { return; }
int numChildren = node->children_m.size();
if (numChildren == 0)
{
if ( node->branch_length )
fprintf(fp, "%s:%0.20lf", node->label.c_str(), node->branch_length);
else
fprintf(fp, "%s:0.1", node->label.c_str());
}
else
{
//fprintf(fp, "(\n");
fprintf(fp, "(");
vector<NewickNode_t *> goodChildren;
for (int i = 0; i < numChildren; i++)
{
goodChildren.push_back(node->children_m[i]);
}
int numGoodChildren = goodChildren.size();
for (int i = 0; i < numGoodChildren; i++)
{
writeNewickNode(goodChildren[i], fp, depth+1);
if (i != numGoodChildren-1) { fprintf(fp, ","); }
//fprintf(fp, "\n");
}
//for (int i = 0; i < depth; i++) { fprintf(fp, " "); }
if ( node->label.empty() )
{
if ( node->branch_length)
fprintf(fp, "):%0.20lf", node->branch_length);
else
fprintf(fp, "):0.1");
}
else
{
if ( node->branch_length)
fprintf(fp, ")%s:%0.20lf", node->label.c_str(), node->branch_length);
else
fprintf(fp, ")%s:0.1", node->label.c_str());
}
if (depth == 0) { fprintf(fp, ";\n"); }
}
}
//--------------------------------------------- writeTree -----
void NewickTree_t::writeTree(FILE * fp)
{
if (root_m == NULL)
{
fprintf(stderr, "ERROR: Root is NULL!\n");
}
writeNewickNode(root_m, fp, 0);
fflush(fp);
}
//--------------------------------------------- writeTree -----
void NewickTree_t::writeTree(FILE * fp, NewickNode_t *node)
{
if (root_m == NULL)
{
fprintf(stderr, "ERROR: Root is NULL!\n");
}
writeNewickNode(node, fp, 0);
fflush(fp);
}
//--------------------------------------------- writeTree -----
void NewickTree_t::writeTree(FILE * fp, const string &nodeLabel)
{
if (root_m == NULL) fprintf(stderr, "ERROR: Root is NULL!\n");
queue<NewickNode_t *> bfs;
bfs.push(root_m);
NewickNode_t *node;
int numChildren;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
if ( node->label==nodeLabel )
{
writeNewickNode(node, fp, 0);
fflush(fp);
break;
}
numChildren = node->children_m.size();
if ( numChildren )
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
}
//--------------------------------------------- getDepth -----
// Determine the depth of a tree
int NewickTree_t::getDepth()
{
deque<NewickNode_t *> dfs;
dfs.push_front(root_m);
NewickNode_t *node;
deque<int> depth;
int maxDepth = 0;
depth.push_front(maxDepth);
while ( !dfs.empty() )
{
node = dfs.front();
dfs.pop_front();
int d = depth.front();
depth.pop_front();
if ( maxDepth < d )
maxDepth = d;
int numChildren = node->children_m.size();
if ( numChildren>0 )
{
for (int i = 0; i < numChildren; i++)
{
dfs.push_front(node->children_m[i]);
depth.push_front(d+1);
}
//if ( maxDepth < d+1 )
// maxDepth = d+1;
}
}
return maxDepth;
}
//--------------------------------------------- printTree -----
//
// prints tree to stdout with different depths at differen indentation levels
// indStr - indentation string
void NewickTree_t::printTree(bool withIdx, const char *indStr)
{
if (root_m == NULL)
{
fprintf(stderr, "ERROR: Root is NULL!\n");
}
// Determine the depth of the tree
int maxDepth = getDepth();
printf("\nmaxDepth: %d\n\n", maxDepth);
maxDepth++;
// Set up indent array of indentation strings
//const char *indStr=" ";
int indStrLen = strlen(indStr);
char **indent = (char **)malloc(maxDepth * sizeof(char*));
indent[0] = (char*)malloc(sizeof(char)); // empty string
indent[0][0] = '\0';
for ( int i = 1; i < maxDepth; i++ )
{
indent[i] = (char*)malloc(indStrLen * (i+1) * sizeof(char));
for ( int j = 0; j < i; j++ )
for ( int k = 0; k < indStrLen; k++ )
indent[i][j * indStrLen + k] = indStr[k];
indent[i][indStrLen * i] = '\0';
}
//Depth first search
deque<NewickNode_t *> dfs;
dfs.push_front(root_m);
NewickNode_t *node;
while ( !dfs.empty() )
{
node = dfs.front();
dfs.pop_front();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
if ( withIdx )
printf("%s%s(%d)\n",indent[node->depth_m],node->label.c_str(), node->idx);
else
//printf("%s%s\n",indent[node->depth_m],node->label.c_str());
printf("(%d)%s%s\n",node->depth_m,indent[node->depth_m],node->label.c_str());
}
else
{
if ( withIdx )
{
if ( node->label.empty() )
printf("%s*(%d)\n",indent[node->depth_m],node->idx);
else
printf("%s%s(%d)\n",indent[node->depth_m],node->label.c_str(), node->idx);
}
else
{
if ( node->label.empty() )
printf("%s*\n",indent[node->depth_m]);
else
//printf("%s%s\n",indent[node->depth_m],node->label.c_str());
printf("(%d)%s%s\n",node->depth_m,indent[node->depth_m],node->label.c_str());
}
for (int i = 0; i < numChildren; i++)
dfs.push_front(node->children_m[i]);
}
}
}
#if 0
//--------------------------------------------- printTreeBFS -----
void NewickTree_t::printTreeBFS()
{
if (root_m == NULL)
{
fprintf(stderr, "ERROR: Root is NULL!\n");
}
//Breath first search
queue<NewickNode_t *> bfs;
bfs.push(root_m);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
printf("%s%s\n",indent[node->depth_m],node->label.c_str());
}
else
{
printf("%s*\n",indent[node->depth_m]);
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
}
#endif
//--------------------------------------------- indexNewickNodes -----
void NewickTree_t::indexNewickNodes( map<int, NewickNode_t*> & idx2node)
/*
populates a hash table of <node index> => <pointer to the node>
returns number of leaves of the tree
*/
{
if ( idx2node_m.size() == 0 )
{
//Breath first search
queue<NewickNode_t *> bfs;
bfs.push(root_m);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
idx2node_m[node->idx] = node;
int numChildren = node->children_m.size();
if ( numChildren != 0 ) // leaf
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
}
idx2node = idx2node_m;
}
//--------------------------------------------- leafLabels -----
char ** NewickTree_t::leafLabels()
{
char **leafLabel = (char**)malloc((nLeaves_m) * sizeof(char*));
queue<NewickNode_t *> bfs;
bfs.push(root_m);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
leafLabel[node->idx] = strdup((node->label).c_str());
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
return leafLabel;
}
// ------------------------- assignIntNodeNames ------------------------
void NewickTree_t::assignIntNodeNames()
/*
Asssign i1, i2, i3 etc names to internal nodes, where iK label corresponds to index -K
*/
{
queue<NewickNode_t *> bfs;
bfs.push(root_m);
NewickNode_t *node;
//int negIdx; // holds negative index of a nod
char str[16]; // holds negIdx
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren ) // not leaf
{
//negIdx = -node->idx;
sprintf(str,"%d", -node->idx);
node->label = string("i") + string(str);
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
}
// ------------------------------ saveCltrMemb ------------------------
void NewickTree_t::saveCltrMemb( const char *outFile,
vector<int> &nodeCut,
int *annIdx,
map<int, string> &idxToAnn)
/*
save clustering membership data to outFile
output file format:
<leaf ID> <cluster ID> <annotation str or NA if absent>
Parameters:
outFile - output file
nodeCut - min-node-cut
annIdx - annIdx[i] = <0-based index of the annotation string assigned to the i-th
element of data table>
annIdx[i] = -1 if the i-th element has no annotation
idxToAnn - idxToAnn[annIdx] = <annotation string associated with annIdx>
*/
{
map<int, NewickNode_t*> idx2node;
indexNewickNodes(idx2node);
FILE *file = fOpen(outFile,"w");
fprintf(file,"readId\tclstr\tannot\n");
int n = nodeCut.size();
for ( int i = 0; i < n; ++i )
{
if ( nodeCut[i] >= 0 )
{
fprintf(file,"%s\t%d\t%s\n",idx2node[nodeCut[i]]->label.c_str(),i,
idxToAnn[ annIdx[nodeCut[i]] ].c_str() );
}
else
{
queue<NewickNode_t *> bfs;
bfs.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
fprintf(file,"%s\t%d\t%s\n",node->label.c_str(),i,
idxToAnn[ annIdx[node->idx] ].c_str() );
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
}
}
fclose(file);
}
// ------------------------------ saveCltrMemb2 ------------------------
void NewickTree_t::saveCltrMemb2( const char *outFile,
vector<int> &nodeCut,
int *annIdx,
map<int, string> &idxToAnn)
/*
save clustering membership data to outFile
output file format:
<cluster_1>:
<leaf1> <annotation of leaf1>
<leaf2> <annotation of leaf2>
...
...
Parameters:
outFile - output file
nodeCut - min-node-cut
annIdx - annIdx[i] = <0-based index of the annotation string assigned to the i-th
element of data table>
annIdx[i] = -1 if the i-th element has no annotation
idxToAnn - idxToAnn[annIdx] = <annotation string associated with annIdx>
*/
{
map<int, NewickNode_t*> idx2node;
indexNewickNodes(idx2node);
FILE *file = fOpen(outFile,"w");
int n = nodeCut.size();
for ( int i = 0; i < n; ++i )
{
fprintf(file,"Cluster %d:\n",i);
if ( nodeCut[i] >= 0 )
{
fprintf(file,"\t%s\t%s\n",idx2node[nodeCut[i]]->label.c_str(),
idxToAnn[ annIdx[nodeCut[i]] ].c_str() );
}
else
{
queue<NewickNode_t *> bfs;
bfs.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
fprintf(file,"\t%s\t%s\n",node->label.c_str(),
idxToAnn[ annIdx[node->idx] ].c_str() );
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
}
}
fclose(file);
}
// this is going to be used to sort map<string,int> in saveCltrAnnStats()
class sort_map
{
public:
string key;
int val;
};
bool Sort_by(const sort_map& a ,const sort_map& b)
{
return a.val > b.val;
}
// ------------------------------ saveCltrAnnStats --------------------------------
void NewickTree_t::saveCltrAnnStats( const char *outFile,
vector<int> &nodeCut,
int *annIdx,
map<int, string> &idxToAnn)
/*
save annotation summary statistics of the clustering induced by nodeCut to outFile
output file format:
<cluster_1>:
<annotation 1,1> <count1,1> <perc1,1>
<annotation 1,2> <count1,2> <perc1,2>
...
...
<cluster_2>:
<annotation 2,1> <count2,1> <perc2,1>
<annotation 2,2> <count2,2> <perc2,2>
...
...
countX,Y is the count of leaves in cluster_X and Y-th annotation (sorted by count)
percX,Y is the percentage of these leaves in the given cluster
Parameters:
outFile - output file
nodeCut - min-node-cut
annIdx - annIdx[i] = <0-based index of the annotation string assigned to the i-th
element of data table>
annIdx[i] = -1 if the i-th element has no annotation
idxToAnn - idxToAnn[annIdx] = <annotation string associated with annIdx>
*/
{
map<int, NewickNode_t*> idx2node;
indexNewickNodes(idx2node);
FILE *file = fOpen(outFile,"w");
int n = nodeCut.size();
for ( int i = 0; i < n; ++i )
{
fprintf(file,"Cluster %d:\n",i);
if ( nodeCut[i] >= 0 )
{
fprintf(file,"\t%s\t1\t100%%\n", idxToAnn[ annIdx[nodeCut[i]] ].c_str() );
}
else
{
map<string,int> annCount; // count of a given annotation string in the subtree of a given cut-node
queue<NewickNode_t *> bfs;
bfs.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
annCount[ idxToAnn[ annIdx[node->idx] ] ]++;
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
// printing annotation counts in the order of their counts
map<string,int>::iterator it;
vector< sort_map > v;
vector< sort_map >::iterator itv;
sort_map sm;
double sum = 0;
for (it = annCount.begin(); it != annCount.end(); ++it)
{
sm.key = (*it).first;
sm.val = (*it).second;
v.push_back(sm);
sum += sm.val;
}
sort(v.begin(),v.end(),Sort_by);
for (itv = v.begin(); itv != v.end(); ++itv)
fprintf(file,"\t%s\t%d\t%.1f%%\n", ((*itv).key).c_str(), (*itv).val, 100.0 * (*itv).val / sum);
if ( v.size() > 1 )
fprintf(file,"\tTOTAL\t%d\t100%%\n", (int)sum);
}
}
fclose(file);
}
// ------------------------------ saveNAcltrAnnStats ------------------------
vector<string> NewickTree_t::saveNAcltrAnnStats( const char *outFile,
vector<int> &nodeCut,
int *annIdx,
map<int, string> &idxToAnn)
/*
It is a version of saveCltrAnnStats() that reports only clusters containig query (NA) elements.
*/
{
map<int, NewickNode_t*> idx2node;
indexNewickNodes(idx2node);
FILE *file = fOpen(outFile,"w");
vector<string> selAnn; // vector of taxons which are memembers of clusters that contain query seqeunces
int n = nodeCut.size();
for ( int i = 0; i < n; ++i )
{
if ( nodeCut[i] < 0 )
{
map<string,int> annCount; // count of a given annotation string in the subtree of a given cut-node
queue<NewickNode_t *> bfs;
bfs.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
bool foundNA = false;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
annCount[ idxToAnn[ annIdx[node->idx] ] ]++;
if ( annIdx[node->idx] == -2) foundNA = true;
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
// printing annotation counts in the order of their counts
if ( foundNA )
{
map<string,int>::iterator it;
vector< sort_map > v;
vector< sort_map >::iterator itv;
sort_map sm;
double sum = 0;
for (it = annCount.begin(); it != annCount.end(); ++it)
{
sm.key = (*it).first;
sm.val = (*it).second;
selAnn.push_back(sm.key);
v.push_back(sm);
sum += sm.val;
}
sort(v.begin(),v.end(),Sort_by);
fprintf(file,"Cluster %d:\n",i);
for (itv = v.begin(); itv != v.end(); ++itv)
fprintf(file,"\t%s\t%d\t%.1f%%\n", ((*itv).key).c_str(), (*itv).val, 100.0 * (*itv).val / sum);
if ( v.size() > 1 )
fprintf(file,"\tTOTAL\t%d\t100%%\n", (int)sum);
}
}
}
fclose(file);
return selAnn;
}
// ------------------------------ saveNAcltrAnnStats ------------------------
void NewickTree_t::saveNAcltrAnnStats( const char *outFileA, // file to with cluster stats of clusters with at least minNA query sequences
const char *outFileB, // file to with cluster stats of clusters with less than minNA query sequences
const char *outFileC, // file with reference IDs of sequences for clusters in outFileA
const char *outFileD, // file with taxons, for clusters in outFileA, with the number of sequences >= minAnn
vector<int> &nodeCut,
int *annIdx,
map<int, string> &idxToAnn,
int minNA,
int minAnn)
/*
It is a version of saveCltrAnnStats() that reports only clusters containig at
least minNA query sequences to outFileA and less than minNA sequences to
outFileB.
output vector contains taxons with at least minAnn elements (in a single cluster).
*/
{
map<int, NewickNode_t*> idx2node;
indexNewickNodes(idx2node);
FILE *fileA = fOpen(outFileA,"w");
FILE *fileB = fOpen(outFileB,"w");
FILE *fileC = fOpen(outFileC,"w");
int nCltrs = 0; // number of clusters with the number of query seq's >= minNA
int nTx = 0; // number of selected taxons from the above clusters with the number of reads >= minAnn
int nRef = 0; // number of reference sequence from the above clusters with taxons with the number of reads >= minAnn
map<string,bool> selTx; // hash table of selected taxons as in nTx; nTx = number of elements in selTx
int n = nodeCut.size();
for ( int i = 0; i < n; ++i )
{
if ( nodeCut[i] < 0 ) // internal node
{
map<string,int> annCount; // count of a given annotation string in the subtree of a given cut-node
queue<NewickNode_t *> bfs;
bfs.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
int naCount = 0;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
annCount[ idxToAnn[ annIdx[node->idx] ] ]++;
if ( annIdx[node->idx] == -2) naCount++;
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
// printing annotation counts in the order of their counts
if ( naCount >= minNA )
{
nCltrs++;
map<string,int>::iterator it;
vector< sort_map > v;
vector< sort_map >::iterator itv;
sort_map sm;
double sum = 0;
for (it = annCount.begin(); it != annCount.end(); ++it)
{
sm.key = (*it).first;
sm.val = (*it).second;
v.push_back(sm);
sum += sm.val;
}
sort(v.begin(),v.end(),Sort_by);
fprintf(fileA,"Cluster %d:\n",i);
for (itv = v.begin(); itv != v.end(); ++itv)
fprintf(fileA,"\t%s\t%d\t%.1f%%\n", ((*itv).key).c_str(), (*itv).val, 100.0 * (*itv).val / sum);
if ( v.size() > 1 )
fprintf(fileA,"\tTOTAL\t%d\t100%%\n", (int)sum);
// traverse the subtree again selecting sequences with annCount of the
// corresponding taxons that have at least minAnn elements to be printed
// in fileC
queue<NewickNode_t *> bfs2;
bfs2.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
while ( !bfs2.empty() )
{
node = bfs2.front();
bfs2.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
if ( annCount[ idxToAnn[ annIdx[node->idx] ] ] > minAnn && idxToAnn[ annIdx[node->idx] ] != "NA" )
{
selTx[ idxToAnn[ annIdx[node->idx] ] ] = true;
nRef++;
fprintf(fileC, "%s\t%s\n",
node->label.c_str(),
idxToAnn[ annIdx[node->idx] ].c_str() );
}
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs2.push(node->children_m[i]);
}
}
}
}
else
{
map<string,int>::iterator it;
vector< sort_map > v;
vector< sort_map >::iterator itv;
sort_map sm;
double sum = 0;
for (it = annCount.begin(); it != annCount.end(); ++it)
{
sm.key = (*it).first;
sm.val = (*it).second;
v.push_back(sm);
sum += sm.val;
}
sort(v.begin(),v.end(),Sort_by);
fprintf(fileB,"Cluster %d:\n",i);
for (itv = v.begin(); itv != v.end(); ++itv)
fprintf(fileB,"\t%s\t%d\t%.1f%%\n", ((*itv).key).c_str(), (*itv).val, 100.0 * (*itv).val / sum);
if ( v.size() > 1 )
fprintf(fileB,"\tTOTAL\t%d\t100%%\n", (int)sum);
}
}
}
fclose(fileA);
fclose(fileB);
fclose(fileC);
// extracting only keys of selTx;
FILE *fileD = fOpen(outFileD,"w");
//vector<string> selTxV; // vector of taxons which are memembers of clusters that contain query seqeunces
for(map<string,bool>::iterator it = selTx.begin(); it != selTx.end(); ++it)
{
//selTxV.push_back(it->first);
fprintf(fileD,"%s\n",(it->first).c_str());
}
fclose(fileD);
nTx = selTx.size();
fprintf(stderr,"\nNumber of clusters with the number of query seq's >= %d: %d\n",minNA, nCltrs);
fprintf(stderr,"Number of selected taxons from the above clusters with the number of reads >= %d: %d\n",minAnn, nTx);
fprintf(stderr,"Number of selected reference sequence from the above clusters with taxons with the number of reads >= %d: %d\n",minAnn, nRef);
}
// comparison between integers producing descending order
bool gr (int i,int j) { return (i>j); }
// ------------------------------ saveNAtaxonomy0 ------------------------
void NewickTree_t::saveNAtaxonomy0( const char *outFile,
const char *logFile, // recording sizes of two most abundant taxa. If there is only one (besides query sequences), recording the number of elements of the dominant taxon and 0.
vector<int> &nodeCut,
int *annIdx,
map<int, string> &idxToAnn,
int minAnn,
int &nNAs,
int &nNAs_with_tx,
int &tx_changed,
int &nClades_modified)
/*
Assigning taxonomy to query sequences and modifying taxonomy of sequences with
non-monolityc clades using majority vote.
This is a special case of saveNAtaxonomy() that does taxonomy assignments of
query sequences from clusters containing at least minAnn reference
sequences. The taxonomy is based on the most abundant reference taxon.
I just extended the algorithm so that taxonomy of all elements of the given
cluster is set to the taxonomy of the cluster with the largest number of
sequences. If there are ties, that is two taxonomies are most abundant, then
there is no change.
*/
{
map<int, NewickNode_t*> idx2node;
indexNewickNodes(idx2node);
map<string,int> otuFreq; // <taxonomic rank name> => number of OTUs already assigned to it
FILE *file = fOpen(outFile,"w");
FILE *logfile = fOpen(logFile,"w");
nNAs = 0;
nNAs_with_tx = 0;
tx_changed = 0;
nClades_modified = 0;
int n = nodeCut.size();
for ( int i = 0; i < n; ++i )
{
map<string,int> annCount; // count of a given annotation string in the subtree of a given node
int naCount = 0;
queue<NewickNode_t *> bfs;
bfs.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
//if ( i==262 )printf("\n%s\t%s", node->label.c_str(), idxToAnn[ annIdx[node->idx] ].c_str());
annCount[ idxToAnn[ annIdx[node->idx] ] ]++;
if ( annIdx[node->idx] == -2) naCount++;
if ( idxToAnn[ annIdx[node->idx] ] == "NA" ) nNAs++;
}
else
{
for (int j = 0; j < numChildren; j++)
{
bfs.push(node->children_m[j]);
}
}
}
//if ( i==262 )printf("\n\n");
//if ( naCount >= minNA && annCount.size() >= minAnn )
if ( annCount.size() >= (unsigned)minAnn ) // Assigning taxonomy to query sequences and modifying taxonomy of sequences with non-monolityc clades using majority vote
{
string cltrTx;
int maxCount = 0; // maximal count among annotated sequences in the cluster
map<string,int>::iterator it;
// Make sure there are not ties for max count
// Copying counts into a vector, sorting it and checking that the first two
// values (when sorting in the decreasing order) are not equal to each
// other.
vector<int> counts;
for (it = annCount.begin(); it != annCount.end(); ++it)
{
if ( (*it).first != "NA" )
counts.push_back((*it).second);
if ( (*it).first != "NA" && (*it).second > maxCount )
{
maxCount = (*it).second;
cltrTx = (*it).first;
}
}
sort( counts.begin(), counts.end(), gr );
#if 0
if ( i==231 )
{
fprintf(stderr,"\ncltrTx: %s\n", cltrTx.c_str());
fprintf(stderr,"\nCluster %d\nannCount\n",i);
for (it = annCount.begin(); it != annCount.end(); ++it)
{
fprintf(stderr,"\t%s\t%d\n", ((*it).first).c_str(), (*it).second);
}
fprintf(stderr,"\nsorted counts: ");
for (int j = 0; j < counts.size(); j++)
fprintf(stderr,"%d, ", counts[j]);
fprintf(stderr,"\n\n");
}
#endif
// Traverse the subtree again assigning taxonomy to all query sequences
int counts_size = counts.size();
if ( counts_size==1 || ( counts_size>1 && counts[0] > counts[1] ) )
{
nClades_modified++;
if ( counts_size > 1 )
fprintf(logfile, "%d\t%d\n", counts[0], counts[1]);
else
fprintf(logfile, "%d\t0\n", counts[0]);
queue<NewickNode_t *> bfs2;
bfs2.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
while ( !bfs2.empty() )
{
node = bfs2.front();
bfs2.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
//if ( idxToAnn[ annIdx[node->idx] ] == "NA" && !cltrTx.empty() )
if ( idxToAnn[ annIdx[node->idx] ] !=cltrTx && !cltrTx.empty() )
{
//idxToAnn[ annIdx[node->idx] ] = cltrTx;
fprintf(file, "%s\t%s\n", node->label.c_str(), cltrTx.c_str());
if ( idxToAnn[ annIdx[node->idx] ] == "NA" )
nNAs_with_tx++;
else
tx_changed++;
}
}
else
{
for (int j = 0; j < numChildren; j++)
bfs2.push(node->children_m[j]);
}
} // end while ( !bfs2.empty() )
} // end if ( counts.size()==1 || ( counts.size()>1 && counts[0] > counts[1] ) )
} // end if ( naCount >= minNA && annCount.size() >= minAnn )
} // end for ( int i = 0; i < n; ++i )
fclose(file);
fclose(logfile);
}
// ------------------------------ saveNAtaxonomy ------------------------
void NewickTree_t::saveNAtaxonomy( const char *outFile,
const char *logFile,
const char *genusOTUsFile,
vector<int> &nodeCut,
int *annIdx,
map<int, string> &idxToAnn,
int minNA,
map<string, string> &txParent)
/*
Taxonomy assignments of query sequences from clusters containing either only
query sequences or query sequences with at least minNA query sequences and
minAnn reference sequences; In the last case the taxonomy is based on the most
abundant reference taxon. In the previous case, the taxonomy is determined by
the first ancestor with reference sequences. The content of reference sequences
determines taxonomy. Here are some rules.
If the ancestor contains reference sequences of the same species, then we
assign this species name to the OTU.
If the ref seq's are from the same genus, then we assign to the OTU the name of
the most abundant ref sequence. A justification for this comes from an
observation that often OTUs form a clade in the middle of which there are two
subtrees with two different species of the same genus. I hypothesize that this
is a clade of one species and the other one is an error. Therefore, the name of
the OTU should be the name of the more abundant species, and the other species
should be renamed to the other one.
Alternatively, the name could be of the form
<genus name>_<species1>.<species2>. ... .<speciesN>
where species1, ... , speciesN are species present in the ancestral node
If the ref seq's are from different genera, then we assign to the OTU a name
<tx rank>_OTUi
where tx rank is the taxonomic rank of common to all ref seq's of the ancestral subtree.
In the extreme case of Bacteria_OTU I am merging
*/
{
FILE *file = fOpen(outFile,"w");
FILE *fh = fOpen(logFile,"w");
FILE *genusFH = fOpen(genusOTUsFile,"w");
//map<string,bool> selTx; // hash table of selected taxons as in nTx; nTx = number of elements in selTx
map<int, NewickNode_t*> idx2node;
indexNewickNodes(idx2node);
map<string,int> otuFreq; // <taxonomic rank name> => number of OTUs already assigned to it
int n = nodeCut.size();
for ( int i = 0; i < n; ++i )
{
//if ( nodeCut[i] < 0 ) // internal node
{
map<string,int> annCount; // count of a given annotation string in the subtree of a given cut-node
queue<NewickNode_t *> bfs;
bfs.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
int naCount = 0;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
annCount[ idxToAnn[ annIdx[node->idx] ] ]++;
if ( annIdx[node->idx] == -2) naCount++;
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
if ( naCount >= minNA )
{
string cltrTx; // = "Unclassified"; // taxonomy for all query reads of the cluster with no annotated sequences
if ( annCount.size() > 1 ) // there is at least one annotated element; setting cltrTx to annotation with the max frequency
{
int maxCount = 0; // maximal count among annotated sequences in the cluster
map<string,int>::iterator it;
for (it = annCount.begin(); it != annCount.end(); ++it)
{
if ( (*it).first != "NA" && (*it).second > maxCount )
{
maxCount = (*it).second;
cltrTx = (*it).first;
}
}
}
else // there are no annotated sequences in the cluster; we are looking for the nearest ancestral node with known taxonomy
{
node = idx2node[nodeCut[i]]; // current node
node = node->parent_m; // looking at the parent node
map<string,int> sppFreq;
int nSpp = cltrSpp(node, annIdx, idxToAnn, sppFreq); // table of species frequencies in the subtree of 'node'
while ( nSpp==0 ) // if the parent node does not have any annotation sequences
{
node = node->parent_m; // move up to its parent node
nSpp = cltrSpp(node, annIdx, idxToAnn, sppFreq);
}
// Debug
// fprintf(stderr, "\n--- i: %d\tCluster %d\n", i, node->idx);
// fprintf(stderr,"Number of species detected in the Unassigned node: %d\n",nSpp);
// besides writing frequencies I am finding taxonomic parents of each species
map<string,int> genus; // this is a map not vector so that I avoid duplication and find out frequence of a genus
map<string,int>::iterator it;
for ( it = sppFreq.begin(); it != sppFreq.end(); it++ )
{
//if ( (*it).first != "NA" )
//fprintf(fh, "%s\t%d\n", ((*it).first).c_str(), (*it).second);
if ( !txParent[(*it).first].empty() )
genus[ txParent[(*it).first] ] += (*it).second;
}
#if 0
// Checking of there is more than one genus present
// If so, we are going higher until we get only one taxonomic rank.
int nRks = genus.size();
map<string,int> txRk = genus; // taxonomic rank
map<string,int> pTxRk; // parent taxonomic rank
while ( nRks>1 )
{
for ( it = txRk.begin(); it != txRk.end(); it++ )
if ( !txParent[(*it).first].empty() )
pTxRk[ txParent[(*it).first] ]++;
// fprintf(fh, "\nTx Rank Frequencies\n");
// for ( it = pTxRk.begin(); it != pTxRk.end(); it++ )
// fprintf(fh, "%s\t%d\n", ((*it).first).c_str(), (*it).second);
nRks = pTxRk.size();
txRk = pTxRk;
pTxRk.clear();
// Debug
// fprintf(stderr,"nRks: %d\n",nRks);
}
it = txRk.begin();
string otuRank = (*it).first;
#endif
// assign OTU ID
if ( genus.size() == 1 ) // assign species name of the most frequent OTU
{
int maxCount = 0; // maximal count among annotated sequences in the cluster
map<string,int>::iterator it;
for (it = sppFreq.begin(); it != sppFreq.end(); ++it)
{
if ( (*it).first != "NA" && (*it).second > maxCount )
{
maxCount = (*it).second;
cltrTx = (*it).first;
}
}
}
else
{
// assigning the same OTU id to all OTUs with the same sppFreq profile
string sppProf;
map<string,int>::iterator it;
for (it = sppFreq.begin(); it != sppFreq.end(); ++it)
{
if ( (*it).first != "NA" )
{
sppProf += (*it).first;
}
}
int maxCount = 0; // maximal count among genera
string otuGenus;
for (it = genus.begin(); it != genus.end(); ++it)
{
if ( (*it).first != "NA" && (*it).second > maxCount )
{
maxCount = (*it).second;
otuGenus = (*it).first;
}
}
it = otuFreq.find(sppProf);
int k = 1;
if ( it != otuFreq.end() )
k = it->second + 1;
otuFreq[sppProf] = k;
char kStr[8];
sprintf(kStr,"%d",k);
cltrTx = otuGenus + string("_OTU") + string(kStr);
}
// Writing sppFreq to log file
fprintf(fh,"\n==== %s\tAncestral node ID: %d ====\n\n",cltrTx.c_str(), node->idx);
fprintf(fh, "-- Species Frequencies\n");
int totalSppLen = 0;
for ( it = sppFreq.begin(); it != sppFreq.end(); it++ )
{
fprintf(fh, "%s\t%d\n", ((*it).first).c_str(), (*it).second);
totalSppLen += ((*it).first).length();
}
// For each species of sppFreq, determine its taxonomy parent and write them to the log file
fprintf(fh, "\n-- Genus Frequencies\n");
for ( it = genus.begin(); it != genus.end(); it++ )
fprintf(fh, "%s\t%d\n", ((*it).first).c_str(), (*it).second);
if ( genus.size() == 1 ) // for genus OTUs print OTU name, ancestral node ID and species names into genusOTUsFile
{
//fprintf(stderr, "%s\t genus.size(): %d\n", cltrTx.c_str(), (int)genus.size());
// number of quary sequences in the OTU
it = sppFreq.find("NA");
if ( it == sppFreq.end() )
fprintf(stderr,"ERROR: OTU %s does not contain any quary sequences\n",cltrTx.c_str());
// OTU_ID, number of query sequences in the OTU, ID of the ancestral node that contains ref sequences
fprintf(genusFH,"%s\t%d\t%d\t",cltrTx.c_str(), (*it).second, node->idx);
int n = sppFreq.size();
char *sppStr = (char*)malloc((totalSppLen+n+1) * sizeof(char));
sppStr[0] = '\0';
int foundSpp = 0;
for ( it = sppFreq.begin(); it != sppFreq.end(); it++ )
{
if ( (*it).first != "NA" && (*it).first != "Unclassified" )
{
if ( foundSpp )
strncat(sppStr, ":",1);
strncat(sppStr, ((*it).first).c_str(), ((*it).first).length());
foundSpp = 1;
}
}
fprintf(genusFH,"%s\n", sppStr);
free(sppStr);
}
#if 0
// Higher taxonomic order frequencies
nRks = genus.size();
txRk = genus; // taxonomic rank
pTxRk.clear(); // parent taxonomic rank
while ( nRks>1 )
{
for ( it = txRk.begin(); it != txRk.end(); it++ )
if ( !txParent[(*it).first].empty() )
pTxRk[ txParent[(*it).first] ]++;
fprintf(fh, "\n-- Tx Rank Frequencies\n");
for ( it = pTxRk.begin(); it != pTxRk.end(); it++ )
fprintf(fh, "%s\t%d\n", ((*it).first).c_str(), (*it).second);
nRks = pTxRk.size();
txRk = pTxRk;
pTxRk.clear();
}
#endif
//Debugging
//fprintf(stderr,"OTU ID: %s\n",cltrTx.c_str());
} // end if ( annCount.size() > 1 )
// traverse the subtree again assigning taxonomy to all query sequences
queue<NewickNode_t *> bfs2;
bfs2.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
while ( !bfs2.empty() )
{
node = bfs2.front();
bfs2.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
if ( idxToAnn[ annIdx[node->idx] ] == "NA" )
{
fprintf(file, "%s\t%s\n", node->label.c_str(), cltrTx.c_str());
}
}
else
{
for (int i = 0; i < numChildren; i++)
bfs2.push(node->children_m[i]);
}
} // end while ( !bfs2.empty() )
} // if ( naCount >= minNA )
} // end if ( nodeCut[i] < 0 ) // internal node
} // end for ( int i = 0; i < n; ++i )
fclose(fh);
fclose(genusFH);
fclose(file);
}
// ------------------------------ cltrSpp ------------------------
// Traverses the subtree of the current tree rooted at '_node' and finds
// annotation strings (taxonomies) of reference sequences present in the subtree
// (if any). sppFreq is the frequency table of found species.
//
// Returns the size of sppFreq
//
int NewickTree_t::cltrSpp(NewickNode_t *_node,
int *annIdx,
map<int, string> &idxToAnn,
map<string,int> &sppFreq)
{
queue<NewickNode_t *> bfs;
bfs.push(_node);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
sppFreq[ idxToAnn[ annIdx[node->idx] ] ]++;
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
return int(sppFreq.size());
}
// ------------------------------ maxAnn ------------------------
// traverse the subtree of the current tree rooted at '_node' and find annotation
// string with max frequency Return empty string if there are no annotation
// sequences in the subtree.
string NewickTree_t::maxAnn( NewickNode_t *_node,
int *annIdx,
map<int, string> &idxToAnn)
{
map<string,int> annCount; // count of a given annotation string in the subtree of the given node
queue<NewickNode_t *> bfs;
bfs.push(_node);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
annCount[ idxToAnn[ annIdx[node->idx] ] ]++;
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
string cltrTx; // = "Unclassified"; // taxonomy for all query reads of the cluster with no annotated sequences
if ( annCount.size() > 1 ) // there is at least one annotated element; setting cltrTx to annotation with the max frequency
{
int maxCount = 0; // maximal count among annotated sequences in the cluster
map<string,int>::iterator it;
for (it = annCount.begin(); it != annCount.end(); ++it)
{
if ( (*it).first != "NA" && (*it).second > maxCount )
{
maxCount = (*it).second;
cltrTx = (*it).first;
}
}
}
return cltrTx;
}
// ------------------------------ findAnnNode ------------------------
// Find a node in lable 'label'
NewickNode_t* NewickTree_t::findAnnNode(std::string label)
{
queue<NewickNode_t *> bfs;
bfs.push(root_m);
NewickNode_t *node = 0;
NewickNode_t *searchedNode = 0;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
if ( node->label == label )
{
searchedNode = node;
break;
}
int numChildren = node->children_m.size();
if ( numChildren ) // not leaf
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
return searchedNode;
}
// ------------------------------ printGenusTrees ------------------------
// For each genus print a subtree rooted at the root nodes of the genus
// * to each genus assign a vector of species/OTU's cut-nodes generated by vicut
// * find a node with the smallest depth (from the root)
// * walk ancestors of this node until all OTU nodes are in the subtree of that node
// * print that tree to a file
void NewickTree_t::printGenusTrees( const char *outDir,
vector<int> &nodeCut,
int *annIdx,
int minNA,
map<int, string> &idxToAnn,
map<string, string> &txParent)
{
//fprintf(stderr,"Entering printGenusTrees()\n");
char s[1024];
sprintf(s,"mkdir -p %s",outDir);
system(s);
// === Assign to each genus a vector of species/OTU nodes
map<string, vector<NewickNode_t*> > genusSpp; // <genus> => vector of OTU/species node
map<int, NewickNode_t*> idx2node;
indexNewickNodes(idx2node);
int n = nodeCut.size();
for ( int i = 0; i < n; ++i )
{
//fprintf(stderr,"i: %d\r", i);
if ( nodeCut[i] < 0 ) // internal node
{
map<string,int> annCount; // count of a given annotation string in the subtree of a given cut-node
queue<NewickNode_t *> bfs;
bfs.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
int naCount = 0;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
annCount[ idxToAnn[ annIdx[node->idx] ] ]++;
if ( annIdx[node->idx] == -2) naCount++;
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
if ( naCount >= minNA )
{
string cltrTx; // taxonomy for all query reads of the cluster with no annotated sequences
if ( annCount.size() > 1 ) // there is at least one annotated element; setting cltrTx to annotation with the max frequency
{
int maxCount = 0; // maximal count among annotated sequences in the cluster
map<string,int>::iterator it;
for (it = annCount.begin(); it != annCount.end(); ++it)
{
if ( (*it).first != "NA" && (*it).second > maxCount )
{
maxCount = (*it).second;
cltrTx = (*it).first;
}
}
genusSpp[ txParent[ cltrTx ] ].push_back( idx2node[nodeCut[i]] );
}
else // there are no annotated sequences in the cluster; we are looking for the nearest ancestral node with known taxonomy
{
//fprintf(stderr, "In if ( naCount >= minNA ) else\n");
node = idx2node[nodeCut[i]]; // current node
node = node->parent_m; // looking at the parent node
map<string,int> sppFreq;
int nSpp = cltrSpp(node, annIdx, idxToAnn, sppFreq); // table of species frequencies in the subtree of 'node'
while ( nSpp==0 ) // if the parent node does not have any annotation sequences
{
node = node->parent_m; // move up to its parent node
nSpp = cltrSpp(node, annIdx, idxToAnn, sppFreq);
}
//fprintf(stderr, "nSpp: %d\n", nSpp);
map<string,int> genus; // this is a map not vector so that I avoid duplication and find out frequence of a genus
map<string,int>::iterator it;
for ( it = sppFreq.begin(); it != sppFreq.end(); it++ )
{
if ( !txParent[(*it).first].empty() )
genus[ txParent[(*it).first] ]++;
}
//fprintf(stderr, "genus.size(): %d\n", (int)genus.size());
if ( genus.size() == 1 ) //
{
it = genus.begin();
//fprintf(stderr,"genus: %s\n", (*it).first.c_str());
genusSpp[ (*it).first ].push_back( node );
}
} // end if ( annCount.size() > 1 )
} // if ( naCount >= minNA )
} // end if ( nodeCut[i] < 0 ) // internal node
} // end for ( int i = 0; i < n; ++i )
// === For each genus, find a node with the smallest depth (from the root)
// === Walk this node until all OTU nodes are in the subtree of that node
// === Print that tree to a file
map<string, vector<NewickNode_t*> >::iterator itr;
for ( itr = genusSpp.begin(); itr != genusSpp.end(); itr++ )
{
vector<NewickNode_t*> v = (*itr).second;
int vn = (int)v.size();
//Debugging
// fprintf(stderr,"%s: ", (*itr).first.c_str());
// for ( int j = 0; j < vn; j++ )
// fprintf(stderr,"(%d, %d) ", v[j]->idx, v[j]->depth_m);
// fprintf(stderr,"\n");
NewickNode_t* minDepthNode = v[0];
int minDepth = v[0]->depth_m;
for ( int j = 1; j < vn; j++ )
{
if ( v[j]->depth_m < minDepth )
{
minDepth = v[j]->depth_m;
minDepthNode = v[j];
}
}
NewickNode_t* node = minDepthNode->parent_m;
bool foundParentNode = hasSelSpp(node, v); // looking for a parent node of all elements of v
while ( foundParentNode==false )
{
node = node->parent_m; // move up to its parent node
foundParentNode = hasSelSpp(node, v);
}
// write subtree rooted in node to a file
int n1 = strlen(outDir);
int n2 = ((*itr).first).length();
char *outFile = (char*)malloc((n1+n2+1+5)*sizeof(char));
strcpy(outFile,outDir);
strcat(outFile,((*itr).first).c_str());
strcat(outFile,".tree");
FILE *fh = fOpen(outFile,"w");
writeTree(fh, node);
fclose(fh);
// write leaf labels to a file
vector<string> leaves;
leafLabels(node, leaves);
char *idsFile = (char*)malloc((n1+n2+1+5)*sizeof(char));
strcpy(idsFile,outDir);
strcat(idsFile,((*itr).first).c_str());
strcat(idsFile,".ids");
writeStrVector(idsFile, leaves);
}
}
// ------------------------------ hasSelSpp ------------------------
// Traverses the subtree of the current tree rooted at '_node'
// and checks if that tree contains all elements of v
//
// Returns true if all elements of v are in the subtree of _node
//
bool NewickTree_t::hasSelSpp(NewickNode_t *_node,
vector<NewickNode_t*> &v)
{
queue<NewickNode_t *> bfs;
bfs.push(_node);
NewickNode_t *node;
int countFoundNodes = 0; // count of nodes of v found in the subtree of _node
// table of indixes of nodes of v; return values of the table are not used
// the table is used only to find is a node is in v
map<int,bool> V;
int n = (int)v.size();
for ( int i = 0; i < n; i++ )
V[v[i]->idx] = true;
map<int,bool>::iterator it;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
it = V.find(node->idx);
if ( it != V.end() )
countFoundNodes++;
int numChildren = node->children_m.size();
if ( numChildren!=0 ) // internal node
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
return countFoundNodes == (int)v.size();
}
//--------------------------------------------- leafLabels -----
// Given a node in the tree, the routine gives leaf labels
// of the subtree rooted at 'node'.
void NewickTree_t::leafLabels(NewickNode_t *_node, vector<string> &leaves)
{
leaves.clear();
queue<NewickNode_t *> bfs;
bfs.push(_node);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
leaves.push_back( node->label );
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
}
//--------------------------------------------- leafLabels -----
// Given a node in the tree, the routine returns a vector of pointes to leaf nodes
// of the subtree rooted at 'node'.
void NewickTree_t::leafLabels(NewickNode_t *_node, vector<NewickNode_t *> &leaves)
{
queue<NewickNode_t *> bfs;
bfs.push(_node);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
leaves.push_back( node );
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
}
//--------------------------------------------- leafLabels -----
// Given a node in the tree, the routine returns a vector of pointes to leaf nodes
// (excluding a selected node) of the subtree rooted at 'node'.
void NewickTree_t::leafLabels(NewickNode_t *_node, vector<NewickNode_t *> &leaves, NewickNode_t *selNode)
{
queue<NewickNode_t *> bfs;
bfs.push(_node);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
if ( node != selNode )
leaves.push_back( node );
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
}
//--------------------------------------------- leafLabels -----
// Given a node in the tree, the routine gives leaf labels
// of the subtree rooted at 'node'.
void NewickTree_t::leafLabels(NewickNode_t *_node, set<string> &leaves)
{
queue<NewickNode_t *> bfs;
bfs.push(_node);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
leaves.insert( node->label );
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
}
//--------------------------------------------- getSppProfs -----
void NewickTree_t::getSppProfs( vector<sppProf_t*> &sppProfs,
vector<int> &nodeCut,
int *annIdx,
int minNA,
map<int, string> &idxToAnn,
map<string, string> &txParent)
/*
Given nodeCut + some other parameters
populate a vector of pointers to sppProf_t's
with i-th element of sppProfs corresponding to the i-th
node cut in nodeCut.
*/
{
map<int, NewickNode_t*> idx2node;
indexNewickNodes(idx2node);
int n = nodeCut.size();
for ( int i = 0; i < n; ++i )
{
map<string,int> annCount; // count of a given annotation string in the subtree of a given cut-node
queue<NewickNode_t *> bfs;
bfs.push(idx2node[nodeCut[i]]);
NewickNode_t *node;
int naCount = 0;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren==0 ) // leaf
{
annCount[ idxToAnn[ annIdx[node->idx] ] ]++;
if ( annIdx[node->idx] == -2) naCount++;
}
else
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
}
}
}
if ( naCount >= minNA )
{
map<string,int> sppFreq;
node = idx2node[nodeCut[i]]; // current node
NewickNode_t * ancNode;
if ( annCount.size() > 1 ) // there is at least one annotated element; setting cltrTx to annotation with the max frequency
{
cltrSpp(node, annIdx, idxToAnn, sppFreq); // table of species frequencies in the subtree of 'node'
ancNode = node;
}
else // there are no annotated sequences in the cluster; we are looking for the nearest ancestral node with known taxonomy
{
ancNode = node->parent_m; // looking at the parent node
int nSpp = cltrSpp(ancNode, annIdx, idxToAnn, sppFreq); // table of species frequencies in the subtree of 'node'
while ( nSpp==0 ) // if the parent node does not have any annotation sequences
{
ancNode = ancNode->parent_m; // move up to its parent node
nSpp = cltrSpp(ancNode, annIdx, idxToAnn, sppFreq);
}
//ancNode = ancNode->parent_m;
}
sppProf_t *sppProf = new sppProf_t();
sppProf->node = node;
sppProf->ancNode = ancNode;
sppProf->sppFreq = sppFreq;
sppProfs.push_back( sppProf );
}
}
}
#if 0
//--------------------------------------------- strMap2Set -----
set<string> NewickTree_t::strMap2Set(map<string,int> &sppFreq)
/*
Extracts keys from map<string,int> and puts them in to a set<string>
*/
{
set<string> sppSet;
map<string,int>::iterator it;
for (it = sppFreq.begin(); it != sppFreq.end(); ++it)
{
if ( (*it).first != "NA" )
{
sppSet.insert( (*it).first );
}
}
return sppSet;
}
#endif
//--------------------------------------------- strMap2Str -----
string NewickTree_t::strMap2Str(map<string,int> &sppFreq)
/*
Extracts keys from map<string,int>, sorts them and then concatenates them in to a string
*/
{
vector<string> spp;
map<string,int>::iterator it;
for (it = sppFreq.begin(); it != sppFreq.end(); ++it)
{
if ( (*it).first != "NA" )
{
spp.push_back( (*it).first );
}
}
sort (spp.begin(), spp.end());
string sppStr = spp[0];
int n = spp.size();
for ( int i = 1; i < n; i++ )
sppStr += string(".") + spp[i];
return sppStr;
}
//--------------------------------------------- getAncRoots -----
void NewickTree_t::getAncRoots(vector<sppProf_t*> &sppProfs,
vector<sppProf_t*> &ancRootProfs) // ancestral root nodes
/*
Finding root ancestral nodes, which are ancestral nodes of
sppProfs, such that on the path from the ancestral node to the root of the tree
there a no other ancestral nodes with the same species profile (excluding frequencies)
*/
{
// creating a table of indices of all ancestral nodes except those which are root_m or whose parent is root_m
// for the ease of identifying ancestral nodes on the path to the root_m
map<int, int> ancNodes;
int n = sppProfs.size();
for ( int i = 0; i < n; ++i )
{
NewickNode_t *node = sppProfs[i]->ancNode;
if ( node != root_m && node->parent_m != root_m )
{
//node = node->parent_m;
//fprintf(stderr,"i: %d\tidx: %d\r",i,node->idx);
ancNodes[ node->idx ] = i;
}
}
// iterating over all ancestral nodes and checking which of them have no other
// ancestral nodes on the path to root_m
for ( int i = 0; i < n; ++i )
{
if ( sppProfs[i]->ancNode == sppProfs[i]->node // cut node with some reference sequences in its subtree
|| sppProfs[i]->ancNode == root_m
|| (sppProfs[i]->ancNode)->parent_m == root_m )
{
ancRootProfs.push_back( sppProfs[i] );
}
else
{
NewickNode_t *node = sppProfs[i]->ancNode;
map<int,int>::iterator it;
while ( node != root_m )
{
if ( (it = ancNodes.find( node->idx )) != ancNodes.end() && // walking to the root_m, another ancestral node was found
strMap2Str(sppProfs[i]->sppFreq) == strMap2Str( sppProfs[it->second]->sppFreq ) ) // it->second is the index of the ancestral node in sppProfs that was found on the path to root_m
break;
node = node->parent_m;
}
if ( node == root_m ) // no ancestral nodes were found on the path to the root_m
ancRootProfs.push_back( sppProfs[i] );
}
}
}
//--------------------------------------------- rmTxErrors -----
void NewickTree_t::rmTxErrors( vector<sppProf_t*> &ancRootProfs,
int depth,
int *annIdx,
map<int, string> &idxToAnn)
/*
Changing taxonomic assignment in a situation when one species is contained in a
clade of another species of the same genus.
depth parameter controls how many ancestors we want to visit before making a decision.
If at the depth ancestor (going up towards the root) species frequencies are
1 (for the current node) and (depth-1) for other species of the same genus, then
sppFreq of the current node is replaced by the one of the other species nodes.
The modification are only applied to ancestral nodes with ancNode=node, because
others will have homogeneous clade structure by construction.
*/
{
int n = ancRootProfs.size();
for ( int i = 0; i < n; ++i )
{
if ( ancRootProfs[i]->ancNode == ancRootProfs[i]->node )
{
NewickNode_t *node = ancRootProfs[i]->ancNode;
for ( int j = 0; j < depth; j++ )
node = node->parent_m;
// compute sppFreq for node
map<string,int> sppFreq;
cltrSpp(node, annIdx, idxToAnn, sppFreq);
// finding max count species in the original node
// and comparing its frequency in sppFreq
//if ( sppFreq[ (ancRootProfs[i]->node)->label ] = sppFreq[
}
}
}
//--------------------------------------------- printTx -----
void NewickTree_t::printTx( const char *outFile,
vector<sppProf_t*> &ancRootProfs)
/*
Generating taxonomic assignment to all leaves of the tree.
The leaves of the subtree of a root ancestral node all have the same taxonomy
based on the majority vote at the species or genus level.
*/
{
FILE *fh = fOpen(outFile,"w");
int n = ancRootProfs.size();
for ( int i = 0; i < n; ++i )
{
NewickNode_t *node = ancRootProfs[i]->ancNode;
map<string,int> sppFreq = ancRootProfs[i]->sppFreq;
string cltrTx; // taxonomy for all query reads of the cluster with no annotated sequences
// determining taxonomy based on the majority vote
int maxCount = 0; // maximal species count
map<string,int>::iterator it;
for (it = sppFreq.begin(); it != sppFreq.end(); ++it)
{
if ( (*it).first != "NA" && (*it).second > maxCount )
{
maxCount = (*it).second;
cltrTx = (*it).first;
}
}
// propagating the taxonomy to all leaves of the subtree of the ancestral root node
vector<string> leaves;
leafLabels(node, leaves);
int m = leaves.size();
for ( int j = 0; j < m; j++ )
fprintf(fh, "%s\t%s\n", leaves[j].c_str(), cltrTx.c_str());
}
fclose(fh);
}
//---------------------------------------------------------- updateLabels ----
void NewickTree_t::updateLabels( strSet_t &tx2seqIDs )
/*
To test txSet2txTree() this routine updates tree labels so they
include the number of sequences associated with each node
*/
{
queue<NewickNode_t *> bfs;
bfs.push(root_m);
NewickNode_t *node;
strSet_t::iterator it;
char nStr[16];
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
if ( node != root_m )
{
it=tx2seqIDs.find( node->label );
if ( it != tx2seqIDs.end() )
{
int n = (it->second).size();
sprintf(nStr,"%d",n);
node->label += string("{") + string(nStr) + string("}");
}
else
{
fprintf(stderr,"ERROR in %s at line %d: node with label %s not found in tx2seqIDs map\n",
__FILE__,__LINE__, node->label.c_str());
exit(1);
}
}
int numChildren = node->children_m.size();
if ( numChildren )
{
for (int i = 0; i < numChildren; i++)
bfs.push(node->children_m[i]);
}
}
}
//---------------------------------------------------------- txSet2txTree ----
void NewickTree_t::txSet2txTree( strSet_t &tx2seqIDs )
/*
tx2seqIDs maps tx (assumed to be labels of the leaves of the tree) into set of
seqIDs corresponding to the given taxon, tx.
The routine extends tx2seqIDs to map also internal nodes to seqIDs associated
with the leaves of the corresponding subtree.
*/
{
queue<NewickNode_t *> bfs;
bfs.push(root_m);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren )
{
for (int i = 0; i < numChildren; i++)
{
bfs.push(node->children_m[i]);
set<string> seqIDs; // sequence IDs from all leaves of the subtree of node->children_m[i]
set<string> leaves;
leafLabels(node->children_m[i], leaves);
set<string>::iterator it;
for (it=leaves.begin(); it!=leaves.end(); it++)
{
set<string> ids = tx2seqIDs[ *it ];
set_union( seqIDs.begin(), seqIDs.end(),
ids.begin(), ids.end(),
inserter(seqIDs, seqIDs.begin()) );
}
if ( (node->children_m[i])->label.empty() )
{
cerr << "ERROR in " << __FILE__ << " at line " << __LINE__ << ": internal node is missing lable\n" << endl;
}
tx2seqIDs[ (node->children_m[i])->label ] = seqIDs;
}
}
}
}
//---------------------------------------------------------- inodeTx ----
void NewickTree_t::inodeTx( const char *fullTxFile, map<string, string> &inodeTx )
/*
Creating <interna node> => <taxonomy> table inodeTx
*/
{
// parse fullTxFile that has the following structure
// BVAB1 g_Shuttleworthia f_Lachnospiraceae o_Clostridiales c_Clostridia p_Firmicutes d_Bacteria
// BVAB2 g_Acetivibrio f_Ruminococcaceae o_Clostridiales c_Clostridia p_Firmicutes d_Bacteria
// BVAB3 g_Acetivibrio f_Ruminococcaceae o_Clostridiales c_Clostridia p_Firmicutes d_Bacteria
// Dialister_sp._type_1 g_Dialister f_Veillonellaceae o_Clostridiales c_Clostridia p_Firmicutes d_Bacteria
const int NUM_TX = 7;
char ***txTbl;
int nRows, nCols;
readCharTbl( fullTxFile, &txTbl, &nRows, &nCols );
#if 0
fprintf(stderr,"fullTxFile txTbl:\n");
printCharTbl(txTbl, 10, nCols); // test
#endif
map<string, vector<string> > fullTx; // fullTx[speciesName] = vector of the corresponding higher rank taxonomies
// for example
// BVAB1 g_Shuttleworthia f_Lachnospiraceae o_Clostridiales c_Clostridia p_Firmicutes d_Bacteria
// corresponds to
// fullTx[BVAB1] = (g_Shuttleworthia, f_Lachnospiraceae, o_Clostridiales, c_Clostridia, p_Firmicutes, d_Bacteria)
charTbl2strVect( txTbl, nRows, nCols, fullTx);
map<string, vector<string> >::iterator it1;
#if 0
map<string, vector<string> >::iterator it1;
for ( it1 = fullTx.begin(); it1 != fullTx.end(); it1++ )
{
fprintf(stderr, "%s: ", (it1->first).c_str());
vector<string> v = it1->second;
for ( int i = 0; i < (int)v.size(); i++ )
fprintf(stderr, "%s ", v[i].c_str());
fprintf(stderr, "\n");
}
for ( it1 = fullTx.begin(); it1 != fullTx.end(); it1++ )
{
vector<string> v = it1->second;
fprintf(stderr, "%s: %d\n", (it1->first).c_str(), (int)v.size());
}
fprintf(stderr, "after\n");
#endif
// traverse the tree and for each internal node find consensus taxonomic rank
// of all leaves of the corresponding subtree
queue<NewickNode_t *> bfs;
bfs.push(root_m);
NewickNode_t *node;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
int numChildren = node->children_m.size();
if ( numChildren ) // internal node
{
for (int i = 0; i < numChildren; i++)
bfs.push(node->children_m[i]);
vector<string> spp;
leafLabels(node, spp);
int txIdx;
set<string> tx;
set<string>::iterator it;
for ( txIdx = 0; txIdx < NUM_TX; txIdx++ )
{
tx.erase( tx.begin(), tx.end() ); // erasing all elements of tx
int n = spp.size();
for ( int j = 0; j < n; j++ )
{
it1 = fullTx.find( spp[j] );
if ( it1==fullTx.end() )
fprintf(stderr, "%s not found in fullTx\n", spp[j].c_str());
tx.insert( fullTx[ spp[j] ][txIdx] );
}
if ( tx.size() == 1 )
break;
}
it = tx.begin(); // now it points to the first and unique element of tx
inodeTx[ node->label ] = *it;
}
}
}
//---------------------------------------------------------- modelIdx ----
// populate model_idx fields of all nodes of the tree
//
// when node labels correspond to model labels model_idx is the index of the node
// label in MarkovChains2_t's modelIds_m
void NewickTree_t::modelIdx( vector<string> &modelIds )
{
map<string, int> modelIdx;
int n = modelIds.size();
for ( int i = 0; i < n; i++ )
modelIdx[ modelIds[i] ] = i;
queue<NewickNode_t *> bfs;
bfs.push(root_m);
NewickNode_t *node;
map<string, int>::iterator it;
while ( !bfs.empty() )
{
node = bfs.front();
bfs.pop();
if ( node != root_m )
{
it = modelIdx.find( node->label );
if ( it != modelIdx.end() )
node->model_idx = modelIdx[ node->label ];
#if 0
else
fprintf(stderr, "ERROR in %s at line %d: Node label %s not found in modelIds\n",
__FILE__, __LINE__, (node->label).c_str());
#endif
}
int numChildren = node->children_m.size();
if ( numChildren ) // internal node
{
for (int i = 0; i < numChildren; i++)
bfs.push(node->children_m[i]);
}
}
}
// ----------------------------------------- readNewickNode() ---------------------------------
//
// This code was lifted/adopted from the spimap-1.1 package
// ~/devel/MCclassifier/packages/spimap-1.1/src
// http://compbio.mit.edu/spimap/
// https://academic.oup.com/mbe/article-lookup/doi/10.1093/molbev/msq189
//
float readDist( FILE *infile )
{
float dist = 0;
fscanf(infile, "%f", &dist);
return dist;
}
char readChar(FILE *stream, int &depth)
{
char chr;
do {
if (fread(&chr, sizeof(char), 1, stream) != 1) {
// indicate EOF
return '\0';
}
} while (chr == ' ' || chr == '\n');
// keep track of paren depth
if (chr == '(') depth++;
if (chr == ')') depth--;
return chr;
}
char readUntil(FILE *stream, string &token, const char *stops, int &depth)
{
char chr;
token = "";
while (true) {
chr = readChar(stream, depth);
if (!chr)
return chr;
// compare char to stop characters
for (const char *i=stops; *i; i++) {
if (chr == *i)
return chr;
}
token += chr;
}
}
string getIdent( int depth )
{
string identStr = "";
for ( int i = 0; i < depth; i++ )
{
identStr += string(" ");
}
return identStr;
}
NewickNode_t *readNewickNode(FILE *infile, NewickTree_t *tree, NewickNode_t *parent, int &depth)
{
#define DEBUG_RNN 0
#if DEBUG_RNN
string ident = getIdent( depth );
fprintf(stderr, "%sIn readNewickNode() depth: %d\n", ident.c_str(), depth);
#endif
char chr, char1;
NewickNode_t *node;
string token;
// read first character
if ( !(char1 = readChar(infile, depth)) )
{
fprintf(stderr, "\n\n\tERROR: Unexpected end of file\n\n");
exit(1);
}
if ( char1 == '(' ) // read internal node
{
int depth2 = depth;
if ( parent )
{
node = parent->addChild();
#if DEBUG_RNN
if ( depth )
{
string ident = getIdent( depth );
fprintf( stderr, "%sCurrently at depth: %d - Adding a child to a parent\n", ident.c_str(), depth );
}
else
{
fprintf( stderr, "Currently at depth: %d - Adding a child to a parent\n", depth );
}
#endif
}
else
{
node = new NewickNode_t();
tree->setRoot( node );
#if DEBUG_RNN
fprintf( stderr, "Currently at depth: %d - Creating a root\n", depth );
#endif
}
// updating node's depth
node->depth_m = depth - 1;
// read all child nodes at this depth
while ( depth == depth2 )
{
NewickNode_t *child = readNewickNode(infile, tree, node, depth);
if (!child)
return NULL;
}
// Assigning a numeric index to the node
node->idx = tree->getMinIdx();
tree->decrementMinIdx();
// read branch_length for this node
// this fragment assumes that the internal nodes do not have labels
char chr = readUntil(infile, token, "):,;", depth);
if ( !token.empty() ) // Reading node's label
{
node->label = trim(token.c_str());
#if DEBUG_RNN
string ident = getIdent( depth );
fprintf( stderr, "%sNode name: %s\n", ident.c_str(), token.c_str() );
#endif
}
if (chr == ':')
{
node->branch_length = readDist( infile );
#if DEBUG_RNN
string ident = getIdent( depth );
fprintf( stderr, "%snode->branch_length: %f\n", ident.c_str(), node->branch_length );
#endif
if ( !(chr = readUntil(infile, token, "):,;", depth)) )
return NULL;
}
//if (chr == ';' && depth == 0)
// return node;
#if DEBUG_RNN
string ident = getIdent( node->depth_m );
fprintf( stderr, "%sNode's depth: %d\n", ident.c_str(), node->depth_m );
#endif
return node;
}
else
{
// Parsing leaf
if (parent)
{
node = parent->addChild();
#if DEBUG_RNN
string ident = getIdent(depth);
fprintf( stderr, "%sCurrently at depth: %d - Found leaf: adding it as a child to a parent\n", ident.c_str(), depth );
#endif
}
else
{
fprintf( stderr, "\n\n\tERROR: Found leaf without a parent\n\n" );
exit(1);
}
// Assigning to the leaf a numeric index
node->idx = tree->leafCount();
tree->incrementLeafCount();
// updating leaf's depth
node->depth_m = depth;
// Reading leaf label
if ( !(chr = readUntil(infile, token, ":),", depth)) )
return NULL;
token = char1 + trim(token.c_str());
node->label = token;
#if DEBUG_RNN
string ident = getIdent( depth );
fprintf( stderr, "%sLeaf name: %s\tdepth: %d\tidx: %d\n", ident.c_str(), token.c_str(), node->depth_m, node->idx );
#endif
// read distance for this node
if (chr == ':')
{
node->branch_length = readDist( infile );
#if DEBUG_RNN
fprintf( stderr, "%sLeaf's branch length: %f\n", ident.c_str(), node->branch_length );
#endif
if ( !(chr = readUntil( infile, token, ":),", depth )) )
return NULL;
}
return node;
}
}
NewickTree_t *readNewickTree( const char *filename )
{
FILE *infile = fOpen(filename, "r");
int depth = 0;
NewickTree_t *tree = new NewickTree_t();
NewickNode_t * node = readNewickNode(infile, tree, NULL, depth);
tree->setRoot( node );
fclose(infile);
return tree;
}
| 26.118616 | 185 | 0.579848 | pgajer |
8205757562d52e5e616fffeca3b4c5e1355f2022 | 3,450 | hpp | C++ | src/c4/regen/regen.hpp | biojppm/c4regen | a5c908ec97c0546b6d1a92df21715bffe330c42c | [
"MIT"
] | 2 | 2019-11-25T09:49:43.000Z | 2021-07-27T08:28:22.000Z | src/c4/regen/regen.hpp | biojppm/c4regen | a5c908ec97c0546b6d1a92df21715bffe330c42c | [
"MIT"
] | null | null | null | src/c4/regen/regen.hpp | biojppm/c4regen | a5c908ec97c0546b6d1a92df21715bffe330c42c | [
"MIT"
] | null | null | null | #ifndef _C4_REGEN_HPP_
#define _C4_REGEN_HPP_
#include "c4/regen/enum.hpp"
#include "c4/regen/function.hpp"
#include "c4/regen/class.hpp"
#include "c4/regen/writer.hpp"
#include <c4/c4_push.hpp>
namespace c4 {
namespace regen {
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
struct Regen
{
std::string m_config_file_name;
std::string m_config_file_yml;
c4::yml::Tree m_config_data;
std::vector<EnumGenerator > m_gens_enum;
std::vector<ClassGenerator > m_gens_class;
std::vector<FunctionGenerator> m_gens_function;
std::vector<Generator* > m_gens_all;
Writer m_writer;
std::vector<SourceFile> m_src_files;
bool m_save_src_files;
ast::StringCollection m_strings;
public:
Regen() : m_save_src_files(false) {}
Regen(const char* config_file) : Regen()
{
load_config(config_file);
}
bool empty() const { return m_gens_all.empty(); }
void load_config(const char* file_name);
void save_src_files(bool yes) { m_save_src_files = yes; }
public:
template<class SourceFileNameCollection>
void gencode(SourceFileNameCollection c$$ collection, const char* db_dir=nullptr, const char* const* flags=nullptr, size_t num_flags=0)
{
ast::CompilationDb db(db_dir);
ast::Index idx;
ast::TranslationUnit unit;
yml::Tree workspace;
SourceFile buf;
if(m_save_src_files)
{
size_t fsz = 0;
for(const char* filename : collection)
{
C4_UNUSED(filename);
fsz++;
}
m_src_files.resize(fsz);
}
m_writer.begin_files();
size_t ifile = 0;
for(const char* filename : collection)
{
if( ! m_save_src_files)
{
buf.clear();
idx.clear();
}
SourceFile &sf = m_save_src_files ? m_src_files[ifile++] : buf;
if(db_dir)
{
unit.reset(idx, filename, db);
}
else
{
unit.reset(idx, filename, flags, num_flags);
}
sf.init_source_file(idx, unit);
sf.extract(m_gens_all.data(), m_gens_all.size());
sf.gencode(m_gens_all.data(), m_gens_all.size(), workspace);
m_writer.write(sf);
}
m_writer.end_files();
m_strings = std::move(idx.yield_strings());
}
template<class SourceFileNameCollection>
void print_output_filenames(SourceFileNameCollection c$$ collection)
{
Writer::set_type workspace;
for(const char* source_file : collection)
{
m_writer.insert_filenames(to_csubstr(source_file), &workspace);
}
for(auto c$$ name : workspace)
{
printf("%s\n", name.c_str());
}
}
private:
template<class GeneratorT>
void _loadgen(c4::yml::NodeRef const& n, std::vector<GeneratorT> *gens)
{
gens->emplace_back();
GeneratorT &g = gens->back();
g.load(n);
m_gens_all.push_back(&g);
}
};
} // namespace regen
} // namespace c4
#include <c4/c4_pop.hpp>
#endif /* _C4_REGEN_HPP_ */
| 25.367647 | 139 | 0.538261 | biojppm |
82065130c76b5a7180c49205b158a6d4e4d00465 | 12,525 | cpp | C++ | src/presentation.cpp | dashboardvision/aspose-php | e2931773cbb1f47ae4086d632faa3012bd952b99 | [
"MIT"
] | null | null | null | src/presentation.cpp | dashboardvision/aspose-php | e2931773cbb1f47ae4086d632faa3012bd952b99 | [
"MIT"
] | null | null | null | src/presentation.cpp | dashboardvision/aspose-php | e2931773cbb1f47ae4086d632faa3012bd952b99 | [
"MIT"
] | 1 | 2021-06-23T08:02:03.000Z | 2021-06-23T08:02:03.000Z | #include "../include/aspose.h"
#include "../include/presentation.h"
#include "../include/slide.h"
#include "../include/islide_collection.h"
#include "../include/slide_size.h"
#include <phpcpp.h>
#include <iostream>
#include "../include/master-slide-collection.h"
#include "../include/image-collection.h"
using namespace Aspose::Slides;
using namespace Aspose::Slides::Export;
using namespace System;
using namespace System::Collections::Generic;
using namespace std;
using namespace System::IO;
namespace AsposePhp {
/**
* @brief PHP Constructor
*
* @param params Path to presentation file to read. This is optional. If not defined, an empty presentation will be created.
*/
void Presentation::__construct(Php::Parameters ¶ms)
{
this->load(params);
if(params.size() > 1) {
this->loadLicense(params);
}
}
/**
* @brief Loads license file
*
* @param params Has one param, the path
*
* @throw System::ArgumentException path is invalid
* @throw System::IO::FileNotFoundException File does not exist
* @throw System::UnauthorizedAccessException Has no right access file
* @throw System::Xml::XmlException File contains invalid XML
*
*/
void Presentation::loadLicense(Php::Parameters ¶ms) {
std::string licensePath = params[1].stringValue();
try {
SharedPtr<Aspose::Slides::License> lic = MakeObject<Aspose::Slides::License>();
lic->SetLicense(String(licensePath));
if(!lic->IsLicensed()) {
throw Php::Exception("Invalid license");
}
}
catch(System::ArgumentException &e) {
throw Php::Exception(e.what());
}
catch(System::IO::FileNotFoundException &e) {
throw Php::Exception(e.what());
}
catch(System::UnauthorizedAccessException &e) {
throw Php::Exception(e.what());
}
catch(System::Xml::XmlException &e) {
throw Php::Exception(e.what());
}
catch(System::InvalidOperationException &e) {
throw Php::Exception(e.what());
}
catch(...) {
throw Php::Exception("Unknown error. Unable to loead license file..");
}
}
/**
* @brief Loads a presentation file.
*
* @param params Path to presentation to read.
*
* @throw System::ArgumentException path is invalid
* @throw System::IO::FileNotFoundException File does not exist
* @throw System::UnauthorizedAccessException Has no right access file
* @return Php::Value
*/
Php::Value Presentation::load(Php::Parameters ¶ms) {
std::string path = params[0].stringValue();
// std::string licencePath = params[1].stringValue();
const String templatePath = String(path);
SharedPtr<LoadOptions> loadOptions = MakeObject<LoadOptions>();
try {
_pres = MakeObject<Aspose::Slides::Presentation>(templatePath);
_slides = _pres->get_Slides();
SharedPtr<PresentationFactory> pFactory = PresentationFactory::get_Instance();
_slideText = pFactory->GetPresentationText(templatePath, TextExtractionArrangingMode::Unarranged)->get_SlidesText();
}
catch(System::ArgumentException &e) {
throw Php::Exception(e.what());
}
catch(System::IO::FileNotFoundException &e) {
throw Php::Exception(e.what());
}
catch(System::UnauthorizedAccessException &e) {
throw Php::Exception(e.what());
}
catch(...) {
throw Php::Exception("Uknown error. Unable to loead input file..");
}
return this;
}
/**
* @brief Writes the presentaton to disk or returns it as byte array.
*
* @param params Output path. File must not exist.
* @param params file format.
* @param params AsArray if true, byte array will be returned.
*
* @throw System::IO::IOException cannot access path
* @throw System::UnauthorizedAccessException Has no right access file
*/
Php::Value Presentation::save(Php::Parameters ¶ms) {
String outfile = String(params[0].stringValue());
std::string fmt = params[1].stringValue();
bool asArray = params[2].boolValue();
SaveFormat format = SaveFormat::Ppt;
ArrayPtr<string> formats = new Array<string>(vector<string> {"ppt", "pptx"});
if(formats->IndexOf(fmt) != -1) {
if(fmt == "ppt") {
format = SaveFormat::Ppt;
} else if(fmt == "pptx") {
format = SaveFormat::Pptx;
}
try {
if(asArray) {
SharedPtr<MemoryStream> stream = MakeObject<MemoryStream>();
_pres->Save(stream, format);
vector<uint8_t> res = stream->ToArray()->data();
return Php::Array(res);
} else {
SharedPtr<Stream> stream = MakeObject<FileStream>(outfile, FileMode::Create);
_pres->Save(stream, format);
}
}
catch(System::IO::IOException &e) {
throw Php::Exception(e.what());
}
catch(System::UnauthorizedAccessException &e) {
throw Php::Exception(e.what());
}
catch(...) {
throw Php::Exception("Uknown error. Unable to write output file..");
}
} else {
throw Php::Exception("Uknown format.");
}
return nullptr;
}
/**
* @brief Clones the slide with given index.
*
* @param params 0 based index of the slide to be cloned
*
* @throw System::ArgumentOutOfRangeException slide index does not exist
* @throw Aspose::Slides::PptxEditException PPT modification failed.
*/
void Presentation::cloneSlide(Php::Parameters ¶ms) {
int slideNo = params[0].numericValue();
try {
_slides->AddClone(_slides->idx_get(slideNo));
}
catch(System::ArgumentOutOfRangeException &e) {
throw Php::Exception("Invalid index: " + to_string(slideNo));
}
catch(Aspose::Slides::PptxEditException &e) {
throw Php::Exception(e.what());
}
catch(...) {
throw Php::Exception("Uknown error. Unable to clone slide..");
}
}
/**
* @brief Returns all text from presentation as string. Does NOT include charts and tables.
*
* @param params An array with 2 string elements: a path to the presentation file and a
* type indicating which type of text should be returned. Type can be either of the following:
* - master
* - layout
* - notes
* - all
*
* @throw System::ArgumentException path is invalid
* @throw System::IO::FileNotFoundException File does not exist
* @throw System::UnauthorizedAccessException Has no right access file
* @return Php::Value
*/
Php::Value Presentation::getPresentationText(Php::Parameters ¶ms) {
std::string path = params[0].stringValue();
std::string type = params[1].stringValue();
String templatePath = String(path);
try {
SharedPtr<PresentationFactory> pFactory = PresentationFactory::get_Instance();
ArrayPtr<SharedPtr<ISlideText>> text = pFactory->GetPresentationText(templatePath, TextExtractionArrangingMode::Unarranged)->get_SlidesText();
string texts = "";
for (int i = 0; i < text->get_Length(); i++) {
if(type == "all") {
texts += text[i]->get_Text().ToUtf8String();
} else if(type == "master") {
texts += text[i]->get_MasterText().ToUtf8String();
} else if(type == "layout") {
texts += text[i]->get_LayoutText().ToUtf8String();
} else if(type == "notes") {
texts += text[i]->get_NotesText().ToUtf8String();
}
}
return texts;
}
catch(System::ArgumentException &e) {
throw Php::Exception(e.what());
}
catch(System::IO::FileNotFoundException &e) {
throw Php::Exception(e.what());
}
catch(System::UnauthorizedAccessException &e) {
throw Php::Exception(e.what());
}
}
/**
* @brief Returns the number of slides in presentation.
*
* @return Php::Value
*/
Php::Value Presentation::getNumberOfSlides() {
return _pres->get_Slides()->get_Count();
}
/**
* @brief Returns an array of slides as Slide objects.
*
* @return Php::Value
*/
Php::Value Presentation::getSlides() {
ISlideCollection* coll = new ISlideCollection(_slides);
return Php::Object("AsposePhp\\Slides\\ISlideCollection", coll);
}
/**
* @brief Returns slide size object
*
* @return Php::Value
*/
Php::Value Presentation::get_SlideSize() {
SlideSize * size = new SlideSize(_pres->get_SlideSize());
return Php::Object("AsposePhp\\Slides\\SlideSize", size);
}
Php::Value Presentation::getSlides2() {
if(_slides == nullptr) {
_slides = _pres->get_Slides();
}
int32_t slideCount = _slides->get_Count();
int32_t slideTextCount = _slideText->get_Count();
vector<Php::Object> slideArr;
SmartPtr<ISlide> slide;
try {
for(int i = 0; i < slideCount; i++) {
slide = _slides->idx_get(i);
AsposePhp::Slide* phpSlide;
if(i >= slideTextCount) {
phpSlide = new AsposePhp::Slide(slide, "", "", "", slide->get_SlideNumber());
} else {
phpSlide = new AsposePhp::Slide(slide,
_slideText[i]->get_LayoutText().ToUtf8String(),
_slideText[i]->get_NotesText().ToUtf8String(),
_slideText[i]->get_MasterText().ToUtf8String(), slide->get_SlideNumber());
}
slideArr.push_back(Php::Object("AsposePhp\\Slides\\Slide", phpSlide));
}
return Php::Array(slideArr);
}
catch(ArgumentOutOfRangeException &e) {
return nullptr;
}
}
/**
* @brief Returns a specific slide by index.
*
* @param params The 0 based index of the slide.
*
* @throw System::ArgumentOutOfRangeException index does not exist.
* @return Php::Value
*/
Php::Value Presentation::getSlide(Php::Parameters ¶ms) {
int slideNo = params[0].numericValue();
try {
SharedPtr<ISlide> slide = _pres->get_Slides()->idx_get(slideNo);
Slide* ret = new Slide(slide,
_slideText[slideNo]->get_LayoutText().ToUtf8String(),
_slideText[slideNo]->get_NotesText().ToUtf8String(),
_slideText[slideNo]->get_MasterText().ToUtf8String(),
slide->get_SlideNumber());
return Php::Object("AsposePhp\\Slides\\Slide", ret);
}
catch(System::ArgumentOutOfRangeException &e) {
throw Php::Exception("Invalid index: " + to_string(slideNo));
}
}
/**
* @brief Returns a list of all master slides that are defined in the presentation. Read-only IMasterSlideCollection
*
* @return Php::Value
*/
Php::Value Presentation::get_Masters() {
SharedPtr<IMasterSlideCollection> items = _pres->get_Masters();
MasterSlideCollection * phpValue = new MasterSlideCollection(items);
return Php::Object("AsposePhp\\Slides\\MasterSlideCollection", phpValue);
}
/**
* @brief Returns the collection of all images in the presentation. Read-only IImageCollection
*
* @return Php::Value
*/
Php::Value Presentation::get_Images() {
SharedPtr<IImageCollection> items = _pres->get_Images();
ImageCollection * phpValue = new ImageCollection(items);
return Php::Object("AsposePhp\\Slides\\ImageCollection", phpValue);
}
}
| 33.943089 | 155 | 0.568862 | dashboardvision |
8206e75e2672adf0814fc251cf05cc578df89a20 | 3,516 | cpp | C++ | aws-cpp-sdk-secretsmanager/source/SecretsManagerErrors.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-secretsmanager/source/SecretsManagerErrors.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-secretsmanager/source/SecretsManagerErrors.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/core/client/AWSError.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/secretsmanager/SecretsManagerErrors.h>
using namespace Aws::Client;
using namespace Aws::Utils;
using namespace Aws::SecretsManager;
namespace Aws
{
namespace SecretsManager
{
namespace SecretsManagerErrorMapper
{
static const int RESOURCE_EXISTS_HASH = HashingUtils::HashString("ResourceExistsException");
static const int MALFORMED_POLICY_DOCUMENT_HASH = HashingUtils::HashString("MalformedPolicyDocumentException");
static const int INTERNAL_SERVICE_HASH = HashingUtils::HashString("InternalServiceError");
static const int INVALID_PARAMETER_HASH = HashingUtils::HashString("InvalidParameterException");
static const int LIMIT_EXCEEDED_HASH = HashingUtils::HashString("LimitExceededException");
static const int DECRYPTION_FAILURE_HASH = HashingUtils::HashString("DecryptionFailure");
static const int PUBLIC_POLICY_HASH = HashingUtils::HashString("PublicPolicyException");
static const int PRECONDITION_NOT_MET_HASH = HashingUtils::HashString("PreconditionNotMetException");
static const int INVALID_NEXT_TOKEN_HASH = HashingUtils::HashString("InvalidNextTokenException");
static const int INVALID_REQUEST_HASH = HashingUtils::HashString("InvalidRequestException");
static const int ENCRYPTION_FAILURE_HASH = HashingUtils::HashString("EncryptionFailure");
AWSError<CoreErrors> GetErrorForName(const char* errorName)
{
int hashCode = HashingUtils::HashString(errorName);
if (hashCode == RESOURCE_EXISTS_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(SecretsManagerErrors::RESOURCE_EXISTS), false);
}
else if (hashCode == MALFORMED_POLICY_DOCUMENT_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(SecretsManagerErrors::MALFORMED_POLICY_DOCUMENT), false);
}
else if (hashCode == INTERNAL_SERVICE_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(SecretsManagerErrors::INTERNAL_SERVICE), false);
}
else if (hashCode == INVALID_PARAMETER_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(SecretsManagerErrors::INVALID_PARAMETER), false);
}
else if (hashCode == LIMIT_EXCEEDED_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(SecretsManagerErrors::LIMIT_EXCEEDED), true);
}
else if (hashCode == DECRYPTION_FAILURE_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(SecretsManagerErrors::DECRYPTION_FAILURE), false);
}
else if (hashCode == PUBLIC_POLICY_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(SecretsManagerErrors::PUBLIC_POLICY), false);
}
else if (hashCode == PRECONDITION_NOT_MET_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(SecretsManagerErrors::PRECONDITION_NOT_MET), false);
}
else if (hashCode == INVALID_NEXT_TOKEN_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(SecretsManagerErrors::INVALID_NEXT_TOKEN), false);
}
else if (hashCode == INVALID_REQUEST_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(SecretsManagerErrors::INVALID_REQUEST), false);
}
else if (hashCode == ENCRYPTION_FAILURE_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(SecretsManagerErrors::ENCRYPTION_FAILURE), false);
}
return AWSError<CoreErrors>(CoreErrors::UNKNOWN, false);
}
} // namespace SecretsManagerErrorMapper
} // namespace SecretsManager
} // namespace Aws
| 39.954545 | 113 | 0.792093 | Neusoft-Technology-Solutions |
82091dab0964d78b4350f72917e686eca57d575c | 5,848 | cpp | C++ | Turso3D/Graphics/D3D11/D3D11ShaderVariation.cpp | cadaver/turso3d | 5659df48b7915b95a351dfcad382b3ed653573f2 | [
"Zlib"
] | 29 | 2015-03-21T22:35:50.000Z | 2022-01-25T04:13:46.000Z | Turso3D/Graphics/D3D11/D3D11ShaderVariation.cpp | cadaver/turso3d | 5659df48b7915b95a351dfcad382b3ed653573f2 | [
"Zlib"
] | 1 | 2016-10-23T16:20:14.000Z | 2018-04-13T13:32:13.000Z | Turso3D/Graphics/D3D11/D3D11ShaderVariation.cpp | cadaver/turso3d | 5659df48b7915b95a351dfcad382b3ed653573f2 | [
"Zlib"
] | 8 | 2015-09-28T06:26:41.000Z | 2020-12-28T14:29:51.000Z | // For conditions of distribution and use, see copyright notice in License.txt
#include "../../Debug/Log.h"
#include "../../Debug/Profiler.h"
#include "../Shader.h"
#include "D3D11Graphics.h"
#include "D3D11ShaderVariation.h"
#include "D3D11VertexBuffer.h"
#include <d3d11.h>
#include <d3dcompiler.h>
#include "../../Debug/DebugNew.h"
namespace Turso3D
{
unsigned InspectInputSignature(ID3DBlob* d3dBlob)
{
ID3D11ShaderReflection* reflection = nullptr;
D3D11_SHADER_DESC shaderDesc;
unsigned elementHash = 0;
D3DReflect(d3dBlob->GetBufferPointer(), d3dBlob->GetBufferSize(), IID_ID3D11ShaderReflection, (void**)&reflection);
if (!reflection)
{
LOGERROR("Failed to reflect vertex shader's input signature");
return elementHash;
}
reflection->GetDesc(&shaderDesc);
for (size_t i = 0; i < shaderDesc.InputParameters; ++i)
{
D3D11_SIGNATURE_PARAMETER_DESC paramDesc;
reflection->GetInputParameterDesc((unsigned)i, ¶mDesc);
for (size_t j = 0; elementSemanticNames[j]; ++j)
{
if (!String::Compare(paramDesc.SemanticName, elementSemanticNames[j]))
{
elementHash |= VertexBuffer::ElementHash(i, (ElementSemantic)j);
break;
}
}
}
reflection->Release();
return elementHash;
}
ShaderVariation::ShaderVariation(Shader* parent_, const String& defines_) :
parent(parent_),
stage(parent->Stage()),
defines(defines_),
blob(nullptr),
shader(nullptr),
elementHash(0),
compiled(false)
{
}
ShaderVariation::~ShaderVariation()
{
Release();
}
void ShaderVariation::Release()
{
if (graphics && (graphics->GetVertexShader() == this || graphics->GetPixelShader() == this))
graphics->SetShaders(nullptr, nullptr);
if (blob)
{
ID3DBlob* d3dBlob = (ID3DBlob*)blob;
d3dBlob->Release();
blob = nullptr;
}
if (shader)
{
if (stage == SHADER_VS)
{
ID3D11VertexShader* d3dShader = (ID3D11VertexShader*)shader;
d3dShader->Release();
}
else
{
ID3D11PixelShader* d3dShader = (ID3D11PixelShader*)shader;
d3dShader->Release();
}
shader = nullptr;
}
elementHash = 0;
compiled = false;
}
bool ShaderVariation::Compile()
{
if (compiled)
return shader != nullptr;
PROFILE(CompileShaderVariation);
// Do not retry without a Release() inbetween
compiled = true;
if (!graphics || !graphics->IsInitialized())
{
LOGERROR("Can not compile shader without initialized Graphics subsystem");
return false;
}
if (!parent)
{
LOGERROR("Can not compile shader without parent shader resource");
return false;
}
// Collect defines into macros
Vector<String> defineNames = defines.Split(' ');
Vector<String> defineValues;
Vector<D3D_SHADER_MACRO> macros;
for (size_t i = 0; i < defineNames.Size(); ++i)
{
size_t equalsPos = defineNames[i].Find('=');
if (equalsPos != String::NPOS)
{
defineValues.Push(defineNames[i].Substring(equalsPos + 1));
defineNames[i].Resize(equalsPos);
}
else
defineValues.Push("1");
}
for (size_t i = 0; i < defineNames.Size(); ++i)
{
D3D_SHADER_MACRO macro;
macro.Name = defineNames[i].CString();
macro.Definition = defineValues[i].CString();
macros.Push(macro);
}
D3D_SHADER_MACRO endMacro;
endMacro.Name = nullptr;
endMacro.Definition = nullptr;
macros.Push(endMacro);
/// \todo Level 3 could be used, but can lead to longer shader compile times, considering there is no binary caching yet
DWORD flags = D3DCOMPILE_OPTIMIZATION_LEVEL2 | D3DCOMPILE_PREFER_FLOW_CONTROL;
ID3DBlob* errorBlob = nullptr;
if (FAILED(D3DCompile(parent->SourceCode().CString(), parent->SourceCode().Length(), "", ¯os[0], 0, "main",
stage == SHADER_VS ? "vs_4_0" : "ps_4_0", flags, 0, (ID3DBlob**)&blob, &errorBlob)))
{
if (errorBlob)
{
LOGERRORF("Could not compile shader %s: %s", FullName().CString(), errorBlob->GetBufferPointer());
errorBlob->Release();
}
return false;
}
if (errorBlob)
{
errorBlob->Release();
errorBlob = nullptr;
}
ID3D11Device* d3dDevice = (ID3D11Device*)graphics->D3DDevice();
ID3DBlob* d3dBlob = (ID3DBlob*)blob;
#ifdef SHOW_DISASSEMBLY
ID3DBlob* asmBlob = nullptr;
D3DDisassemble(d3dBlob->GetBufferPointer(), d3dBlob->GetBufferSize(), 0, nullptr, &asmBlob);
if (asmBlob)
{
String text((const char*)asmBlob->GetBufferPointer(), asmBlob->GetBufferSize());
LOGINFOF("Shader %s disassembly: %s", FullName().CString(), text.CString());
asmBlob->Release();
}
#endif
if (stage == SHADER_VS)
{
elementHash = InspectInputSignature(d3dBlob);
d3dDevice->CreateVertexShader(d3dBlob->GetBufferPointer(), d3dBlob->GetBufferSize(), 0, (ID3D11VertexShader**)&shader);
}
else
d3dDevice->CreatePixelShader(d3dBlob->GetBufferPointer(), d3dBlob->GetBufferSize(), 0, (ID3D11PixelShader**)&shader);
if (!shader)
{
LOGERROR("Failed to create shader " + FullName());
return false;
}
else
LOGDEBUGF("Compiled shader %s bytecode size %u", FullName().CString(), (unsigned)d3dBlob->GetBufferSize());
return true;
}
Shader* ShaderVariation::Parent() const
{
return parent;
}
String ShaderVariation::FullName() const
{
if (parent)
return defines.IsEmpty() ? parent->Name() : parent->Name() + " (" + defines + ")";
else
return String::EMPTY;
}
} | 27.455399 | 127 | 0.619015 | cadaver |
82096793b59d06e566a3415fff02129b63587fd8 | 13,536 | cc | C++ | DQM/HLTEvF/plugins/TriggerBxMonitor.cc | PKUfudawei/cmssw | 8fbb5ce74398269c8a32956d7c7943766770c093 | [
"Apache-2.0"
] | 2 | 2020-10-26T18:40:32.000Z | 2021-04-10T16:33:25.000Z | DQM/HLTEvF/plugins/TriggerBxMonitor.cc | gartung/cmssw | 3072dde3ce94dcd1791d778988198a44cde02162 | [
"Apache-2.0"
] | 30 | 2015-11-04T11:42:27.000Z | 2021-12-01T07:56:34.000Z | DQM/HLTEvF/plugins/TriggerBxMonitor.cc | gartung/cmssw | 3072dde3ce94dcd1791d778988198a44cde02162 | [
"Apache-2.0"
] | 8 | 2016-03-25T07:17:43.000Z | 2021-07-08T17:11:21.000Z | // C++ headers
#include <cstring>
#include <iterator>
#include <string>
// {fmt} headers
#include <fmt/printf.h>
// CMSSW headers
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/LuminosityBlock.h"
#include "FWCore/Framework/interface/Run.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/ParameterSet/interface/ParameterSetDescription.h"
#include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h"
#include "FWCore/ParameterSet/interface/Registry.h"
#include "FWCore/ServiceRegistry/interface/Service.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "DataFormats/Provenance/interface/ProcessHistory.h"
#include "DataFormats/Common/interface/TriggerResults.h"
#include "DataFormats/L1TGlobal/interface/GlobalAlgBlk.h"
#include "CondFormats/DataRecord/interface/L1TUtmTriggerMenuRcd.h"
#include "CondFormats/L1TObjects/interface/L1TUtmTriggerMenu.h"
#include "HLTrigger/HLTcore/interface/HLTConfigProvider.h"
#include "DQMServices/Core/interface/DQMGlobalEDAnalyzer.h"
namespace {
struct RunBasedHistograms {
public:
typedef dqm::reco::MonitorElement MonitorElement;
RunBasedHistograms()
: // L1T and HLT configuration
hltConfig(),
// L1T and HLT results
tcds_bx_all(nullptr),
l1t_bx_all(nullptr),
hlt_bx_all(nullptr),
tcds_bx(),
l1t_bx(),
hlt_bx(),
tcds_bx_2d(),
l1t_bx_2d(),
hlt_bx_2d() {}
public:
// HLT configuration
HLTConfigProvider hltConfig;
// L1T and HLT results
dqm::reco::MonitorElement* tcds_bx_all;
dqm::reco::MonitorElement* l1t_bx_all;
dqm::reco::MonitorElement* hlt_bx_all;
std::vector<dqm::reco::MonitorElement*> tcds_bx;
std::vector<dqm::reco::MonitorElement*> l1t_bx;
std::vector<dqm::reco::MonitorElement*> hlt_bx;
std::vector<dqm::reco::MonitorElement*> tcds_bx_2d;
std::vector<dqm::reco::MonitorElement*> l1t_bx_2d;
std::vector<dqm::reco::MonitorElement*> hlt_bx_2d;
};
} // namespace
class TriggerBxMonitor : public DQMGlobalEDAnalyzer<RunBasedHistograms> {
public:
explicit TriggerBxMonitor(edm::ParameterSet const&);
~TriggerBxMonitor() override = default;
static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);
private:
void dqmBeginRun(edm::Run const&, edm::EventSetup const&, RunBasedHistograms&) const override;
void bookHistograms(DQMStore::IBooker&, edm::Run const&, edm::EventSetup const&, RunBasedHistograms&) const override;
void dqmAnalyze(edm::Event const&, edm::EventSetup const&, RunBasedHistograms const&) const override;
// number of bunch crossings
static const unsigned int s_bx_range = 3564;
// TCDS trigger types
// see https://twiki.cern.ch/twiki/bin/viewauth/CMS/TcdsEventRecord
static constexpr const char* s_tcds_trigger_types[] = {
"Empty", // 0 - No trigger
"Physics", // 1 - GT trigger
"Calibration", // 2 - Sequence trigger (calibration)
"Random", // 3 - Random trigger
"Auxiliary", // 4 - Auxiliary (CPM front panel NIM input) trigger
nullptr, // 5 - reserved
nullptr, // 6 - reserved
nullptr, // 7 - reserved
"Cyclic", // 8 - Cyclic trigger
"Bunch-pattern", // 9 - Bunch-pattern trigger
"Software", // 10 - Software trigger
"TTS", // 11 - TTS-sourced trigger
nullptr, // 12 - reserved
nullptr, // 13 - reserved
nullptr, // 14 - reserved
nullptr // 15 - reserved
};
// module configuration
const edm::ESGetToken<L1TUtmTriggerMenu, L1TUtmTriggerMenuRcd> m_l1tMenuToken;
const edm::EDGetTokenT<GlobalAlgBlkBxCollection> m_l1t_results;
const edm::EDGetTokenT<edm::TriggerResults> m_hlt_results;
const std::string m_dqm_path;
const bool m_make_1d_plots;
const bool m_make_2d_plots;
const uint32_t m_ls_range;
};
// definition
constexpr const char* TriggerBxMonitor::s_tcds_trigger_types[];
void TriggerBxMonitor::fillDescriptions(edm::ConfigurationDescriptions& descriptions) {
edm::ParameterSetDescription desc;
desc.addUntracked<edm::InputTag>("l1tResults", edm::InputTag("gtStage2Digis"));
desc.addUntracked<edm::InputTag>("hltResults", edm::InputTag("TriggerResults"));
desc.addUntracked<std::string>("dqmPath", "HLT/TriggerBx");
desc.addUntracked<bool>("make1DPlots", true);
desc.addUntracked<bool>("make2DPlots", false);
desc.addUntracked<uint32_t>("lsRange", 4000);
descriptions.add("triggerBxMonitor", desc);
}
TriggerBxMonitor::TriggerBxMonitor(edm::ParameterSet const& config)
: // module configuration
m_l1tMenuToken{esConsumes<edm::Transition::BeginRun>()},
m_l1t_results(consumes<GlobalAlgBlkBxCollection>(config.getUntrackedParameter<edm::InputTag>("l1tResults"))),
m_hlt_results(consumes<edm::TriggerResults>(config.getUntrackedParameter<edm::InputTag>("hltResults"))),
m_dqm_path(config.getUntrackedParameter<std::string>("dqmPath")),
m_make_1d_plots(config.getUntrackedParameter<bool>("make1DPlots")),
m_make_2d_plots(config.getUntrackedParameter<bool>("make2DPlots")),
m_ls_range(config.getUntrackedParameter<uint32_t>("lsRange")) {}
void TriggerBxMonitor::dqmBeginRun(edm::Run const& run,
edm::EventSetup const& setup,
RunBasedHistograms& histograms) const {
// initialise the TCDS vector
if (m_make_1d_plots) {
histograms.tcds_bx.clear();
histograms.tcds_bx.resize(std::size(s_tcds_trigger_types));
}
if (m_make_2d_plots) {
histograms.tcds_bx_2d.clear();
histograms.tcds_bx_2d.resize(std::size(s_tcds_trigger_types));
}
// cache the L1 trigger menu
if (m_make_1d_plots) {
histograms.l1t_bx.clear();
histograms.l1t_bx.resize(GlobalAlgBlk::maxPhysicsTriggers);
}
if (m_make_2d_plots) {
histograms.l1t_bx_2d.clear();
histograms.l1t_bx_2d.resize(GlobalAlgBlk::maxPhysicsTriggers);
}
// initialise the HLTConfigProvider
bool changed = true;
edm::EDConsumerBase::Labels labels;
labelsForToken(m_hlt_results, labels);
if (histograms.hltConfig.init(run, setup, labels.process, changed)) {
if (m_make_1d_plots) {
histograms.hlt_bx.clear();
histograms.hlt_bx.resize(histograms.hltConfig.size());
}
if (m_make_2d_plots) {
histograms.hlt_bx_2d.clear();
histograms.hlt_bx_2d.resize(histograms.hltConfig.size());
}
} else {
// HLTConfigProvider not initialised, skip the the HLT monitoring
edm::LogError("TriggerBxMonitor")
<< "failed to initialise HLTConfigProvider, the HLT bx distribution will not be monitored";
}
}
void TriggerBxMonitor::bookHistograms(DQMStore::IBooker& booker,
edm::Run const& run,
edm::EventSetup const& setup,
RunBasedHistograms& histograms) const {
// TCDS trigger type plots
{
size_t size = std::size(s_tcds_trigger_types);
// book 2D histogram to monitor all TCDS trigger types in a single plot
booker.setCurrentFolder(m_dqm_path);
histograms.tcds_bx_all = booker.book2D("TCDS Trigger Types",
"TCDS Trigger Types vs. bunch crossing",
s_bx_range + 1,
-0.5,
s_bx_range + 0.5,
size,
-0.5,
size - 0.5);
// book the individual histograms for the known TCDS trigger types
booker.setCurrentFolder(m_dqm_path + "/TCDS");
for (unsigned int i = 0; i < size; ++i) {
if (s_tcds_trigger_types[i]) {
if (m_make_1d_plots) {
histograms.tcds_bx.at(i) =
booker.book1D(s_tcds_trigger_types[i], s_tcds_trigger_types[i], s_bx_range + 1, -0.5, s_bx_range + 0.5);
}
if (m_make_2d_plots) {
std::string const& name_ls = std::string(s_tcds_trigger_types[i]) + " vs LS";
histograms.tcds_bx_2d.at(i) = booker.book2D(
name_ls, name_ls, s_bx_range + 1, -0.5, s_bx_range + 0.5, m_ls_range, 0.5, m_ls_range + 0.5);
}
histograms.tcds_bx_all->setBinLabel(i + 1, s_tcds_trigger_types[i], 2); // Y axis
}
}
}
// L1T plots
{
// book 2D histogram to monitor all L1 triggers in a single plot
booker.setCurrentFolder(m_dqm_path);
histograms.l1t_bx_all = booker.book2D("Level 1 Triggers",
"Level 1 Triggers vs. bunch crossing",
s_bx_range + 1,
-0.5,
s_bx_range + 0.5,
GlobalAlgBlk::maxPhysicsTriggers,
-0.5,
GlobalAlgBlk::maxPhysicsTriggers - 0.5);
// book the individual histograms for the L1 triggers that are included in the L1 menu
booker.setCurrentFolder(m_dqm_path + "/L1T");
auto const& l1tMenu = setup.getData(m_l1tMenuToken);
for (auto const& keyval : l1tMenu.getAlgorithmMap()) {
unsigned int bit = keyval.second.getIndex();
std::string const& name = fmt::sprintf("%s (bit %d)", keyval.first, bit);
if (m_make_1d_plots) {
histograms.l1t_bx.at(bit) = booker.book1D(name, name, s_bx_range + 1, -0.5, s_bx_range + 0.5);
}
if (m_make_2d_plots) {
std::string const& name_ls = name + " vs LS";
histograms.l1t_bx_2d.at(bit) =
booker.book2D(name_ls, name_ls, s_bx_range + 1, -0.5, s_bx_range + 0.5, m_ls_range, 0.5, m_ls_range + 0.5);
}
histograms.l1t_bx_all->setBinLabel(bit + 1, keyval.first, 2); // Y axis
}
}
// HLT plots
if (histograms.hltConfig.inited()) {
// book 2D histogram to monitor all HLT paths in a single plot
booker.setCurrentFolder(m_dqm_path);
histograms.hlt_bx_all = booker.book2D("High Level Triggers",
"High Level Triggers vs. bunch crossing",
s_bx_range + 1,
-0.5,
s_bx_range + 0.5,
histograms.hltConfig.size(),
-0.5,
histograms.hltConfig.size() - 0.5);
// book the individual HLT triggers histograms
booker.setCurrentFolder(m_dqm_path + "/HLT");
for (unsigned int i = 0; i < histograms.hltConfig.size(); ++i) {
std::string const& name = histograms.hltConfig.triggerName(i);
if (m_make_1d_plots) {
histograms.hlt_bx[i] = booker.book1D(name, name, s_bx_range + 1, -0.5, s_bx_range + 0.5);
}
if (m_make_2d_plots) {
std::string const& name_ls = name + " vs LS";
histograms.hlt_bx_2d[i] =
booker.book2D(name_ls, name_ls, s_bx_range + 1, -0.5, s_bx_range + 0.5, m_ls_range, 0.5, m_ls_range + 0.5);
}
histograms.hlt_bx_all->setBinLabel(i + 1, name, 2); // Y axis
}
}
}
void TriggerBxMonitor::dqmAnalyze(edm::Event const& event,
edm::EventSetup const& setup,
RunBasedHistograms const& histograms) const {
unsigned int bx = event.bunchCrossing();
unsigned int ls = event.luminosityBlock();
// monitor the bx distribution for the TCDS trigger types
{
size_t size = std::size(s_tcds_trigger_types);
unsigned int type = event.experimentType();
if (type < size) {
if (m_make_1d_plots and histograms.tcds_bx.at(type))
histograms.tcds_bx[type]->Fill(bx);
if (m_make_2d_plots and histograms.tcds_bx_2d.at(type))
histograms.tcds_bx_2d[type]->Fill(bx, ls);
}
histograms.tcds_bx_all->Fill(bx, type);
}
// monitor the bx distribution for the L1 triggers
{
auto const& bxvector = event.get(m_l1t_results);
if (not bxvector.isEmpty(0)) {
auto const& results = bxvector.at(0, 0);
for (unsigned int i = 0; i < GlobalAlgBlk::maxPhysicsTriggers; ++i)
if (results.getAlgoDecisionFinal(i)) {
if (m_make_1d_plots and histograms.l1t_bx.at(i))
histograms.l1t_bx[i]->Fill(bx);
if (m_make_2d_plots and histograms.l1t_bx_2d.at(i))
histograms.l1t_bx_2d[i]->Fill(bx, ls);
histograms.l1t_bx_all->Fill(bx, i);
}
}
}
// monitor the bx distribution for the HLT triggers
if (histograms.hltConfig.inited()) {
auto const& hltResults = event.get(m_hlt_results);
for (unsigned int i = 0; i < hltResults.size(); ++i) {
if (hltResults.at(i).accept()) {
if (m_make_1d_plots and histograms.hlt_bx.at(i))
histograms.hlt_bx[i]->Fill(bx);
if (m_make_2d_plots and histograms.hlt_bx_2d.at(i))
histograms.hlt_bx_2d[i]->Fill(bx, ls);
histograms.hlt_bx_all->Fill(bx, i);
}
}
}
}
//define this as a plug-in
#include "FWCore/Framework/interface/MakerMacros.h"
DEFINE_FWK_MODULE(TriggerBxMonitor);
| 41.018182 | 119 | 0.628251 | PKUfudawei |
820cdf3a3d77a20635d03b3abed4fc05e66f4cd5 | 18,023 | cpp | C++ | src/ConEmu/AboutDlg.cpp | clcarwin/ConEmu_lite | f7ed818f8ba52677d3787c180579558c4296f810 | [
"MIT"
] | null | null | null | src/ConEmu/AboutDlg.cpp | clcarwin/ConEmu_lite | f7ed818f8ba52677d3787c180579558c4296f810 | [
"MIT"
] | null | null | null | src/ConEmu/AboutDlg.cpp | clcarwin/ConEmu_lite | f7ed818f8ba52677d3787c180579558c4296f810 | [
"MIT"
] | null | null | null |
// WM_DRAWITEM, SS_OWNERDRAW|SS_NOTIFY, Bmp & hBmp -> global vars
// DPI resize.
/*
Copyright (c) 2014-2017 Maximus5
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. The name of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''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 AUTHOR 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.
*/
#undef HIDE_USE_EXCEPTION_INFO
#define SHOWDEBUGSTR
#include "Header.h"
#include "About.h"
#include "AboutDlg.h"
#include "ConEmu.h"
#include "DpiAware.h"
#include "DynDialog.h"
#include "ImgButton.h"
#include "LngRc.h"
#include "OptionsClass.h"
#include "PushInfo.h"
#include "RealConsole.h"
#include "SearchCtrl.h"
#include "Update.h"
#include "VirtualConsole.h"
#include "VConChild.h"
#include "version.h"
#include "../common/MSetter.h"
#include "../common/WObjects.h"
#include "../common/StartupEnvEx.h"
namespace ConEmuAbout
{
void InitCommCtrls();
bool mb_CommCtrlsInitialized = false;
HWND mh_AboutDlg = NULL;
DWORD nLastCrashReported = 0;
CDpiForDialog* mp_DpiAware = NULL;
INT_PTR WINAPI aboutProc(HWND hDlg, UINT messg, WPARAM wParam, LPARAM lParam);
void searchProc(HWND hDlg, HWND hSearch, bool bReentr);
void OnInfo_DonateLink();
void OnInfo_FlattrLink();
CImgButtons* mp_ImgBtn = NULL;
static struct {LPCWSTR Title; LPCWSTR Text;} Pages[] =
{
{L"About", pAbout},
{L"ConEmu /?", pCmdLine},
{L"Tasks", pAboutTasks},
{L"-new_console", pNewConsoleHelpFull},
{L"ConEmuC /?", pConsoleHelpFull},
{L"Macro", pGuiMacro},
{L"DosBox", pDosBoxHelpFull},
{L"Contributors", pAboutContributors},
{L"License", pAboutLicense},
{L"SysInfo", L""},
};
wchar_t sLastOpenTab[32] = L"";
void TabSelected(HWND hDlg, int idx);
wchar_t* gsSysInfo = NULL;
void ReloadSysInfo();
void LogStartEnvInt(LPCWSTR asText, LPARAM lParam, bool bFirst, bool bNewLine);
DWORD nTextSelStart = 0, nTextSelEnd = 0;
};
INT_PTR WINAPI ConEmuAbout::aboutProc(HWND hDlg, UINT messg, WPARAM wParam, LPARAM lParam)
{
INT_PTR lRc = 0;
if ((mp_ImgBtn && mp_ImgBtn->Process(hDlg, messg, wParam, lParam, lRc))
|| EditIconHint_Process(hDlg, messg, wParam, lParam, lRc))
{
SetWindowLongPtr(hDlg, DWLP_MSGRESULT, lRc);
return TRUE;
}
PatchMsgBoxIcon(hDlg, messg, wParam, lParam);
switch (messg)
{
case WM_INITDIALOG:
{
gpConEmu->OnOurDialogOpened();
mh_AboutDlg = hDlg;
CDynDialog::LocalizeDialog(hDlg);
_ASSERTE(mp_ImgBtn==NULL);
SafeDelete(mp_ImgBtn);
mp_ImgBtn = new CImgButtons(hDlg, pIconCtrl, IDOK);
mp_ImgBtn->AddDonateButtons();
if (mp_DpiAware)
{
mp_DpiAware->Attach(hDlg, ghWnd, CDynDialog::GetDlgClass(hDlg));
}
CDpiAware::CenterDialog(hDlg);
if ((ghOpWnd && IsWindow(ghOpWnd)) || (WS_EX_TOPMOST & GetWindowLongPtr(ghWnd, GWL_EXSTYLE)))
{
SetWindowPos(hDlg, HWND_TOPMOST, 0,0,0,0, SWP_NOMOVE|SWP_NOSIZE);
}
LPCWSTR pszActivePage = (LPCWSTR)lParam;
LPCWSTR psStage = (ConEmuVersionStage == CEVS_STABLE) ? L"{Stable}"
: (ConEmuVersionStage == CEVS_PREVIEW) ? L"{Preview}"
: L"{Alpha}";
CEStr lsTitle(
CLngRc::getRsrc(lng_DlgAbout/*"About"*/),
L" ",
gpConEmu->GetDefaultTitle(),
L" ",
psStage,
NULL);
if (lsTitle)
{
SetWindowText(hDlg, lsTitle);
}
if (hClassIcon)
{
SendMessage(hDlg, WM_SETICON, ICON_BIG, (LPARAM)hClassIcon);
SendMessage(hDlg, WM_SETICON, ICON_SMALL, (LPARAM)CreateNullIcon());
SetClassLongPtr(hDlg, GCLP_HICON, (LONG_PTR)hClassIcon);
}
// "Console Emulation program (local terminal)"
SetDlgItemText(hDlg, stConEmuAbout, CLngRc::getRsrc(lng_AboutAppName));
SetDlgItemText(hDlg, stConEmuUrl, gsHomePage);
EditIconHint_Set(hDlg, GetDlgItem(hDlg, tAboutSearch), true,
CLngRc::getRsrc(lng_Search/*"Search"*/),
false, UM_SEARCH, IDOK);
EditIconHint_Subclass(hDlg);
wchar_t* pszLabel = GetDlgItemTextPtr(hDlg, stConEmuVersion);
if (pszLabel)
{
wchar_t* pszSet = NULL;
if (gpUpd)
{
wchar_t* pszVerInfo = gpUpd->GetCurVerInfo();
if (pszVerInfo)
{
pszSet = lstrmerge(pszLabel, L" ", pszVerInfo);
free(pszVerInfo);
}
}
if (!pszSet)
{
pszSet = lstrmerge(pszLabel, L" ", CLngRc::getRsrc(lng_PleaseCheckManually/*"Please check for updates manually"*/));
}
if (pszSet)
{
SetDlgItemText(hDlg, stConEmuVersion, pszSet);
free(pszSet);
}
free(pszLabel);
}
HWND hTab = GetDlgItem(hDlg, tbAboutTabs);
INT_PTR nPage = -1;
for (size_t i = 0; i < countof(Pages); i++)
{
TCITEM tie = {};
tie.mask = TCIF_TEXT;
tie.pszText = (LPWSTR)Pages[i].Title;
TabCtrl_InsertItem(hTab, i, &tie);
if (pszActivePage && (lstrcmpi(pszActivePage, Pages[i].Title) == 0))
nPage = i;
}
if (nPage >= 0)
{
TabSelected(hDlg, nPage);
TabCtrl_SetCurSel(hTab, (int)nPage);
}
else if (!pszActivePage)
{
TabSelected(hDlg, 0);
}
else
{
_ASSERTE(pszActivePage==NULL && "Unknown page name?");
}
SetFocus(hTab);
return FALSE;
}
case WM_CTLCOLORSTATIC:
if (GetWindowLongPtr((HWND)lParam, GWLP_ID) == stConEmuUrl)
{
SetTextColor((HDC)wParam, GetSysColor(COLOR_HOTLIGHT));
HBRUSH hBrush = GetSysColorBrush(COLOR_3DFACE);
SetBkMode((HDC)wParam, TRANSPARENT);
return (INT_PTR)hBrush;
}
else
{
SetTextColor((HDC)wParam, GetSysColor(COLOR_WINDOWTEXT));
HBRUSH hBrush = GetSysColorBrush(COLOR_3DFACE);
SetBkMode((HDC)wParam, TRANSPARENT);
return (INT_PTR)hBrush;
}
break;
case WM_SETCURSOR:
{
if (GetWindowLongPtr((HWND)wParam, GWLP_ID) == stConEmuUrl)
{
SetCursor(LoadCursor(NULL, IDC_HAND));
SetWindowLongPtr(hDlg, DWLP_MSGRESULT, TRUE);
return TRUE;
}
return FALSE;
}
break;
case WM_COMMAND:
switch (HIWORD(wParam))
{
case BN_CLICKED:
switch (LOWORD(wParam))
{
case IDOK:
case IDCANCEL:
case IDCLOSE:
aboutProc(hDlg, WM_CLOSE, 0, 0);
return 1;
case stConEmuUrl:
ConEmuAbout::OnInfo_HomePage();
return 1;
} // BN_CLICKED
break;
case EN_SETFOCUS:
switch (LOWORD(wParam))
{
case tAboutText:
{
// Do not autosel all text
HWND hEdit = (HWND)lParam;
DWORD nStart = 0, nEnd = 0;
SendMessage(hEdit, EM_GETSEL, (WPARAM)&nStart, (LPARAM)&nEnd);
if (nStart != nEnd)
{
SendMessage(hEdit, EM_SETSEL, nTextSelStart, nTextSelEnd);
}
}
break;
}
} // switch (HIWORD(wParam))
break;
case WM_NOTIFY:
{
LPNMHDR nmhdr = (LPNMHDR)lParam;
if ((nmhdr->code == TCN_SELCHANGE) && (nmhdr->idFrom == tbAboutTabs))
{
int iPage = TabCtrl_GetCurSel(nmhdr->hwndFrom);
if ((iPage >= 0) && (iPage < (int)countof(Pages)))
TabSelected(hDlg, iPage);
}
break;
}
case UM_SEARCH:
searchProc(hDlg, (HWND)lParam, false);
break;
case UM_EDIT_KILL_FOCUS:
SendMessage((HWND)lParam, EM_GETSEL, (WPARAM)&nTextSelStart, (LPARAM)&nTextSelEnd);
break;
case WM_CLOSE:
//if (ghWnd == NULL)
gpConEmu->OnOurDialogClosed();
if (mp_DpiAware)
mp_DpiAware->Detach();
EndDialog(hDlg, IDOK);
SafeDelete(mp_ImgBtn);
break;
case WM_DESTROY:
mh_AboutDlg = NULL;
break;
default:
if (mp_DpiAware && mp_DpiAware->ProcessDpiMessages(hDlg, messg, wParam, lParam))
{
return TRUE;
}
}
return FALSE;
}
void ConEmuAbout::searchProc(HWND hDlg, HWND hSearch, bool bReentr)
{
HWND hEdit = GetDlgItem(hDlg, tAboutText);
wchar_t* pszPart = GetDlgItemTextPtr(hSearch, 0);
wchar_t* pszText = GetDlgItemTextPtr(hEdit, 0);
bool bRetry = false;
if (pszPart && *pszPart && pszText && *pszText)
{
LPCWSTR pszFrom = pszText;
DWORD nStart = 0, nEnd = 0;
SendMessage(hEdit, EM_GETSEL, (WPARAM)&nStart, (LPARAM)&nEnd);
size_t cchMax = wcslen(pszText);
size_t cchFrom = max(nStart,nEnd);
if (cchMax > cchFrom)
pszFrom += cchFrom;
LPCWSTR pszFind = StrStrI(pszFrom, pszPart);
if (!pszFind && bReentr && (pszFrom != pszText))
pszFind = StrStrI(pszText, pszPart);
if (pszFind)
{
const wchar_t szBrkChars[] = L"()[]<>{}:;,.-=\\/ \t\r\n";
LPCWSTR pszEnd = wcspbrk(pszFind, szBrkChars);
INT_PTR nPartLen = wcslen(pszPart);
if (!pszEnd || ((pszEnd - pszFind) > max(nPartLen,60)))
pszEnd = pszFind + nPartLen;
while ((pszFind > pszFrom) && !wcschr(szBrkChars, *(pszFind-1)))
pszFind--;
//SetFocus(hEdit);
nTextSelStart = (DWORD)(pszEnd-pszText);
nTextSelEnd = (DWORD)(pszFind-pszText);
SendMessage(hEdit, EM_SETSEL, nTextSelStart, nTextSelEnd);
SendMessage(hEdit, EM_SCROLLCARET, 0, 0);
}
else if (!bReentr)
{
HWND hTab = GetDlgItem(hDlg, tbAboutTabs);
int iPage = TabCtrl_GetCurSel(hTab);
int iFound = -1;
for (int s = 0; (iFound == -1) && (s <= 1); s++)
{
int iFrom = (s == 0) ? (iPage+1) : 0;
int iTo = (s == 0) ? (int)countof(Pages) : (iPage-1);
for (int i = iFrom; i < iTo; i++)
{
if (StrStrI(Pages[i].Title, pszPart)
|| StrStrI(Pages[i].Text, pszPart))
{
iFound = i; break;
}
}
}
if (iFound >= 0)
{
TabSelected(hDlg, iFound);
TabCtrl_SetCurSel(hTab, iFound);
//SetFocus(hEdit);
bRetry = true;
}
}
}
SafeFree(pszPart);
SafeFree(pszText);
if (bRetry)
{
searchProc(hDlg, hSearch, true);
}
}
void ConEmuAbout::InitCommCtrls()
{
if (mb_CommCtrlsInitialized)
return;
INITCOMMONCONTROLSEX icex;
icex.dwSize = sizeof(INITCOMMONCONTROLSEX);
icex.dwICC = ICC_COOL_CLASSES|ICC_BAR_CLASSES|ICC_TAB_CLASSES|ICC_PROGRESS_CLASS; //|ICC_STANDARD_CLASSES|ICC_WIN95_CLASSES;
InitCommonControlsEx(&icex);
mb_CommCtrlsInitialized = true;
}
void ConEmuAbout::OnInfo_OnlineWiki(LPCWSTR asPageName /*= NULL*/)
{
CEStr szUrl(CEWIKIBASE, asPageName ? asPageName : L"TableOfContents", L".html");
DWORD shellRc = (DWORD)(INT_PTR)ShellExecute(ghWnd, L"open", szUrl, NULL, NULL, SW_SHOWNORMAL);
if (shellRc <= 32)
{
DisplayLastError(L"ShellExecute failed", shellRc);
}
}
void ConEmuAbout::OnInfo_Donate()
{
int nBtn = MsgBox(
L"You can show your appreciation and support future development by donating.\n\n"
L"Open ConEmu's donate web page?"
,MB_YESNO|MB_ICONINFORMATION);
if (nBtn == IDYES)
{
OnInfo_DonateLink();
//OnInfo_HomePage();
}
}
void ConEmuAbout::OnInfo_DonateLink()
{
DWORD shellRc = (DWORD)(INT_PTR)ShellExecute(ghWnd, L"open", gsDonatePage, NULL, NULL, SW_SHOWNORMAL);
if (shellRc <= 32)
{
DisplayLastError(L"ShellExecute failed", shellRc);
}
}
void ConEmuAbout::OnInfo_FlattrLink()
{
DWORD shellRc = (DWORD)(INT_PTR)ShellExecute(ghWnd, L"open", gsFlattrPage, NULL, NULL, SW_SHOWNORMAL);
if (shellRc <= 32)
{
DisplayLastError(L"ShellExecute failed", shellRc);
}
}
void ConEmuAbout::TabSelected(HWND hDlg, int idx)
{
if (idx < 0 || idx >= countof(Pages))
return;
wcscpy_c(sLastOpenTab, Pages[idx].Title);
LPCWSTR pszNewText = Pages[idx].Text;
CEStr lsTemp;
if (gpConEmu->mp_PushInfo && gpConEmu->mp_PushInfo->mp_Active && gpConEmu->mp_PushInfo->mp_Active->pszFullMessage)
{
// EDIT control requires \r\n as line endings
lsTemp = lstrmerge(gpConEmu->mp_PushInfo->mp_Active->pszFullMessage, L"\r\n\r\n\r\n", pszNewText);
pszNewText = lsTemp.ms_Val;
}
SetDlgItemText(hDlg, tAboutText, pszNewText);
}
void ConEmuAbout::LogStartEnvInt(LPCWSTR asText, LPARAM lParam, bool bFirst, bool bNewLine)
{
lstrmerge(&gsSysInfo, asText, bNewLine ? L"\r\n" : NULL);
if (bFirst && gpConEmu)
{
lstrmerge(&gsSysInfo, L" AppID: ", gpConEmu->ms_AppID, L"\r\n");
}
}
void ConEmuAbout::ReloadSysInfo()
{
if (!gpStartEnv)
return;
_ASSERTE(lstrcmp(Pages[countof(Pages)-1].Title, L"SysInfo") == 0);
SafeFree(gsSysInfo);
LoadStartupEnvEx::ToString(gpStartEnv, LogStartEnvInt, 0);
Pages[countof(Pages)-1].Text = gsSysInfo;
}
void ConEmuAbout::OnInfo_About(LPCWSTR asPageName /*= NULL*/)
{
InitCommCtrls();
bool bOk = false;
if (!asPageName && sLastOpenTab[0])
{
// Reopen last active tab
asPageName = sLastOpenTab;
}
ReloadSysInfo();
{
DontEnable de;
if (!mp_DpiAware)
mp_DpiAware = new CDpiForDialog();
HWND hParent = (ghOpWnd && IsWindowVisible(ghOpWnd)) ? ghOpWnd : ghWnd;
// Modal dialog (CreateDialog)
INT_PTR iRc = CDynDialog::ExecuteDialog(IDD_ABOUT, hParent, aboutProc, (LPARAM)asPageName);
bOk = (iRc != 0 && iRc != -1);
mh_AboutDlg = NULL;
if (mp_DpiAware)
mp_DpiAware->Detach();
#ifdef _DEBUG
// Any problems with dialog resource?
if (!bOk) DisplayLastError(L"DialogBoxParam(IDD_ABOUT) failed");
#endif
}
if (!bOk)
{
CEStr szTitle(gpConEmu->GetDefaultTitle(), L" ", CLngRc::getRsrc(lng_DlgAbout/*"About"*/));
DontEnable de;
MSGBOXPARAMS mb = {sizeof(MSGBOXPARAMS), ghWnd, g_hInstance,
pAbout,
szTitle.ms_Val,
MB_USERICON, MAKEINTRESOURCE(IMAGE_ICON), 0, NULL, LANG_NEUTRAL
};
MSetter lInCall(&gnInMsgBox);
// Use MessageBoxIndirect instead of MessageBox to show our icon instead of std ICONINFORMATION
MessageBoxIndirect(&mb);
}
}
void ConEmuAbout::OnInfo_WhatsNew(bool bLocal)
{
wchar_t sFile[MAX_PATH+80];
INT_PTR iExec = -1;
if (bLocal)
{
wcscpy_c(sFile, gpConEmu->ms_ConEmuBaseDir);
wcscat_c(sFile, L"\\WhatsNew-ConEmu.txt");
if (FileExists(sFile))
{
iExec = (INT_PTR)ShellExecute(ghWnd, L"open", sFile, NULL, NULL, SW_SHOWNORMAL);
if (iExec >= 32)
{
return;
}
}
}
wcscpy_c(sFile, gsWhatsNew);
iExec = (INT_PTR)ShellExecute(ghWnd, L"open", sFile, NULL, NULL, SW_SHOWNORMAL);
if (iExec >= 32)
{
return;
}
DisplayLastError(L"File 'WhatsNew-ConEmu.txt' not found, go to web page failed", (int)LODWORD(iExec));
}
void ConEmuAbout::OnInfo_Help()
{
static HMODULE hhctrl = NULL;
if (!hhctrl) hhctrl = GetModuleHandle(L"hhctrl.ocx");
if (!hhctrl) hhctrl = LoadLibrary(L"hhctrl.ocx");
if (hhctrl)
{
typedef BOOL (WINAPI* HTMLHelpW_t)(HWND hWnd, LPCWSTR pszFile, INT uCommand, INT dwData);
HTMLHelpW_t fHTMLHelpW = (HTMLHelpW_t)GetProcAddress(hhctrl, "HtmlHelpW");
if (fHTMLHelpW)
{
wchar_t szHelpFile[MAX_PATH*2];
lstrcpy(szHelpFile, gpConEmu->ms_ConEmuChm);
//wchar_t* pszSlash = wcsrchr(szHelpFile, L'\\');
//if (pszSlash) pszSlash++; else pszSlash = szHelpFile;
//lstrcpy(pszSlash, L"ConEmu.chm");
// lstrcat(szHelpFile, L::/Intro.htm");
#define HH_HELP_CONTEXT 0x000F
#define HH_DISPLAY_TOC 0x0001
//fHTMLHelpW(NULL /*чтобы окно не блокировалось*/, szHelpFile, HH_HELP_CONTEXT, contextID);
fHTMLHelpW(NULL /*чтобы окно не блокировалось*/, szHelpFile, HH_DISPLAY_TOC, 0);
}
}
}
void ConEmuAbout::OnInfo_HomePage()
{
DWORD shellRc = (DWORD)(INT_PTR)ShellExecute(ghWnd, L"open", gsHomePage, NULL, NULL, SW_SHOWNORMAL);
if (shellRc <= 32)
{
DisplayLastError(L"ShellExecute failed", shellRc);
}
}
void ConEmuAbout::OnInfo_DownloadPage()
{
DWORD shellRc = (DWORD)(INT_PTR)ShellExecute(ghWnd, L"open", gsDownlPage, NULL, NULL, SW_SHOWNORMAL);
if (shellRc <= 32)
{
DisplayLastError(L"ShellExecute failed", shellRc);
}
}
void ConEmuAbout::OnInfo_FirstStartPage()
{
DWORD shellRc = (DWORD)(INT_PTR)ShellExecute(ghWnd, L"open", gsFirstStart, NULL, NULL, SW_SHOWNORMAL);
if (shellRc <= 32)
{
DisplayLastError(L"ShellExecute failed", shellRc);
}
}
void ConEmuAbout::OnInfo_ReportBug()
{
DWORD shellRc = (DWORD)(INT_PTR)ShellExecute(ghWnd, L"open", gsReportBug, NULL, NULL, SW_SHOWNORMAL);
if (shellRc <= 32)
{
DisplayLastError(L"ShellExecute failed", shellRc);
}
}
void ConEmuAbout::OnInfo_ReportCrash(LPCWSTR asDumpWasCreatedMsg)
{
if (nLastCrashReported)
{
// if previous gsReportCrash was opened less than 60 sec ago
DWORD nLast = GetTickCount() - nLastCrashReported;
if (nLast < 60000)
{
// Skip this time
return;
}
}
if (asDumpWasCreatedMsg && !*asDumpWasCreatedMsg)
{
asDumpWasCreatedMsg = NULL;
}
DWORD shellRc = (DWORD)(INT_PTR)ShellExecute(ghWnd, L"open", gsReportCrash, NULL, NULL, SW_SHOWNORMAL);
if (shellRc <= 32)
{
DisplayLastError(L"ShellExecute failed", shellRc);
}
else if (asDumpWasCreatedMsg)
{
MsgBox(asDumpWasCreatedMsg, MB_OK|MB_ICONEXCLAMATION|MB_SYSTEMMODAL);
}
nLastCrashReported = GetTickCount();
}
void ConEmuAbout::OnInfo_ThrowTrapException(bool bMainThread)
{
if (bMainThread)
{
if (MsgBox(L"Are you sure?\nApplication will terminate after that!\nThrow exception in ConEmu's main thread?", MB_ICONEXCLAMATION|MB_YESNO|MB_DEFBUTTON2)==IDYES)
{
//#ifdef _DEBUG
//MyAssertTrap();
//#else
//DebugBreak();
//#endif
// -- trigger division by 0
RaiseTestException();
}
}
else
{
if (MsgBox(L"Are you sure?\nApplication will terminate after that!\nThrow exception in ConEmu's monitor thread?", MB_ICONEXCLAMATION|MB_YESNO|MB_DEFBUTTON2)==IDYES)
{
CVConGuard VCon;
if ((gpConEmu->GetActiveVCon(&VCon) >= 0) && VCon->RCon())
VCon->RCon()->MonitorAssertTrap();
}
}
}
| 25.456215 | 166 | 0.687233 | clcarwin |
820cdfc304b61d37aac2f00a8eecacea5d1f7af0 | 2,655 | cpp | C++ | sharedcpp/libeditcore/videoeffect/image_effect/sharpen_effect.cpp | daimaren/TikTok | 786437b8a05e84dead1bd54ba718edd68f893635 | [
"MIT"
] | 3 | 2020-11-11T04:08:19.000Z | 2021-04-27T01:07:42.000Z | sharedcpp/libeditcore/videoeffect/image_effect/sharpen_effect.cpp | daimaren/TikTok | 786437b8a05e84dead1bd54ba718edd68f893635 | [
"MIT"
] | 2 | 2020-09-22T20:42:16.000Z | 2020-11-11T04:08:57.000Z | sharedcpp/libeditcore/videoeffect/image_effect/sharpen_effect.cpp | daimaren/TikTok | 786437b8a05e84dead1bd54ba718edd68f893635 | [
"MIT"
] | 11 | 2020-07-04T03:03:18.000Z | 2022-03-17T10:19:19.000Z | //
// sharpen_effect.cpp
// liveDemo
//
// Created by apple on 16/5/12.
// Copyright © 2016年 changba. All rights reserved.
//
#include "sharpen_effect.h"
#define LOG_TAG "SharpenEffect"
SharpenEffect::SharpenEffect() {
mVertexShader = SHARPEN_EFFECT_VERTEX_SHADER;
mFragmentShader = SHARPEN_EFFECT_FRAGMENT_SHADER;
}
SharpenEffect::~SharpenEffect() {
}
bool SharpenEffect::init() {
if (BaseVideoEffect::init()) {
sharpnessUniform = glGetUniformLocation(mGLProgId, "sharpness");
checkGlError("glGetUniformLocation sharpnessUniform");
imageWidthFactorUniform = glGetUniformLocation(mGLProgId, "imageWidthFactor");
checkGlError("glGetUniformLocation imageWidthFactorUniform");
imageHeightFactorUniform = glGetUniformLocation(mGLProgId, "imageHeightFactor");
checkGlError("glGetUniformLocation imageHeightFactorUniform");
return true;
}
return false;
}
void SharpenEffect::onDrawArraysPre(EffectCallback * filterCallback) {
if (filterCallback) {
ParamVal val;
bool suc = filterCallback->getParamValue(string(SHARPEN_EFFECT_SHARPNESS), val);
if (suc) {
float sharpness = 0.0f;
if (suc) {
sharpness = val.u.fltVal;
// LOGI("get success, sharpness:%.3f", sharpness);
} else {
LOGI("get sharpness failed, use default value sharpness");
}
glUniform1f(sharpnessUniform, sharpness);
checkGlError("glUniform1f sharpnessUniform");
}
suc = filterCallback->getParamValue(string(IMAGE_EFFECT_GROUP_TEXTURE_WIDTH), val);
if (suc) {
float inputWidth = 720.f;
if (suc) {
inputWidth = val.u.intVal;
// LOGI("get success, inputWidth:%.3f", inputWidth);
} else {
LOGI("get inputWidth failed, use default value inputWidth");
}
glUniform1f(imageWidthFactorUniform, 1.0 / inputWidth);
checkGlError("glUniform1f imageWidthFactorUniform");
}
suc = filterCallback->getParamValue(string(IMAGE_EFFECT_GROUP_TEXTURE_HEIGHT), val);
if (suc) {
float inputHeight = 1280.f;
if (suc) {
inputHeight = val.u.intVal;
// LOGI("get success, inputHeight:%.3f", inputHeight);
} else {
LOGI("get inputHeight failed, use default value inputHeight");
}
glUniform1f(imageHeightFactorUniform, 1.0 / inputHeight);
checkGlError("glUniform1f imageHeightFactorUniform");
}
}
} | 35.878378 | 92 | 0.622976 | daimaren |
820d5bca902a08daedae509f900ce8e4924c9acc | 1,490 | cpp | C++ | tests/util/lambda_invoker.cpp | preempt/fruit | 9ea3e31b63836797ec7ba1dd759ead8c00d0d227 | [
"Apache-2.0"
] | null | null | null | tests/util/lambda_invoker.cpp | preempt/fruit | 9ea3e31b63836797ec7ba1dd759ead8c00d0d227 | [
"Apache-2.0"
] | null | null | null | tests/util/lambda_invoker.cpp | preempt/fruit | 9ea3e31b63836797ec7ba1dd759ead8c00d0d227 | [
"Apache-2.0"
] | null | null | null | // expect-success
/*
* Copyright 2014 Google Inc. 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.
*/
#define IN_FRUIT_CPP_FILE
#include <fruit/impl/util/lambda_invoker.h>
#include "../test_macros.h"
#include <cassert>
using namespace std;
using namespace fruit::impl;
void test_invoke_no_args() {
// This is static because the lambda must have no captures.
static int num_invocations = 0;
auto l = []() {
++num_invocations;
};
using L = decltype(l);
LambdaInvoker::invoke<L>();
Assert(num_invocations == 1);
}
void test_invoke_some_args() {
// This is static because the lambda must have no captures.
static int num_invocations = 0;
auto l = [](int n, double x) {
Assert(n == 5);
Assert(x == 3.14);
++num_invocations;
};
using L = decltype(l);
LambdaInvoker::invoke<L>(5, 3.14);
Assert(num_invocations == 1);
}
int main() {
test_invoke_no_args();
test_invoke_some_args();
return 0;
}
| 23.650794 | 75 | 0.691275 | preempt |
820e8224bfd7dc1b58445bdf091866102e0d5e92 | 4,265 | hpp | C++ | mars/boost/mpl/list/aux_/preprocessed/plain/list20.hpp | habbyge/mars | f30884ab41599780c51eb57a19dc1e0662cbc98a | [
"BSD-2-Clause",
"Apache-2.0"
] | 1 | 2020-09-17T06:29:28.000Z | 2020-09-17T06:29:28.000Z | mars/boost/mpl/list/aux_/preprocessed/plain/list20.hpp | habbyge/mars | f30884ab41599780c51eb57a19dc1e0662cbc98a | [
"BSD-2-Clause",
"Apache-2.0"
] | null | null | null | mars/boost/mpl/list/aux_/preprocessed/plain/list20.hpp | habbyge/mars | f30884ab41599780c51eb57a19dc1e0662cbc98a | [
"BSD-2-Clause",
"Apache-2.0"
] | null | null | null |
// Copyright Aleksey Gurtovoy 2000-2004
//
// 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)
//
// Preprocessed version of "boost/mpl/list/list20.hpp" header
// -- DO NOT modify by hand!
namespace mars_boost {}
namespace boost = mars_boost;
namespace mars_boost {
namespace mpl {
template<
typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10
>
struct list11
: l_item<
long_ < 11>, T0, list10<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>
> {
typedef list11 type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11
>
struct list12
: l_item<
long_ < 12>, T0, list11<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>
> {
typedef list12 type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12
>
struct list13
: l_item<
long_ < 13>, T0, list12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>
>
{
typedef list13 type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13
>
struct list14
: l_item<
long_ < 14>, T0, list13<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>
>
{
typedef list14 type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14
>
struct list15
: l_item<
long_ < 15>, T0, list14<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>
>
{
typedef list15 type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15
>
struct list16
: l_item<
long_ < 16>, T0, list15<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>
>
{
typedef list16 type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16
>
struct list17
: l_item<
long_ < 17>, T0, list16<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>
>
{
typedef list17 type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17
>
struct list18
: l_item<
long_ < 18>, T0, list17<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17>
>
{
typedef list18 type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18
>
struct list19
: l_item<
long_ < 19>, T0, list18<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18>
>
{
typedef list19 type;
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct list20
: l_item<
long_ < 20>, T0, list19<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19>
>
{
typedef list20 type;
};
}}
| 33.849206 | 273 | 0.660961 | habbyge |
820eda8c4d0cd64bdba964503f8c4964c15b0e03 | 7,276 | cpp | C++ | cpp/test/core/json_tests.cpp | glenfe/microsoft.bond | dc388e9ffb00a780fcad0c8b9fdc06ea7092e225 | [
"MIT"
] | 539 | 2019-05-08T10:48:41.000Z | 2022-03-26T22:47:59.000Z | cpp/test/core/json_tests.cpp | glenfe/microsoft.bond | dc388e9ffb00a780fcad0c8b9fdc06ea7092e225 | [
"MIT"
] | 168 | 2019-05-07T22:01:24.000Z | 2022-03-30T21:18:40.000Z | cpp/test/core/json_tests.cpp | glenfe/microsoft.bond | dc388e9ffb00a780fcad0c8b9fdc06ea7092e225 | [
"MIT"
] | 81 | 2019-05-12T20:56:27.000Z | 2022-03-01T22:23:12.000Z | #include "precompiled.h"
#include "json_tests.h"
#include <boost/format.hpp>
#include <boost/static_assert.hpp>
#include <locale>
#include <stdarg.h>
#include <type_traits>
using namespace bond;
template <typename From, typename To>
const To& operator->*(const From& from, To& to)
{
bond::OutputBuffer buffer;
bond::SimpleJsonWriter<bond::OutputBuffer> json_writer(buffer);
bond::Serialize(from, json_writer);
bond::SimpleJsonReader<bond::InputBuffer> json_reader(buffer.GetBuffer());
bond::Deserialize(json_reader, to);
return to;
}
template <typename Reader, typename Writer>
TEST_CASE_BEGIN(StringRoundtripTest)
{
BondStruct<std::string> str1, str2;
BondStruct<std::wstring> wstr1, wstr2;
str1.field += "Arabic: \xD9\x85\xD8\xB1\xD8\xAD\xD8\xA8\xD8\xA7 \xD8\xA7\xD9\x84\xD8\xB9\xD8\xA7\xD9\x84\xD9\x85 | ";
str1.field += "Chinese: \xE4\xBD\xA0\xE5\xA5\xBD\xE4\xB8\x96\xE7\x95\x8C | ";
str1.field += "Hebrew: \xD7\xA9\xD7\x9C\xD7\x95\xD7\x9D \xD7\xA2\xD7\x95\xD7\x9C\xD7\x9D | ";
str1.field += "Japanese: \xE3\x81\x93\xE3\x82\x93\xE3\x81\xAB\xE3\x81\xA1\xE3\x81\xAF\xE4\xB8\x96\xE7\x95\x8C | ";
str1.field += "Russian: \xD0\x9F\xD1\x80\xD0\xB8\xD0\xB2\xD0\xB5\xD1\x82 \xD0\xBC\xD0\xB8\xD1\x80 | ";
str1.field += "Escaped: \" \\ / \b \f \n \r \t \x1 \x1f ";
str1.field += '\x0';
str1 ->* wstr1 ->* str2 ->* wstr2;
UT_AssertIsTrue(str1 == str2);
UT_AssertIsTrue(wstr1 == wstr2);
}
TEST_CASE_END
template <typename T, typename Reader, typename Writer>
TEST_CASE_BEGIN(StreamDeserializationTest)
{
const int count = 10;
T from[count];
typename Writer::Buffer output;
// Serialize random objects
{
Writer writer(output);
for (int i = count; i--;)
{
from[i] = InitRandom<T>();
Serialize(from[i], writer);
}
}
// Deserialize the objects
{
Reader reader(output.GetBuffer());
bond::bonded<T, Reader&> stream(reader);
for (int i = count; i--;)
{
T record = InitRandom<T>();
stream.Deserialize(record);
UT_Equal(from[i], record);
}
}
// Deserialize the first object twice
{
Reader reader(output.GetBuffer());
T r1, r2;
r1 = InitRandom<T>();
r2 = InitRandom<T>();
Deserialize(reader, r1);
Deserialize(reader, r2);
UT_Equal(r1, r2);
bond::bonded<T> bonded(reader);
r1 = InitRandom<T>();
r2 = InitRandom<T>();
bonded.Deserialize(r1);
bonded.Deserialize(r2);
UT_Equal(r1, r2);
}
}
TEST_CASE_END
template <typename Record, typename Intermediate, typename Reader1, typename Writer1, typename Reader2, typename Writer2>
void StreamTranscoding(uint16_t version = bond::v1)
{
const int count = 10;
Record records[count];
// Serialize random objects using protocol 1
typename Writer1::Buffer output1;
Writer1 writer1(output1);
for (int i = count; i--;)
{
records[i] = InitRandom<Record>();
Serialize(records[i], writer1);
}
// Tanscode the objects from protocol 1 to protocol 2
Reader1 reader1(output1.GetBuffer());
typename Writer2::Buffer output2;
Writer2 writer2(output2, version);
for (int i = count; i--;)
{
bond::bonded<Intermediate> record;
bond::bonded<Intermediate, Reader1&>(reader1).Deserialize(record);
Serialize(record, writer2);
}
// Deserialize the objects from protocol 2
Reader2 reader2(output2.GetBuffer(), version);
bond::bonded<Record, Reader2&> stream(reader2);
for (int i = count; i--;)
{
Record record = InitRandom<Record>();
stream.Deserialize(record);
UT_Equal(records[i], record);
}
}
template <typename Reader, typename Writer>
TEST_CASE_BEGIN(StreamTranscodingTest)
{
StreamTranscoding<
StructWithBase,
SimpleStruct,
Reader,
Writer,
bond::CompactBinaryReader<bond::InputBuffer>,
bond::CompactBinaryWriter<bond::OutputBuffer>
>(bond::v1);
StreamTranscoding<
StructWithBase,
SimpleStruct,
Reader,
Writer,
bond::CompactBinaryReader<bond::InputBuffer>,
bond::CompactBinaryWriter<bond::OutputBuffer>
>(bond::v2);
StreamTranscoding<
NestedStruct,
NestedStructBondedView,
Reader,
Writer,
bond::CompactBinaryReader<bond::InputBuffer>,
bond::CompactBinaryWriter<bond::OutputBuffer>
>(bond::v1);
StreamTranscoding<
NestedStruct,
NestedStructBondedView,
Reader,
Writer,
bond::CompactBinaryReader<bond::InputBuffer>,
bond::CompactBinaryWriter<bond::OutputBuffer>
>(bond::v2);
}
TEST_CASE_END
template <uint16_t N, typename Reader, typename Writer>
void StringTests(UnitTestSuite& suite)
{
BOOST_STATIC_ASSERT(std::is_copy_constructible<Reader>::value);
BOOST_STATIC_ASSERT(std::is_move_constructible<Reader>::value);
BOOST_STATIC_ASSERT(std::is_copy_assignable<Reader>::value);
BOOST_STATIC_ASSERT(std::is_move_assignable<Reader>::value);
AddTestCase<TEST_ID(N),
StringRoundtripTest, Reader, Writer>(suite, "Roundtrip string/wstring");
AddTestCase<TEST_ID(N),
StreamDeserializationTest, NestedStruct, Reader, Writer>(suite, "Stream deserialization test");
}
TEST_CASE_BEGIN(ReaderOverCStr)
{
using Reader = bond::SimpleJsonReader<const char*>;
BOOST_STATIC_ASSERT(std::is_copy_constructible<Reader>::value);
BOOST_STATIC_ASSERT(std::is_move_constructible<Reader>::value);
BOOST_STATIC_ASSERT(std::is_copy_assignable<Reader>::value);
BOOST_STATIC_ASSERT(std::is_move_assignable<Reader>::value);
const char* literalJson = "{ \"m_str\": \"specialized for const char*\" }";
Reader json_reader(literalJson);
SimpleStruct to;
bond::Deserialize(json_reader, to);
BOOST_CHECK_EQUAL("specialized for const char*", to.m_str);
}
TEST_CASE_END
TEST_CASE_BEGIN(DeepNesting)
{
const size_t nestingDepth = 10000;
std::string listOpens(nestingDepth, '[');
std::string listCloses(nestingDepth, ']');
std::string deeplyNestedList = boost::str(
boost::format("{\"deeplyNestedList\": %strue%s}") % listOpens % listCloses);
bond::SimpleJsonReader<const char*> json_reader(deeplyNestedList.c_str());
// The type here doesn't really matter. We need something with no
// required fields, as we're really just testing that we can parse a
// deeply nested JSON array without crashing.
SimpleStruct to;
bond::Deserialize(json_reader, to);
}
TEST_CASE_END
void JSONTest::Initialize()
{
UnitTestSuite suite("Simple JSON test");
TEST_SIMPLE_JSON_PROTOCOL(
StringTests<
0x1c04,
bond::SimpleJsonReader<bond::InputBuffer>,
bond::SimpleJsonWriter<bond::OutputBuffer> >(suite);
);
AddTestCase<TEST_ID(0x1c05), DeepNesting>(suite, "Deeply nested JSON struct");
AddTestCase<TEST_ID(0x1c06), ReaderOverCStr>(suite, "SimpleJsonReader<const char*> specialization");
}
bool init_unit_test()
{
JSONTest::Initialize();
return true;
}
| 27.149254 | 121 | 0.65613 | glenfe |
820f0ac7bfda590319e15f973cb601ca0d6a2c5c | 1,215 | cpp | C++ | native/androidaudioplugin/android/src/android-application-context.cpp | atsushieno/android-audio-plugin-framework | f382d5964af24498972e51cbe52af34361a02dc3 | [
"MIT"
] | 34 | 2020-03-05T23:40:44.000Z | 2022-03-23T04:50:43.000Z | native/androidaudioplugin/android/src/android-application-context.cpp | atsushieno/android-audio-plugin-framework | f382d5964af24498972e51cbe52af34361a02dc3 | [
"MIT"
] | 87 | 2020-01-04T14:47:55.000Z | 2022-03-31T16:42:11.000Z | native/androidaudioplugin/android/src/android-application-context.cpp | atsushieno/android-audio-plugin-framework | f382d5964af24498972e51cbe52af34361a02dc3 | [
"MIT"
] | 1 | 2021-01-31T11:16:40.000Z | 2021-01-31T11:16:40.000Z | #include "aap/android-application-context.h"
namespace aap {
// Android-specific API. Not sure if we would like to keep it in the host API - it is for plugins.
JavaVM *android_vm{nullptr};
jobject application_context{nullptr};
extern "C" JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) {
android_vm = vm;
return JNI_VERSION_1_6;
}
void unset_application_context(JNIEnv *env) {
if (application_context)
env->DeleteGlobalRef(application_context);
}
void set_application_context(JNIEnv *env, jobject jobjectApplicationContext) {
if (application_context)
unset_application_context(env);
application_context = env->NewGlobalRef((jobject) jobjectApplicationContext);
}
JavaVM *get_android_jvm() { return android_vm; }
jobject get_android_application_context() { return application_context; }
AAssetManager *get_android_asset_manager(JNIEnv* env) {
if (!application_context)
return nullptr;
auto appClass = env->GetObjectClass(application_context);
auto getAssetsID = env->GetMethodID(appClass, "getAssets", "()Landroid/content/res/AssetManager;");
auto assetManagerJ = env->CallObjectMethod(application_context, getAssetsID);
return AAssetManager_fromJava(env, assetManagerJ);
}
}
| 31.153846 | 100 | 0.784362 | atsushieno |
820f19b1d5d97bcad5aeb32520d2902f09939c24 | 1,854 | cpp | C++ | vnext/ReactWindowsCore/Modules/PlatformConstantsModule.cpp | tahmidbintaslim/react-native-windows | ff72d1b4acc9cc82771b5b58a625c987c93d1f8f | [
"MIT"
] | 2 | 2019-02-08T18:11:24.000Z | 2022-01-04T17:46:46.000Z | vnext/ReactWindowsCore/Modules/PlatformConstantsModule.cpp | mjfusa/react-native-windows | eb2d614511c20caffed6b0105b92061be5ebeb4e | [
"MIT"
] | null | null | null | vnext/ReactWindowsCore/Modules/PlatformConstantsModule.cpp | mjfusa/react-native-windows | eb2d614511c20caffed6b0105b92061be5ebeb4e | [
"MIT"
] | 1 | 2022-03-22T20:00:29.000Z | 2022-03-22T20:00:29.000Z | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "PlatformConstantsModule.h"
#include <VersionHelpers.h>
using Method = facebook::xplat::module::CxxModule::Method;
#ifndef RNW_PKG_VERSION_MAJOR
#define RNW_PKG_VERSION_MAJOR 1000
#endif
#ifndef RNW_PKG_VERSION_MINOR
#define RNW_PKG_VERSION_MINOR 0
#endif
#ifndef RNW_PKG_VERSION_PATCH
#define RNW_PKG_VERSION_PATCH 0
#endif
namespace facebook::react {
const char *PlatformConstantsModule::Name = "PlatformConstants";
std::string PlatformConstantsModule::getName() {
return PlatformConstantsModule::Name;
}
std::vector<Method> PlatformConstantsModule::getMethods() {
return {};
}
std::map<std::string, folly::dynamic> PlatformConstantsModule::getConstants() {
return {
// We don't currently treat Native code differently in a test environment
{"isTesting", false},
// Since we're out-of-tree, we don't know the exact version of React Native
// we're paired with. Provide something sane for now, and try to provide a
// better source of truth later. Tracked by Issue #4073
{"reactNativeVersion", folly::dynamic::object("major", 0)("minor", 62)("patch", 0)},
// Provide version information for react-native-windows -- which is independant of
// the version of react-native we are built from
{"reactNativeWindowsVersion",
folly::dynamic::object("major", RNW_PKG_VERSION_MAJOR)("minor", RNW_PKG_VERSION_MINOR)(
"patch", RNW_PKG_VERSION_PATCH)}
// We don't provide the typical OS version here. Windows make it hard to
// get an exact version by-design. In the future we should consider
// exposing something here like a facility to check Universal API
// Contract.
};
}
} // namespace facebook::react
| 32.526316 | 95 | 0.702265 | tahmidbintaslim |
820fe4340e7e4071065ead3b3047a5545e13d213 | 4,190 | cpp | C++ | third_party/WebKit/Source/modules/screen_orientation/ScreenOrientationInspectorAgent.cpp | wenfeifei/miniblink49 | 2ed562ff70130485148d94b0e5f4c343da0c2ba4 | [
"Apache-2.0"
] | 5,964 | 2016-09-27T03:46:29.000Z | 2022-03-31T16:25:27.000Z | third_party/WebKit/Source/modules/screen_orientation/ScreenOrientationInspectorAgent.cpp | w4454962/miniblink49 | b294b6eacb3333659bf7b94d670d96edeeba14c0 | [
"Apache-2.0"
] | 459 | 2016-09-29T00:51:38.000Z | 2022-03-07T14:37:46.000Z | third_party/WebKit/Source/modules/screen_orientation/ScreenOrientationInspectorAgent.cpp | w4454962/miniblink49 | b294b6eacb3333659bf7b94d670d96edeeba14c0 | [
"Apache-2.0"
] | 1,006 | 2016-09-27T05:17:27.000Z | 2022-03-30T02:46:51.000Z | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "config.h"
#include "modules/screen_orientation/ScreenOrientationInspectorAgent.h"
#include "core/InspectorTypeBuilder.h"
#include "core/frame/LocalFrame.h"
#include "core/inspector/InspectorState.h"
#include "modules/screen_orientation/ScreenOrientation.h"
#include "modules/screen_orientation/ScreenOrientationController.h"
namespace blink {
namespace ScreenOrientationInspectorAgentState {
static const char angle[] = "angle";
static const char type[] = "type";
static const char overrideEnabled[] = "overrideEnabled";
}
namespace {
WebScreenOrientationType WebScreenOrientationTypeFromString(const String& type)
{
if (type == TypeBuilder::getEnumConstantValue(TypeBuilder::ScreenOrientation::OrientationType::PortraitPrimary))
return WebScreenOrientationPortraitPrimary;
if (type == TypeBuilder::getEnumConstantValue(TypeBuilder::ScreenOrientation::OrientationType::PortraitSecondary))
return WebScreenOrientationPortraitSecondary;
if (type == TypeBuilder::getEnumConstantValue(TypeBuilder::ScreenOrientation::OrientationType::LandscapePrimary))
return WebScreenOrientationLandscapePrimary;
if (type == TypeBuilder::getEnumConstantValue(TypeBuilder::ScreenOrientation::OrientationType::LandscapeSecondary))
return WebScreenOrientationLandscapeSecondary;
return WebScreenOrientationUndefined;
}
} // namespace
// static
PassOwnPtrWillBeRawPtr<ScreenOrientationInspectorAgent> ScreenOrientationInspectorAgent::create(LocalFrame& frame)
{
return adoptPtrWillBeNoop(new ScreenOrientationInspectorAgent(frame));
}
ScreenOrientationInspectorAgent::~ScreenOrientationInspectorAgent()
{
}
ScreenOrientationInspectorAgent::ScreenOrientationInspectorAgent(LocalFrame& frame)
: InspectorBaseAgent<ScreenOrientationInspectorAgent, InspectorFrontend::ScreenOrientation>("ScreenOrientation")
, m_frame(frame)
{
}
void ScreenOrientationInspectorAgent::setScreenOrientationOverride(ErrorString* error, int angle, const String& typeString)
{
if (angle < 0 || angle >= 360) {
*error = "Angle should be in [0; 360) interval";
return;
}
WebScreenOrientationType type = WebScreenOrientationTypeFromString(typeString);
if (type == WebScreenOrientationUndefined) {
*error = "Wrong type value";
return;
}
ScreenOrientationController* controller = ScreenOrientationController::from(m_frame);
if (!controller) {
*error = "Cannot connect to orientation controller";
return;
}
m_state->setBoolean(ScreenOrientationInspectorAgentState::overrideEnabled, true);
m_state->setLong(ScreenOrientationInspectorAgentState::angle, angle);
m_state->setLong(ScreenOrientationInspectorAgentState::type, type);
controller->setOverride(type, angle);
}
void ScreenOrientationInspectorAgent::clearScreenOrientationOverride(ErrorString* error)
{
ScreenOrientationController* controller = ScreenOrientationController::from(m_frame);
if (!controller) {
*error = "Cannot connect to orientation controller";
return;
}
m_state->setBoolean(ScreenOrientationInspectorAgentState::overrideEnabled, false);
controller->clearOverride();
}
void ScreenOrientationInspectorAgent::disable(ErrorString*)
{
m_state->setBoolean(ScreenOrientationInspectorAgentState::overrideEnabled, false);
if (ScreenOrientationController* controller = ScreenOrientationController::from(m_frame))
controller->clearOverride();
}
void ScreenOrientationInspectorAgent::restore()
{
if (m_state->getBoolean(ScreenOrientationInspectorAgentState::overrideEnabled)) {
WebScreenOrientationType type = static_cast<WebScreenOrientationType>(m_state->getLong(ScreenOrientationInspectorAgentState::type));
int angle = m_state->getLong(ScreenOrientationInspectorAgentState::angle);
if (ScreenOrientationController* controller = ScreenOrientationController::from(m_frame))
controller->setOverride(type, angle);
}
}
} // namespace blink
| 39.528302 | 140 | 0.778998 | wenfeifei |
8210a05e5b0d978d2b7fdfea173193ab68af5b29 | 7,142 | cpp | C++ | ext/include/osgEarthUtil/ContourMap.cpp | energonQuest/dtEarth | 47b04bb272ec8781702dea46f5ee9a03d4a22196 | [
"MIT"
] | 6 | 2015-09-26T15:33:41.000Z | 2021-06-13T13:21:50.000Z | ext/include/osgEarthUtil/ContourMap.cpp | energonQuest/dtEarth | 47b04bb272ec8781702dea46f5ee9a03d4a22196 | [
"MIT"
] | null | null | null | ext/include/osgEarthUtil/ContourMap.cpp | energonQuest/dtEarth | 47b04bb272ec8781702dea46f5ee9a03d4a22196 | [
"MIT"
] | 5 | 2015-05-04T09:02:23.000Z | 2019-06-17T11:34:12.000Z | /* -*-c++-*- */
/* osgEarth - Dynamic map generation toolkit for OpenSceneGraph
* Copyright 2008-2012 Pelican Mapping
* http://osgearth.org
*
* osgEarth 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 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
#include <osgEarthUtil/ContourMap>
#include <osgEarth/Registry>
#include <osgEarth/Capabilities>
#include <osgEarth/VirtualProgram>
#include <osgEarth/TerrainEngineNode>
#define LC "[ContourMap] "
using namespace osgEarth;
using namespace osgEarth::Util;
namespace
{
const char* vs =
"#version " GLSL_VERSION_STR "\n"
GLSL_DEFAULT_PRECISION_FLOAT "\n"
"attribute vec4 oe_terrain_attr; \n"
"uniform float oe_contour_min; \n"
"uniform float oe_contour_range; \n"
"varying float oe_contour_lookup; \n"
"void oe_contour_vertex(inout vec4 VertexModel) \n"
"{ \n"
" float height = oe_terrain_attr[3]; \n"
" float height_normalized = (height-oe_contour_min)/oe_contour_range; \n"
" oe_contour_lookup = clamp( height_normalized, 0.0, 1.0 ); \n"
"} \n";
const char* fs =
"#version " GLSL_VERSION_STR "\n"
GLSL_DEFAULT_PRECISION_FLOAT "\n"
"uniform sampler1D oe_contour_xfer; \n"
"uniform float oe_contour_opacity; \n"
"varying float oe_contour_lookup; \n"
"void oe_contour_fragment( inout vec4 color ) \n"
"{ \n"
" vec4 texel = texture1D( oe_contour_xfer, oe_contour_lookup ); \n"
" color.rgb = mix(color.rgb, texel.rgb, texel.a * oe_contour_opacity); \n"
"} \n";
}
ContourMap::ContourMap() :
TerrainEffect()
{
init();
}
ContourMap::ContourMap(const Config& conf) :
TerrainEffect()
{
mergeConfig(conf);
init();
}
void
ContourMap::init()
{
// negative means unset:
_unit = -1;
// uniforms we'll need:
_xferMin = new osg::Uniform(osg::Uniform::FLOAT, "oe_contour_min" );
_xferRange = new osg::Uniform(osg::Uniform::FLOAT, "oe_contour_range" );
_xferSampler = new osg::Uniform(osg::Uniform::SAMPLER_1D, "oe_contour_xfer" );
_opacityUniform = new osg::Uniform(osg::Uniform::FLOAT, "oe_contour_opacity" );
_opacityUniform->set( _opacity.getOrUse(1.0f) );
// Create a 1D texture from the transfer function's image.
_xferTexture = new osg::Texture1D();
_xferTexture->setResizeNonPowerOfTwoHint( false );
_xferTexture->setFilter( osg::Texture::MIN_FILTER, osg::Texture::LINEAR );
_xferTexture->setFilter( osg::Texture::MAG_FILTER, osg::Texture::LINEAR );
_xferTexture->setWrap( osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE );
// build a default transfer function.
// TODO: think about scale/bias controls.
osg::TransferFunction1D* xfer = new osg::TransferFunction1D();
float s = 2500.0f;
xfer->setColor( -1.0000 * s, osg::Vec4f(0, 0, 0.5, 1), false);
xfer->setColor( -0.2500 * s, osg::Vec4f(0, 0, 1, 1), false);
xfer->setColor( 0.0000 * s, osg::Vec4f(0, .5, 1, 1), false);
xfer->setColor( 0.0062 * s, osg::Vec4f(.84,.84,.25,1), false);
//xfer->setColor( 0.0625 * s, osg::Vec4f(.94,.94,.25,1), false);
xfer->setColor( 0.1250 * s, osg::Vec4f(.125,.62,0,1), false);
xfer->setColor( 0.3250 * s, osg::Vec4f(.80,.70,.47,1), false);
xfer->setColor( 0.7500 * s, osg::Vec4f(.5,.5,.5,1), false);
xfer->setColor( 1.0000 * s, osg::Vec4f(1,1,1,1), false);
xfer->updateImage();
this->setTransferFunction( xfer );
}
ContourMap::~ContourMap()
{
//nop
}
void
ContourMap::setTransferFunction(osg::TransferFunction1D* xfer)
{
_xfer = xfer;
_xferTexture->setImage( _xfer->getImage() );
_xferMin->set( _xfer->getMinimum() );
_xferRange->set( _xfer->getMaximum() - _xfer->getMinimum() );
}
void
ContourMap::setOpacity(float opacity)
{
_opacity = osg::clampBetween(opacity, 0.0f, 1.0f);
_opacityUniform->set( _opacity.get() );
}
void
ContourMap::onInstall(TerrainEngineNode* engine)
{
if ( engine )
{
if ( !engine->getTextureCompositor()->reserveTextureImageUnit(_unit) )
{
OE_WARN << LC << "Failed to reserve a texture image unit; disabled." << std::endl;
return;
}
osg::StateSet* stateset = engine->getOrCreateStateSet();
// Install the texture and its sampler uniform:
stateset->setTextureAttributeAndModes( _unit, _xferTexture.get(), osg::StateAttribute::ON );
stateset->addUniform( _xferSampler.get() );
_xferSampler->set( _unit );
// (By the way: if you want to draw image layers on top of the contoured terrain,
// set the "priority" parameter to setFunction() to a negative number so that it draws
// before the terrain's layers.)
VirtualProgram* vp = VirtualProgram::getOrCreate(stateset);
vp->setFunction( "oe_contour_vertex", vs, ShaderComp::LOCATION_VERTEX_MODEL);
vp->setFunction( "oe_contour_fragment", fs, ShaderComp::LOCATION_FRAGMENT_COLORING ); //, -1.0);
// Install some uniforms that tell the shader the height range of the color map.
stateset->addUniform( _xferMin.get() );
_xferMin->set( _xfer->getMinimum() );
stateset->addUniform( _xferRange.get() );
_xferRange->set( _xfer->getMaximum() - _xfer->getMinimum() );
stateset->addUniform( _opacityUniform.get() );
}
}
void
ContourMap::onUninstall(TerrainEngineNode* engine)
{
if ( engine )
{
osg::StateSet* stateset = engine->getStateSet();
if ( stateset )
{
stateset->removeUniform( _xferMin.get() );
stateset->removeUniform( _xferRange.get() );
stateset->removeUniform( _xferSampler.get() );
stateset->removeUniform( _opacityUniform.get() );
stateset->removeTextureAttribute( _unit, osg::StateAttribute::TEXTURE );
VirtualProgram* vp = VirtualProgram::get(stateset);
if ( vp )
{
vp->removeShader( "oe_contour_vertex" );
vp->removeShader( "oe_contour_fragment" );
}
}
if ( _unit >= 0 )
{
engine->getTextureCompositor()->releaseTextureImageUnit( _unit );
_unit = -1;
}
}
}
//-------------------------------------------------------------
void
ContourMap::mergeConfig(const Config& conf)
{
conf.getIfSet("opacity", _opacity);
}
Config
ContourMap::getConfig() const
{
Config conf("contour_map");
conf.addIfSet("opacity", _opacity);
return conf;
}
| 31.462555 | 104 | 0.635536 | energonQuest |
821105fc2a223f312eedb419e6a35e528a03888a | 878 | cpp | C++ | MonoNative.Tests/mscorlib/System/Runtime/Serialization/mscorlib_System_Runtime_Serialization_IObjectReference_Fixture.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | 7 | 2015-03-10T03:36:16.000Z | 2021-11-05T01:16:58.000Z | MonoNative.Tests/mscorlib/System/Runtime/Serialization/mscorlib_System_Runtime_Serialization_IObjectReference_Fixture.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | 1 | 2020-06-23T10:02:33.000Z | 2020-06-24T02:05:47.000Z | MonoNative.Tests/mscorlib/System/Runtime/Serialization/mscorlib_System_Runtime_Serialization_IObjectReference_Fixture.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | null | null | null | // Mono Native Fixture
// Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// Namespace: System.Runtime.Serialization
// Name: IObjectReference
// C++ Typed Name: mscorlib::System::Runtime::Serialization::IObjectReference
#include <gtest/gtest.h>
#include <mscorlib/System/Runtime/Serialization/mscorlib_System_Runtime_Serialization_IObjectReference.h>
#include <mscorlib/System/Runtime/Serialization/mscorlib_System_Runtime_Serialization_StreamingContext.h>
namespace mscorlib
{
namespace System
{
namespace Runtime
{
namespace Serialization
{
//Public Methods Tests
// Method GetRealObject
// Signature: mscorlib::System::Runtime::Serialization::StreamingContext context
TEST(mscorlib_System_Runtime_Serialization_IObjectReference_Fixture,GetRealObject_Test)
{
}
}
}
}
}
| 23.105263 | 105 | 0.763098 | brunolauze |
8211183ac47ea4607914043950614220e8b2ee76 | 1,249 | hpp | C++ | include/opentxs/cash/DigitalCash.hpp | nopdotcom/opentxs | 140428ba8f1bd4c09654ebf0a1c1725f396efa8b | [
"MIT"
] | null | null | null | include/opentxs/cash/DigitalCash.hpp | nopdotcom/opentxs | 140428ba8f1bd4c09654ebf0a1c1725f396efa8b | [
"MIT"
] | null | null | null | include/opentxs/cash/DigitalCash.hpp | nopdotcom/opentxs | 140428ba8f1bd4c09654ebf0a1c1725f396efa8b | [
"MIT"
] | null | null | null | // Copyright (c) 2018 The Open-Transactions developers
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef OPENTXS_CASH_DIGITALCASH_HPP
#define OPENTXS_CASH_DIGITALCASH_HPP
#include "opentxs/Forward.hpp"
#if OT_CASH
// WHICH DIGITAL CASH LIBRARY?
//
// Many algorithms may come available. We are currently using Lucre, by Ben
// Laurie,
// which is an implementation of Wagner, which is a variant of Chaum.
//
// We plan to have alternatives such as "Magic Money" by Pr0duct Cypher.
//
// Implementations for Chaum and Brands are circulating online. They could all
// be easily added here as options for Open-Transactions.
#if OT_CASH_USING_LUCRE
// IWYU pragma: begin_exports
#include <lucre/bank.h>
// IWYU pragma: end_exports
#endif
#if OT_CASH_USING_MAGIC_MONEY
#include... // someday
#endif
#include <string>
namespace opentxs
{
#if OT_CASH_USING_LUCRE
class LucreDumper
{
std::string m_str_dumpfile;
public:
LucreDumper();
~LucreDumper();
};
#endif
#if OT_CASH_USING_MAGIC_MONEY
// Todo: Someday...
#endif
} // namespace opentxs
#endif // OT_CASH
#endif
| 20.816667 | 78 | 0.740592 | nopdotcom |
8214e0929db0b1bae3b8b8b6cd4f2683793e8267 | 4,643 | hh | C++ | wrappers/c++/include/utils.hh | klaasjacobdevries/lothar | 38ad3e4e0552abaff253e77c4a6cf0657d920196 | [
"MIT"
] | 2 | 2016-07-23T13:05:10.000Z | 2021-01-25T01:10:33.000Z | wrappers/c++/include/utils.hh | klaasjacobdevries/lothar | 38ad3e4e0552abaff253e77c4a6cf0657d920196 | [
"MIT"
] | null | null | null | wrappers/c++/include/utils.hh | klaasjacobdevries/lothar | 38ad3e4e0552abaff253e77c4a6cf0657d920196 | [
"MIT"
] | 1 | 2019-06-26T19:39:28.000Z | 2019-06-26T19:39:28.000Z | #ifndef LOTHAR_UTILS_HH
#define LOTHAR_UTILS_HH
#include "utils.h"
#include "error_handling.hh"
#include <algorithm>
// a bit dirty, but avoid all tr1/c++11/whatever trickery by redeclaring shared_ptr in the lothar namespace
#ifdef HAVE_SHARED_PTR
#include <memory>
namespace lothar
{
template <typename T>
class shared_ptr : public std::shared_ptr<T>
{
public:
explicit shared_ptr(T *p = 0) : std::shared_ptr<T>(p)
{}
};
}
#else // HAVE_SHARED_PTR need the tr1 version
// microsoft has std::tr1::shared_ptr in <memory> by default, others (i.e. gcc) in <tr1/memory>
#if _MSC_VER
#include <memory>
#else
#include <tr1/memory>
#endif
namespace lothar
{
template <typename T>
class shared_ptr : public std::tr1::shared_ptr<T>
{
public:
explicit shared_ptr(T *p = 0) : std::tr1::shared_ptr<T>(p)
{}
};
}
#endif // HAVE_SHARED_PTR
namespace lothar
{
/** \brief return the value, but no smaller than min, no greater than max
*/
template <typename T>
T const &clamp(T const &val, T const &min, T const &max)
{
return (val < min ? min : (val > max ? max : val));
}
/** \brief The minimum value of a and b
*/
template <typename T>
T const &min(T const &a, T const &b)
{
return std::min<T>(a, b);
}
/** \brief The maximum value of a and b
*/
template <typename T>
T const &max(T const &a, T const &b)
{
return std::max<T>(a, b);
}
/** \brief Convert degrees to radians
*/
template <typename T1, typename T2>
T1 degtorad(T2 const °)
{
return static_cast<T1>(deg * M_PI / 180.0);
}
/** \brief Convert radians to degrees
*/
template <typename T1, typename T2>
T1 radtodeg(T2 const &rad)
{
T2 t = static_cast<T2>(rad * 180.0 / M_PI);
return static_cast<T1>(t);
}
/** \brief Convert a short from host endianness to NXT (small) endianness
*
* \param val a 32 bit integer
* \param buf a 2 byte buffer to hold the result
*/
inline void htonxts(uint16_t val, uint8_t buf[2])
{
lothar_htonxts(val, buf);
}
/** \brief Convert a short from NXT (small) endianness to host endianness
*
* \param buf a 2 byte buffer received from the NXT
* \returns the value in host endianness
*/
inline uint16_t nxttohs(uint8_t const buf[2])
{
return lothar_nxttohs(buf);
}
/** \brief Convert a long from host endianness to NXT (small) endianness
*
* \param val a 32 bit integer
* \param buf a 4 byte buffer to hold the result
*/
inline void htonxtl(uint32_t val, uint8_t buf[4])
{
lothar_htonxtl(val, buf);
}
/** \brief Convert a long from NXT (small) endianness to host endianness
*
* \param buf a 4 byte buffer received from the NXT
* \returns the value in host endianness
*/
inline uint32_t nxttohl(uint8_t const buf[4])
{
return lothar_nxttohl(buf);
}
/** \brief The output ports (A-C, ALL)
*/
typedef enum lothar_output_port output_port;
/** \brief The input ports (1-4)
*/
typedef enum lothar_input_port input_port;
/** \brief The motor modes
*/
typedef enum lothar_output_motor_mode output_motor_mode;
/** \brief The motor regulation modes
*/
typedef enum lothar_output_regulation_mode output_regulation_mode;
/** \brief The motor runstates
*/
typedef enum lothar_output_runstate output_runstate;
/** \brief Varius types of sensors
*/
typedef enum lothar_sensor_type sensor_type;
/** \brief varius input modes */
typedef enum lothar_sensor_mode sensor_mode;
/** \brief enum for the SENSOR_COLORFULL detection mode
*/
typedef enum lothar_color color;
/** \brief redaclaration in lothar namespace
*/
typedef lothar_time_t time_t;
/** \brief sleep for the specified number of milliseconds
*/
inline void msleep(lothar_time_t ms)
{
check_return(lothar_msleep(ms));
}
/** \brief simple timer, returns the number of milliseconds since the last time this function was called (0 if this is
* the first time this function is called)
*/
inline time_t time()
{
return lothar_time();
}
/** \brief slightly more advanced timer.
*
* use timer(NULL) to create a new timer, and pass the return value to the next calls to get the number of
* milliseconds since the creation time
*/
inline time_t timer(time_t *timer)
{
return lothar_timer(timer);
}
/** \brief base class for classes that shouldn't allow copying
*/
class no_copy
{
// private and not implemented
no_copy(no_copy const &);
no_copy &operator=(no_copy const &);
public:
no_copy()
{}
};
}
#endif // LOTHAR_UTILS_HH
| 22.871921 | 120 | 0.665087 | klaasjacobdevries |
821a0c662245750cd0fff195666d90a5cce302bc | 236 | cpp | C++ | spinok/source/ECS/Entity.cpp | ckgomes/projects_archive | f5282d51dd1539bbefb5c1d12d2ab35ec3d6e548 | [
"MIT"
] | 1 | 2016-06-04T14:34:23.000Z | 2016-06-04T14:34:23.000Z | spinok/source/ECS/Entity.cpp | ckgomes/projects_archive | f5282d51dd1539bbefb5c1d12d2ab35ec3d6e548 | [
"MIT"
] | null | null | null | spinok/source/ECS/Entity.cpp | ckgomes/projects_archive | f5282d51dd1539bbefb5c1d12d2ab35ec3d6e548 | [
"MIT"
] | null | null | null | #include "Entity.hpp"
void Entity::scheduleRemoval()
{
m_remove = true;
}
void Entity::update()
{
ext::for_each(m_components, [](auto* ptr)
{
if (ptr != nullptr && ptr->active)
ptr->update();
});
}
| 14.75 | 45 | 0.54661 | ckgomes |
821badb96303ab3886e30a9a8584b13a4e6c591a | 3,926 | cc | C++ | chromium/storage/common/data_element.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/storage/common/data_element.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/storage/common/data_element.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | // Copyright 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 "storage/common/data_element.h"
#include <stddef.h>
#include <stdint.h>
#include <algorithm>
#include "base/strings/string_number_conversions.h"
namespace storage {
DataElement::DataElement()
: type_(TYPE_UNKNOWN),
bytes_(NULL),
offset_(0),
length_(std::numeric_limits<uint64_t>::max()) {}
DataElement::~DataElement() {}
void DataElement::SetToFilePathRange(
const base::FilePath& path,
uint64_t offset,
uint64_t length,
const base::Time& expected_modification_time) {
type_ = TYPE_FILE;
path_ = path;
offset_ = offset;
length_ = length;
expected_modification_time_ = expected_modification_time;
}
void DataElement::SetToBlobRange(const std::string& blob_uuid,
uint64_t offset,
uint64_t length) {
type_ = TYPE_BLOB;
blob_uuid_ = blob_uuid;
offset_ = offset;
length_ = length;
}
void DataElement::SetToFileSystemUrlRange(
const GURL& filesystem_url,
uint64_t offset,
uint64_t length,
const base::Time& expected_modification_time) {
type_ = TYPE_FILE_FILESYSTEM;
filesystem_url_ = filesystem_url;
offset_ = offset;
length_ = length;
expected_modification_time_ = expected_modification_time;
}
void DataElement::SetToDiskCacheEntryRange(uint64_t offset, uint64_t length) {
type_ = TYPE_DISK_CACHE_ENTRY;
offset_ = offset;
length_ = length;
}
void PrintTo(const DataElement& x, std::ostream* os) {
const uint64_t kMaxDataPrintLength = 40;
*os << "<DataElement>{type: ";
switch (x.type()) {
case DataElement::TYPE_BYTES: {
uint64_t length = std::min(x.length(), kMaxDataPrintLength);
*os << "TYPE_BYTES, data: ["
<< base::HexEncode(x.bytes(), static_cast<size_t>(length));
if (length < x.length()) {
*os << "<...truncated due to length...>";
}
*os << "]";
break;
}
case DataElement::TYPE_FILE:
*os << "TYPE_FILE, path: " << x.path().AsUTF8Unsafe()
<< ", expected_modification_time: " << x.expected_modification_time();
break;
case DataElement::TYPE_BLOB:
*os << "TYPE_BLOB, uuid: " << x.blob_uuid();
break;
case DataElement::TYPE_FILE_FILESYSTEM:
*os << "TYPE_FILE_FILESYSTEM, filesystem_url: " << x.filesystem_url();
break;
case DataElement::TYPE_DISK_CACHE_ENTRY:
*os << "TYPE_DISK_CACHE_ENTRY";
break;
case DataElement::TYPE_BYTES_DESCRIPTION:
*os << "TYPE_BYTES_DESCRIPTION";
break;
case DataElement::TYPE_UNKNOWN:
*os << "TYPE_UNKNOWN";
break;
}
*os << ", length: " << x.length() << ", offset: " << x.offset() << "}";
}
bool operator==(const DataElement& a, const DataElement& b) {
if (a.type() != b.type() || a.offset() != b.offset() ||
a.length() != b.length())
return false;
switch (a.type()) {
case DataElement::TYPE_BYTES:
return memcmp(a.bytes(), b.bytes(), b.length()) == 0;
case DataElement::TYPE_FILE:
return a.path() == b.path() &&
a.expected_modification_time() == b.expected_modification_time();
case DataElement::TYPE_BLOB:
return a.blob_uuid() == b.blob_uuid();
case DataElement::TYPE_FILE_FILESYSTEM:
return a.filesystem_url() == b.filesystem_url();
case DataElement::TYPE_DISK_CACHE_ENTRY:
// We compare only length and offset; we trust the entry itself was
// compared at some higher level such as in BlobDataItem.
return true;
case DataElement::TYPE_BYTES_DESCRIPTION:
return true;
case DataElement::TYPE_UNKNOWN:
NOTREACHED();
return false;
}
return false;
}
bool operator!=(const DataElement& a, const DataElement& b) {
return !(a == b);
}
} // namespace storage
| 29.742424 | 80 | 0.65079 | wedataintelligence |
821da146e307ca80a83fc676bdad0b0b8c66a390 | 9,164 | cc | C++ | pin/thread_start.cc | elau/graphite_pep | ddce5890f20e272c587c5caed07161db043247b2 | [
"MIT"
] | 1 | 2022-03-03T21:04:09.000Z | 2022-03-03T21:04:09.000Z | pin/thread_start.cc | trevorcarlson/Graphite | 8aeb2cb199864dbf517c4a88dfac7fb6ac7d74f4 | [
"MIT"
] | 1 | 2022-03-04T20:03:50.000Z | 2022-03-04T20:03:50.000Z | pin/thread_start.cc | elau/graphite_pep | ddce5890f20e272c587c5caed07161db043247b2 | [
"MIT"
] | null | null | null | #include <string.h>
#include <sys/mman.h>
#include "thread_start.h"
#include "log.h"
#include "core.h"
#include "simulator.h"
#include "fixed_types.h"
#include "pin_config.h"
#include "tile_manager.h"
#include "thread_manager.h"
#include "thread_support.h"
int spawnThreadSpawner(CONTEXT *ctxt)
{
int res;
IntPtr reg_eip = PIN_GetContextReg(ctxt, REG_INST_PTR);
PIN_LockClient();
AFUNPTR thread_spawner;
IMG img = IMG_FindByAddress(reg_eip);
RTN rtn = RTN_FindByName(img, "CarbonSpawnThreadSpawner");
thread_spawner = RTN_Funptr(rtn);
PIN_UnlockClient();
LOG_ASSERT_ERROR( thread_spawner != NULL, "ThreadSpawner function is null. You may not have linked to the carbon APIs correctly.");
LOG_PRINT("Starting CarbonSpawnThreadSpawner(%p)", thread_spawner);
PIN_CallApplicationFunction(ctxt,
PIN_ThreadId(),
CALLINGSTD_DEFAULT,
thread_spawner,
PIN_PARG(int), &res,
PIN_PARG_END());
LOG_PRINT("Thread spawner spawned");
LOG_ASSERT_ERROR(res == 0, "Failed to spawn Thread Spawner");
return res;
}
VOID copyStaticData(IMG& img)
{
Core* core = Sim()->getTileManager()->getCurrentCore();
LOG_ASSERT_ERROR (core != NULL, "Does not have a valid Core ID");
for (SEC sec = IMG_SecHead(img); SEC_Valid(sec); sec = SEC_Next(sec))
{
IntPtr sec_address;
// I am not sure whether we want ot copy over all the sections or just the
// sections which are relevant like the sections below: DATA, BSS, GOT
// Copy all the mapped sections except the executable section now
SEC_TYPE sec_type = SEC_Type(sec);
if (sec_type != SEC_TYPE_EXEC)
{
if (SEC_Mapped(sec))
{
sec_address = SEC_Address(sec);
LOG_PRINT ("Copying Section: %s at Address: 0x%x of Size: %u to Simulated Memory", SEC_Name(sec).c_str(), (UInt32) sec_address, (UInt32) SEC_Size(sec));
core->accessMemory(Core::NONE, Core::WRITE, sec_address, (char*) sec_address, SEC_Size(sec));
}
}
}
}
VOID copyInitialStackData(IntPtr& reg_esp, core_id_t core_id)
{
// We should not get core_id for this stack_ptr
Core* core = Sim()->getTileManager()->getCurrentCore();
LOG_ASSERT_ERROR (core != NULL, "Does not have a valid Core ID");
// 1) Command Line Arguments
// 2) Environment Variables
// 3) Auxiliary Vector Entries
SInt32 initial_stack_size = 0;
IntPtr stack_ptr_base;
IntPtr stack_ptr_top;
IntPtr params = reg_esp;
carbon_reg_t argc = * ((carbon_reg_t *) params);
char **argv = (char **) (params + sizeof(carbon_reg_t));
char **envir = argv+argc+1;
//////////////////////////////////////////////////////////////////////
// Pass 1
// Determine the Initial Stack Size
// Variables: size_argv_ptrs, size_env_ptrs, size_information_block
//////////////////////////////////////////////////////////////////////
// Write argc
initial_stack_size += sizeof(argc);
// Write argv
for (SInt32 i = 0; i < (SInt32) argc; i++)
{
// Writing argv[i]
initial_stack_size += sizeof(char*);
initial_stack_size += (strlen(argv[i]) + 1);
}
// A '0' at the end
initial_stack_size += sizeof(char*);
// We need to copy over the environmental parameters also
for (SInt32 i = 0; ; i++)
{
// Writing environ[i]
initial_stack_size += sizeof(char*);
if (envir[i] == 0)
{
break;
}
initial_stack_size += (strlen(envir[i]) + 1);
}
// Auxiliary Vector Entry
#ifdef TARGET_IA32
initial_stack_size += sizeof(Elf32_auxv_t);
#elif TARGET_X86_64
initial_stack_size += sizeof(Elf64_auxv_t);
#else
LOG_PRINT_ERROR("Unrecognized Architecture Type");
#endif
//////////////////////////////////////////////////////////////////////
// Pass 2
// Copy over the actual data
// Variables: stack_ptr_base_sim
//////////////////////////////////////////////////////////////////////
PinConfig::StackAttributes stack_attr;
PinConfig::getSingleton()->getStackAttributesFromCoreID (core_id, stack_attr);
stack_ptr_top = stack_attr.lower_limit + stack_attr.size;
stack_ptr_base = stack_ptr_top - initial_stack_size;
stack_ptr_base = (stack_ptr_base >> (sizeof(IntPtr))) << (sizeof(IntPtr));
// Assign the new ESP
reg_esp = stack_ptr_base;
// fprintf (stderr, "argc = %d\n", argc);
// Write argc
core->accessMemory(Core::NONE, Core::WRITE, stack_ptr_base, (char*) &argc, sizeof(argc));
stack_ptr_base += sizeof(argc);
LOG_PRINT("Copying Command Line Arguments to Simulated Memory");
for (SInt32 i = 0; i < (SInt32) argc; i++)
{
// Writing argv[i]
stack_ptr_top -= (strlen(argv[i]) + 1);
core->accessMemory(Core::NONE, Core::WRITE, stack_ptr_top, (char*) argv[i], strlen(argv[i])+1);
core->accessMemory(Core::NONE, Core::WRITE, stack_ptr_base, (char*) &stack_ptr_top, sizeof(stack_ptr_top));
stack_ptr_base += sizeof(stack_ptr_top);
}
// I have found this to be '0' in most cases
core->accessMemory(Core::NONE, Core::WRITE, stack_ptr_base, (char*) &argv[argc], sizeof(argv[argc]));
stack_ptr_base += sizeof(argv[argc]);
// We need to copy over the environmental parameters also
LOG_PRINT("Copying Environmental Variables to Simulated Memory");
for (SInt32 i = 0; ; i++)
{
// Writing environ[i]
if (envir[i] == 0)
{
core->accessMemory(Core::NONE, Core::WRITE, stack_ptr_base, (char*) &envir[i], sizeof(envir[i]));
stack_ptr_base += sizeof(envir[i]);
break;
}
stack_ptr_top -= (strlen(envir[i]) + 1);
core->accessMemory(Core::NONE, Core::WRITE, stack_ptr_top, (char*) envir[i], strlen(envir[i])+1);
core->accessMemory(Core::NONE, Core::WRITE, stack_ptr_base, (char*) &stack_ptr_top, sizeof(stack_ptr_top));
stack_ptr_base += sizeof(stack_ptr_top);
}
LOG_PRINT("Copying Auxiliary Vector to Simulated Memory");
#ifdef TARGET_IA32
Elf32_auxv_t auxiliary_vector_entry_null;
#elif TARGET_X86_64
Elf64_auxv_t auxiliary_vector_entry_null;
#else
LOG_PRINT_ERROR("Unrecognized architecture type");
#endif
auxiliary_vector_entry_null.a_type = AT_NULL;
auxiliary_vector_entry_null.a_un.a_val = 0;
core->accessMemory(Core::NONE, Core::WRITE, stack_ptr_base, (char*) &auxiliary_vector_entry_null, sizeof(auxiliary_vector_entry_null));
stack_ptr_base += sizeof(auxiliary_vector_entry_null);
LOG_ASSERT_ERROR(stack_ptr_base <= stack_ptr_top, "stack_ptr_base = 0x%x, stack_ptr_top = 0x%x", stack_ptr_base, stack_ptr_top);
}
VOID copySpawnedThreadStackData(IntPtr reg_esp)
{
core_id_t core_id = PinConfig::getSingleton()->getCoreIDFromStackPtr(reg_esp);
PinConfig::StackAttributes stack_attr;
PinConfig::getSingleton()->getStackAttributesFromCoreID(core_id, stack_attr);
IntPtr stack_upper_limit = stack_attr.lower_limit + stack_attr.size;
UInt32 num_bytes_to_copy = (UInt32) (stack_upper_limit - reg_esp);
Core* core = Sim()->getTileManager()->getCurrentCore();
core->accessMemory(Core::NONE, Core::WRITE, reg_esp, (char*) reg_esp, num_bytes_to_copy);
}
VOID allocateStackSpace()
{
// Note that 1 core = 1 thread currently
// We should probably get the amount of stack space per thread from a configuration parameter
// Each process allocates whatever it is responsible for !!
__attribute(__unused__) UInt32 stack_size_per_core = PinConfig::getSingleton()->getStackSizePerCore();
__attribute(__unused__) UInt32 num_tiles = Sim()->getConfig()->getNumLocalTiles();
__attribute(__unused__) IntPtr stack_base = PinConfig::getSingleton()->getStackLowerLimit();
LOG_PRINT("allocateStackSpace: stack_size_per_core = 0x%x", stack_size_per_core);
LOG_PRINT("allocateStackSpace: num_local_cores = %i", num_tiles);
LOG_PRINT("allocateStackSpace: stack_base = 0x%x", stack_base);
// TODO: Make sure that this is a multiple of the page size
// mmap() the total amount of memory needed for the stacks
LOG_ASSERT_ERROR((mmap((void*) stack_base, stack_size_per_core * num_tiles, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) == (void*) stack_base),
"mmap(%p, %u) failed: Cannot allocate stack on host machine", (void*) stack_base, stack_size_per_core * num_tiles);
}
VOID SimPthreadAttrInitOtherAttr(pthread_attr_t *attr)
{
LOG_PRINT ("In SimPthreadAttrInitOtherAttr");
//tile_id_t tile_id;
core_id_t core_id;
ThreadSpawnRequest* req = Sim()->getThreadManager()->getThreadSpawnReq();
if (req == NULL)
{
// This is the thread spawner
core_id = Sim()->getConfig()->getCurrentThreadSpawnerCoreId();
}
else
{
// This is an application thread
core_id = (core_id_t) {req->destination.tile_id, req->destination.core_type};
}
PinConfig::StackAttributes stack_attr;
PinConfig::getSingleton()->getStackAttributesFromCoreID(core_id, stack_attr);
pthread_attr_setstack(attr, (void*) stack_attr.lower_limit, stack_attr.size);
LOG_PRINT ("Done with SimPthreadAttrInitOtherAttr");
}
| 33.202899 | 164 | 0.666412 | elau |
822003dcc8852383956382623a8e11ce250f464d | 612 | cpp | C++ | examples/tree.cpp | mbrcknl/functional.cc | a9172f8ed61ac5a9aa3330bdbf1cdd52fc133632 | [
"BSL-1.0"
] | 1 | 2017-09-17T16:06:33.000Z | 2017-09-17T16:06:33.000Z | examples/tree.cpp | mbrcknl/functional.cc | a9172f8ed61ac5a9aa3330bdbf1cdd52fc133632 | [
"BSL-1.0"
] | null | null | null | examples/tree.cpp | mbrcknl/functional.cc | a9172f8ed61ac5a9aa3330bdbf1cdd52fc133632 | [
"BSL-1.0"
] | null | null | null |
// Copyright (c) Matthew Brecknell 2013.
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE.txt or a copy at http://www.boost.org/LICENSE_1_0.txt).
#include <iostream>
#include <string>
#include "tree.hpp"
typedef tree<int> tri;
int main() {
tri foo = tri(tri(tri(1), 2, tri(3)), 4, tri(tri(5), 6, tri()));
tri bar = insert(7, foo);
for (const tri & tr: {foo,bar}) {
std::cout << tr << std::endl;
}
for (const tri & tr: {foo,bar}) {
std::cout
<< map_tree<const int*>([](const int & i) { return &i; }, tr)
<< std::endl;
}
}
| 20.4 | 79 | 0.591503 | mbrcknl |
822071ab31478074150e59726e6ad7cbe136836e | 2,253 | cc | C++ | caffe2/binaries/fb_run_plan_mpi.cc | shijieS/Caffe2 | f71695dcc27053e52b78f893344ea2ef2bd2da83 | [
"MIT"
] | 1 | 2021-04-22T00:07:58.000Z | 2021-04-22T00:07:58.000Z | caffe2/binaries/fb_run_plan_mpi.cc | ZhaoJ9014/caffe2 | 40a1ae36afd2d1b6126f171209c83a4a5b95737c | [
"MIT"
] | null | null | null | caffe2/binaries/fb_run_plan_mpi.cc | ZhaoJ9014/caffe2 | 40a1ae36afd2d1b6126f171209c83a4a5b95737c | [
"MIT"
] | null | null | null | // Runs a plan with mpi enabled without mpirun. This differs from run_plan_mpi
// in the sense that the common world is formed by joining during runtime,
// instead of being set up by mpirun.
//
// This util assumes that you have a common path (like NFS) that multiple
// instances can read from.
#include <mpi.h>
#include "caffe2/core/init.h"
#include "caffe2/core/logging.h"
#include "caffe2/core/operator.h"
#include "caffe2/mpi/mpi_common.h"
#include "caffe2/proto/caffe2.pb.h"
#include "caffe2/utils/proto_utils.h"
using caffe2::MPICommSize;
using caffe2::GlobalMPIComm;
CAFFE2_DEFINE_string(plan, "", "The given path to the plan protobuffer.");
CAFFE2_DEFINE_string(role, "", "server | client");
CAFFE2_DEFINE_int(
replicas,
2,
"The total number of replicas (clients + server) to wait for");
CAFFE2_DEFINE_string(job_path, "", "The path to write to");
namespace {
// RAAI for MPI so that we always run MPI_Finalize when exiting.
class MPIContext {
public:
MPIContext(int argc, char** argv) {
int mpi_ret;
MPI_CHECK(MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &mpi_ret));
if (mpi_ret != MPI_THREAD_MULTIPLE && mpi_ret != MPI_THREAD_SERIALIZED) {
throw std::runtime_error(
"Caffe2 MPI requires the underlying MPI to support the "
"MPI_THREAD_SERIALIZED or MPI_THREAD_MULTIPLE mode.");
}
}
~MPIContext() {
MPI_Finalize();
}
};
}
int main(int argc, char** argv) {
MPIContext mpi_context(argc, argv);
caffe2::SetUsageMessage("Runs a caffe2 plan that has MPI operators in it.");
caffe2::GlobalInit(&argc, &argv);
caffe2::MPISetupPeers(
caffe2::FLAGS_replicas, caffe2::FLAGS_role, caffe2::FLAGS_job_path);
// Only check if plan is specified AFTER MPI setup such that we can test
// whether or not MPI setup works without having a plan to run.
if (FLAGS_plan == "") {
std::cerr << "No plan defined! Exiting...\n";
return 0;
}
caffe2::PlanDef plan_def;
CAFFE_ENFORCE(ReadProtoFromFile(caffe2::FLAGS_plan, &plan_def));
std::unique_ptr<caffe2::Workspace> workspace(new caffe2::Workspace());
workspace->RunPlan(plan_def);
// This is to allow us to use memory leak checks.
google::protobuf::ShutdownProtobufLibrary();
return 0;
}
| 30.863014 | 78 | 0.711496 | shijieS |
8223818873576463b61e22ceb7c64095d83896d6 | 3,478 | cpp | C++ | samples/printto.cpp | yumetodo/iutest | 69bdc23a4da4b8752e04d944b3fb308c7523653b | [
"BSD-3-Clause"
] | null | null | null | samples/printto.cpp | yumetodo/iutest | 69bdc23a4da4b8752e04d944b3fb308c7523653b | [
"BSD-3-Clause"
] | null | null | null | samples/printto.cpp | yumetodo/iutest | 69bdc23a4da4b8752e04d944b3fb308c7523653b | [
"BSD-3-Clause"
] | null | null | null | //======================================================================
//-----------------------------------------------------------------------
/**
* @file printto.cpp
* @brief printto sample
*
* @author t.shirayanagi
* @par copyright
* Copyright (C) 2014-2017, Takazumi Shirayanagi\n
* This software is released under the new BSD License,
* see LICENSE
*/
//-----------------------------------------------------------------------
//======================================================================
#include "../include/iutest.hpp"
/* ---------------------------------------------------
* PrintTo
*//*--------------------------------------------------*/
#if IUTEST_HAS_PRINT_TO
struct Bar
{
int x, y, z;
bool operator == (const Bar& rhs) const
{
return x == rhs.x && y == rhs.y && z == rhs.z;
}
};
::iutest::iu_ostream& operator << (::iutest::iu_ostream& os, const Bar& bar)
{
return os << "X:" << bar.x << " Y:" << bar.y << " Z:" << bar.z;
}
void PrintTo(const Bar& bar, ::iutest::iu_ostream* os)
{
*os << "x:" << bar.x << " y:" << bar.y << " z:" << bar.z;
}
IUTEST(PrintToTest, Test1)
{
::std::vector<int> a;
for( int i=0; i < 10; ++i )
a.push_back(i);
IUTEST_SUCCEED() << ::iutest::PrintToString(a);
int* pi=NULL;
void* p=NULL;
IUTEST_SUCCEED() << ::iutest::PrintToString(p);
IUTEST_SUCCEED() << ::iutest::PrintToString(pi);
Bar bar = {0, 1, 2};
IUTEST_SUCCEED() << ::iutest::PrintToString(bar);
}
IUTEST(PrintToTest, Test2)
{
Bar bar1 = {0, 1, 2};
Bar bar2 = {0, 1, 2};
IUTEST_ASSERT_EQ(bar1, bar2);
}
IUTEST(PrintToTest, RawArray)
{
{
unsigned char a[3] = {0, 1, 2};
const unsigned char b[3] = {0, 1, 2};
const volatile unsigned char c[3] = {0, 1, 2};
volatile unsigned char d[3] = {0, 1, 2};
IUTEST_SUCCEED() << ::iutest::PrintToString(a);
IUTEST_SUCCEED() << ::iutest::PrintToString(b);
IUTEST_SUCCEED() << ::iutest::PrintToString(c);
IUTEST_SUCCEED() << ::iutest::PrintToString(d);
}
{
char a[3] = {0, 1, 2};
const char b[3] = {0, 1, 2};
const volatile char c[3] = {0, 1, 2};
volatile char d[3] = {0, 1, 2};
IUTEST_SUCCEED() << ::iutest::PrintToString(a);
IUTEST_SUCCEED() << ::iutest::PrintToString(b);
IUTEST_SUCCEED() << ::iutest::PrintToString(c);
IUTEST_SUCCEED() << ::iutest::PrintToString(d);
}
}
#if IUTEST_HAS_TYPED_TEST
template<typename T>
class TypedPrintToTest : public ::iutest::Test {};
typedef ::iutest::Types<char, unsigned char
, short, unsigned short
, int, unsigned int
, long, unsigned long
, int*> PrintStringTestTypes;
IUTEST_TYPED_TEST_CASE(TypedPrintToTest, PrintStringTestTypes);
IUTEST_TYPED_TEST(TypedPrintToTest, Print)
{
TypeParam a = 0;
TypeParam& b = a;
const TypeParam c = a;
const volatile TypeParam d = a;
IUTEST_SUCCEED() << ::iutest::PrintToString(a);
IUTEST_SUCCEED() << ::iutest::PrintToString(b);
IUTEST_SUCCEED() << ::iutest::PrintToString(c);
IUTEST_SUCCEED() << ::iutest::PrintToString(d);
}
#if IUTEST_HAS_CHAR16_T
IUTEST(PrintToTest, U16String)
{
IUTEST_SUCCEED() << ::iutest::PrintToString(u"テスト");
}
#endif
#if IUTEST_HAS_CHAR32_T
IUTEST(PrintToTest, U32String)
{
IUTEST_SUCCEED() << ::iutest::PrintToString(U"テスト");
}
#endif
#endif
#endif
| 26.549618 | 76 | 0.519839 | yumetodo |
82241d067baf2199fcd682043a06b50d7c796403 | 2,391 | cc | C++ | dataworks-public/src/model/GetInstanceStatusCountResult.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | dataworks-public/src/model/GetInstanceStatusCountResult.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | dataworks-public/src/model/GetInstanceStatusCountResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* 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.
*/
#include <alibabacloud/dataworks-public/model/GetInstanceStatusCountResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Dataworks_public;
using namespace AlibabaCloud::Dataworks_public::Model;
GetInstanceStatusCountResult::GetInstanceStatusCountResult() :
ServiceResult()
{}
GetInstanceStatusCountResult::GetInstanceStatusCountResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
GetInstanceStatusCountResult::~GetInstanceStatusCountResult()
{}
void GetInstanceStatusCountResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto statusCountNode = value["StatusCount"];
if(!statusCountNode["TotalCount"].isNull())
statusCount_.totalCount = std::stoi(statusCountNode["TotalCount"].asString());
if(!statusCountNode["NotRunCount"].isNull())
statusCount_.notRunCount = std::stoi(statusCountNode["NotRunCount"].asString());
if(!statusCountNode["WaitTimeCount"].isNull())
statusCount_.waitTimeCount = std::stoi(statusCountNode["WaitTimeCount"].asString());
if(!statusCountNode["WaitResCount"].isNull())
statusCount_.waitResCount = std::stoi(statusCountNode["WaitResCount"].asString());
if(!statusCountNode["RunningCount"].isNull())
statusCount_.runningCount = std::stoi(statusCountNode["RunningCount"].asString());
if(!statusCountNode["FailureCount"].isNull())
statusCount_.failureCount = std::stoi(statusCountNode["FailureCount"].asString());
if(!statusCountNode["SuccessCount"].isNull())
statusCount_.successCount = std::stoi(statusCountNode["SuccessCount"].asString());
}
GetInstanceStatusCountResult::StatusCount GetInstanceStatusCountResult::getStatusCount()const
{
return statusCount_;
}
| 36.784615 | 93 | 0.77248 | iamzken |
82257f436a6d072adfa04e3391aa17d50a373bbb | 3,960 | cpp | C++ | main/src/hal/amp-1.0.0/amp-leds.cpp | intentfulmotion/firmware-amp | fecd97ae3882907af10e05e7e688786110da0461 | [
"MIT"
] | null | null | null | main/src/hal/amp-1.0.0/amp-leds.cpp | intentfulmotion/firmware-amp | fecd97ae3882907af10e05e7e688786110da0461 | [
"MIT"
] | null | null | null | main/src/hal/amp-1.0.0/amp-leds.cpp | intentfulmotion/firmware-amp | fecd97ae3882907af10e05e7e688786110da0461 | [
"MIT"
] | null | null | null | #include <hal/amp-1.0.0/amp-leds.h>
FreeRTOS::Semaphore AmpLeds::ledsReady = FreeRTOS::Semaphore("leds");
void AmpLeds::init() {
// setup the status led
status = new OneWireLED(NeoPixel, STATUS_LED, 0, 1);
(*status)[0] = lightOff;
}
void AmpLeds::deinit() {
delay(50);
}
void AmpLeds::process() {
ledsReady.wait();
if (dirty) {
status->show();
for (auto pair : channels) {
if (pair.second != nullptr) {
if (pair.second->wait(5))
pair.second->show();
}
}
}
// if (statusDirty) {
// ESP_LOGV(LEDS_TAG,"Status is dirty. Re-rendering");
// status->wait();
// status->show();
// statusDirty = false;
// }
// // check the dirty bit for each
// for (auto pair : channels) {
// if (pair.second != nullptr && dirty[pair.first]) {
// ESP_LOGV(LEDS_TAG,"Channel %d is dirty. Re-rendering", pair.first);
// pair.second->wait();
// pair.second->show();
// // unset dirty bit
// dirty[pair.first] = false;
// }
// }
}
LightController* AmpLeds::addLEDStrip(LightChannel data) {
ledsReady.wait();
ledsReady.take();
ESP_LOGD(LEDS_TAG,"Adding type %d strip on channel %d with %d LEDs", data.type, data.channel, data.leds);
AddressableLED *controller = nullptr;
if (channels.find(data.channel) != channels.end()) {
// remove old controller
auto old = channels[data.channel];
delete old;
}
switch(data.type) {
case LEDType::NeoPixel:
case LEDType::WS2813:
case LEDType::SK6812:
controller = new OneWireLED(data.type, lightMap[data.channel], data.channel, data.leds);
break;
case LEDType::SK6812_RGBW:
controller = new OneWireLED(data.type, lightMap[data.channel], data.channel, data.leds, PixelOrder::GRBW);
break;
case LEDType::DotStar:
controller = new TwoWireLED(HSPI_HOST, data.leds, lightMap[data.channel], lightMap[data.channel + 4]);
break;
default:
return nullptr;
}
for (uint16_t i = 0; i < data.leds; i++)
(*controller)[i] = lightOff;
channels[data.channel] = controller;
leds[data.channel] = data.leds;
// dirty[data.channel] = true;
ledsReady.give();
return controller;
}
void AmpLeds::setStatus(Color color) {
(*status)[0] = gammaCorrected(color);
dirty = true;
// statusDirty = true;
}
void AmpLeds::render(bool all, int8_t channel) {
dirty = true;
// statusDirty = true;
// // set all dirty bits
// if (all) {
// for (auto pair : dirty)
// dirty[pair.first] = true;
// }
// else if (channel != -1 && channel >= 1 && channel <= 8)
// dirty[channel] = true;
}
Color AmpLeds::gammaCorrected(Color color) {
return Color(gamma8[color.r], gamma8[color.g], gamma8[color.b]);
}
void AmpLeds::setPixel(uint8_t channelNumber, Color color, uint16_t index) {
ledsReady.wait();
if (index >= leds[channelNumber]) {
ESP_LOGE(LEDS_TAG, "Pixel %d exceeds channel %d led count (%d)", index, channelNumber, leds[channelNumber]);
return;
}
auto controller = channels[channelNumber];
if (controller == nullptr)
return;
(*controller)[index] = color;
}
Color AmpLeds::getPixel(uint8_t channelNumber, uint16_t index) {
ledsReady.wait();
if (index >= leds[channelNumber]) {
ESP_LOGE(LEDS_TAG, "Pixel %d exceeds channel %d led count (%d)", index, channelNumber, leds[channelNumber]);
return lightOff;
}
auto controller = channels[channelNumber];
if (controller == nullptr)
return lightOff;
return (*controller)[index];
}
void AmpLeds::setPixels(uint8_t channelNumber, Color color, uint16_t start, uint16_t end) {
ledsReady.wait();
auto controller = channels[channelNumber];
if (controller == nullptr)
return;
for (uint16_t i = start; i < end; i++) {
if (i < leds[channelNumber])
(*controller)[i] = color;
else
ESP_LOGE(LEDS_TAG, "Pixel %d exceeds channel %d led count (%d)", i, channelNumber, leds[channelNumber]);
}
} | 26.577181 | 112 | 0.636364 | intentfulmotion |
82284cfa850da06bedc67553778ce7c6723ff33e | 1,284 | cpp | C++ | solutions/number_with_same_consecutive_differences.cpp | kmykoh97/My-Leetcode | 0ffdea16c3025805873aafb6feffacaf3411a258 | [
"Apache-2.0"
] | null | null | null | solutions/number_with_same_consecutive_differences.cpp | kmykoh97/My-Leetcode | 0ffdea16c3025805873aafb6feffacaf3411a258 | [
"Apache-2.0"
] | null | null | null | solutions/number_with_same_consecutive_differences.cpp | kmykoh97/My-Leetcode | 0ffdea16c3025805873aafb6feffacaf3411a258 | [
"Apache-2.0"
] | null | null | null | // Return all non-negative integers of length N such that the absolute difference between every two consecutive digits is K.
// Note that every number in the answer must not have leading zeros except for the number 0 itself. For example, 01 has one leading zero and is invalid, but 0 is valid.
// You may return the answer in any order.
// Example 1:
// Input: N = 3, K = 7
// Output: [181,292,707,818,929]
// Explanation: Note that 070 is not a valid number, because it has leading zeroes.
// Example 2:
// Input: N = 2, K = 1
// Output: [10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]
// Note:
// 1 <= N <= 9
// 0 <= K <= 9
// solution: dfs
class Solution {
public:
void dfs(int num, int N, int K, vector<int>& result){
if (N == 0) {
result.push_back(num);
return;
}
int last_digit = num%10;
if (last_digit >= K) dfs(num*10 + last_digit - K, N-1, K, result);
if (K > 0 && last_digit + K < 10) dfs(num*10 + last_digit + K, N-1, K, result);
}
vector<int> numsSameConsecDiff(int N, int K) {
vector<int> result;
if (N == 1) result.push_back(0);
for (int d = 1; d < 10; ++d) {
dfs(d, N-1, K, result);
}
return result;
}
}; | 24.692308 | 168 | 0.573209 | kmykoh97 |
8229ebaa6d032ab38129b40f5e0a11ed33b674d4 | 2,405 | cpp | C++ | src/nanoFramework.System.Collections/nf_system_collections_System_Collections_Queue.cpp | TIPConsulting/nf-interpreter | d5407872f4705d6177e1ee5a2e966bd02fd476e4 | [
"MIT"
] | null | null | null | src/nanoFramework.System.Collections/nf_system_collections_System_Collections_Queue.cpp | TIPConsulting/nf-interpreter | d5407872f4705d6177e1ee5a2e966bd02fd476e4 | [
"MIT"
] | 1 | 2021-02-22T07:54:30.000Z | 2021-02-22T07:54:30.000Z | src/nanoFramework.System.Collections/nf_system_collections_System_Collections_Queue.cpp | TIPConsulting/nf-interpreter | d5407872f4705d6177e1ee5a2e966bd02fd476e4 | [
"MIT"
] | null | null | null | //
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
#include "nf_system_collections.h"
HRESULT Library_nf_system_collections_System_Collections_Queue::CopyTo___VOID__SystemArray__I4( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
CLR_RT_HeapBlock_Queue* pThis;
CLR_RT_HeapBlock_Array* array;
CLR_INT32 index;
pThis = (CLR_RT_HeapBlock_Queue*)stack.This(); FAULT_ON_NULL(pThis);
array = stack.Arg1().DereferenceArray(); FAULT_ON_NULL_ARG(array);
index = stack.Arg2().NumericByRef().s4;
NANOCLR_SET_AND_LEAVE(pThis->CopyTo( array, index ));
NANOCLR_NOCLEANUP();
}
HRESULT Library_nf_system_collections_System_Collections_Queue::Clear___VOID( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
CLR_RT_HeapBlock_Queue* pThis = (CLR_RT_HeapBlock_Queue*)stack.This(); FAULT_ON_NULL(pThis);
NANOCLR_SET_AND_LEAVE(pThis->Clear());
NANOCLR_NOCLEANUP();
}
HRESULT Library_nf_system_collections_System_Collections_Queue::Enqueue___VOID__OBJECT( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
CLR_RT_HeapBlock_Queue* pThis = (CLR_RT_HeapBlock_Queue*)stack.This(); FAULT_ON_NULL(pThis);
NANOCLR_SET_AND_LEAVE(pThis->Enqueue( stack.Arg1().Dereference() ));
NANOCLR_NOCLEANUP();
}
HRESULT Library_nf_system_collections_System_Collections_Queue::Dequeue___OBJECT( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
CLR_RT_HeapBlock_Queue* pThis = (CLR_RT_HeapBlock_Queue*)stack.This(); FAULT_ON_NULL(pThis);
CLR_RT_HeapBlock* value;
NANOCLR_CHECK_HRESULT(pThis->Dequeue( value ));
stack.SetResult_Object( value );
NANOCLR_NOCLEANUP();
}
HRESULT Library_nf_system_collections_System_Collections_Queue::Peek___OBJECT( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
NANOCLR_HEADER();
CLR_RT_HeapBlock_Queue* pThis = (CLR_RT_HeapBlock_Queue*)stack.This(); FAULT_ON_NULL(pThis);
CLR_RT_HeapBlock* value;
NANOCLR_CHECK_HRESULT(pThis->Peek( value ));
stack.SetResult_Object( value );
NANOCLR_NOCLEANUP();
}
| 29.691358 | 123 | 0.729314 | TIPConsulting |
822a33bd8dd25acd61eb9e4d90992818da114355 | 9,367 | cpp | C++ | src/main.cpp | MaGetzUb/SoftwareRenderer | e1d6242617863a1d9fdc272c1011a3938d1dbbc9 | [
"BSD-2-Clause"
] | 1 | 2020-01-01T12:07:07.000Z | 2020-01-01T12:07:07.000Z | src/main.cpp | MaGetzUb/SoftwareRenderer | e1d6242617863a1d9fdc272c1011a3938d1dbbc9 | [
"BSD-2-Clause"
] | null | null | null | src/main.cpp | MaGetzUb/SoftwareRenderer | e1d6242617863a1d9fdc272c1011a3938d1dbbc9 | [
"BSD-2-Clause"
] | 1 | 2018-07-20T07:51:06.000Z | 2018-07-20T07:51:06.000Z | /*
Copyright © 2018, Marko Ranta
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.
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 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 "System/window.hpp"
#include "Renderer/canvas.hpp"
#include "System/inputmanager.hpp"
#include "System/timer.hpp"
#include <string>
#include <iostream>
#include <regex> //MEH
#include "Renderer/rendercontext.hpp"
#include "Renderer/mesh.hpp"
#include "starfield.hpp"
#include "Math/quat.hpp"
#define NONE 0
#define STARFIELD 1
#define RENDERCONTEXT 2
#define TEST RENDERCONTEXT
#ifdef NDEBUG
int CALLBACK WinMain(
HINSTANCE /*hInstance*/,
HINSTANCE /*hPrevInstance*/,
LPSTR /*lpCmdLine*/,
int /*nCmdShow*/
)
#else
int main()
#endif
{
int screenWidth = 640, screenHeight = 480;
int canvasWidth = 512, canvasHeight = 384;
std::fstream settings;
settings.open("settings.ini", std::ios::in);
if(!settings.is_open()) {
settings.open("settings.ini", std::ios::out);
settings << "Modify these values at your own risk." << std::endl;
settings << "ScreenWidth = " << screenWidth << std::endl;
settings << "ScreenHeight = " << screenHeight << std::endl;
settings << "CanvasWidth = " << canvasWidth << std::endl;
settings << "CanvasHeight = " << canvasHeight << std::endl;
settings.close();
} else {
std::string line;
std::string var, value;
std::regex match("(\\w+)\\s*=(\\d+)\\s*");
while(std::getline(settings, line)) {
std::smatch subMatches;
if(std::regex_match(line, subMatches, match)) {
if(subMatches.size() == 3) {
var = subMatches[1].str();
value = subMatches[2].str();
}
}
if(var == "ScreenWidth") screenWidth = stoi(value);
if(var == "ScreenHeight") screenHeight = stoi(value);
if(var == "CanvasWidth") canvasWidth = stoi(value);
if(var == "CanvasHeight") canvasHeight = stoi(value);
}
settings.close();
}
Window window;
window.initialize(screenWidth, screenHeight, "Software Renderer");
Canvas canvas(window);
canvas.resize(canvasWidth, canvasHeight);
float aRatio = 4.0f / 3.0f;
InputManager inputs;
inputs.setCustomMessageCallback([&aRatio](Window& window, UINT msg, WPARAM wparam, LPARAM lparam)->LRESULT {
switch(msg) {
case WM_SIZE: {
float w = GET_X_LPARAM(lparam);
float h = GET_Y_LPARAM(lparam);
aRatio = w / h;
} break;
}
return window.defaultWindowProc(msg, wparam, lparam);
});
window.setMessageCallback(inputs.callbackProcessor());
#if TEST == STARFIELD
Starfield starfield(canvas);
#endif
#if TEST == RENDERCONTEXT
RenderContext rc(canvas);
Texture texture1;
texture1.load("res/texture1.png");
Texture texture2;
texture2.load("res/texture2.png");
Mesh mesh1;
mesh1.load("res/suzanne.obj");
Mesh mesh2;
mesh2.load("res/terrain.obj");
Mesh mesh3;
mesh3.load("res/cube.obj");
#endif
auto prevtime = Timer();
double deltaTime = 0.0f;
float ang = 0.0f;
#ifdef TEXT_INPUT_TEST
std::string input;
auto eraseTime = Timer();
#endif
//TL---TR
//| |
//| |
//BL---BR
Vertex vertices[] = {
{-1.0f, -1.0f}, //Bottom left
{-1.0f, 1.0f}, //Top left
{ 1.0f, 1.0f}, //Top right
{ 1.0f, -1.0f} //Bottom right
};
vertices[0].setColor({ 1.0f, 0.0f, 0.0f, 1.0 });
vertices[1].setColor({ 1.0f, 1.0f, 0.0f, 1.0 });
vertices[2].setColor({ 0.0f, 0.0f, 1.0f, 1.0 });
vertices[3].setColor({ 0.0f, 1.0f, 1.0f, 1.0 });
vertices[0].setTexCoord({ 0.0f, 1.0f });
vertices[1].setTexCoord({ 0.0f, 0.0f });
vertices[2].setTexCoord({ 1.0f, 0.0f });
vertices[3].setTexCoord({ 1.0f, 1.0f });
int frames = 0, fps = 0;
float z = -2.0f;
double fpsTime = 0.0f;
float cameraYaw = 0.0f;
float cameraPitch = 0.0f;
vec3 cameraPosition;
float suzanneAngle = 0.f;
rc.setSamplingMode(Texture::Sampling::CubicHermite);
rc.setTextureWrapingMode(Texture::Wraping::Repeat);
rc.enableLighting(true);
rc.setAmbientColor({0.2f, 0.1f, 0.6f});
rc.setAmbientIntensity(0.3f);
rc.setSunColor({ 1.f, 0.6f, 0.2f });
rc.setSunIntensity(4.f);
rc.setSunPosition(vec3(16.f, 3.f, 8.f));
while(!window.isClosed()) {
window.pollEvents();
rc.reset();
canvas.clearCheckerboard(rc.checkerBoard(), rc.ambientColor()*rc.ambientIntensity());
if(!rc.checkerBoard()) {
rc.clearDepthBuffer();
}
#if TEST == STARFIELD
starfield.updateAndDraw(deltaTime);
#endif
#if TEST == RENDERCONTEXT
mat4 mat;
if(inputs.isMouseHit(0)) ShowCursor(FALSE);
if(inputs.isMouseUp(0)) ShowCursor(TRUE);
if(inputs.isMouseDown(0)) {
RECT rct;
GetClientRect(window.handle(), &rct);
POINT p;
p.x = (rct.right - rct.left) / 2;
p.y = (rct.bottom - rct.top) / 2;
float mx = (p.x - inputs.mouseX());
float my = (p.y - inputs.mouseY());
cameraPitch += mx * deltaTime;
cameraYaw += my * deltaTime;
ClientToScreen(window.handle(), &p);
SetCursorPos(p.x, p.y);
}
mat4 rotation = mat4::Rotation(cameraYaw, 1.0f, 0.0f, 0.0f)*mat4::Rotation(cameraPitch, 0.0f, 1.0f, 0.0f);
vec3 dir = rotation.transposed() * vec3(0.f, 0.f, 1.f);
vec3 right = cross(dir, vec3(0.f, 1.f, 0.f));
right = reorthogonalize(right, dir);
if(inputs.isKeyHit('C')) rc.setTextureWrapingMode(Texture::Wraping::Clamp);
if(inputs.isKeyHit('R')) rc.setTextureWrapingMode(Texture::Wraping::Repeat);
if(inputs.isKeyHit(0x31)) rc.setSamplingMode(Texture::Sampling::None);
if(inputs.isKeyHit(0x32)) rc.setSamplingMode(Texture::Sampling::Linear);
if(inputs.isKeyHit(0x33)) rc.setSamplingMode(Texture::Sampling::CubicHermite);
if(inputs.isKeyDown('W')) cameraPosition += dir*5.f * deltaTime;
if(inputs.isKeyDown('S')) cameraPosition -= dir*5.f * deltaTime;
if(inputs.isKeyDown('D')) cameraPosition += right*5.f * deltaTime;
if(inputs.isKeyDown('A')) cameraPosition -= right*5.f * deltaTime;
/*
if(inputs.isKeyHit(VK_SPACE)) {
rc.testMipmap(!rc.isMipMapTesting());
}
if(rc.isMipMapTesting()) {
rc.setMipMapLevel(rc.mipMapLevel() + (inputs.isKeyHit(VK_UP) - inputs.isKeyHit(VK_DOWN)));
}*/
mat4 viewProjection = mat4::Perspective(aRatio, 90.0f, .01f, 100.f) * rotation * mat4::Translate(cameraPosition);
z -= (float)(inputs.isKeyDown(VK_UP) - inputs.isKeyDown(VK_DOWN)) * deltaTime;
mat4 suzanneRotation = mat4::Rotation(QMod(suzanneAngle, 360.0f), 0.f, 1.f, 0.f);
mat4 model = mat4::Translate(0.0f, 0.0f, -2.0f) * suzanneRotation;
mat = viewProjection * model;
rc.drawMesh(mesh1, mat, texture1, suzanneRotation);
suzanneAngle += deltaTime*20.f;
model = mat4::Translate(0.0f, -4.0f, 0.0f);
mat = viewProjection * model;
rc.drawMesh(mesh2, mat, texture2);
model = mat4::Translate(0.0f, -2.0f, -2.0f);
mat = viewProjection * model;
rc.drawMesh(mesh3, mat);
#endif
#ifdef NDEBUG
std::cout << inputs.mouseX() << ", " << inputs.mouseY() << '\r';
#endif
canvas.swapBuffers();
rc.advanceCheckerboard();
#ifdef TEXT_INPUT_TEST
RECT rct = { 0, 0, 800, 300 };
unsigned int ch;
if(inputs.isTextInput(ch)) {
if(isprint(ch)) {
input += ((char)ch);
}
}
if((inputs.isKeyHit(8) || (inputs.isKeyDown(8) && eraseTime > 1000)) && !input.empty()) {
eraseTime = Timer()/10 - eraseTime;
input.pop_back();
}
rct.top += 20;
DrawTextA(window.dc(), input.c_str(), -1, &rct, 0);
#endif
auto tp = Timer();
deltaTime = (double)(tp - prevtime) / (double)TIMER_PRECISION;
//Cap the FPS, so movement won't become too slow.
if(deltaTime < (1.0 / 120.0)) {
Sleep((int)1000.0*(1.0 / 120.0));
}
//Calculate FPS
prevtime = tp;
frames++;
fpsTime += (double)deltaTime;
if(fpsTime > 1.0) {
fps = frames;
frames = 0;
fpsTime = 0;
}
window.setTitle("Software Rendering | FPS: " + std::to_string(fps) + " | Triangles: "+std::to_string(rc.renderedTriangles()) /*+ (rc.isMipMapTesting() ? " | MipMap testing! " + std::to_string(rc.mipMapLevel()) : "")*/);
inputs.update();
}
return 0;
}
| 27.229651 | 222 | 0.645564 | MaGetzUb |
822b8a4f8aa4df4e7e225d0191f8d4b56ccf6f98 | 1,282 | cpp | C++ | benchmarks/distances_b.cpp | ssciwr/geolib4d | dd79a746559235e47c2cb5e7c7ba71ef3ae21e29 | [
"MIT"
] | 3 | 2022-01-28T14:18:05.000Z | 2022-03-02T21:52:43.000Z | benchmarks/distances_b.cpp | ssciwr/geolib4d | dd79a746559235e47c2cb5e7c7ba71ef3ae21e29 | [
"MIT"
] | 104 | 2021-06-18T14:10:37.000Z | 2022-03-04T06:12:58.000Z | benchmarks/distances_b.cpp | ssciwr/py4dgeo | dd79a746559235e47c2cb5e7c7ba71ef3ae21e29 | [
"MIT"
] | null | null | null | #include "testsetup.hpp"
#include <py4dgeo/compute.hpp>
#include <py4dgeo/epoch.hpp>
#include <benchmark/benchmark.h>
using namespace py4dgeo;
static void
distances_benchmark(benchmark::State& state)
{
auto [cloud, corepoints] = ahk_benchcloud();
Epoch epoch(*cloud);
epoch.kdtree.build_tree(10);
std::vector<double> scales{ 1.0 };
EigenNormalSet directions(corepoints->rows(), 3);
EigenNormalSet orientation(1, 3);
orientation << 0, 0, 1;
// Precompute the multiscale directions
compute_multiscale_directions(
epoch, *corepoints, scales, orientation, directions);
// We try to test all callback combinations
auto wsfinder = radius_workingset_finder;
auto uncertaintymeasure = standard_deviation_uncertainty;
for (auto _ : state) {
// Calculate the distances
DistanceVector distances;
UncertaintyVector uncertainties;
compute_distances(*corepoints,
2.0,
epoch,
epoch,
directions,
0.0,
distances,
uncertainties,
wsfinder,
uncertaintymeasure);
}
}
BENCHMARK(distances_benchmark)->Unit(benchmark::kMillisecond);
BENCHMARK_MAIN();
| 26.163265 | 62 | 0.634165 | ssciwr |
822ba932fff7ff255c3c71384c0d15f11a82339d | 3,820 | hpp | C++ | storage/map_files_downloader.hpp | dualword/organicmaps | c0a73aea4835517edef3b5a7d68a3a50d55a4471 | [
"Apache-2.0"
] | 3,062 | 2021-04-09T16:51:55.000Z | 2022-03-31T21:02:51.000Z | storage/map_files_downloader.hpp | MAPSWorks/organicmaps | b5fef4b5954cb27153c0dafddd7eed3bfa0b1e7f | [
"Apache-2.0"
] | 1,396 | 2021-04-08T07:26:49.000Z | 2022-03-31T20:27:46.000Z | storage/map_files_downloader.hpp | MAPSWorks/organicmaps | b5fef4b5954cb27153c0dafddd7eed3bfa0b1e7f | [
"Apache-2.0"
] | 242 | 2021-04-10T17:10:46.000Z | 2022-03-31T13:41:07.000Z | #pragma once
#include "storage/downloader_queue_universal.hpp"
#include "storage/downloading_policy.hpp"
#include "storage/queued_country.hpp"
#include "platform/downloader_defines.hpp"
#include "platform/http_request.hpp"
#include "platform/safe_callback.hpp"
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
#include <utility>
#include <vector>
namespace storage
{
// This interface encapsulates HTTP routines for receiving servers
// URLs and downloading a single map file.
class MapFilesDownloader
{
public:
// Denotes bytes downloaded and total number of bytes.
using ServersList = std::vector<std::string>;
using ServersListCallback = platform::SafeCallback<void(ServersList const & serverList)>;
virtual ~MapFilesDownloader() = default;
/// Asynchronously downloads a map file, periodically invokes
/// onProgress callback and finally invokes onDownloaded
/// callback. Both callbacks will be invoked on the main thread.
void DownloadMapFile(QueuedCountry && queuedCountry);
// Removes item from m_quarantine queue when list of servers is not received.
// Parent method must be called into override method.
virtual void Remove(CountryId const & id);
// Clears m_quarantine queue when list of servers is not received.
// Parent method must be called into override method.
virtual void Clear();
// Returns m_quarantine queue when list of servers is not received.
// Parent method must be called into override method.
virtual QueueInterface const & GetQueue() const;
/**
* @brief Async file download as string buffer (for small files only).
* Request can be skipped if current servers list is empty.
* Callback will be skipped on download error.
* @param[in] url Final url part like "index.json" or "maps/210415/countries.txt".
* @param[in] forceReset True - force reset current request, if any.
*/
void DownloadAsString(std::string url, std::function<bool (std::string const &)> && callback, bool forceReset = false);
void SetServersList(ServersList const & serversList);
void SetDownloadingPolicy(DownloadingPolicy * policy);
void SetDataVersion(int64_t version) { m_dataVersion = version; }
/// @name Legacy functions for Android resourses downloading routine.
/// @{
void EnsureServersListReady(std::function<void ()> && callback);
std::vector<std::string> MakeUrlListLegacy(std::string const & fileName) const;
/// @}
protected:
bool IsDownloadingAllowed() const;
std::vector<std::string> MakeUrlList(std::string const & relativeUrl) const;
// Synchronously loads list of servers by http client.
ServersList LoadServersList();
private:
/**
* @brief This method is blocking and should be called on network thread.
* Default implementation receives a list of all servers that can be asked
* for a map file and invokes callback on the main thread (@see ServersListCallback as SafeCallback).
*/
virtual void GetServersList(ServersListCallback const & callback);
/// Asynchronously downloads the file and saves result to provided directory.
virtual void Download(QueuedCountry && queuedCountry) = 0;
/// @param[in] callback Called in main thread (@see GetServersList).
void RunServersListAsync(std::function<void()> && callback);
/// Current file downloading request for DownloadAsString.
using RequestT = downloader::HttpRequest;
std::unique_ptr<RequestT> m_fileRequest;
ServersList m_serversList;
int64_t m_dataVersion = 0;
/// Used as guard for m_serversList assign.
std::atomic_bool m_isServersListRequested = false;
DownloadingPolicy * m_downloadingPolicy = nullptr;
// This queue accumulates download requests before
// the servers list is received on the network thread.
Queue m_pendingRequests;
};
} // namespace storage
| 36.730769 | 121 | 0.750524 | dualword |
822f0e3b530cb767804478225c1aad7bb89ce441 | 917 | inl | C++ | src/binder/inc/bindinglog.inl | CyberSys/coreclr-mono | 83b2cb83b32faa45b4f790237b5c5e259692294a | [
"MIT"
] | 10 | 2015-11-03T16:35:25.000Z | 2021-07-31T16:36:29.000Z | src/binder/inc/bindinglog.inl | CyberSys/coreclr-mono | 83b2cb83b32faa45b4f790237b5c5e259692294a | [
"MIT"
] | 1 | 2019-03-05T18:50:09.000Z | 2019-03-05T18:50:09.000Z | src/binder/inc/bindinglog.inl | CyberSys/coreclr-mono | 83b2cb83b32faa45b4f790237b5c5e259692294a | [
"MIT"
] | 4 | 2015-10-28T12:26:26.000Z | 2021-09-04T11:36:04.000Z | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
// ============================================================
//
// BindingLog.inl
//
//
// Implements inlined methods of BindingLog
//
// ============================================================
#ifndef __BINDER__BINDING_LOG_INL__
#define __BINDER__BINDING_LOG_INL__
BOOL BindingLog::CanLog()
{
return (m_pCDebugLog != NULL);
}
CDebugLog *BindingLog::GetDebugLog()
{
_ASSERTE(m_pCDebugLog != NULL);
return m_pCDebugLog;
}
HRESULT BindingLog::Log(LPCWSTR pwzInfo)
{
PathString info(pwzInfo);
return BindingLog::Log(info);
}
HRESULT BindingLog::Log(LPCWSTR pwzPrefix,
SString &info)
{
PathString message;
message.Append(pwzPrefix);
message.Append(info);
return Log(message);
}
#endif
| 19.104167 | 101 | 0.597601 | CyberSys |
43619168bbe67d887c4410779ccafd0308947c90 | 1,014 | hpp | C++ | include/pdmath/util.hpp | pdm-pcb/pdmath | 6c8ac4288c68bbe547e71f5bb7d1e44d3f1e35ab | [
"MIT"
] | null | null | null | include/pdmath/util.hpp | pdm-pcb/pdmath | 6c8ac4288c68bbe547e71f5bb7d1e44d3f1e35ab | [
"MIT"
] | null | null | null | include/pdmath/util.hpp | pdm-pcb/pdmath | 6c8ac4288c68bbe547e71f5bb7d1e44d3f1e35ab | [
"MIT"
] | null | null | null | #ifndef PDMATH_UTIL_HPP
#define PDMATH_UTIL_HPP
#include <cstdint>
#include <utility>
namespace pdm {
static constexpr uint8_t float_precision = 7;
static constexpr float float_epsilon = 1.0e-6f;
static float clamp(const float val, const float min, const float max) {
if(val > max) {
return max;
}
if(val < min) {
return min;
}
return val;
}
static float clamp(const float val, const std::pair<float, float> &min_max) {
if(val > min_max.second) {
return min_max.second;
}
if(val < min_max.first) {
return min_max.first;
}
return val;
}
static bool overlap(const std::pair<float, float> &a,
const std::pair<float, float> &b) {
return (a.second >= b.first) && (a.first <= b.second);
}
static bool overlap(const float a_min, const float a_max,
const float b_min, const float b_max) {
return (a_max >= b_min) && (a_min <= b_max);
}
} //namespace pdm
#endif // PDMATH_UTIL_HPP | 22.043478 | 77 | 0.616371 | pdm-pcb |
43635ffd74fb3e438de90879c7b7a1a68b5cf4ad | 734 | cpp | C++ | src/main.cpp | KentaKawamata/load_params | 98204612fccc301f92fa183fbbdec7381d70534a | [
"MIT"
] | null | null | null | src/main.cpp | KentaKawamata/load_params | 98204612fccc301f92fa183fbbdec7381d70534a | [
"MIT"
] | null | null | null | src/main.cpp | KentaKawamata/load_params | 98204612fccc301f92fa183fbbdec7381d70534a | [
"MIT"
] | null | null | null | #include <iostream>
#include "./../include/loadParams.hpp"
int main(int argc, char* argv[])
{
LoadParams *load;
load = new LoadParams();
float test_num = 0;
double test_double = 0;
//char test_error = 0;
std::string test_str;
bool test_bool = true;
load->get_param<float>("test3", test_num);
load->get_param<double>("test4", test_double);
//load->get_param<char>("test4", test_error);
load->get_param<std::string>("set_string", test_str);
load->get_param<bool>("set_bool", test_bool);
load->get_param<bool>("error_bool", test_bool);
std::cout << test_num << std::endl;
std::cout << test_double << std::endl;
std::cout << test_str << std::endl;
std::cout << test_bool << std::endl;
return 0;
}
| 25.310345 | 55 | 0.658038 | KentaKawamata |
436545db17f286d4dba949dc416e0433a9f6f77f | 1,058 | cpp | C++ | KetaminRudwolf/src/game/scene/SceneMenu.cpp | Vasile2k/KetaminRudwolf | 8e1703a2737c2ff914380a14c71f679e27786a10 | [
"Apache-2.0"
] | 5 | 2019-01-13T09:53:05.000Z | 2021-01-25T11:02:12.000Z | KetaminRudwolf/src/game/scene/SceneMenu.cpp | Vasile2k/KetaminRudwolf | 8e1703a2737c2ff914380a14c71f679e27786a10 | [
"Apache-2.0"
] | null | null | null | KetaminRudwolf/src/game/scene/SceneMenu.cpp | Vasile2k/KetaminRudwolf | 8e1703a2737c2ff914380a14c71f679e27786a10 | [
"Apache-2.0"
] | null | null | null | #include "SceneMenu.hpp"
#include "SceneOptions.hpp"
#include "SceneGame.hpp"
#include "../Game.hpp"
SceneMenu::SceneMenu(Scene*& currentScene) : currentScene(currentScene) {
}
SceneMenu::~SceneMenu() {
}
void SceneMenu::onUpdate(std::chrono::milliseconds deltaTime) {
}
void SceneMenu::onRender(Renderer* renderer) {
renderer->clear();
renderer->clearColor(0.176470588F, 0.176470588F, 0.176470588F, 1.0F);
}
void SceneMenu::onGUIRender(GUIRenderer* guiRenderer) {
guiRenderer->begin("Game", (float)Game::getInstance()->getWindow()->getWidth() / 2.0F - 100.0F, 100.0F, 200.0F, 300.0F);
guiRenderer->row(15, 1);
guiRenderer->row(70, 1);
if (guiRenderer->button("Play")) {
currentScene = new SceneGame();
}
guiRenderer->row(15, 1);
guiRenderer->row(70, 1);
if (guiRenderer->button("Options")) {
currentScene = new SceneOptions();
}
guiRenderer->row(15, 1);
guiRenderer->row(70, 1);
if (guiRenderer->button("Exit")) {
done = true;
}
guiRenderer->end();
}
void SceneMenu::onMouseButton(int button, int action, int modifiers) {
}
| 22.510638 | 121 | 0.694707 | Vasile2k |
4367bff43ea688a5548411e48b0e1e5d26dc5a6c | 5,258 | cpp | C++ | src/TtbarHypothesis.cpp | kreczko/AnalysisSoftware | fa83a3775a8d644e6098d28dbc6f3d7f1a11b400 | [
"Apache-2.0"
] | null | null | null | src/TtbarHypothesis.cpp | kreczko/AnalysisSoftware | fa83a3775a8d644e6098d28dbc6f3d7f1a11b400 | [
"Apache-2.0"
] | null | null | null | src/TtbarHypothesis.cpp | kreczko/AnalysisSoftware | fa83a3775a8d644e6098d28dbc6f3d7f1a11b400 | [
"Apache-2.0"
] | null | null | null | /*
* TtbarHypothesis.cpp
*
* Created on: Dec 4, 2010
* Author: lkreczko
*/
#include "../interface/TtbarHypothesis.h"
#include "../interface/ReconstructionModules/ReconstructionException.h"
//#include "../interface/ReconstructionModules/BasicNeutrinoReconstruction.h"
// #include <iostream>
// using namespace std;
namespace BAT {
TtbarHypothesis::TtbarHypothesis() :
totalChi2(99999.), //
leptonicChi2(99999.), //
hadronicChi2(99999.), //
globalChi2(99999.), //
neutrinoChi2(99999.),//
discriminator(999999), //
NuChi2Discriminator(99999),
MassDiscriminator(99999),
CSVDiscriminator(99999),
hadronicTop(), //
leptonicTop(), //
leptonicW(), //
hadronicW(), //
resonance(), //
neutrinoFromW(), //
leptonicBjet(), //
hadronicBJet(), //
jet1FromW(), //
jet2FromW(), //
leptonFromW(), //
met(), //
decayChannel(Decay::unknown) {
}
TtbarHypothesis::TtbarHypothesis(const LeptonPointer& lepton,
const ParticlePointer& neut, const JetPointer& lepBJet,
const JetPointer& hadBJet, const JetPointer& hadWJet1,
const JetPointer& hadWJet2) :
totalChi2(99999.), //
leptonicChi2(99999.), //
hadronicChi2(99999.), //
globalChi2(99999.), //
neutrinoChi2(99999.),//
discriminator(999999), //
NuChi2Discriminator(99999),
MassDiscriminator(99999),
CSVDiscriminator(99999),
hadronicTop(), //
leptonicTop(), //
leptonicW(new Particle(*lepton + *neut)), //
hadronicW(new Particle(*hadWJet1 + *hadWJet2)), //
resonance(), //
neutrinoFromW(neut), //
leptonicBjet(lepBJet), //
hadronicBJet(hadBJet), //
jet1FromW(hadWJet1), //
jet2FromW(hadWJet2), //
leptonFromW(lepton), //
met(new MET(neut->px(), neut->py())), //
decayChannel(Decay::unknown) {
}
TtbarHypothesis::~TtbarHypothesis() {
}
bool TtbarHypothesis::isCorrect() const {
bool isCorrect = false;
if (hadronicBJet->ttbar_decay_parton() == 6){
if (leptonicBjet->ttbar_decay_parton() == 5){
if ((jet1FromW->ttbar_decay_parton() == 3 && jet2FromW->ttbar_decay_parton() == 4 ) || (jet2FromW->ttbar_decay_parton() == 3 && jet1FromW->ttbar_decay_parton() == 4 )){
isCorrect = true;
}
}
}
// std::cout << "Event Reconstruction is : " << isCorrect << std::endl;
return isCorrect;
}
bool TtbarHypothesis::isValid() const {
bool hasObjects = leptonFromW && neutrinoFromW && jet1FromW && jet2FromW && hadronicBJet
&& leptonicBjet;
return hasObjects;
}
bool TtbarHypothesis::isPhysical() const {
bool hasPhysicalSolution = leptonicTop->mass() > 0 && leptonicW->mass() > 0 && hadronicW->mass() > 0
&& hadronicTop->mass() > 0;
return hasPhysicalSolution;
}
void TtbarHypothesis::combineReconstructedObjects() {
if (isValid()) {
leptonicW = ParticlePointer(new Particle(*neutrinoFromW + *leptonFromW));
if (jet1FromW != jet2FromW)
hadronicW = ParticlePointer(new Particle(*jet1FromW + *jet2FromW));
else
hadronicW = jet1FromW;
leptonicTop = ParticlePointer(new Particle(*leptonicBjet + *leptonicW));
hadronicTop = ParticlePointer(new Particle(*hadronicBJet + *hadronicW));
resonance = ParticlePointer(new Particle(*leptonicTop + *hadronicTop));
// if(fabs(leptonicW->mass() - BasicNeutrinoReconstruction::W_mass) > 0.1)
// cout << "Unexpected mass difference " << fabs(leptonicW->mass() - BasicNeutrinoReconstruction::W_mass) << endl;
} else {
throwDetailedException();
}
}
void TtbarHypothesis::throwDetailedException() const {
std::string msg = "TTbar Hypothesis not filled properly: \n";
if (leptonFromW == 0)
msg += "Lepton from W: not filled \n";
else
msg += "Lepton from W: filled \n";
if (neutrinoFromW == 0)
msg += "Neutrino from W: not filled \n";
else
msg += "Neutrino from W: filled \n";
if (jet1FromW == 0)
msg += "Jet 1 from W: not filled \n";
else
msg += "Jet 1 from W: filled \n";
if (jet2FromW == 0)
msg += "Jet 2 from W: not filled \n";
else
msg += "Jet 2 from W: filled \n";
if (leptonicBjet == 0)
msg += "Leptonic b-jet: not filled \n";
else
msg += "Leptonic b-jet: filled \n";
if (hadronicBJet == 0)
msg += "Hadronic b-jet: not filled \n";
else
msg += "Hadronic b-jet: filled \n";
throw ReconstructionException(msg);
}
double TtbarHypothesis::M3() const {
JetCollection jets;
jets.clear();
jets.push_back(jet1FromW);
jets.push_back(jet2FromW);
jets.push_back(leptonicBjet);
jets.push_back(hadronicBJet);
return M3(jets);
}
double TtbarHypothesis::M3(const JetCollection jets) {
double m3(0), max_pt(0);
if (jets.size() >= 3) {
for (unsigned int index1 = 0; index1 < jets.size() - 2; ++index1) {
for (unsigned int index2 = index1 + 1; index2 < jets.size() - 1; ++index2) {
for (unsigned int index3 = index2 + 1; index3 < jets.size(); ++index3) {
FourVector m3Vector(
jets.at(index1)->getFourVector() + jets.at(index2)->getFourVector()
+ jets.at(index3)->getFourVector());
double currentPt = m3Vector.Pt();
if (currentPt > max_pt) {
max_pt = currentPt;
m3 = m3Vector.M();
}
}
}
}
}
return m3;
}
double TtbarHypothesis::sumPt() const {
return leptonicBjet->pt() + hadronicBJet->pt() + jet1FromW->pt() + jet2FromW->pt();
}
double TtbarHypothesis::PtTtbarSystem() const {
return resonance->pt();
}
} // namespace BAT
| 26.422111 | 171 | 0.667554 | kreczko |
43685654950843e8ca85131adee61782cc9fd832 | 674 | cpp | C++ | lang/C++/bitwise-operations.cpp | ethansaxenian/RosettaDecode | 8ea1a42a5f792280b50193ad47545d14ee371fb7 | [
"MIT"
] | 5 | 2021-01-29T20:08:05.000Z | 2022-03-22T06:16:05.000Z | lang/C++/bitwise-operations.cpp | ethansaxenian/RosettaDecode | 8ea1a42a5f792280b50193ad47545d14ee371fb7 | [
"MIT"
] | null | null | null | lang/C++/bitwise-operations.cpp | ethansaxenian/RosettaDecode | 8ea1a42a5f792280b50193ad47545d14ee371fb7 | [
"MIT"
] | 1 | 2021-04-13T04:19:31.000Z | 2021-04-13T04:19:31.000Z | #include <iostream>
void bitwise(int a, int b)
{
std::cout << "a and b: " << (a & b) << '\n'; // Note: parentheses are needed because & has lower precedence than <<
std::cout << "a or b: " << (a | b) << '\n';
std::cout << "a xor b: " << (a ^ b) << '\n';
std::cout << "not a: " << ~a << '\n';
std::cout << "a shl b: " << (a << b) << '\n'; // Note: "<<" is used both for output and for left shift
std::cout << "a shr b: " << (a >> b) << '\n'; // typically arithmetic right shift, but not guaranteed
unsigned int c = a;
std::cout << "c sra b: " << (c >> b) << '\n'; // logical right shift (guaranteed)
// there are no rotation operators in C++
}
| 44.933333 | 118 | 0.507418 | ethansaxenian |
43698c61e904273cdc874f57de12dc71b512feaa | 6,145 | cc | C++ | client/appsensorapi/handlermanager_unittest.cc | zamorajavi/google-input-tools | fc9f11d80d957560f7accf85a5fc27dd23625f70 | [
"Apache-2.0"
] | 175 | 2015-01-01T12:40:33.000Z | 2019-05-24T22:33:59.000Z | client/appsensorapi/handlermanager_unittest.cc | zamorajavi/google-input-tools | fc9f11d80d957560f7accf85a5fc27dd23625f70 | [
"Apache-2.0"
] | 11 | 2015-01-19T16:30:56.000Z | 2018-04-25T01:06:52.000Z | client/appsensorapi/handlermanager_unittest.cc | zamorajavi/google-input-tools | fc9f11d80d957560f7accf85a5fc27dd23625f70 | [
"Apache-2.0"
] | 97 | 2015-01-19T15:35:29.000Z | 2019-05-15T05:48:02.000Z | /*
Copyright 2014 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "appsensorapi/handlermanager.h"
#include <gtest/gunit.h>
#include "appsensorapi/handler.h"
#include "appsensorapi/versionreader.h"
using ime_goopy::HandlerManager;
using ime_goopy::VersionInfo;
using ime_goopy::Handler;
namespace {
const int kNumHandlers = 20;
// Customize the handler with special rules to validate if the rules are
// invoked.
class CustomHandler : public Handler {
public:
explicit CustomHandler(size_t size) : Handler() {
version_info_.file_size = size;
}
// Validate if the method is invoked by whether data is null.
BOOL HandleCommand(uint32 command, void *data) const {
return data != NULL;
}
// Validate if the method is invoked by whether wparam is zero.
LRESULT HandleMessage(HWND hwnd,
UINT message,
WPARAM wparam,
LPARAM lparam) const {
return wparam != 0;
}
private:
DISALLOW_EVIL_CONSTRUCTORS(CustomHandler);
};
class HandlerManagerTest : public testing::Test {
protected:
void SetUp() {
handler_manager_.reset(new HandlerManager());
for (int i = 0; i < arraysize(handler_); i++) {
handler_[i] = NULL;
}
}
void TearDown() {
for (int i = 0; i < arraysize(handler_); i++) {
delete handler_[i];
handler_[i] = NULL;
}
}
// Create an array of handlers with specified size. They are used to
// validate the logic of HandlerManager.
void PrepareData() {
for (int i = 0; i < arraysize(handler_); i++) {
handler_[i] = new CustomHandler(1000 * (i + 1));
ASSERT_TRUE(handler_manager_->AddHandler(handler_[i]));
}
ASSERT_EQ(arraysize(handler_), handler_manager_->GetCount());
}
scoped_ptr<HandlerManager> handler_manager_;
CustomHandler *handler_[kNumHandlers];
};
TEST_F(HandlerManagerTest, AddHandler) {
// Prepare handler instances.
for (int i = 0; i < arraysize(handler_); i++) {
handler_[i] = new CustomHandler(1000 * (i + 1));
}
// Add the handlers and validate its success.
for (int i = 0; i < arraysize(handler_); i++) {
EXPECT_TRUE(handler_manager_->AddHandler(handler_[i]));
EXPECT_EQ(i + 1, handler_manager_->GetCount());
}
// Add the same handlers, should be failed and the number of handlers
// should not be changed.
for (int i = 0; i < arraysize(handler_); i++) {
EXPECT_FALSE(handler_manager_->AddHandler(handler_[i]));
EXPECT_EQ(arraysize(handler_), handler_manager_->GetCount());
}
}
TEST_F(HandlerManagerTest, RemoveHandler) {
// Prepare the handlers array.
PrepareData();
// Remove each handler and validate the number of handlers is
// decreasing.
for (int i = 0; i < arraysize(handler_); i++) {
EXPECT_TRUE(handler_manager_->RemoveHandler(handler_[i]));
EXPECT_EQ(arraysize(handler_) - i - 1,
handler_manager_->GetCount());
}
// Try to remove again, should not be able to removed.
for (int i = 0; i < arraysize(handler_); i++) {
EXPECT_FALSE(handler_manager_->RemoveHandler(handler_[i]));
}
EXPECT_EQ(0, handler_manager_->GetCount());
}
TEST_F(HandlerManagerTest, GetHandlerBySize) {
// Prepare the handlers array.
PrepareData();
// Validate all handlers are obtained by their sizes.
for (int i = 0; i < arraysize(handler_); i++) {
const Handler *handler = handler_manager_->GetHandlerBySize(
handler_[i]->version_info()->file_size);
ASSERT_TRUE(handler != NULL);
EXPECT_EQ(handler_[i]->version_info()->file_size,
handler->version_info()->file_size);
}
// Try to remove each handler, then validate the failure of the method.
for (int i = 0; i < arraysize(handler_); i++) {
ASSERT_TRUE(handler_manager_->RemoveHandler(handler_[i]));
EXPECT_TRUE(handler_manager_->GetHandlerBySize(
handler_[i]->version_info()->file_size) == NULL);
}
}
TEST_F(HandlerManagerTest, GetHandlerByInfo) {
// Prepare the handlers array.
PrepareData();
// Validate all handlers are obtained by their info.
for (int i = 0; i < arraysize(handler_); i++) {
const Handler *handler = handler_manager_->GetHandlerByInfo(
*handler_[i]->version_info());
ASSERT_TRUE(handler != NULL);
EXPECT_EQ(handler_[i]->version_info()->file_size,
handler->version_info()->file_size);
}
// Try to remove each handler, then validate the failure of the method.
for (int i = 0; i < arraysize(handler_); i++) {
ASSERT_TRUE(handler_manager_->RemoveHandler(handler_[i]));
EXPECT_TRUE(handler_manager_->GetHandlerByInfo(
*handler_[i]->version_info()) == NULL);
}
}
TEST_F(HandlerManagerTest, HandleCommand) {
PrepareData();
// Validate the customized rule is invoked.
// The rule is based on the assume:
// data = non-null -> return true
// null -> return false
EXPECT_TRUE(handler_manager_->HandleCommand(
*handler_[0]->version_info(), 1, "Not Null"));
EXPECT_FALSE(handler_manager_->HandleCommand(
*handler_[0]->version_info(), 1, NULL));
}
TEST_F(HandlerManagerTest, HandleMessage) {
PrepareData();
// Validate the customized rule is invoked.
// The rule is based on the assume:
// wparam = non-zero -> return true
// zero -> return false
EXPECT_TRUE(handler_manager_->HandleMessage(
*handler_[0]->version_info(), NULL, WM_USER, 1, 0));
EXPECT_FALSE(handler_manager_->HandleMessage(
*handler_[0]->version_info(), NULL, WM_USER, 0, 0));
}
} // namespace
int main(int argc, char *argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 31.675258 | 74 | 0.678438 | zamorajavi |
436e7faa816efb828719d2e5174d8dc74b5b13a6 | 1,152 | cpp | C++ | src/pipeline/node/EdgeDetector.cpp | SpectacularAI/depthai-core | 7516ca0d179c5f0769ecdab0020ac3a6de09cab9 | [
"MIT"
] | 112 | 2020-09-05T01:56:31.000Z | 2022-03-27T15:20:07.000Z | src/pipeline/node/EdgeDetector.cpp | SpectacularAI/depthai-core | 7516ca0d179c5f0769ecdab0020ac3a6de09cab9 | [
"MIT"
] | 226 | 2020-06-12T11:14:17.000Z | 2022-03-31T13:32:36.000Z | src/pipeline/node/EdgeDetector.cpp | SpectacularAI/depthai-core | 7516ca0d179c5f0769ecdab0020ac3a6de09cab9 | [
"MIT"
] | 66 | 2020-09-06T03:22:27.000Z | 2022-03-30T09:01:29.000Z | #include "depthai/pipeline/node/EdgeDetector.hpp"
#include "spdlog/fmt/fmt.h"
namespace dai {
namespace node {
EdgeDetector::EdgeDetector(const std::shared_ptr<PipelineImpl>& par, int64_t nodeId)
: Node(par, nodeId), rawConfig(std::make_shared<RawEdgeDetectorConfig>()), initialConfig(rawConfig) {
inputs = {&inputConfig, &inputImage};
outputs = {&outputImage, &passthroughInputImage};
}
std::string EdgeDetector::getName() const {
return "EdgeDetector";
}
nlohmann::json EdgeDetector::getProperties() {
nlohmann::json j;
properties.initialConfig = *rawConfig;
nlohmann::to_json(j, properties);
return j;
}
// Node properties configuration
void EdgeDetector::setWaitForConfigInput(bool wait) {
properties.inputConfigSync = wait;
}
void EdgeDetector::setNumFramesPool(int numFramesPool) {
properties.numFramesPool = numFramesPool;
}
void EdgeDetector::setMaxOutputFrameSize(int maxFrameSize) {
properties.outputFrameSize = maxFrameSize;
}
std::shared_ptr<Node> EdgeDetector::clone() {
return std::make_shared<std::decay<decltype(*this)>::type>(*this);
}
} // namespace node
} // namespace dai
| 26.181818 | 105 | 0.736111 | SpectacularAI |
436f3a23d1836199dbd9bb42f3e3185a747865dc | 16,867 | cpp | C++ | libs/crpropa/src/Variant.cpp | carmeloevoli/hecr_diffusion | 0b23fd102de391f37a11c6a27f4f69c8ac172fcd | [
"MIT"
] | 2 | 2019-05-02T10:15:41.000Z | 2021-04-06T10:08:54.000Z | libs/crpropa/src/Variant.cpp | carmeloevoli/hecr_diffusion | 0b23fd102de391f37a11c6a27f4f69c8ac172fcd | [
"MIT"
] | null | null | null | libs/crpropa/src/Variant.cpp | carmeloevoli/hecr_diffusion | 0b23fd102de391f37a11c6a27f4f69c8ac172fcd | [
"MIT"
] | 1 | 2019-05-01T15:15:51.000Z | 2019-05-01T15:15:51.000Z | //-------------------------------------------------------------
// Based on Variant.cc in the Physics eXtension Library (PXL) -
// http://vispa.physik.rwth-aachen.de/ -
// Licensed under a LGPL-2 or later license -
//-------------------------------------------------------------
#include "crpropa/Variant.h"
#include <algorithm>
namespace crpropa
{
Variant::Variant() :
type(TYPE_NONE)
{
}
Variant::~Variant()
{
clear();
}
Variant::Variant(const Variant& a) :
type(TYPE_NONE)
{
copy(a);
}
Variant::Variant(const char *s)
{
data._String = new std::string(s);
type = TYPE_STRING;
}
void Variant::clear()
{
if (type == TYPE_STRING)
{
if(data._String)
{
delete data._String;
data._String = NULL;
}
}
type = TYPE_NONE;
}
void Variant::check(const Type t) const
{
if (type != t)
throw bad_conversion(type, t);
}
void Variant::check(const Type t)
{
if (type == TYPE_NONE)
{
std::memset(&data, 0, sizeof(data));
switch (t)
{
case TYPE_STRING:
data._String = new std::string;
break;
default:
break;
}
type = t;
}
else if (type != t)
{
throw bad_conversion(type, t);
}
}
const std::type_info& Variant::getTypeInfo() const
{
if (type == TYPE_BOOL)
{
const std::type_info &ti = typeid(data._Bool);
return ti;
}
else if (type == TYPE_CHAR)
{
const std::type_info &ti = typeid(data._Char);
return ti;
}
else if (type == TYPE_UCHAR)
{
const std::type_info &ti = typeid(data._UChar);
return ti;
}
else if (type == TYPE_INT16)
{
const std::type_info &ti = typeid(data._Int16);
return ti;
}
else if (type == TYPE_UINT16)
{
const std::type_info &ti = typeid(data._UInt16);
return ti;
}
else if (type == TYPE_INT32)
{
const std::type_info &ti = typeid(data._Int32);
return ti;
}
else if (type == TYPE_UINT32)
{
const std::type_info &ti = typeid(data._UInt32);
return ti;
}
else if (type == TYPE_INT64)
{
const std::type_info &ti = typeid(data._Int64);
return ti;
}
else if (type == TYPE_UINT64)
{
const std::type_info &ti = typeid(data._UInt64);
return ti;
}
else if (type == TYPE_FLOAT)
{
const std::type_info &ti = typeid(data._Float);
return ti;
}
else if (type == TYPE_DOUBLE)
{
const std::type_info &ti = typeid(data._Double);
return ti;
}
else if (type == TYPE_STRING)
{
const std::type_info &ti = typeid(*data._String);
return ti;
}
else
{
const std::type_info &ti = typeid(0);
return ti;
}
}
const char *Variant::getTypeName(Type type)
{
if (type == TYPE_NONE)
{
return "none";
}
else if (type == TYPE_BOOL)
{
return "bool";
}
else if (type == TYPE_CHAR)
{
return "char";
}
else if (type == TYPE_UCHAR)
{
return "uchar";
}
else if (type == TYPE_INT16)
{
return "int16";
}
else if (type == TYPE_UINT16)
{
return "uint16";
}
else if (type == TYPE_INT32)
{
return "int32";
}
else if (type == TYPE_UINT32)
{
return "uint32";
}
else if (type == TYPE_INT64)
{
return "int64";
}
else if (type == TYPE_UINT64)
{
return "uint64";
}
else if (type == TYPE_FLOAT)
{
return "float";
}
else if (type == TYPE_DOUBLE)
{
return "double";
}
else if (type == TYPE_STRING)
{
return "string";
}
else
{
return "unknown";
}
}
Variant::Type Variant::toType(const std::string &name)
{
if (name == "none")
{
return TYPE_NONE;
}
else if (name == "bool")
{
return TYPE_BOOL;
}
else if (name == "char")
{
return TYPE_CHAR;
}
else if (name == "uchar")
{
return TYPE_UCHAR;
}
else if (name == "int16")
{
return TYPE_INT16;
}
else if (name == "uint16")
{
return TYPE_UINT16;
}
else if (name == "int32")
{
return TYPE_INT32;
}
else if (name == "uint32")
{
return TYPE_UINT32;
}
else if (name == "int64")
{
return TYPE_INT64;
}
else if (name == "uint64")
{
return TYPE_UINT64;
}
else if (name == "float")
{
return TYPE_FLOAT;
}
else if (name == "double")
{
return TYPE_DOUBLE;
}
else if (name == "string")
{
return TYPE_STRING;
}
else
{
return TYPE_NONE;
}
}
bool Variant::operator ==(const Variant &a) const
{
if (type != a.type)
return false;
if (type == TYPE_BOOL)
{
return (data._Bool == a.data._Bool);
}
else if (type == TYPE_CHAR)
{
return (data._Char == a.data._Char);
}
else if (type == TYPE_UCHAR)
{
return (data._UChar == a.data._UChar);
}
else if (type == TYPE_INT16)
{
return (data._Int16 == a.data._Int16);
}
else if (type == TYPE_UINT16)
{
return (data._UInt16 == a.data._UInt16);
}
else if (type == TYPE_INT32)
{
return (data._Int32 == a.data._Int32);
}
else if (type == TYPE_UINT32)
{
return (data._UInt32 == a.data._UInt32);
}
else if (type == TYPE_INT64)
{
return (data._Int64 == a.data._Int64);
}
else if (type == TYPE_UINT64)
{
return (data._UInt64 == a.data._UInt64);
}
else if (type == TYPE_FLOAT)
{
return (data._Float == a.data._Float);
}
else if (type == TYPE_DOUBLE)
{
return (data._Double == a.data._Double);
}
else if (type == TYPE_STRING)
{
return (*data._String == *a.data._String);
}
else
{
throw std::runtime_error("compare operator not implemented");
}
}
std::string Variant::toString() const
{
if (type == TYPE_STRING)
return *data._String;
std::stringstream sstr;
if (type == TYPE_BOOL)
{
sstr << data._Bool;
}
else if (type == TYPE_CHAR)
{
sstr << data._Char;
}
else if (type == TYPE_UCHAR)
{
sstr << data._UChar;
}
else if (type == TYPE_INT16)
{
sstr << data._Int16;
}
else if (type == TYPE_UINT16)
{
sstr << data._UInt16;
}
else if (type == TYPE_INT32)
{
sstr << data._Int32;
}
else if (type == TYPE_UINT32)
{
sstr << data._UInt32;
}
else if (type == TYPE_INT64)
{
sstr << data._Int64;
}
else if (type == TYPE_UINT64)
{
sstr << data._UInt64;
}
else if (type == TYPE_FLOAT)
{
sstr << std::scientific << data._Float;
}
else if (type == TYPE_DOUBLE)
{
sstr << std::scientific << data._Double;
}
return sstr.str();
}
Variant Variant::fromString(const std::string &str, Type type)
{
std::stringstream sstr(str);
switch (type)
{
case TYPE_BOOL:
{
std::string upperstr(str);
std::transform(upperstr.begin(), upperstr.end(), upperstr.begin(),
(int(*)(int))toupper);if
( upperstr == "YES")
return Variant(true);
else if (upperstr == "NO")
return Variant(false);
if (upperstr == "TRUE")
return Variant(true);
else if (upperstr == "FALSE")
return Variant(false);
if (upperstr == "1")
return Variant(true);
else if (upperstr == "0")
return Variant(false);
throw bad_conversion(type, TYPE_BOOL);
}
case TYPE_CHAR:
{
char c;
sstr >> c;
return Variant(c);
}
case TYPE_UCHAR:
{
unsigned char c;
sstr >> c;
return Variant(c);
}
case TYPE_INT16:
{
int16_t c;
sstr >> c;
return Variant(c);
}
case TYPE_UINT16:
{
uint16_t c;
sstr >> c;
return Variant(c);
}
case TYPE_INT32:
{
int32_t c;
sstr >> c;
return Variant(c);
}
case TYPE_UINT32:
{
uint32_t c;
sstr >> c;
return Variant(c);
}
case TYPE_INT64:
{
int64_t c;
sstr >> c;
return Variant(c);
}
case TYPE_UINT64:
{
uint64_t c;
sstr >> c;
return Variant(c);
}
case TYPE_FLOAT:
{
float c;
sstr >> c;
return Variant(c);
}
case TYPE_DOUBLE:
{
double c;
sstr >> c;
return Variant(c);
}
case TYPE_STRING:
{
return Variant(str);
}
default:
throw std::runtime_error("pxl::Variant::fromString: unknown type");
}
}
bool Variant::operator !=(const Variant &a) const
{
if (type != a.type)
return true;
switch (type)
{
case TYPE_BOOL:
return (data._Bool != a.data._Bool);
case TYPE_CHAR:
return (data._Char != a.data._Char);
case TYPE_UCHAR:
return (data._UChar != a.data._UChar);
case TYPE_INT16:
return (data._Int16 != a.data._Int16);
case TYPE_UINT16:
return (data._UInt16 == a.data._UInt16);
case TYPE_INT32:
return (data._Int32 == a.data._Int32);
case TYPE_UINT32:
return (data._UInt32 == a.data._UInt32);
case TYPE_INT64:
return (data._Int64 == a.data._Int64);
case TYPE_UINT64:
return (data._UInt64 == a.data._UInt64);
case TYPE_FLOAT:
return (data._Float == a.data._Float);
case TYPE_DOUBLE:
return (data._Double == a.data._Double);
case TYPE_STRING:
return (*data._String == *a.data._String);
default:
throw std::runtime_error("compare operator not implemented");
}
}
void Variant::copy(const Variant &a)
{
Type t = a.type;
if (t == TYPE_BOOL)
{
operator =(a.data._Bool);
}
else if (t == TYPE_CHAR)
{
operator =(a.data._Char);
}
else if (t == TYPE_UCHAR)
{
operator =(a.data._UChar);
}
else if (t == TYPE_INT16)
{
operator =(a.data._Int16);
}
else if (t == TYPE_UINT16)
{
operator =(a.data._UInt16);
}
else if (t == TYPE_INT32)
{
operator =(a.data._Int32);
}
else if (t == TYPE_UINT32)
{
operator =(a.data._UInt32);
}
else if (t == TYPE_INT64)
{
operator =(a.data._Int64);
}
else if (t == TYPE_UINT64)
{
operator =(a.data._UInt64);
}
else if (t == TYPE_FLOAT)
{
operator =(a.data._Float);
}
else if (t == TYPE_DOUBLE)
{
operator =(a.data._Double);
}
else if (t == TYPE_STRING)
{
operator =(*a.data._String);
}
else
{
type = TYPE_NONE;
}
}
bool Variant::toBool() const
{
switch (type)
{
case TYPE_BOOL:
return data._Bool;
break;
case TYPE_CHAR:
return data._Char != 0;
break;
case TYPE_UCHAR:
return data._UChar != 0;
break;
case TYPE_INT16:
return data._Int16 != 0;
break;
case TYPE_UINT16:
return data._UInt16 != 0;
break;
case TYPE_INT32:
return data._Int32 != 0;
break;
case TYPE_UINT32:
return data._UInt32 != 0;
break;
case TYPE_INT64:
return data._Int64 != 0;
break;
case TYPE_UINT64:
return data._UInt64 != 0;
break;
case TYPE_STRING:
{
std::string upperstr(*data._String);
std::transform(upperstr.begin(), upperstr.end(), upperstr.begin(),
(int(*)(int))toupper);if
( upperstr == "YES")
return true;
else if (upperstr == "NO")
return false;
if (upperstr == "TRUE")
return true;
else if (upperstr == "FALSE")
return false;
if (upperstr == "1")
return true;
else if (upperstr == "0")
return false;
else
throw bad_conversion(type, TYPE_BOOL);
}
break;
case TYPE_FLOAT:
case TYPE_DOUBLE:
case TYPE_NONE:
throw bad_conversion(type, TYPE_BOOL);
break;
}
return false;
}
#define INT_CASE(from_var, from_type, to_type, to) \
case Variant::from_type:\
if (data._##from_var < std::numeric_limits<to>::min() || data._##from_var > std::numeric_limits<to>::max())\
throw bad_conversion(type, to_type);\
else\
return static_cast<to>(data._##from_var);\
break;\
#define INT_FUNCTION(to_type, fun, to) \
to Variant::fun() const { \
switch (type) { \
case Variant::TYPE_BOOL: \
return data._Bool ? 1 : 0; \
break; \
INT_CASE(Char, TYPE_CHAR, to_type, to) \
INT_CASE(UChar, TYPE_UCHAR, to_type, to) \
INT_CASE(Int16, TYPE_INT16, to_type, to) \
INT_CASE(UInt16, TYPE_UINT16, to_type, to) \
INT_CASE(Int32, TYPE_INT32, to_type, to) \
INT_CASE(UInt32, TYPE_UINT32, to_type, to) \
INT_CASE(Int64, TYPE_INT64, to_type, to) \
INT_CASE(UInt64, TYPE_UINT64, to_type, to) \
INT_CASE(Float, TYPE_FLOAT, to_type, to) \
INT_CASE(Double, TYPE_DOUBLE, to_type, to) \
case Variant::TYPE_STRING: \
{ \
long l = atol(data._String->c_str()); \
if (l < std::numeric_limits<to>::min() || l > std::numeric_limits<to>::max()) \
throw bad_conversion(type, to_type); \
else \
return l; \
} \
break; \
case Variant::TYPE_NONE: \
throw bad_conversion(type, TYPE_INT16); \
break;\
}\
return 0;\
}
INT_FUNCTION( TYPE_CHAR, toChar, char)
INT_FUNCTION( TYPE_UCHAR, toUChar, unsigned char)
INT_FUNCTION( TYPE_INT16, toInt16, int16_t)
INT_FUNCTION( TYPE_UINT16, toUInt16, uint16_t)
INT_FUNCTION( TYPE_INT32, toInt32, int32_t)
INT_FUNCTION( TYPE_UINT32, toUInt32, uint32_t)
INT_FUNCTION( TYPE_INT64, toInt64, int64_t)
INT_FUNCTION( TYPE_UINT64, toUInt64, uint64_t)
std::ostream& operator <<(std::ostream& os, const Variant &v)
{
switch (v.getType())
{
case Variant::TYPE_BOOL:
os << v.asBool();
break;
case Variant::TYPE_CHAR:
os << v.asChar();
break;
case Variant::TYPE_UCHAR:
os << v.asUChar();
break;
case Variant::TYPE_INT16:
os << v.asInt16();
break;
case Variant::TYPE_UINT16:
os << v.asUInt16();
break;
case Variant::TYPE_INT32:
os << v.asInt32();
break;
case Variant::TYPE_UINT32:
os << v.asUInt32();
break;
case Variant::TYPE_INT64:
os << v.asInt64();
break;
case Variant::TYPE_UINT64:
os << v.asUInt64();
break;
case Variant::TYPE_FLOAT:
os << v.asFloat();
break;
case Variant::TYPE_DOUBLE:
os << v.asDouble();
break;
case Variant::TYPE_STRING:
os << v.asString();
break;
default:
break;
}
return os;
}
float Variant::toFloat() const
{
if (type == TYPE_CHAR)
{
return static_cast<float>(data._Char);
}
else if (type == TYPE_UCHAR)
{
return static_cast<float>(data._UChar);
}
else if (type == TYPE_INT16)
{
return static_cast<float>(data._Int16);
}
else if (type == TYPE_UINT16)
{
return static_cast<float>(data._UInt16);
}
else if (type == TYPE_INT32)
{
return static_cast<float>(data._Int32);
}
else if (type == TYPE_UINT32)
{
return static_cast<float>(data._UInt32);
}
else if (type == TYPE_INT64)
{
return static_cast<float>(data._Int64);
}
else if (type == TYPE_UINT64)
{
return static_cast<float>(data._UInt64);
}
else if (type == TYPE_FLOAT)
{
return static_cast<float>(data._Float);
}
else if (type == TYPE_DOUBLE)
{
return static_cast<float>(data._Double);
}
else if (type == TYPE_STRING)
{
return static_cast<float>(std::atof(data._String->c_str()));
}
else if (type == TYPE_BOOL)
{
return data._Bool ? 1.0f : 0.0f;
}
else
{
return 0.0;
}
}
double Variant::toDouble() const
{
if (type == TYPE_CHAR)
{
return static_cast<double>(data._Char);
}
else if (type == TYPE_UCHAR)
{
return static_cast<double>(data._UChar);
}
else if (type == TYPE_INT16)
{
return static_cast<double>(data._Int16);
}
else if (type == TYPE_UINT16)
{
return static_cast<double>(data._UInt16);
}
else if (type == TYPE_INT32)
{
return static_cast<double>(data._Int32);
}
else if (type == TYPE_UINT32)
{
return static_cast<double>(data._UInt32);
}
else if (type == TYPE_INT64)
{
return static_cast<double>(data._Int64);
}
else if (type == TYPE_UINT64)
{
return static_cast<double>(data._UInt64);
}
else if (type == TYPE_FLOAT)
{
return static_cast<double>(data._Float);
}
else if (type == TYPE_DOUBLE)
{
return static_cast<double>(data._Double);
}
else if (type == TYPE_STRING)
{
return std::atof(data._String->c_str());
}
else if (type == TYPE_BOOL)
{
return data._Bool ? 1.0 : 0.0;
}
else
{
return 0.0;
}
}
#define MEMCPYRET(VAR) \
memcpy(buffer, &VAR, sizeof( VAR) );\
return sizeof( VAR );
size_t Variant::copyToBuffer(void* buffer)
{
if (type == TYPE_CHAR)
{
MEMCPYRET( data._Char )
}
else if (type == TYPE_UCHAR)
{
MEMCPYRET( data._UChar )
}
else if (type == TYPE_INT16)
{
MEMCPYRET(data._Int16);
}
else if (type == TYPE_UINT16)
{
MEMCPYRET(data._UInt16);
}
else if (type == TYPE_INT32)
{
MEMCPYRET(data._Int32);
}
else if (type == TYPE_UINT32)
{
MEMCPYRET(data._UInt32);
}
else if (type == TYPE_INT64)
{
MEMCPYRET(data._Int64);
}
else if (type == TYPE_UINT64)
{
MEMCPYRET(data._UInt64);
}
else if (type == TYPE_FLOAT)
{
MEMCPYRET(data._Float);
}
else if (type == TYPE_DOUBLE)
{
MEMCPYRET(data._Double);
}
else if (type == TYPE_STRING)
{
size_t len = data._String->size();
memcpy(buffer, data._String->c_str(), len);
return len;
}
else if (type == TYPE_BOOL)
{
MEMCPYRET(data._Bool);
}
else if (type == TYPE_NONE)
{
return 0;
}
throw std::runtime_error("This is serious: Type not handled in copyToBuffer()!");
};
size_t Variant::getSize() const
{
if (type == TYPE_CHAR)
{
return sizeof(data._Char);
}
else if (type == TYPE_UCHAR)
{
return sizeof(data._UChar);
}
else if (type == TYPE_INT16)
{
return sizeof(data._Int16);
}
else if (type == TYPE_UINT16)
{
return sizeof(data._UInt16);
}
else if (type == TYPE_INT32)
{
return sizeof(data._Int32);
}
else if (type == TYPE_UINT32)
{
return sizeof(data._UInt32);
}
else if (type == TYPE_INT64)
{
return sizeof(data._Int64);
}
else if (type == TYPE_UINT64)
{
return sizeof(data._UInt64);
}
else if (type == TYPE_FLOAT)
{
return sizeof(data._Float);
}
else if (type == TYPE_DOUBLE)
{
return sizeof(data._Double);
}
else if (type == TYPE_STRING)
{
size_t len = strlen(data._String->c_str()+1);
return len;
}
else if (type == TYPE_BOOL)
{
return sizeof(data._Bool);
}
else if (type == TYPE_NONE)
{
return 0;
}
throw std::runtime_error("This is serious: Type not handled in getSize()!");
};
} // namespace pxl
| 17.515057 | 110 | 0.630699 | carmeloevoli |
4370630b80632664eaa5738c62caa6c199609e2e | 26,711 | hpp | C++ | include/RAJA/policy/tensor/arch/cuda/cuda_warp.hpp | andrewcorrigan/RAJA | a326fad43321eadaebf75cb264461d3889ee6942 | [
"BSD-3-Clause"
] | null | null | null | include/RAJA/policy/tensor/arch/cuda/cuda_warp.hpp | andrewcorrigan/RAJA | a326fad43321eadaebf75cb264461d3889ee6942 | [
"BSD-3-Clause"
] | null | null | null | include/RAJA/policy/tensor/arch/cuda/cuda_warp.hpp | andrewcorrigan/RAJA | a326fad43321eadaebf75cb264461d3889ee6942 | [
"BSD-3-Clause"
] | null | null | null | /*!
******************************************************************************
*
* \file
*
* \brief Header file containing SIMT distrubuted register abstractions for
* CUDA
*
******************************************************************************
*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Copyright (c) 2016-22, Lawrence Livermore National Security, LLC
// and RAJA project contributors. See the RAJA/LICENSE file for details.
//
// SPDX-License-Identifier: (BSD-3-Clause)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
#include "RAJA/config.hpp"
#include "RAJA/util/macros.hpp"
#include "RAJA/pattern/tensor/internal/RegisterBase.hpp"
#include "RAJA/util/macros.hpp"
#include "RAJA/util/Operators.hpp"
#ifdef RAJA_ENABLE_CUDA
#include "RAJA/policy/cuda/reduce.hpp"
#ifndef RAJA_policy_tensor_arch_cuda_cuda_warp_register_HPP
#define RAJA_policy_tensor_arch_cuda_cuda_warp_register_HPP
namespace RAJA
{
namespace expt
{
template<typename ELEMENT_TYPE>
class Register<ELEMENT_TYPE, cuda_warp_register> :
public internal::expt::RegisterBase<Register<ELEMENT_TYPE, cuda_warp_register>>
{
public:
using base_type = internal::expt::RegisterBase<Register<ELEMENT_TYPE, cuda_warp_register>>;
using register_policy = cuda_warp_register;
using self_type = Register<ELEMENT_TYPE, cuda_warp_register>;
using element_type = ELEMENT_TYPE;
using register_type = ELEMENT_TYPE;
using int_vector_type = Register<int64_t, cuda_warp_register>;
private:
element_type m_value;
public:
static constexpr int s_num_elem = 32;
/*!
* @brief Default constructor, zeros register contents
*/
RAJA_INLINE
RAJA_DEVICE
constexpr
Register() : base_type(), m_value(0) {
}
/*!
* @brief Copy constructor from raw value
*/
RAJA_INLINE
RAJA_DEVICE
constexpr
Register(element_type c) : base_type(), m_value(c) {}
/*!
* @brief Copy constructor
*/
RAJA_INLINE
RAJA_DEVICE
constexpr
Register(self_type const &c) : base_type(), m_value(c.m_value) {}
/*!
* @brief Copy assignment operator
*/
RAJA_INLINE
RAJA_DEVICE
self_type &operator=(self_type const &c){
m_value = c.m_value;
return *this;
}
RAJA_INLINE
RAJA_DEVICE
self_type &operator=(element_type c){
m_value = c;
return *this;
}
/*!
* @brief Gets our warp lane
*/
RAJA_INLINE
RAJA_DEVICE
constexpr
static
int get_lane() {
return threadIdx.x;
}
RAJA_DEVICE
RAJA_INLINE
constexpr
element_type const &get_raw_value() const {
return m_value;
}
RAJA_DEVICE
RAJA_INLINE
element_type &get_raw_value() {
return m_value;
}
RAJA_DEVICE
RAJA_INLINE
static
constexpr
bool is_root() {
return get_lane() == 0;
}
/*!
* @brief Load a full register from a stride-one memory location
*
*/
RAJA_INLINE
RAJA_DEVICE
self_type &load_packed(element_type const *ptr){
auto lane = get_lane();
m_value = ptr[lane];
return *this;
}
/*!
* @brief Partially load a register from a stride-one memory location given
* a run-time number of elements.
*
*/
RAJA_INLINE
RAJA_DEVICE
self_type &load_packed_n(element_type const *ptr, int N){
auto lane = get_lane();
if(lane < N){
m_value = ptr[lane];
}
else{
m_value = element_type(0);
}
return *this;
}
/*!
* @brief Gather a full register from a strided memory location
*
*/
RAJA_INLINE
RAJA_DEVICE
self_type &load_strided(element_type const *ptr, int stride){
auto lane = get_lane();
m_value = ptr[stride*lane];
return *this;
}
/*!
* @brief Partially load a register from a stride-one memory location given
* a run-time number of elements.
*
*/
RAJA_INLINE
RAJA_DEVICE
self_type &load_strided_n(element_type const *ptr, int stride, int N){
auto lane = get_lane();
if(lane < N){
m_value = ptr[stride*lane];
}
else{
m_value = element_type(0);
}
return *this;
}
/*!
* @brief Generic gather operation for full vector.
*
* Must provide another register containing offsets of all values
* to be loaded relative to supplied pointer.
*
* Offsets are element-wise, not byte-wise.
*
*/
RAJA_INLINE
RAJA_DEVICE
self_type &gather(element_type const *ptr, int_vector_type offsets){
m_value = ptr[offsets.get_raw_value()];
return *this;
}
/*!
* @brief Generic gather operation for n-length subvector.
*
* Must provide another register containing offsets of all values
* to be loaded relative to supplied pointer.
*
* Offsets are element-wise, not byte-wise.
*
*/
RAJA_INLINE
RAJA_DEVICE
self_type &gather_n(element_type const *ptr, int_vector_type offsets, camp::idx_t N){
if(get_lane() < N){
m_value = ptr[offsets.get_raw_value()];
}
else{
m_value = element_type(0);
}
return *this;
}
/*!
* @brief Generic segmented load operation used for loading sub-matrices
* from larger arrays.
*
* The default operation combines the s_segmented_offsets and gather
* operations.
*
*
*/
RAJA_DEVICE
RAJA_INLINE
self_type &segmented_load(element_type const *ptr, camp::idx_t segbits, camp::idx_t stride_inner, camp::idx_t stride_outer){
auto lane = get_lane();
// compute segment and segment_size
auto seg = lane >> segbits;
auto i = lane & ((1<<segbits)-1);
m_value = ptr[seg*stride_outer + i*stride_inner];
return *this;
}
/*!
* @brief Generic segmented load operation used for loading sub-matrices
* from larger arrays where we load partial segments.
*
*
*
*/
RAJA_DEVICE
RAJA_INLINE
self_type &segmented_load_nm(element_type const *ptr, camp::idx_t segbits,
camp::idx_t stride_inner, camp::idx_t stride_outer,
camp::idx_t num_inner, camp::idx_t num_outer)
{
auto lane = get_lane();
// compute segment and segment_size
auto seg = lane >> segbits;
auto i = lane & ((1<<segbits)-1);
if(seg >= num_outer || i >= num_inner){
m_value = element_type(0);
}
else{
m_value = ptr[seg*stride_outer + i*stride_inner];
}
return *this;
}
/*!
* @brief Store entire register to consecutive memory locations
*
*/
RAJA_INLINE
RAJA_DEVICE
self_type const &store_packed(element_type *ptr) const{
auto lane = get_lane();
ptr[lane] = m_value;
return *this;
}
/*!
* @brief Store entire register to consecutive memory locations
*
*/
RAJA_INLINE
RAJA_DEVICE
self_type const &store_packed_n(element_type *ptr, int N) const{
auto lane = get_lane();
if(lane < N){
ptr[lane] = m_value;
}
return *this;
}
/*!
* @brief Store entire register to consecutive memory locations
*
*/
RAJA_INLINE
RAJA_DEVICE
self_type const &store_strided(element_type *ptr, int stride) const{
auto lane = get_lane();
ptr[lane*stride] = m_value;
return *this;
}
/*!
* @brief Store partial register to consecutive memory locations
*
*/
RAJA_INLINE
RAJA_DEVICE
self_type const &store_strided_n(element_type *ptr, int stride, int N) const{
auto lane = get_lane();
if(lane < N){
ptr[lane*stride] = m_value;
}
return *this;
}
/*!
* @brief Generic scatter operation for full vector.
*
* Must provide another register containing offsets of all values
* to be stored relative to supplied pointer.
*
* Offsets are element-wise, not byte-wise.
*
*/
template<typename T2>
RAJA_DEVICE
RAJA_INLINE
self_type const &scatter(element_type *ptr, T2 const &offsets) const {
ptr[offsets.get_raw_value()] = m_value;
return *this;
}
/*!
* @brief Generic scatter operation for n-length subvector.
*
* Must provide another register containing offsets of all values
* to be stored relative to supplied pointer.
*
* Offsets are element-wise, not byte-wise.
*
*/
template<typename T2>
RAJA_DEVICE
RAJA_INLINE
self_type const &scatter_n(element_type *ptr, T2 const &offsets, camp::idx_t N) const {
if(get_lane() < N){
ptr[offsets.get_raw_value()] = m_value;
}
return *this;
}
/*!
* @brief Generic segmented store operation used for storing sub-matrices
* to larger arrays.
*
*/
RAJA_DEVICE
RAJA_INLINE
self_type const &segmented_store(element_type *ptr, camp::idx_t segbits, camp::idx_t stride_inner, camp::idx_t stride_outer) const {
auto lane = get_lane();
// compute segment and segment_size
auto seg = lane >> segbits;
auto i = lane & ((1<<segbits)-1);
ptr[seg*stride_outer + i*stride_inner] = m_value;
return *this;
}
/*!
* @brief Generic segmented store operation used for storing sub-matrices
* to larger arrays where we store partial segments.
*
*/
RAJA_DEVICE
RAJA_INLINE
self_type const &segmented_store_nm(element_type *ptr, camp::idx_t segbits,
camp::idx_t stride_inner, camp::idx_t stride_outer,
camp::idx_t num_inner, camp::idx_t num_outer) const
{
auto lane = get_lane();
// compute segment and segment_size
auto seg = lane >> segbits;
auto i = lane & ((1<<segbits)-1);
if(seg >= num_outer || i >= num_inner){
// nop
}
else{
ptr[seg*stride_outer + i*stride_inner] = m_value;
}
return *this;
}
/*!
* @brief Get scalar value from vector register
* @param i Offset of scalar to get
* @return Returns scalar value at i
*/
constexpr
RAJA_INLINE
RAJA_DEVICE
element_type get(int i) const
{
return __shfl_sync(0xffffffff, m_value, i, 32);
}
/*!
* @brief Set scalar value in vector register
* @param i Offset of scalar to set
* @param value Value of scalar to set
*/
RAJA_INLINE
RAJA_DEVICE
self_type &set(element_type value, int i)
{
auto lane = get_lane();
if(lane == i){
m_value = value;
}
return *this;
}
RAJA_DEVICE
RAJA_INLINE
self_type &broadcast(element_type const &a){
m_value = a;
return *this;
}
/*!
* @brief Extracts a scalar value and broadcasts to a new register
*/
RAJA_DEVICE
RAJA_INLINE
self_type get_and_broadcast(int i) const {
self_type x;
x.m_value = __shfl_sync(0xffffffff, m_value, i, 32);
return x;
}
RAJA_DEVICE
RAJA_INLINE
self_type ©(self_type const &src){
m_value = src.m_value;
return *this;
}
RAJA_DEVICE
RAJA_INLINE
self_type add(self_type const &b) const {
return self_type(m_value + b.m_value);
}
RAJA_DEVICE
RAJA_INLINE
self_type subtract(self_type const &b) const {
return self_type(m_value - b.m_value);
}
RAJA_DEVICE
RAJA_INLINE
self_type multiply(self_type const &b) const {
return self_type(m_value * b.m_value);
}
RAJA_DEVICE
RAJA_INLINE
self_type divide(self_type const &b) const {
return self_type(m_value / b.m_value);
}
RAJA_DEVICE
RAJA_INLINE
self_type divide_n(self_type const &b, int N) const {
return get_lane() < N ? self_type(m_value / b.m_value) : self_type(element_type(0));
}
/**
* floats and doubles use the CUDA instrinsic FMA
*/
template<typename RETURN_TYPE = self_type>
RAJA_DEVICE
RAJA_INLINE
typename std::enable_if<!std::numeric_limits<element_type>::is_integer,
RETURN_TYPE>::type
multiply_add(self_type const &b, self_type const &c) const
{
return self_type(fma(m_value, b.m_value, c.m_value));
}
/**
* int32 and int64 don't have a CUDA intrinsic FMA, do unfused ops
*/
template<typename RETURN_TYPE = self_type>
RAJA_DEVICE
RAJA_INLINE
typename std::enable_if<std::numeric_limits<element_type>::is_integer,
RETURN_TYPE>::type
multiply_add(self_type const &b, self_type const &c) const
{
return self_type(m_value * b.m_value + c.m_value);
}
/**
* floats and doubles use the CUDA instrinsic FMS
*/
template<typename RETURN_TYPE = self_type>
RAJA_DEVICE
RAJA_INLINE
typename std::enable_if<!std::numeric_limits<element_type>::is_integer,
RETURN_TYPE>::type
multiply_subtract(self_type const &b, self_type const &c) const
{
return self_type(fma(m_value, b.m_value, -c.m_value));
}
/**
* int32 and int64 don't have a CUDA intrinsic FMS, do unfused ops
*/
template<typename RETURN_TYPE = self_type>
RAJA_DEVICE
RAJA_INLINE
typename std::enable_if<std::numeric_limits<element_type>::is_integer,
RETURN_TYPE>::type
multiply_subtract(self_type const &b, self_type const &c) const
{
return self_type(m_value * b.m_value - c.m_value);
}
/*!
* @brief Sum the elements of this vector
* @return Sum of the values of the vectors scalar elements
*/
RAJA_INLINE
RAJA_DEVICE
element_type sum() const
{
// Allreduce sum
using combiner_t = RAJA::reduce::detail::op_adapter<element_type, RAJA::operators::plus>;
return RAJA::cuda::impl::warp_allreduce<combiner_t, element_type>(m_value);
}
/*!
* @brief Returns the largest element
* @return The largest scalar element in the register
*/
RAJA_INLINE
RAJA_DEVICE
element_type max() const
{
// Allreduce maximum
using combiner_t = RAJA::reduce::detail::op_adapter<element_type, RAJA::operators::maximum>;
return RAJA::cuda::impl::warp_allreduce<combiner_t, element_type>(m_value);
}
/*!
* @brief Returns the largest element
* @return The largest scalar element in the register
*/
RAJA_INLINE
RAJA_DEVICE
element_type max_n(int N) const
{
// Allreduce maximum
using combiner_t = RAJA::reduce::detail::op_adapter<element_type, RAJA::operators::maximum>;
auto ident = RAJA::operators::limits<element_type>::min();
auto lane = get_lane();
auto value = lane < N ? m_value : ident;
return RAJA::cuda::impl::warp_allreduce<combiner_t, element_type>(value);
}
/*!
* @brief Returns element-wise largest values
* @return Vector of the element-wise max values
*/
RAJA_INLINE
RAJA_DEVICE
self_type vmax(self_type a) const
{
return self_type{RAJA::max<element_type>(m_value, a.m_value)};
}
/*!
* @brief Returns the largest element
* @return The largest scalar element in the register
*/
RAJA_INLINE
RAJA_DEVICE
element_type min() const
{
// Allreduce minimum
using combiner_t = RAJA::reduce::detail::op_adapter<element_type, RAJA::operators::minimum>;
return RAJA::cuda::impl::warp_allreduce<combiner_t, element_type>(m_value);
}
/*!
* @brief Returns the largest element from first N lanes
* @return The largest scalar element in the register
*/
RAJA_INLINE
RAJA_DEVICE
element_type min_n(int N) const
{
// Allreduce minimum
using combiner_t = RAJA::reduce::detail::op_adapter<element_type, RAJA::operators::minimum>;
auto ident = RAJA::operators::limits<element_type>::max();
auto lane = get_lane();
auto value = lane < N ? m_value : ident;
return RAJA::cuda::impl::warp_allreduce<combiner_t, element_type>(value);
}
/*!
* @brief Returns element-wise largest values
* @return Vector of the element-wise max values
*/
RAJA_INLINE
RAJA_DEVICE
self_type vmin(self_type a) const
{
return self_type{RAJA::min<element_type>(m_value, a.m_value)};
}
/*!
* Provides gather/scatter indices for segmented loads and stores
*
* THe number of segment bits (segbits) is specified, as well as the
* stride between elements in a segment (stride_inner),
* and the stride between segments (stride_outer)
*/
RAJA_INLINE
RAJA_DEVICE
static
int_vector_type s_segmented_offsets(camp::idx_t segbits, camp::idx_t stride_inner, camp::idx_t stride_outer)
{
int_vector_type result;
auto lane = get_lane();
// compute segment and segment_size
auto seg = lane >> segbits;
auto i = lane & ((1<<segbits)-1);
result.get_raw_value() = seg*stride_outer + i*stride_inner;
return result;
}
/*!
* Sum elements within each segment, with segment size defined by segbits.
* Stores each segments sum consecutively, but shifed to the
* corresponding output_segment slot.
*
* Note: segment size is 1<<segbits elements
* number of segments is s_num_elem>>seg_bits
*
*
*
*
* Example:
*
* Given input vector X = x0, x1, x2, x3, x4, x5, x6, x7
*
* segbits=0 is equivalent to the input vector, since there are 8
* outputs, there is only 1 output segment
*
* Result= x0, x1, x2, x3, x4, x5, x6, x7
*
* segbits=1 sums neighboring pairs of values. There are 4 output,
* so there are possible output segments.
*
* output_segment=0:
* Result= x0+x1, x2+x3, x4+x5, x6+x7, 0, 0, 0, 0
*
* output_segment=1:
* Result= 0, 0, 0, 0, x0+x1, x2+x3, x4+x5, x6+x7
*
* and so on up to segbits=3, which is a full sum of x0..x7, and the
* output_segment denotes the vector position of the sum
*
*/
RAJA_INLINE
RAJA_DEVICE
self_type segmented_sum_inner(camp::idx_t segbits, camp::idx_t output_segment) const
{
// First: tree reduce values within each segment
element_type x = m_value;
RAJA_UNROLL
for(int delta = 1;delta < 1<<segbits;delta = delta<<1){
// tree shuffle
element_type y = __shfl_sync(0xffffffff, x, get_lane()+delta);
// reduce
x += y;
}
// Second: send result to output segment lanes
self_type result;
result.get_raw_value() = __shfl_sync(0xffffffff, x, get_lane()<<segbits);
// Third: mask off everything but output_segment
// this is because all output segments are valid at this point
// (5-segbits), the 5 is since the warp-width is 32 == 1<<5
int our_output_segment = get_lane()>>(5-segbits);
bool in_output_segment = our_output_segment == output_segment;
if(!in_output_segment){
result.get_raw_value() = 0;
}
return result;
}
/*!
* Sum across segments, with segment size defined by segbits
*
* Note: segment size is 1<<segbits elements
* number of segments is s_num_elem>>seg_bits
*
*
*
*
* Example:
*
* Given input vector X = x0, x1, x2, x3, x4, x5, x6, x7
*
* segbits=0 is equivalent to the input vector, since there are 8
* outputs, there is only 1 output segment
*
* Result= x0, x1, x2, x3, x4, x5, x6, x7
*
* segbits=1 sums strided pairs of values. There are 4 output,
* so there are possible output segments.
*
* output_segment=0:
* Result= x0+x4, x1+x5, x2+x6, x3+x7, 0, 0, 0, 0
*
* output_segment=1:
* Result= 0, 0, 0, 0, x0+x4, x1+x5, x2+x6, x3+x7
*
* and so on up to segbits=3, which is a full sum of x0..x7, and the
* output_segment denotes the vector position of the sum
*
*/
RAJA_INLINE
RAJA_DEVICE
self_type segmented_sum_outer(camp::idx_t segbits, camp::idx_t output_segment) const
{
// First: tree reduce values within each segment
element_type x = m_value;
RAJA_UNROLL
for(int i = 0;i < 5-segbits; ++ i){
// tree shuffle
int delta = s_num_elem >> (i+1);
element_type y = __shfl_sync(0xffffffff, x, get_lane()+delta);
// reduce
x += y;
}
// Second: send result to output segment lanes
self_type result;
int get_from = get_lane()&( (1<<segbits)-1);
result.get_raw_value() = __shfl_sync(0xffffffff, x, get_from);
int mask = (get_lane()>>segbits) == output_segment;
// Third: mask off everything but output_segment
if(!mask){
result.get_raw_value() = 0;
}
return result;
}
RAJA_INLINE
RAJA_DEVICE
self_type segmented_divide_nm(self_type den, camp::idx_t segbits, camp::idx_t num_inner, camp::idx_t num_outer) const
{
self_type result;
auto lane = get_lane();
// compute segment and segment_size
auto seg = lane >> segbits;
auto i = lane & ((1<<segbits)-1);
if(seg >= num_outer || i >= num_inner){
// nop
}
else{
result.get_raw_value() = m_value / den.get_raw_value();
}
return result;
}
/*!
* Segmented broadcast copies a segment to all output segments of a vector
*
* Note: segment size is 1<<segbits elements
* number of segments is s_num_elem>>seg_bits
*
*
* Example:
*
* Given input vector X = x0, x1, x2, x3, x4, x5, x6, x7
*
* segbits=0 means the input segment size is 1, so this selects the
* value at x[input_segmnet] and broadcasts it to the rest of the
* vector
*
* input segments allowed are from 0 to 7, inclusive
*
* input_segment=0
* Result= x0, x0, x0, x0, x0, x0, x0, x0
*
* input_segment=5
* Result= x5, x5, x5, x5, x5, x5, x5, x5
*
* segbits=1 means that the input segments are each pair of x values:
*
* input segments allowed are from 0 to 3, inclusive
*
* output_segment=0:
* Result= x0, x1, x0, x1, x0, x1, x0, x1
*
* output_segment=1:
* Result= x2, x3, x2, x3, x2, x3, x2, x3
*
* output_segment=3:
* Result= x6, x7, x6, x7, x6, x7, x6, x7
*
* and so on up to segbits=2, the input segments are 4 wide:
*
* input segments allowed are from 0 or 1
*
* output_segment=0:
* Result= x0, x1, x2, x3, x0, x1, x2, x3
*
* output_segment=1:
* Result= x4, x5, x6, x7, x4, x5, x6, x7
*
*/
RAJA_INLINE
RAJA_DEVICE
self_type segmented_broadcast_inner(camp::idx_t segbits, camp::idx_t input_segment) const
{
self_type result;
camp::idx_t mask = (1<<segbits)-1;
camp::idx_t offset = input_segment << segbits;
camp::idx_t i = (get_lane()&mask) + offset;
result.get_raw_value() = __shfl_sync(0xffffffff, m_value, i);
return result;
}
/*!
* Segmented broadcast spreads a segment to all output segments of a vector
*
* Note: segment size is 1<<segbits elements
* number of segments is s_num_elem>>seg_bits
*
*
* Example:
*
* Given input vector X = x0, x1, x2, x3, x4, x5, x6, x7
*
* segbits=0 means the input segment size is 1, so this selects the
* value at x[input_segmnet] and broadcasts it to the rest of the
* vector
*
* input segments allowed are from 0 to 7, inclusive
*
* input_segment=0
* Result= x0, x0, x0, x0, x0, x0, x0, x0
*
* input_segment=5
* Result= x5, x5, x5, x5, x5, x5, x5, x5
*
* segbits=1 means that the input segments are each pair of x values:
*
* input segments allowed are from 0 to 3, inclusive
*
* output_segment=0:
* Result= x0, x0, x0, x0, x1, x1, x1, x1
*
* output_segment=1:
* Result= x2, x2, x2, x2, x3, x3, x3, x3
*
* output_segment=3:
* Result= x6, x6, x6, x6, x7, x7, x7, x7
*/
RAJA_INLINE
RAJA_DEVICE
self_type segmented_broadcast_outer(camp::idx_t segbits, camp::idx_t input_segment) const
{
self_type result;
camp::idx_t offset = input_segment * (self_type::s_num_elem >> segbits);
camp::idx_t i = (get_lane() >> segbits) + offset;
result.get_raw_value() = __shfl_sync(0xffffffff, m_value, i);
return result;
}
};
} // namespace expt
} // namespace RAJA
#endif // Guard
#endif // CUDA
| 26.420376 | 138 | 0.565759 | andrewcorrigan |
4370e2b3f90fcc1782fc4a044ecf2467be47550e | 19,250 | hpp | C++ | include/libpmemobj++/container/array.hpp | sanjay-cpu/libpmemobj-cpp | 12c98c1d7a3780ca37c96fcc8124c720887066d0 | [
"BSD-3-Clause"
] | null | null | null | include/libpmemobj++/container/array.hpp | sanjay-cpu/libpmemobj-cpp | 12c98c1d7a3780ca37c96fcc8124c720887066d0 | [
"BSD-3-Clause"
] | null | null | null | include/libpmemobj++/container/array.hpp | sanjay-cpu/libpmemobj-cpp | 12c98c1d7a3780ca37c96fcc8124c720887066d0 | [
"BSD-3-Clause"
] | null | null | null | // SPDX-License-Identifier: BSD-3-Clause
/* Copyright 2018-2020, Intel Corporation */
/**
* @file
* Array container with std::array compatible interface.
*/
#ifndef LIBPMEMOBJ_CPP_ARRAY_HPP
#define LIBPMEMOBJ_CPP_ARRAY_HPP
#include <algorithm>
#include <functional>
#include <libpmemobj++/container/detail/contiguous_iterator.hpp>
#include <libpmemobj++/detail/common.hpp>
#include <libpmemobj++/persistent_ptr.hpp>
#include <libpmemobj++/pext.hpp>
#include <libpmemobj++/slice.hpp>
#include <libpmemobj++/transaction.hpp>
#include <libpmemobj++/utils.hpp>
#include <libpmemobj/base.h>
namespace pmem
{
namespace obj
{
/**
* pmem::obj::array - persistent container with std::array compatible interface.
*
* pmem::obj::array can only be stored on pmem. Creating array on
* stack will result with "pool_error" exception.
*
* All methods which allow write access to specific element will add it to an
* active transaction.
*
* All methods which return non-const pointer to raw data add entire array
* to a transaction.
*
* When a non-const iterator is returned it adds part of the array
* to a transaction while traversing.
*/
template <typename T, std::size_t N>
struct array {
template <typename Y, std::size_t M>
struct standard_array_traits {
using type = Y[N];
};
/* zero-sized array support */
template <typename Y>
struct standard_array_traits<Y, 0> {
struct _alignment_struct {
Y _data[1];
};
struct alignas(_alignment_struct) type {
char _data[sizeof(_alignment_struct)];
};
};
/* Member types */
using value_type = T;
using pointer = value_type *;
using const_pointer = const value_type *;
using reference = value_type &;
using const_reference = const value_type &;
using iterator = pmem::detail::basic_contiguous_iterator<T>;
using const_iterator = const_pointer;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
using range_snapshotting_iterator =
pmem::detail::range_snapshotting_iterator<T>;
/* Underlying array */
typename standard_array_traits<T, N>::type _data;
/**
* Defaulted constructor.
*/
array() = default;
/**
* Defaulted copy constructor.
*/
array(const array &) = default;
/**
* Defaulted move constructor.
*
* Performs member-wise move but do NOT add moved-from array to the
* transaction.
*/
array(array &&) = default;
/**
* Copy assignment operator - perform assignment from other
* pmem::obj::array.
*
* This function creates a transaction internally.
*
* @throw transaction_error when adding the object to the
* transaction failed.
* @throw pmem::pool_error if an object is not in persistent memory.
*/
array &
operator=(const array &other)
{
/*
* _get_pool should be called before self assignment check to
* maintain the same behaviour for all arguments.
*/
auto pop = _get_pool();
if (this == &other)
return *this;
transaction::run(pop, [&] {
detail::conditional_add_to_tx(
this, 1, POBJ_XADD_ASSUME_INITIALIZED);
std::copy(other.cbegin(), other.cend(), _get_data());
});
return *this;
}
/**
* Move assignment operator - perform move assignment from other
* pmem::obj::array.
*
* This function creates a transaction internally.
*
* @throw transaction_error when adding the object to the
* transaction failed.
* @throw pmem::pool_error if an object is not in persistent memory.
*/
array &
operator=(array &&other)
{
/*
* _get_pool should be called before self assignment check to
* maintain the same behaviour for all arguments.
*/
auto pop = _get_pool();
if (this == &other)
return *this;
transaction::run(pop, [&] {
detail::conditional_add_to_tx(
this, 1, POBJ_XADD_ASSUME_INITIALIZED);
detail::conditional_add_to_tx(
&other, 1, POBJ_XADD_ASSUME_INITIALIZED);
std::move(other._get_data(), other._get_data() + size(),
_get_data());
});
return *this;
}
/**
* Access element at specific index and add it to a transaction.
*
* @throw std::out_of_range if index is out of bound.
* @throw transaction_error when adding the object to the
* transaction failed.
*/
reference
at(size_type n)
{
if (n >= N)
throw std::out_of_range("array::at");
detail::conditional_add_to_tx(_get_data() + n, 1,
POBJ_XADD_ASSUME_INITIALIZED);
return _get_data()[n];
}
/**
* Access element at specific index.
*
* @throw std::out_of_range if index is out of bound.
*/
const_reference
at(size_type n) const
{
if (n >= N)
throw std::out_of_range("array::at");
return _get_data()[n];
}
/**
* Access element at specific index.
*
* @throw std::out_of_range if index is out of bound.
*/
const_reference
const_at(size_type n) const
{
if (n >= N)
throw std::out_of_range("array::const_at");
return _get_data()[n];
}
/**
* Access element at specific index and add it to a transaction.
* No bounds checking is performed.
*
* @throw transaction_error when adding the object to the
* transaction failed.
*/
reference operator[](size_type n)
{
detail::conditional_add_to_tx(_get_data() + n, 1,
POBJ_XADD_ASSUME_INITIALIZED);
return _get_data()[n];
}
/**
* Access element at specific index.
* No bounds checking is performed.
*/
const_reference operator[](size_type n) const
{
return _get_data()[n];
}
/**
* Returns raw pointer to the underlying data
* and adds entire array to a transaction.
*
* @throw transaction_error when adding the object to the
* transaction failed.
*/
T *
data()
{
detail::conditional_add_to_tx(this, 1,
POBJ_XADD_ASSUME_INITIALIZED);
return _get_data();
}
/**
* Returns const raw pointer to the underlying data.
*/
const T *
data() const noexcept
{
return _get_data();
}
/**
* Returns const raw pointer to the underlying data.
*/
const T *
cdata() const noexcept
{
return _get_data();
}
/**
* Returns an iterator to the beginning.
*
* @throw transaction_error when adding the object to the
* transaction failed.
*/
iterator
begin()
{
return iterator(_get_data());
}
/**
* Returns an iterator to the end.
*
* @throw transaction_error when adding the object to the
* transaction failed.
*/
iterator
end()
{
return iterator(_get_data() + size());
}
/**
* Returns const iterator to the beginning.
*/
const_iterator
begin() const noexcept
{
return const_iterator(_get_data());
}
/**
* Returns const iterator to the beginning.
*/
const_iterator
cbegin() const noexcept
{
return const_iterator(_get_data());
}
/**
* Returns a const iterator to the end.
*/
const_iterator
end() const noexcept
{
return const_iterator(_get_data() + size());
}
/**
* Returns a const iterator to the end.
*/
const_iterator
cend() const noexcept
{
return const_iterator(_get_data() + size());
}
/**
* Returns a reverse iterator to the beginning.
*
* @throw transaction_error when adding the object to the
* transaction failed.
*/
reverse_iterator
rbegin()
{
return reverse_iterator(iterator(_get_data() + size()));
}
/**
* Returns a reverse iterator to the end.
*
* @throw transaction_error when adding the object to the
* transaction failed.
*/
reverse_iterator
rend()
{
return reverse_iterator(iterator(_get_data()));
}
/**
* Returns a const reverse iterator to the beginning.
*/
const_reverse_iterator
rbegin() const noexcept
{
return const_reverse_iterator(cend());
}
/**
* Returns a const reverse iterator to the beginning.
*/
const_reverse_iterator
crbegin() const noexcept
{
return const_reverse_iterator(cend());
}
/**
* Returns a const reverse iterator to the end.
*/
const_reverse_iterator
rend() const noexcept
{
return const_reverse_iterator(cbegin());
}
/**
* Returns a const reverse iterator to the beginning.
*/
const_reverse_iterator
crend() const noexcept
{
return const_reverse_iterator(cbegin());
}
/**
* Access the first element and add this element to a transaction.
*
* @throw transaction_error when adding the object to the
* transaction failed.
*/
reference
front()
{
detail::conditional_add_to_tx(_get_data(), 1,
POBJ_XADD_ASSUME_INITIALIZED);
return _get_data()[0];
}
/**
* Access the last element and add this element to a transaction.
*
* @throw transaction_error when adding the object to the
* transaction failed.
*/
reference
back()
{
detail::conditional_add_to_tx(&_get_data()[size() - 1], 1,
POBJ_XADD_ASSUME_INITIALIZED);
return _get_data()[size() - 1];
}
/**
* Access the first element.
*/
const_reference
front() const
{
return _get_data()[0];
}
/**
* Access the first element.
*/
const_reference
cfront() const
{
return _get_data()[0];
}
/**
* Access the last element.
*/
const_reference
back() const
{
return _get_data()[size() - 1];
}
/**
* Access the last element.
*/
const_reference
cback() const
{
return _get_data()[size() - 1];
}
/**
* Returns slice and snapshots requested range.
*
* @param[in] start start index of requested range.
* @param[in] n number of elements in range.
*
* @return slice from start to start + n.
*
* @throw std::out_of_range if any element of the range would be
* outside of the array.
*/
slice<pointer>
range(size_type start, size_type n)
{
if (start + n > N)
throw std::out_of_range("array::range");
detail::conditional_add_to_tx(_get_data() + start, n,
POBJ_XADD_ASSUME_INITIALIZED);
return {_get_data() + start, _get_data() + start + n};
}
/**
* Returns slice.
*
* @param[in] start start index of requested range.
* @param[in] n number of elements in range.
* @param[in] snapshot_size number of elements which should be
* snapshotted in a bulk while traversing this slice.
* If provided value is larger or equal to n, entire range is
* added to a transaction. If value is equal to 0 no snapshotting
* happens.
*
* @return slice from start to start + n.
*
* @throw std::out_of_range if any element of the range would be
* outside of the array.
*/
slice<range_snapshotting_iterator>
range(size_type start, size_type n, size_type snapshot_size)
{
if (start + n > N)
throw std::out_of_range("array::range");
if (snapshot_size > n)
snapshot_size = n;
return {range_snapshotting_iterator(_get_data() + start,
_get_data() + start, n,
snapshot_size),
range_snapshotting_iterator(_get_data() + start + n,
_get_data() + start, n,
snapshot_size)};
}
/**
* Returns const slice.
*
* @param[in] start start index of requested range.
* @param[in] n number of elements in range.
*
* @return slice from start to start + n.
*
* @throw std::out_of_range if any element of the range would be
* outside of the array.
*/
slice<const_iterator>
range(size_type start, size_type n) const
{
if (start + n > N)
throw std::out_of_range("array::range");
return {const_iterator(_get_data() + start),
const_iterator(_get_data() + start + n)};
}
/**
* Returns const slice.
*
* @param[in] start start index of requested range.
* @param[in] n number of elements in range.
*
* @return slice from start to start + n.
*
* @throw std::out_of_range if any element of the range would be
* outside of the array.
*/
slice<const_iterator>
crange(size_type start, size_type n) const
{
if (start + n > N)
throw std::out_of_range("array::crange");
return {const_iterator(_get_data() + start),
const_iterator(_get_data() + start + n)};
}
/**
* Returns size of the array.
*/
constexpr size_type
size() const noexcept
{
return N;
}
/**
* Returns the maximum size of the array.
*/
constexpr size_type
max_size() const noexcept
{
return N;
}
/**
* Checks whether array is empty.
*/
constexpr bool
empty() const noexcept
{
return size() == 0;
}
/**
* Fills array with specified value inside internal transaction.
*
* @throw transaction_error when adding the object to the
* transaction failed.
* @throw pmem::pool_error if an object is not in persistent memory.
*/
void
fill(const_reference value)
{
auto pop = _get_pool();
transaction::run(pop, [&] {
detail::conditional_add_to_tx(
this, 1, POBJ_XADD_ASSUME_INITIALIZED);
std::fill(_get_data(), _get_data() + size(), value);
});
}
/**
* Swaps content with other array's content inside internal transaction.
*
* @throw transaction_error when adding the object to the
* transaction failed.
* @throw pmem::pool_error if an object is not in persistent memory.
*/
template <std::size_t Size = N>
typename std::enable_if<Size != 0>::type
swap(array &other)
{
/*
* _get_pool should be called before self assignment check to
* maintain the same behaviour for all arguments.
*/
auto pop = _get_pool();
if (this == &other)
return;
transaction::run(pop, [&] {
detail::conditional_add_to_tx(
this, 1, POBJ_XADD_ASSUME_INITIALIZED);
detail::conditional_add_to_tx(
&other, 1, POBJ_XADD_ASSUME_INITIALIZED);
std::swap_ranges(_get_data(), _get_data() + size(),
other._get_data());
});
}
/**
* Swap for zero-sized array.
*/
template <std::size_t Size = N>
typename std::enable_if<Size == 0>::type
swap(array &other)
{
static_assert(!std::is_const<T>::value,
"cannot swap zero-sized array of type 'const T'");
}
private:
/**
* Support for non-zero sized array.
*/
template <std::size_t Size = N>
typename std::enable_if<Size != 0, T *>::type
_get_data()
{
return this->_data;
}
/**
* Support for non-zero sized array.
*/
template <std::size_t Size = N>
typename std::enable_if<Size != 0, const T *>::type
_get_data() const
{
return this->_data;
}
/**
* Support for zero sized array.
* Return value is a unique address (address of the array itself);
*/
template <std::size_t Size = N>
typename std::enable_if<Size == 0, T *>::type
_get_data()
{
return reinterpret_cast<T *>(&this->_data);
}
/**
* Support for zero sized array.
*/
template <std::size_t Size = N>
typename std::enable_if<Size == 0, const T *>::type
_get_data() const
{
return reinterpret_cast<const T *>(&this->_data);
}
/**
* Check whether object is on pmem and return pool_base instance.
*
* @throw pmem::pool_error if an object is not in persistent memory.
*/
pool_base
_get_pool() const
{
return pmem::obj::pool_by_vptr(this);
}
};
/**
* Non-member equal operator.
*/
template <typename T, std::size_t N>
inline bool
operator==(const array<T, N> &lhs, const array<T, N> &rhs)
{
return std::equal(lhs.cbegin(), lhs.cend(), rhs.cbegin());
}
/**
* Non-member not-equal operator.
*/
template <typename T, std::size_t N>
inline bool
operator!=(const array<T, N> &lhs, const array<T, N> &rhs)
{
return !(lhs == rhs);
}
/**
* Non-member less than operator.
*/
template <typename T, std::size_t N>
inline bool
operator<(const array<T, N> &lhs, const array<T, N> &rhs)
{
return std::lexicographical_compare(lhs.cbegin(), lhs.cend(),
rhs.cbegin(), rhs.cend());
}
/**
* Non-member greater than operator.
*/
template <typename T, std::size_t N>
inline bool
operator>(const array<T, N> &lhs, const array<T, N> &rhs)
{
return rhs < lhs;
}
/**
* Non-member greater or equal operator.
*/
template <typename T, std::size_t N>
inline bool
operator>=(const array<T, N> &lhs, const array<T, N> &rhs)
{
return !(lhs < rhs);
}
/**
* Non-member less or equal operator.
*/
template <typename T, std::size_t N>
inline bool
operator<=(const array<T, N> &lhs, const array<T, N> &rhs)
{
return !(lhs > rhs);
}
/**
* Non-member cbegin.
*/
template <typename T, std::size_t N>
typename pmem::obj::array<T, N>::const_iterator
cbegin(const pmem::obj::array<T, N> &a)
{
return a.cbegin();
}
/**
* Non-member cend.
*/
template <typename T, std::size_t N>
typename pmem::obj::array<T, N>::const_iterator
cend(const pmem::obj::array<T, N> &a)
{
return a.cend();
}
/**
* Non-member crbegin.
*/
template <typename T, std::size_t N>
typename pmem::obj::array<T, N>::const_reverse_iterator
crbegin(const pmem::obj::array<T, N> &a)
{
return a.crbegin();
}
/**
* Non-member crend.
*/
template <typename T, std::size_t N>
typename pmem::obj::array<T, N>::const_reverse_iterator
crend(const pmem::obj::array<T, N> &a)
{
return a.crend();
}
/**
* Non-member begin.
*/
template <typename T, std::size_t N>
typename pmem::obj::array<T, N>::iterator
begin(pmem::obj::array<T, N> &a)
{
return a.begin();
}
/**
* Non-member begin.
*/
template <typename T, std::size_t N>
typename pmem::obj::array<T, N>::const_iterator
begin(const pmem::obj::array<T, N> &a)
{
return a.begin();
}
/**
* Non-member end.
*/
template <typename T, std::size_t N>
typename pmem::obj::array<T, N>::iterator
end(pmem::obj::array<T, N> &a)
{
return a.end();
}
/**
* Non-member end.
*/
template <typename T, std::size_t N>
typename pmem::obj::array<T, N>::const_iterator
end(const pmem::obj::array<T, N> &a)
{
return a.end();
}
/**
* Non-member rbegin.
*/
template <typename T, std::size_t N>
typename pmem::obj::array<T, N>::reverse_iterator
rbegin(pmem::obj::array<T, N> &a)
{
return a.rbegin();
}
/**
* Non-member rbegin.
*/
template <typename T, std::size_t N>
typename pmem::obj::array<T, N>::const_reverse_iterator
rbegin(const pmem::obj::array<T, N> &a)
{
return a.rbegin();
}
/**
* Non-member rend.
*/
template <typename T, std::size_t N>
typename pmem::obj::array<T, N>::reverse_iterator
rend(pmem::obj::array<T, N> &a)
{
return a.rend();
}
/**
* Non-member rend.
*/
template <typename T, std::size_t N>
typename pmem::obj::array<T, N>::const_reverse_iterator
rend(const pmem::obj::array<T, N> &a)
{
return a.rend();
}
/**
* Non-member swap function.
*/
template <typename T, size_t N>
inline void
swap(pmem::obj::array<T, N> &lhs, pmem::obj::array<T, N> &rhs)
{
lhs.swap(rhs);
}
/**
* Non-member get function.
*/
template <size_t I, typename T, size_t N>
T &
get(pmem::obj::array<T, N> &a)
{
static_assert(I < N,
"Index out of bounds in std::get<> (pmem::obj::array)");
return a.at(I);
}
/**
* Non-member get function.
*/
template <size_t I, typename T, size_t N>
T &&
get(pmem::obj::array<T, N> &&a)
{
static_assert(I < N,
"Index out of bounds in std::get<> (pmem::obj::array)");
return std::move(a.at(I));
}
/**
* Non-member get function.
*/
template <size_t I, typename T, size_t N>
const T &
get(const pmem::obj::array<T, N> &a) noexcept
{
static_assert(I < N,
"Index out of bounds in std::get<> (pmem::obj::array)");
return a.at(I);
}
/**
* Non-member get function.
*/
template <size_t I, typename T, size_t N>
const T &&
get(const pmem::obj::array<T, N> &&a) noexcept
{
static_assert(I < N,
"Index out of bounds in std::get<> (pmem::obj::array)");
return std::move(a.at(I));
}
} /* namespace obj */
} /* namespace pmem */
#endif /* LIBPMEMOBJ_CPP_ARRAY_HPP */
| 20.522388 | 80 | 0.663273 | sanjay-cpu |
4370e4d0662ae6e12313e8f8ddfaed54baae3939 | 664 | cpp | C++ | Leetcode_167.cpp | xulu199705/LeetCode | 9a654a10117a93f9ad9728d6b86eb3713185545e | [
"MIT"
] | null | null | null | Leetcode_167.cpp | xulu199705/LeetCode | 9a654a10117a93f9ad9728d6b86eb3713185545e | [
"MIT"
] | null | null | null | Leetcode_167.cpp | xulu199705/LeetCode | 9a654a10117a93f9ad9728d6b86eb3713185545e | [
"MIT"
] | null | null | null | // Two Sum II Input array is sorted
#include <leetcode.h>
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
vector<int> ans;
for (int i = 0; i < numbers.size(); i++)
{
if (i != 0 && numbers[i] == numbers[i-1]) {
continue;
}
if (numbers[i] > target) {
break;
}
if (numbers.end() != find(numbers.begin() + i + 1, numbers.end(), target - numbers[i])) {
for (int j = i + 1; j < numbers.size(); j++)
{
if (numbers[i] + numbers[j] == target) {
ans.push_back(i + 1);
ans.push_back(j + 1);
return ans;
}
}
}
}
return ans;
}
}; | 20.121212 | 92 | 0.496988 | xulu199705 |
4374f7570f23c6207af5f08630009c83c93945d1 | 174 | cpp | C++ | src/DoNotOptimize.cpp | oliora/sltbench | 9b33e47c7963de84f3db511a0b74b77e69ce5fcd | [
"Apache-2.0"
] | 146 | 2016-08-27T08:30:50.000Z | 2022-02-22T12:57:56.000Z | src/DoNotOptimize.cpp | qjhuang/sltbench | a3347f85cea0eac2f8e798ff2c9e9b40e3d1967d | [
"Apache-2.0"
] | 70 | 2016-12-27T07:45:53.000Z | 2021-01-01T07:27:48.000Z | src/DoNotOptimize.cpp | qjhuang/sltbench | a3347f85cea0eac2f8e798ff2c9e9b40e3d1967d | [
"Apache-2.0"
] | 12 | 2017-10-10T19:23:18.000Z | 2020-06-25T17:44:21.000Z | #include <sltbench/impl/DoNotOptimize.h>
namespace sltbench {
namespace priv {
void empty_function(volatile const char*)
{
}
} // namespace priv
} // namespace sltbench
| 14.5 | 41 | 0.735632 | oliora |
43753501b3b17c99027017e4ac6f742120260517 | 4,172 | cpp | C++ | tests/async/StaticThreadPoolTests.cpp | MichaelE1000/libazul | 4a18c5d9d71722b09e04ab5d837d5f012ae4e8b0 | [
"MIT"
] | 3 | 2019-01-29T09:18:48.000Z | 2019-01-29T15:08:06.000Z | tests/async/StaticThreadPoolTests.cpp | MichaelE1000/libimpulso | 4a18c5d9d71722b09e04ab5d837d5f012ae4e8b0 | [
"MIT"
] | 1 | 2020-11-29T01:54:33.000Z | 2020-12-10T06:48:30.000Z | tests/async/StaticThreadPoolTests.cpp | MichaelE1000/libimpulso | 4a18c5d9d71722b09e04ab5d837d5f012ae4e8b0 | [
"MIT"
] | null | null | null | #include <gmock/gmock.h>
#include <azul/async/StaticThreadPool.hpp>
#include <thread>
class StaticThreadPoolTestFixture : public testing::Test
{
};
TEST_F(StaticThreadPoolTestFixture, Execute_EmptyTask_FutureReady)
{
azul::async::StaticThreadPool threadPool(1);
auto result = threadPool.Execute([](){});
result.Wait();
ASSERT_TRUE(result.IsReady());
ASSERT_NO_THROW(result.Get());
}
TEST_F(StaticThreadPoolTestFixture, Execute_TaskEnqueued_Success)
{
azul::async::StaticThreadPool executor(1);
auto result = executor.Execute([](){ return 42; });
ASSERT_EQ(42, result.Get());
}
TEST_F(StaticThreadPoolTestFixture, Execute_TaskThrowsException_ExceptionForwarded)
{
azul::async::StaticThreadPool executor(1);
auto result = executor.Execute([](){ throw std::invalid_argument(""); });
ASSERT_THROW(result.Get(), std::invalid_argument);
}
TEST_F(StaticThreadPoolTestFixture, Execute_MultipleTasksAndThreads_Success)
{
azul::async::StaticThreadPool executor(4);
std::vector<azul::async::Future<int>> results;
const int tasksToExecute = 100;
for (int i = 0; i < tasksToExecute; ++i)
{
auto result = executor.Execute([i](){ return i; });
results.emplace_back(std::move(result));
}
for (int i = 0; i < tasksToExecute; ++i)
{
ASSERT_EQ(i, results[i].Get());
}
}
TEST_F(StaticThreadPoolTestFixture, Execute_OneDependency_ExecutedInOrder)
{
azul::async::StaticThreadPool executor(2);
const auto firstTaskId = 1;
const auto secondTaskId = 2;
std::vector<int> ids;
auto action1 = [&]() { std::this_thread::sleep_for(std::chrono::milliseconds(50)); ids.push_back(firstTaskId); };
auto action2 = [&]() { ids.push_back(secondTaskId); };
auto future1 = executor.Execute(action1);
auto future2 = executor.Execute(action2, future1);
ASSERT_NO_THROW(future1.Get());
ASSERT_NO_THROW(future2.Get());
ASSERT_EQ(firstTaskId, ids[0]);
ASSERT_EQ(secondTaskId, ids[1]);
}
TEST_F(StaticThreadPoolTestFixture, Execute_DependencyThrowingException_FollowingTaskStillExecuted)
{
azul::async::StaticThreadPool executor(2);
auto action1 = [&]() { throw std::runtime_error(""); };
auto action2 = [&]() { };
auto future1 = executor.Execute(action1);
auto future2 = executor.Execute(action2, future1);
ASSERT_THROW(future1.Get(), std::runtime_error);
ASSERT_NO_THROW(future2.Get());
}
TEST_F(StaticThreadPoolTestFixture, Execute_MultipleDependencies_ValidExecutionOrder)
{
std::vector<int> executedTasks;
std::mutex mutex;
auto log_task_id = [&mutex, &executedTasks](const int id) mutable {
std::lock_guard<std::mutex> lock(mutex);
executedTasks.push_back(id);
};
azul::async::StaticThreadPool executor(2);
// dependency graph:
// task1 <---- task3 <------ task4
// task2 <-----------------|
auto future1 = executor.Execute(std::bind(log_task_id, 1));
auto future2 = executor.Execute(std::bind(log_task_id, 2));
auto future3 = executor.Execute(std::bind(log_task_id, 3), future1);
auto future4 = executor.Execute(std::bind(log_task_id, 4), future3, future2);
ASSERT_NO_THROW(future4.Get());
ASSERT_EQ(3, executedTasks[2]);
ASSERT_EQ(4, executedTasks[3]);
}
TEST_F(StaticThreadPoolTestFixture, Execute_MultipleTasksNoDependencies_AllThreadsOccupied)
{
std::vector<std::thread::id> utlizedThreadIds;
std::mutex mutex;
auto logThreadId = [&mutex, &utlizedThreadIds]() mutable {
std::lock_guard<std::mutex> lock(mutex);
utlizedThreadIds.push_back(std::this_thread::get_id());
};
azul::async::StaticThreadPool executor(4);
auto action = [&logThreadId](){
logThreadId();
std::this_thread::sleep_for(std::chrono::milliseconds(50));
};
std::vector<azul::async::Future<void>> futures;
for (std::size_t i = 0; i < executor.ThreadCount(); ++i)
{
futures.emplace_back(executor.Execute(action));
}
std::for_each(futures.begin(), futures.end(), [](auto f){ f.Wait(); });
ASSERT_EQ(utlizedThreadIds.size(), executor.ThreadCount());
}
| 28.972222 | 117 | 0.68001 | MichaelE1000 |
43792eec702b1dfe3031e6f480458443889048d9 | 3,065 | hpp | C++ | jigtest/src/application/characterobject.hpp | Ludophonic/JigLib | 541ec63b345ccf01e58cce49eb2f73c21eaf6aa6 | [
"Zlib"
] | 10 | 2016-06-01T12:54:45.000Z | 2021-09-07T17:34:37.000Z | jigtest/src/application/characterobject.hpp | Ludophonic/JigLib | 541ec63b345ccf01e58cce49eb2f73c21eaf6aa6 | [
"Zlib"
] | null | null | null | jigtest/src/application/characterobject.hpp | Ludophonic/JigLib | 541ec63b345ccf01e58cce49eb2f73c21eaf6aa6 | [
"Zlib"
] | 4 | 2017-05-03T14:03:03.000Z | 2021-01-04T04:31:15.000Z | //==============================================================
// Copyright (C) 2004 Danny Chapman
// danny@rowlhouse.freeserve.co.uk
//--------------------------------------------------------------
//
/// @file characterobject.hpp
//
//==============================================================
#ifndef CHARACTEROBJECT_HPP
#define CHARACTEROBJECT_HPP
#include "object.hpp"
#include "graphics.hpp"
#include "jiglib.hpp"
/// This is a game-object - i.e. a character that can be rendered.
class tCharacterObject : public tObject
{
public:
tCharacterObject(JigLib::tScalar radius, JigLib::tScalar height);
~tCharacterObject();
void SetProperties(JigLib::tScalar elasticity,
JigLib::tScalar staticFriction,
JigLib::tScalar dynamicFriction);
void SetDensity(JigLib::tScalar density, JigLib::tPrimitive::tPrimitiveProperties::tMassDistribution massDistribution = JigLib::tPrimitive::tPrimitiveProperties::SOLID);
void SetMass(JigLib::tScalar mass, JigLib::tPrimitive::tPrimitiveProperties::tMassDistribution massDistribution = JigLib::tPrimitive::tPrimitiveProperties::SOLID);
// inherited from tObject
JigLib::tBody * GetBody() {return &mBody;}
// inherited from tObject - interpolated between the physics old and
// current positions.
void SetRenderPosition(JigLib::tScalar renderFraction);
// inherited from tRenderObject
void Render(tRenderType renderType);
const JigLib::tSphere & GetRenderBoundingSphere() const;
const JigLib::tVector3 & GetRenderPosition() const;
const JigLib::tMatrix33 & GetRenderOrientation() const;
/// If start, then set control to be forward, else stop going forward
void ControlFwd(bool start);
void ControlBack(bool start);
void ControlLeft(bool start);
void ControlRight(bool start);
void ControlJump();
private:
class tCharacterBody : public JigLib::tBody
{
public:
virtual void PostPhysics(JigLib::tScalar dt);
JigLib::tScalar mDesiredFwdSpeed;
JigLib::tScalar mDesiredLeftSpeed;
JigLib::tScalar mJumpSpeed;
// used for smoothing
JigLib::tScalar mFwdSpeed;
JigLib::tScalar mLeftSpeed;
JigLib::tScalar mFwdSpeedRate;
JigLib::tScalar mLeftSpeedRate;
JigLib::tScalar mTimescale;
};
void UpdateControl();
tCharacterBody mBody;
JigLib::tCollisionSkin mCollisionSkin;
JigLib::tVector3 mLookDir;
JigLib::tVector3 mRenderPosition;
JigLib::tMatrix33 mRenderOrientation;
GLuint mDisplayListNum;
enum tMoveDir {MOVE_NONE = 1 << 0,
MOVE_FWD = 1 << 1,
MOVE_BACK = 1 << 2,
MOVE_LEFT = 1 << 3,
MOVE_RIGHT = 1 << 4};
/// bitmask from tMoveDir
unsigned mMoveDir;
JigLib::tScalar mBodyAngle; ///< in degrees - rotation around z
JigLib::tScalar mLookUpAngle; ///< in Degrees
JigLib::tScalar mMoveFwdSpeed;
JigLib::tScalar mMoveBackSpeed;
JigLib::tScalar mMoveSideSpeed;
JigLib::tScalar mJumpSpeed;
bool mDoJump;
};
#endif
| 30.959596 | 171 | 0.655791 | Ludophonic |
437b4fb3092c973ac2b6e6f20de02cdad6b5567b | 6,593 | cc | C++ | src/ufo/profile/ObsProfileAverageData.cc | JCSDA/ufo | 69a6475f478306dd4d4f6728705fe0cd205752c7 | [
"Apache-2.0"
] | 4 | 2020-12-04T08:26:06.000Z | 2021-11-20T01:18:47.000Z | src/ufo/profile/ObsProfileAverageData.cc | JCSDA/ufo | 69a6475f478306dd4d4f6728705fe0cd205752c7 | [
"Apache-2.0"
] | 21 | 2020-10-30T08:57:16.000Z | 2021-05-17T15:11:20.000Z | src/ufo/profile/ObsProfileAverageData.cc | JCSDA/ufo | 69a6475f478306dd4d4f6728705fe0cd205752c7 | [
"Apache-2.0"
] | 8 | 2020-11-04T00:10:11.000Z | 2021-11-14T09:18:14.000Z | /*
* (C) Copyright 2021 Met Office UK
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
*/
#include "oops/util/FloatCompare.h"
#include "oops/util/missingValues.h"
#include "ufo/profile/ObsProfileAverageData.h"
#include "ufo/profile/SlantPathLocations.h"
#include "ufo/utils/OperatorUtils.h" // for getOperatorVariables
namespace ufo {
ObsProfileAverageData::ObsProfileAverageData(const ioda::ObsSpace & odb,
const eckit::Configuration & config)
: odb_(odb)
{
// Ensure observations have been grouped into profiles.
if (odb_.obs_group_vars().empty())
throw eckit::UserError("Group variables configuration is empty", Here());
// Ensure observations have been sorted by air pressure in descending order.
if (odb_.obs_sort_var() != "air_pressure")
throw eckit::UserError("Sort variable must be air_pressure", Here());
if (odb_.obs_sort_order() != "descending")
throw eckit::UserError("Profiles must be sorted in descending order", Here());
// Check the ObsSpace has been extended. If this is not the case
// then it will not be possible to access profiles in the original and
// extended sections of the ObsSpace.
if (!odb_.has("MetaData", "extended_obs_space"))
throw eckit::UserError("The extended obs space has not been produced", Here());
// Check the observed pressure is present. This is necessary in order to
// determine the slant path locations.
if (!odb_.has("MetaData", "air_pressure"))
throw eckit::UserError("air_pressure@MetaData not present", Here());
// Set up configuration options.
options_.validateAndDeserialize(config);
// Add model air pressure to the list of variables used in this operator.
// This GeoVaL is used to determine the slant path locations.
modelVerticalCoord_ = options_.modelVerticalCoordinate;
requiredVars_ += oops::Variables({modelVerticalCoord_});
// Add any simulated variables to the list of variables used in this operator.
getOperatorVariables(config, odb_.obsvariables(), operatorVars_, operatorVarIndices_);
requiredVars_ += operatorVars_;
// If required, set up vectors for OPS comparison.
if (options_.compareWithOPS.value())
this->setUpAuxiliaryReferenceVariables();
}
const oops::Variables & ObsProfileAverageData::requiredVars() const {
return requiredVars_;
}
const oops::Variables & ObsProfileAverageData::simulatedVars() const {
return operatorVars_;
}
const std::vector<int> & ObsProfileAverageData::operatorVarIndices() const {
return operatorVarIndices_;
}
void ObsProfileAverageData::cacheGeoVaLs(const GeoVaLs & gv) const {
// Only perform the caching once.
if (!cachedGeoVaLs_) cachedGeoVaLs_.reset(new GeoVaLs(gv));
}
std::vector<std::size_t> ObsProfileAverageData::getSlantPathLocations
(const std::vector<std::size_t> & locsOriginal,
const std::vector<std::size_t> & locsExtended) const
{
const std::vector<std::size_t> slant_path_location =
ufo::getSlantPathLocations(odb_,
*cachedGeoVaLs_,
locsOriginal,
modelVerticalCoord_,
options_.numIntersectionIterations.value() - 1);
// If required, compare slant path locations and slant pressure with OPS output.
if (options_.compareWithOPS.value()) {
// Vector of slanted pressures, used for comparisons with OPS.
std::vector<float> slant_pressure;
// Number of levels for model pressure.
const std::size_t nlevs_p = cachedGeoVaLs_->nlevs(modelVerticalCoord_);
// Vector used to store different pressure GeoVaLs.
std::vector <float> pressure_gv(nlevs_p);
for (std::size_t mlev = 0; mlev < nlevs_p; ++mlev) {
cachedGeoVaLs_->getAtLocation(pressure_gv, modelVerticalCoord_, slant_path_location[mlev]);
slant_pressure.push_back(pressure_gv[mlev]);
}
this->compareAuxiliaryReferenceVariables(locsExtended,
slant_path_location,
slant_pressure);
}
return slant_path_location;
}
void ObsProfileAverageData::setUpAuxiliaryReferenceVariables() {
if (!(odb_.has("MetOfficeHofX", "slant_path_location") &&
odb_.has("MetOfficeHofX", "slant_pressure")))
throw eckit::UserError("At least one reference variable is not present", Here());
// Get reference values of the slant path locations and pressures.
slant_path_location_ref_.resize(odb_.nlocs());
slant_pressure_ref_.resize(odb_.nlocs());
odb_.get_db("MetOfficeHofX", "slant_path_location", slant_path_location_ref_);
odb_.get_db("MetOfficeHofX", "slant_pressure", slant_pressure_ref_);
}
void ObsProfileAverageData::compareAuxiliaryReferenceVariables
(const std::vector<std::size_t> & locsExtended,
const std::vector<std::size_t> & slant_path_location,
const std::vector<float> & slant_pressure) const {
std::vector<int> slant_path_location_ref_profile;
std::vector<float> slant_pressure_ref_profile;
for (const std::size_t loc : locsExtended) {
slant_path_location_ref_profile.push_back(slant_path_location_ref_[loc]);
slant_pressure_ref_profile.push_back(slant_pressure_ref_[loc]);
}
std::stringstream errmsg;
for (std::size_t mlev = 0; mlev < locsExtended.size(); ++mlev) {
if (slant_path_location[mlev] != slant_path_location_ref_profile[mlev]) {
errmsg << "Mismatch for slant_path_location, level = " << mlev
<< " (this code, OPS): "
<< slant_path_location[mlev] << ", "
<< slant_path_location_ref_profile[mlev];
throw eckit::BadValue(errmsg.str(), Here());
}
if (!oops::is_close_relative(slant_pressure[mlev],
slant_pressure_ref_profile[mlev],
1e-5f)) {
errmsg << "Mismatch for slant_pressure, level = " << mlev
<< " (this code, OPS): "
<< slant_pressure[mlev] << ", "
<< slant_pressure_ref_profile[mlev];
throw eckit::BadValue(errmsg.str(), Here());
}
}
}
void ObsProfileAverageData::print(std::ostream & os) const {
os << "ObsProfileAverage operator" << std::endl;
os << "config = " << options_ << std::endl;
}
} // namespace ufo
| 42.811688 | 99 | 0.668285 | JCSDA |
437c26dfb215bd0edcb62df9777a61c1a1158bf2 | 3,717 | hpp | C++ | global/test/TestCwd.hpp | AvciRecep/chaste_2019 | 1d46cdac647820d5c5030f8a9ea3a1019f6651c1 | [
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2020-04-05T12:11:54.000Z | 2020-04-05T12:11:54.000Z | global/test/TestCwd.hpp | AvciRecep/chaste_2019 | 1d46cdac647820d5c5030f8a9ea3a1019f6651c1 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | global/test/TestCwd.hpp | AvciRecep/chaste_2019 | 1d46cdac647820d5c5030f8a9ea3a1019f6651c1 | [
"Apache-2.0",
"BSD-3-Clause"
] | 2 | 2020-04-05T14:26:13.000Z | 2021-03-09T08:18:17.000Z | /*
Copyright (c) 2005-2019, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _TESTCWD_HPP_
#define _TESTCWD_HPP_
#include <cxxtest/TestSuite.h>
#include <cstdlib>
#include <climits>
#include "FakePetscSetup.hpp"
#include "ChasteBuildRoot.hpp"
#include "GetCurrentWorkingDirectory.hpp"
#include "BoostFilesystem.hpp"
#include "IsNan.hpp"
/**
* Test for a strange 'feature' of Debian sarge systems, where the
* current working directory changes on PETSc initialisation. There
* is now code in PetscSetupUtils::CommonSetup() to work around this.
*/
class TestCwd : public CxxTest::TestSuite
{
public:
void TestShowCwd()
{
std::string chaste_source_root(ChasteSourceRootDir());
fs::path chaste_source_root_path(chaste_source_root);
fs::path cwd(GetCurrentWorkingDirectory()+"/");
TS_ASSERT(fs::equivalent(cwd,chaste_source_root));
}
void TestDivideOneByZero()
{
double one = 1.0;
double zero = 0.0;
double ans;
#ifdef TEST_FOR_FPE
// If we are testing for divide-by-zero, then this will throw an exception
//TS_ASSERT_THROWS_ANYTHING(ans = one / zero);
ans=zero*one;//otherwise compiler would complain
ans=ans*zero;//otherwise compiler would complain
#else
// If we aren't testing for it, then there will be no exception
TS_ASSERT_THROWS_NOTHING(ans = one / zero);
double negative_infinity = std::numeric_limits<double>::infinity();
TS_ASSERT_EQUALS(ans, negative_infinity);
#endif
}
void TestDivideZeroByZero()
{
double zero = 0.0;
double ans;
#ifdef TEST_FOR_FPE
// If we are testing for divide-by-zero, then this will throw an exception
//TS_ASSERT_THROWS_ANYTHING(ans = zero / zero);
ans=zero;//otherwise compiler would complain
ans=ans*zero;//otherwise compiler would complain
#else
// If we aren't testing for it, then there will be no exception
TS_ASSERT_THROWS_NOTHING(ans = zero / zero);
TS_ASSERT(std::isnan(ans));
#endif
}
};
#endif /*_TESTCWD_HPP_*/
| 36.441176 | 79 | 0.744149 | AvciRecep |
437ea4e95b0b958443b50b4fce650b1d03bb6792 | 10,121 | cpp | C++ | roomedit/source/lprogdlg.cpp | Darkman-M59/Meridian59_115 | 671b7ebe9fa2b1f40c8bd453652d596042291b90 | [
"FSFAP"
] | 1 | 2021-05-19T02:13:59.000Z | 2021-05-19T02:13:59.000Z | roomedit/source/lprogdlg.cpp | siwithaneye/Meridian59 | 9dc8df728d41ba354c9b11574484da5b3e013a87 | [
"FSFAP"
] | null | null | null | roomedit/source/lprogdlg.cpp | siwithaneye/Meridian59 | 9dc8df728d41ba354c9b11574484da5b3e013a87 | [
"FSFAP"
] | null | null | null | /*----------------------------------------------------------------------------*
| This file is part of WinDEU, the port of DEU to Windows. |
| WinDEU was created by the DEU team: |
| Renaud Paquay, Raphael Quinet, Brendon Wyber and others... |
| |
| DEU is an open project: if you think that you can contribute, please join |
| the DEU team. You will be credited for any code (or ideas) included in |
| the next version of the program. |
| |
| If you want to make any modifications and re-distribute them on your own, |
| you must follow the conditions of the WinDEU license. Read the file |
| LICENSE or README.TXT in the top directory. If do not have a copy of |
| these files, you can request them from any member of the DEU team, or by |
| mail: Raphael Quinet, Rue des Martyrs 9, B-4550 Nandrin (Belgium). |
| |
| This program comes with absolutely no warranty. Use it at your own risks! |
*----------------------------------------------------------------------------*
Project WinDEU
DEU team
Jul-Dec 1994, Jan-Mar 1995
FILE: lprogdlg.cpp
OVERVIEW
========
Source file for implementation of TLevelProgressDialog (TDialog).
*/
#include "common.h"
#pragma hdrstop
#ifndef __lprogdlg_h
#include "lprogdlg.h"
#endif
#ifndef __levels_h
#include "levels.h"
#endif
#ifndef __objects_h
#include "objects.h"
#endif
//
// Build a response table for all messages/commands handled
// by the application.
//
DEFINE_RESPONSE_TABLE1(TLevelProgressDialog, TDialog)
//{{TLevelProgressDialogRSP_TBL_BEGIN}}
EV_WM_SIZE,
EV_WM_PAINT,
//{{TLevelProgressDialogRSP_TBL_END}}
END_RESPONSE_TABLE;
//{{TLevelProgressDialog Implementation}}
///////////////////////////////////////////////////////////////
// TLevelProgressDialog
// --------------------
//
TLevelProgressDialog::TLevelProgressDialog (TWindow* parent, TResId resId,
TModule* module) :
TDialog(parent, resId, module)
{
Minimized = FALSE;
//
// Create interface object for NODES building
//
pNodesText = new TStatic (this, IDC_BUILD_NODES);
pNodesGauge = new TGauge (this, "%d%%", 200,
/*pNodesText->Attr.X,
pNodesText->Attr.Y+10,
pNodesText->Attr.W,
pNodesText->Attr.H*/
10, 20, 100, 10);
pNodesGauge->SetRange (0, 100);
pNodesGauge->SetValue (0);
pVertexesStatic = new TStatic (this, IDC_VERTEXES);
pSideDefsStatic = new TStatic (this, IDC_SIDEDEFS);
pSegsStatic = new TStatic (this, IDC_SEGS);
pSSectorsStatic = new TStatic (this, IDC_SSECTORS);
//
// Create interface object for REJECT building
//
pRejectFrame = new TStatic (this, IDC_FRAME_REJECT);
// pRejectFrame->Attr.Style &= ~(WS_VISIBLE);
pRejectText = new TStatic (this, IDC_BUILD_REJECT);
// pRejectText->Attr.Style &= ~(WS_VISIBLE);
pRejectGauge = new TGauge (this, "%d%%", 201,
/* pRejectText->Attr.X,
pRejectText->Attr.Y+10,
pRejectText->Attr.W,
pRejectText->Attr.H*/
10, 50, 100, 10);
// pRejectGauge->Attr.Style &= ~(WS_VISIBLE);
pRejectGauge->SetRange (0, 100);
pRejectGauge->SetValue (0);
//
// Create interface object for BLOCKMAP building
//
pBlockmapFrame = new TStatic (this, IDC_FRAME_BLOCKMAP);
// pBlockmapFrame->Attr.Style &= ~(WS_VISIBLE);
pBlockmapText = new TStatic (this, IDC_BUILD_BLOCKMAP);
// pBlockmapText->Attr.Style &= ~(WS_VISIBLE);
pBlockmapGauge = new TGauge (this, "%d%%", 202,
/* pBlockmapText->Attr.X,
pBlockmapText->Attr.Y+10,
pBlockmapText->Attr.W,
pBlockmapText->Attr.H*/
10, 80, 100, 10);
// pBlockmapGauge->Attr.Style &= ~(WS_VISIBLE);
pBlockmapGauge->SetRange (0, 100);
pBlockmapGauge->SetValue (0);
}
///////////////////////////////////////////////////////////////
// TLevelProgressDialog
// --------------------
//
TLevelProgressDialog::~TLevelProgressDialog ()
{
Destroy();
}
///////////////////////////////////////////////////////////////
// TLevelProgressDialog
// --------------------
//
void TLevelProgressDialog::SetupWindow ()
{
TRect wRect, cRect;
TPoint TopLeft ;
TDialog::SetupWindow();
::CenterWindow (this);
// Setup size and pos. of NODES gauge window
pNodesText->GetClientRect(cRect);
pNodesText->GetWindowRect(wRect);
TopLeft = TPoint(wRect.left, wRect.top);
ScreenToClient (TopLeft);
pNodesGauge->MoveWindow (TopLeft.x, TopLeft.y + 16,
cRect.right, 20, TRUE);
// Setup size and pos. of REJECT gauge window
pRejectText->GetClientRect(cRect);
pRejectText->GetWindowRect(wRect);
TopLeft = TPoint(wRect.left, wRect.top);
ScreenToClient (TopLeft);
pRejectGauge->MoveWindow (TopLeft.x, TopLeft.y + 16,
cRect.right, 20, TRUE);
// Setup size and pos. of BLOCKMAP gauge window
pBlockmapText->GetClientRect(cRect);
pBlockmapText->GetWindowRect(wRect);
TopLeft = TPoint(wRect.left, wRect.top);
ScreenToClient (TopLeft);
pBlockmapGauge->MoveWindow (TopLeft.x, TopLeft.y + 16,
cRect.right, 20, TRUE);
/*
pRejectText->ShowWindow (SW_HIDE);
pRejectFrame->ShowWindow (SW_HIDE);
pRejectGauge->ShowWindow (SW_HIDE);
*/
/*
pBlockmapText->ShowWindow (SW_HIDE);
pBlockmapFrame->ShowWindow (SW_HIDE);
pBlockmapGauge->ShowWindow (SW_HIDE);
*/
}
///////////////////////////////////////////////////////////////
// TLevelProgressDialog
// --------------------
//
void TLevelProgressDialog::ShowNodesProgress (int objtype)
{
static int SavedNumVertexes = 0;
char msg[10] ;
switch (objtype)
{
case OBJ_VERTEXES:
wsprintf (msg, "%d", NumVertexes);
pVertexesStatic->SetText (msg);
break;
case OBJ_SIDEDEFS:
wsprintf (msg, "%d", NumSideDefs);
pSideDefsStatic->SetText (msg);
SavedNumVertexes = NumVertexes;
break;
case OBJ_SSECTORS:
wsprintf (msg, "%d", NumSegs);
pSegsStatic->SetText (msg);
wsprintf (msg, "%d", NumSectors);
pSSectorsStatic->SetText (msg);
//BUG: We must test the division, because of empty levels
//
if (NumSideDefs + NumVertexes - SavedNumVertexes > 0 )
{
pNodesGauge->SetValue (100.0 * ((float) NumSegs /
(float) (NumSideDefs + NumVertexes -
SavedNumVertexes)));
}
else
pNodesGauge->SetValue (100);
// If minimized, we must paint the icon, else we paint the gauge
if ( Minimized )
{
Invalidate(FALSE); // Don't repaint background
UpdateWindow();
}
else
pNodesGauge->UpdateWindow();
break;
}
}
///////////////////////////////////////////////////////////////
// TLevelProgressDialog
// --------------------
//
void TLevelProgressDialog::ShowRejectControls ()
{
/*
pRejectFrame->ShowWindow (SW_SHOW);
pRejectText->ShowWindow (SW_SHOW);
pRejectGauge->ShowWindow (SW_SHOW);
*/
}
///////////////////////////////////////////////////////////////
// TLevelProgressDialog
// --------------------
//
void TLevelProgressDialog::ShowRejectProgress (int value)
{
pRejectGauge->SetValue (value);
// If minimized, we must paint the icon, else we paint the gauge
if ( Minimized )
{
Invalidate(FALSE); // Don't repaint background
UpdateWindow();
}
else
pRejectGauge->UpdateWindow ();
}
///////////////////////////////////////////////////////////////
// TLevelProgressDialog
// --------------------
//
void TLevelProgressDialog::ShowBlockmapControls ()
{
/*
pBlockmapFrame->ShowWindow (SW_SHOW);
pBlockmapText->ShowWindow (SW_SHOW);
pBlockmapGauge->ShowWindow (SW_SHOW);
*/
}
///////////////////////////////////////////////////////////////
// TLevelProgressDialog
// --------------------
//
void TLevelProgressDialog::ShowBlockmapProgress (int value)
{
pBlockmapGauge->SetValue (value);
// If minimized, we must paint the icon, else we paint the gauge
if ( Minimized )
{
Invalidate(FALSE); // Don't repaint background
UpdateWindow();
}
else
pBlockmapGauge->UpdateWindow ();
}
///////////////////////////////////////////////////////////////
// TLevelProgressDialog
// --------------------
//
void TLevelProgressDialog::EvSize (UINT sizeType, TSize& size)
{
if ( sizeType == SIZE_MINIMIZED )
{
Minimized = TRUE;
Parent->ShowWindow(SW_HIDE);
}
else if ( sizeType == SIZE_RESTORED )
{
Parent->ShowWindow(SW_SHOW);
Minimized = FALSE;
}
else
{
Minimized = FALSE;
TDialog::EvSize(sizeType, size);
}
}
///////////////////////////////////////////////////////////////
// TLevelProgressDialog
// --------------------
//
void DrawIconicGauge(TDC &dc, int yPosition, int Width, int Height, int Value)
{
TBrush BleueBrush(TColor(0,0,255));
TPen BleuePen (TColor(0,0,255));
// TBrush GrayBrush (TColor(200,200,200));
TPen WhitePen (TColor(255,255,255));
TPen GrayPen (TColor(100,100,100));
// TPen GrayPen (TColor(0,0,0));
// Draw upper left white border
dc.SelectObject(GrayPen);
dc.MoveTo(0, yPosition + Height - 1);
dc.LineTo(0, yPosition);
dc.LineTo(Width - 1, yPosition);
// Draw lower right border
dc.SelectObject(WhitePen);
dc.LineTo(Width - 1, yPosition + Height - 1);
dc.LineTo(0, yPosition + Height - 1);
// Draw gauge
dc.SelectObject(BleueBrush);
dc.SelectObject(BleuePen);
dc.Rectangle(1, yPosition + 1, (Width - 1) * Value / 100, yPosition + Height - 1);
dc.RestoreObjects();
}
///////////////////////////////////////////////////////////////
// TLevelProgressDialog
// --------------------
//
void TLevelProgressDialog::EvPaint ()
{
if ( Minimized )
{
TPaintDC dc(*this);
TRect ClientRect;
// Get size of iconic window
GetClientRect(ClientRect);
int Width = ClientRect.Width();
int Height = ClientRect.Height();
DrawIconicGauge (dc, 0,
Width, Height / 3, pNodesGauge->GetValue());
DrawIconicGauge (dc, Height / 3,
Width, Height / 3, pRejectGauge->GetValue());
DrawIconicGauge (dc, 2 * Height / 3,
Width, Height / 3, pBlockmapGauge->GetValue());
}
else
TDialog::EvPaint();
}
| 25.753181 | 83 | 0.590159 | Darkman-M59 |
438032ae65eb3f62d471f9f1951683f94f3378a9 | 531 | hpp | C++ | blocker/blockerd/Clouds/icloud.hpp | TheKuko/blocker | c19839ff65f7e31b3a428f902ce3c7cdf5ec46ab | [
"MIT"
] | null | null | null | blocker/blockerd/Clouds/icloud.hpp | TheKuko/blocker | c19839ff65f7e31b3a428f902ce3c7cdf5ec46ab | [
"MIT"
] | null | null | null | blocker/blockerd/Clouds/icloud.hpp | TheKuko/blocker | c19839ff65f7e31b3a428f902ce3c7cdf5ec46ab | [
"MIT"
] | null | null | null | //
// icloud.hpp
// blockerd
//
// Created by Jozef on 05/06/2020.
//
#ifndef icloud_hpp
#define icloud_hpp
#include "base.hpp"
struct ICloud : public CloudProvider
{
ICloud(const BlockLevel Bl, const std::vector<std::string> &Paths) {
id = CloudProviderId::ICLOUD;
bl = Bl;
paths = Paths;
allowedBundleIds = {
"com.apple.bird",
};
};
~ICloud() = default;
static std::vector<std::string> FindPaths(const std::string &homePath);
};
#endif /* icloud_hpp */
| 18.310345 | 75 | 0.596987 | TheKuko |
438123566dcba8e27c70e489054414dc81f425cf | 3,298 | cpp | C++ | src/rdm/util/test/SystemTest.cpp | cwj5012/rdm-cppserver | 6eed70cc89e2a09eaac93f0833fd9c3c4a273eb8 | [
"MIT"
] | 1 | 2020-06-11T01:31:26.000Z | 2020-06-11T01:31:26.000Z | src/rdm/util/test/SystemTest.cpp | cwj5012/rdm-cppserver | 6eed70cc89e2a09eaac93f0833fd9c3c4a273eb8 | [
"MIT"
] | null | null | null | src/rdm/util/test/SystemTest.cpp | cwj5012/rdm-cppserver | 6eed70cc89e2a09eaac93f0833fd9c3c4a273eb8 | [
"MIT"
] | null | null | null | #include <catch2/catch.hpp>
#include "../../log/Logger.h"
#include "../System.h"
using namespace rdm;
// TODO linux
//TEST_CASE("System", "getProcessorCount") {
// uint64_t min = 1;
// uint64_t max = 1024;
// ASSERT_LE(min, System::getProcessorCount());
// ASSERT_GE(max, System::getProcessorCount());
//
// LOG_DEBUG("processor count: {}",
// System::getProcessorCount());
//}
//
//TEST_CASE(System, getTotalVirtualMemory) {
// uint64_t min = 1;
// uint64_t max = 1ULL << 63;
// ASSERT_LE(min, System::getTotalVirtualMemory());
// ASSERT_GE(max, System::getTotalVirtualMemory());
//
// LOG_DEBUG("total virtual memory: {} GB",
// System::getTotalVirtualMemory() / 1024 / 1024 / 1024.f);
//}
//
//TEST_CASE(System, getVirtualMemoryUsage) {
// uint64_t min = 1;
// uint64_t max = 1ULL << 63;
// ASSERT_LE(min, System::getVirtualMemoryUsage());
// ASSERT_GE(max, System::getVirtualMemoryUsage());
//
// LOG_DEBUG("virtual memory usage: {} GB",
// System::getVirtualMemoryUsage() / 1024 / 1024 / 1024.f);
//}
//
//TEST_CASE(System, getVirtualMemoryUsageCurrentProcess) {
// uint64_t min = 1;
// uint64_t max = 1ULL << 63;
// ASSERT_LE(min, System::getVirtualMemoryUsageCurrentProcess());
// ASSERT_GE(max, System::getVirtualMemoryUsageCurrentProcess());
//
// LOG_DEBUG("virtual memory usage current process: {} MB",
// System::getVirtualMemoryUsageCurrentProcess() / 1024 / 1024.f);
//}
//
//TEST_CASE(System, getTotalPhysicalMemory) {
// uint64_t min = 1;
// uint64_t max = 1ULL << 63;
// ASSERT_LE(min, System::getTotalPhysicalMemory());
// ASSERT_GE(max, System::getTotalPhysicalMemory());
//
// LOG_DEBUG("total physical memory: {} GB",
// System::getTotalPhysicalMemory() / 1024 / 1024 / 1024.f);
//}
//
//TEST_CASE(System, getPhysicalMemoryUsage) {
// uint64_t min = 1;
// uint64_t max = 1ULL << 63;
// ASSERT_LE(min, System::getPhysicalMemoryUsage());
// ASSERT_GE(max, System::getPhysicalMemoryUsage());
//
// LOG_DEBUG("physical memory usage: {} GB",
// System::getPhysicalMemoryUsage() / 1024 / 1024 / 1024.f);
//}
//
//TEST_CASE(System, gePhysicalMemoryUsageCurrentProcess) {
// uint64_t min = 1;
// uint64_t max = 1ULL << 63;
// ASSERT_LE(min <= System::gePhysicalMemoryUsageCurrentProcess());
// ASSERT_GE(max >= System::gePhysicalMemoryUsageCurrentProcess());
//
// LOG_DEBUG("physical memory usage current process: {} MB",
// System::gePhysicalMemoryUsageCurrentProcess() / 1024 / 1024.f);
//}
//
//TEST_CASE(System, getCpuCurrentUsage) {
// System::initCpuCurrentUsage();
// for (auto i = 0; i < 1 * 1000 * 1000; ++i) {
// std::srand(0);
// }
// auto usage = System::getCpuCurrentUsage();
// ASSERT_LT(0 < usage);
// ASSERT_GE(100 >= usage);
//
// LOG_DEBUG("cup current usage: {} %", usage);
//}
//
//TEST_CASE(System, getCpuCurrentProcessUsage) {
// System::initCpuCurrentProcessUsage();
// for (auto i = 0; i < 1 * 1000 * 1000; ++i) {
// std::srand(0);
// }
// auto usage = System::getCpuCurrentProcessUsage();
// ASSERT_LT(0 < usage);
// ASSERT_GE(100 >= usage);
//
// LOG_DEBUG("cup current process usage: {} %", usage);
//} | 32.653465 | 79 | 0.624015 | cwj5012 |
4382f89ed40654758a4c6fb84fac1f3399f09f62 | 1,588 | cc | C++ | camera/common/libcamera_connector/camera_module_callbacks.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | camera/common/libcamera_connector/camera_module_callbacks.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | camera/common/libcamera_connector/camera_module_callbacks.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright 2020 The Chromium OS 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 "cros-camera/common.h"
#include <base/notreached.h>
#include <utility>
#include "common/libcamera_connector/camera_module_callbacks.h"
namespace cros {
CameraModuleCallbacks::CameraModuleCallbacks(
DeviceStatusCallback device_status_callback)
: camera_module_callbacks_(this),
device_status_callback_(std::move(device_status_callback)) {}
mojo::PendingAssociatedRemote<mojom::CameraModuleCallbacks>
CameraModuleCallbacks::GetModuleCallbacks() {
if (camera_module_callbacks_.is_bound()) {
camera_module_callbacks_.reset();
}
return camera_module_callbacks_.BindNewEndpointAndPassRemote();
}
void CameraModuleCallbacks::CameraDeviceStatusChange(
int32_t camera_id, mojom::CameraDeviceStatus new_status) {
LOGF(INFO) << "Camera " << camera_id << " status changed: " << new_status;
switch (new_status) {
case mojom::CameraDeviceStatus::CAMERA_DEVICE_STATUS_PRESENT:
device_status_callback_.Run(camera_id, true);
break;
case mojom::CameraDeviceStatus::CAMERA_DEVICE_STATUS_NOT_PRESENT:
device_status_callback_.Run(camera_id, false);
break;
default:
NOTREACHED() << "Unexpected new device status: " << new_status;
}
}
void CameraModuleCallbacks::TorchModeStatusChange(
int32_t camera_id, mojom::TorchModeStatus new_status) {
// We don't need to do anything for torch mode status change for now.
}
} // namespace cros
| 31.137255 | 76 | 0.758816 | Toromino |
4385da117941f712541a26a4d42567cb64511637 | 1,780 | cc | C++ | flutter/cpp/flutter/dart_backend_match.cc | fatihcakirs/mobile_app_open | 7de0c9d38fc953c81908276887e9542cfd27c467 | [
"Apache-2.0"
] | null | null | null | flutter/cpp/flutter/dart_backend_match.cc | fatihcakirs/mobile_app_open | 7de0c9d38fc953c81908276887e9542cfd27c467 | [
"Apache-2.0"
] | null | null | null | flutter/cpp/flutter/dart_backend_match.cc | fatihcakirs/mobile_app_open | 7de0c9d38fc953c81908276887e9542cfd27c467 | [
"Apache-2.0"
] | null | null | null | #include <google/protobuf/text_format.h>
#include <cstring>
#include "flutter/cpp/backends/external.h"
#include "flutter/cpp/proto/backend_setting.pb.h"
#include "main.h"
extern "C" struct dart_ffi_backend_match_result *dart_ffi_backend_match(
const char *lib_path, const char *manufacturer, const char *model) {
::mlperf::mobile::BackendFunctions backend(lib_path);
if (*lib_path != '\0' && !backend.isLoaded()) {
std::cerr << "backend '" << lib_path << "' can't be loaded\n";
return nullptr;
}
mlperf_device_info_t device_info{model, manufacturer};
// backends should set pbdata to a statically allocated string, so we don't
// need to free it
const char *pbdata = nullptr;
auto result = new dart_ffi_backend_match_result;
result->matches =
backend.match(&result->error_message, &pbdata, &device_info);
if (pbdata == nullptr) {
std::cout << "Backend haven't filled settings" << std::endl;
return result;
}
::mlperf::mobile::BackendSetting setting;
if (!google::protobuf::TextFormat::ParseFromString(pbdata, &setting)) {
std::cout << "Can't parse backend settings before serialization:\n"
<< pbdata << std::endl;
return result;
}
std::string res;
if (!setting.SerializeToString(&res)) {
std::cout << "Can't serialize backend settings\n";
return result;
}
result->pbdata_size = res.length();
result->pbdata = new char[result->pbdata_size];
memcpy(result->pbdata, res.data(), result->pbdata_size);
return result;
}
extern "C" void dart_ffi_backend_match_free(
dart_ffi_backend_match_result *result) {
(void)result->error_message; // should be statically allocated
delete result->pbdata; // pbdata is allocated in dart_ffi_backend_match
delete result;
}
| 30.689655 | 80 | 0.696629 | fatihcakirs |
438641da74ef46a7b1fcdfb4a60cba87ea114d2e | 185 | cpp | C++ | Math.cpp | sknjpn/Math | 85de8d696f4f1ea212e998a076ee0c4dbd3956fa | [
"MIT"
] | null | null | null | Math.cpp | sknjpn/Math | 85de8d696f4f1ea212e998a076ee0c4dbd3956fa | [
"MIT"
] | null | null | null | Math.cpp | sknjpn/Math | 85de8d696f4f1ea212e998a076ee0c4dbd3956fa | [
"MIT"
] | null | null | null | #include "Math.hpp"
Vector2 operator*(float s, const Vector2& v) { return { v.x * s, v.y * s }; }
Vector3 operator*(float s, const Vector3& v) { return { v.x * s, v.y * s, v.z * s }; } | 46.25 | 86 | 0.589189 | sknjpn |
43883be75c6646f89c0b16b8e7648ffaae05e65c | 632 | inl | C++ | package/win32/android/gameplay/src/PhysicsConstraint.inl | sharkpp/openhsp | 0d412fd8f79a6ccae1d33c13addc06fb623fb1fe | [
"BSD-3-Clause"
] | 1 | 2021-06-17T02:16:22.000Z | 2021-06-17T02:16:22.000Z | package/win32/android/gameplay/src/PhysicsConstraint.inl | sharkpp/openhsp | 0d412fd8f79a6ccae1d33c13addc06fb623fb1fe | [
"BSD-3-Clause"
] | null | null | null | package/win32/android/gameplay/src/PhysicsConstraint.inl | sharkpp/openhsp | 0d412fd8f79a6ccae1d33c13addc06fb623fb1fe | [
"BSD-3-Clause"
] | 1 | 2021-04-06T14:58:08.000Z | 2021-04-06T14:58:08.000Z | #include "PhysicsConstraint.h"
namespace gameplay
{
inline float PhysicsConstraint::getBreakingImpulse() const
{
GP_ASSERT(_constraint);
return _constraint->getBreakingImpulseThreshold();
}
inline void PhysicsConstraint::setBreakingImpulse(float impulse)
{
GP_ASSERT(_constraint);
_constraint->setBreakingImpulseThreshold(impulse);
}
inline bool PhysicsConstraint::isEnabled() const
{
GP_ASSERT(_constraint);
return _constraint->isEnabled();
}
inline void PhysicsConstraint::setEnabled(bool enabled)
{
GP_ASSERT(_constraint);
_constraint->setEnabled(enabled);
}
}
| 20.387097 | 65 | 0.731013 | sharkpp |
438a4f4dcfe022f75af02697075fee7b96de29d1 | 2,146 | cpp | C++ | src/gui-qt4/libs/seiscomp3/gui/datamodel/origintime.cpp | thefroid/seiscomp3 | 0b05d5550dcea000a93c7d9a39c5347d8786a91a | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 2 | 2015-09-17T22:43:50.000Z | 2017-11-29T20:27:11.000Z | src/gui-qt4/libs/seiscomp3/gui/datamodel/origintime.cpp | thefroid/seiscomp3 | 0b05d5550dcea000a93c7d9a39c5347d8786a91a | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 2 | 2016-04-26T00:03:09.000Z | 2017-12-05T02:24:50.000Z | src/gui-qt4/libs/seiscomp3/gui/datamodel/origintime.cpp | salichon/seiscomp3 | 4f7715f9ff9a35e7912c379ebf10446d0bceaeb2 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 1 | 2022-01-13T02:49:31.000Z | 2022-01-13T02:49:31.000Z | /***************************************************************************
* Copyright (C) by GFZ Potsdam *
* *
* You can redistribute and/or modify this program under the *
* terms of the SeisComP Public License. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* SeisComP Public License for more details. *
***************************************************************************/
#include "origintime.h"
#include <iostream>
#include <seiscomp3/gui/core/application.h>
namespace Seiscomp {
namespace Gui {
OriginTimeDialog::OriginTimeDialog(double lon, double lat,
Seiscomp::Core::Time time,
QWidget * parent, Qt::WFlags f)
: QDialog(parent, f) {
_ui.setupUi(this);
_ui.label->setFont(SCScheme.fonts.normal);
_ui.label_2->setFont(SCScheme.fonts.normal);
_ui.labelLatitude->setFont(SCScheme.fonts.highlight);
_ui.labelLongitude->setFont(SCScheme.fonts.highlight);
_ui.labelLatitude->setText(QString("%1 %2").arg(lat, 0, 'f', 2).arg(QChar(0x00b0)));
_ui.labelLongitude->setText(QString("%1 %2").arg(lon, 0, 'f', 2).arg(QChar(0x00b0)));
int y = 0, M = 0, d = 0, h = 0, m = 0, s = 0;
time.get(&y, &M, &d, &h, &m, &s);
_ui.timeEdit->setTime(QTime(h, m, s));
_ui.dateEdit->setDate(QDate(y, M, d));
}
Seiscomp::Core::Time OriginTimeDialog::time() const {
QDateTime dt(_ui.dateEdit->date(), _ui.timeEdit->time());
Seiscomp::Core::Time t;
t.set(_ui.dateEdit->date().year(),
_ui.dateEdit->date().month(),
_ui.dateEdit->date().day(),
_ui.timeEdit->time().hour(),
_ui.timeEdit->time().minute(),
_ui.timeEdit->time().second(),
0);
return t;
}
}
}
| 33.53125 | 86 | 0.50699 | thefroid |
438c54506c0dcea5576988d6b396a53ce333725f | 4,550 | cpp | C++ | core/src/marker/marker.cpp | bentley/tangram-es | 5bbc422506580f0cbd7988533004b9b445f8fd2d | [
"MIT"
] | null | null | null | core/src/marker/marker.cpp | bentley/tangram-es | 5bbc422506580f0cbd7988533004b9b445f8fd2d | [
"MIT"
] | null | null | null | core/src/marker/marker.cpp | bentley/tangram-es | 5bbc422506580f0cbd7988533004b9b445f8fd2d | [
"MIT"
] | null | null | null | #include "marker/marker.h"
#include "data/tileData.h"
#include "gl/texture.h"
#include "scene/dataLayer.h"
#include "scene/drawRule.h"
#include "scene/scene.h"
#include "style/style.h"
#include "view/view.h"
#include "glm/gtc/matrix_transform.hpp"
#include "glm/gtx/transform.hpp"
namespace Tangram {
Marker::Marker(MarkerID id) : m_id(id) {
m_drawRuleSet.reset(new DrawRuleMergeSet());
}
Marker::~Marker() {
}
void Marker::setBounds(BoundingBox bounds) {
m_bounds = bounds;
m_origin = bounds.min; // South-West corner
}
void Marker::setFeature(std::unique_ptr<Feature> feature) {
m_feature = std::move(feature);
}
void Marker::setStyling(std::string styling, bool isPath) {
m_styling.string = styling;
m_styling.isPath = isPath;
}
bool Marker::evaluateRuleForContext(StyleContext& ctx) {
return m_drawRuleSet->evaluateRuleForContext(*drawRule(), ctx);
}
void Marker::setDrawRuleData(std::unique_ptr<DrawRuleData> drawRuleData) {
m_drawRuleData = std::move(drawRuleData);
m_drawRule = std::make_unique<DrawRule>(*m_drawRuleData, "", 0);
}
void Marker::mergeRules(const SceneLayer& layer) {
m_drawRuleSet->mergeRules(layer);
}
bool Marker::finalizeRuleMergingForName(const std::string& name) {
bool found = false;
for (auto& rule : m_drawRuleSet->matchedRules()) {
if (name == *rule.name) {
m_drawRule = std::make_unique<DrawRule>(rule);
found = true;
break;
}
}
if (found) {
// Clear leftover data (outside the loop so we don't invalidate iterators).
m_drawRuleData.reset(nullptr);
m_drawRuleSet->matchedRules().clear();
}
return found;
}
void Marker::setMesh(uint32_t styleId, uint32_t zoom, std::unique_ptr<StyledMesh> mesh) {
m_mesh = std::move(mesh);
m_styleId = styleId;
m_builtZoomLevel = zoom;
float scale;
if (m_feature && m_feature->geometryType == GeometryType::points) {
scale = (MapProjection::HALF_CIRCUMFERENCE * 2) / (1 << zoom);
} else {
scale = modelScale();
}
m_modelMatrix = glm::scale(glm::vec3(scale));
}
void Marker::clearMesh() {
m_mesh.reset();
}
void Marker::setTexture(std::unique_ptr<Texture> texture) {
m_texture = std::move(texture);
}
void Marker::setEase(const glm::dvec2& dest, float duration, EaseType e) {
auto origin = m_origin;
auto cb = [=](float t) { m_origin = { ease(origin.x, dest.x, t, e), ease(origin.y, dest.y, t, e) }; };
m_ease = { duration, cb };
}
void Marker::update(float dt, const View& view) {
// Update easing
if (!m_ease.finished()) { m_ease.update(dt); }
// Apply marker-view translation to the model matrix
const auto& viewOrigin = view.getPosition();
m_modelMatrix[3][0] = m_origin.x - viewOrigin.x;
m_modelMatrix[3][1] = m_origin.y - viewOrigin.y;
m_modelViewProjectionMatrix = view.getViewProjectionMatrix() * m_modelMatrix;
}
void Marker::setVisible(bool visible) {
m_visible = visible;
}
void Marker::setDrawOrder(int drawOrder) {
m_drawOrder = drawOrder;
}
void Marker::setSelectionColor(uint32_t selectionColor) {
m_selectionColor = selectionColor;
}
int Marker::builtZoomLevel() const {
return m_builtZoomLevel;
}
int Marker::drawOrder() const {
return m_drawOrder;
}
MarkerID Marker::id() const {
return m_id;
}
uint32_t Marker::styleId() const {
return m_styleId;
}
float Marker::extent() const {
return glm::max(m_bounds.width(), m_bounds.height());
}
float Marker::modelScale() const {
return glm::max(extent(), 4096.0f);
}
Feature* Marker::feature() const {
return m_feature.get();
}
DrawRule* Marker::drawRule() const {
return m_drawRule.get();
}
StyledMesh* Marker::mesh() const {
return m_mesh.get();
}
Texture* Marker::texture() const {
return m_texture.get();
}
const BoundingBox& Marker::bounds() const {
return m_bounds;
}
const glm::dvec2& Marker::origin() const {
return m_origin;
}
const glm::mat4& Marker::modelMatrix() const {
return m_modelMatrix;
}
const glm::mat4& Marker::modelViewProjectionMatrix() const {
return m_modelViewProjectionMatrix;
}
bool Marker::isEasing() const {
return !m_ease.finished();
}
bool Marker::isVisible() const {
return m_visible;
}
uint32_t Marker::selectionColor() const {
return m_selectionColor;
}
bool Marker::compareByDrawOrder(const std::unique_ptr<Marker>& lhs, const std::unique_ptr<Marker>& rhs) {
return lhs->m_drawOrder < rhs->m_drawOrder;
}
} // namespace Tangram
| 23.82199 | 106 | 0.678242 | bentley |
438e255560f37998bb483abf87bface559867087 | 849 | cpp | C++ | CFB_Cursos/QT/Qtimer/Qtime/mainwindow.cpp | marcospontoexe/Cpp | d640be32fda2a25f871271e024efef727e7890c1 | [
"MIT"
] | null | null | null | CFB_Cursos/QT/Qtimer/Qtime/mainwindow.cpp | marcospontoexe/Cpp | d640be32fda2a25f871271e024efef727e7890c1 | [
"MIT"
] | null | null | null | CFB_Cursos/QT/Qtimer/Qtime/mainwindow.cpp | marcospontoexe/Cpp | d640be32fda2a25f871271e024efef727e7890c1 | [
"MIT"
] | null | null | null | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDateTime> //biblioteca para trabalhar com da e hora
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
tempo = new QTimer(this); //instanciando o objeto 'tempo'
connect(tempo, SIGNAL(timeout()), this, SLOT(relogio())); //conxão entr um sinal e um slot
tempo->start(1000); //dispara o sinal 'tempo' a cada 1 segundo, executando a função 'funcaoTempo'.
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::relogio()
{
QTime tempoatual = QTime::currentTime(); //retorna o tempo do sistema operacional
QString data = tempoatual.toString("hh:mm:ss"); //converte de QString para QString
ui->textEdit->setText(data);
}
| 30.321429 | 118 | 0.640754 | marcospontoexe |
438f3afed3f10f33c3a03dc3eecc64cefa9e07da | 2,551 | cpp | C++ | embedbin/embedbin.cpp | omega-graphics/common | 8e5202b2b0f93b5d40eb56a77e888181fb30e02d | [
"Apache-2.0"
] | null | null | null | embedbin/embedbin.cpp | omega-graphics/common | 8e5202b2b0f93b5d40eb56a77e888181fb30e02d | [
"Apache-2.0"
] | null | null | null | embedbin/embedbin.cpp | omega-graphics/common | 8e5202b2b0f93b5d40eb56a77e888181fb30e02d | [
"Apache-2.0"
] | null | null | null | #include <omega-common/common.h>
#include <iostream>
using namespace OmegaCommon;
static Map<String,String> srcs;
inline void extractSources(StrRef lineBuffer){
std::string name,src;
auto line_it = lineBuffer.begin();
while(line_it != lineBuffer.end()){
auto & c =*line_it;
if(c == '=') {
break;
}
name.push_back(c);
++line_it;
};
++line_it;
while(line_it != lineBuffer.end()){
auto & c =*line_it;
src.push_back(c);
++line_it;
};
srcs.insert(std::make_pair(name,src));
};
auto header =
R"(// WARNING!! This file was generated by omega-ebin.
// )";
#define STATIC_BUFFER_DECLARE "const char "
#define CHAR_LINE_MAX 20
int main(int argc,char *argv[]){
StrRef input;
StrRef output;
for(unsigned i = 1;i < argc;i++){
StrRef in(argv[i]);
if(in == "-o"){
output = argv[++i];
}
else if(in == "-i"){
input = argv[++i];
};
};
std::ifstream infile {input,std::ios::in};
if (infile.is_open()) {
while(!infile.eof()){
std::string line;
std::getline(infile,line);
// std::cout << line << std::endl;
extractSources(line);
}
}
else {
std::cerr << "ERROR: " << input.data() << " cannot be opened. Exiting..." << std::endl;
exit(1);
}
infile.close();
std::ofstream out {output.data(),std::ios::out};
auto p = FS::Path(input);
std::cout << p.dir() << std::endl;
FS::changeCWD(p.dir());
out << header << std::endl;
for(auto & s : srcs){
out << STATIC_BUFFER_DECLARE << s.first << "[] =";
out << "{";
std::ifstream binIn(s.second,std::ios::binary | std::ios::in);
if(!binIn.is_open()){
std::cerr << "ERROR: " << s.second << " cannot be opened. Exiting..." << std::endl;
exit(1);
};
unsigned c_count = 0;
out << std::hex;
while(!binIn.eof()) {
int c = binIn.get();
++c_count;
if(!binIn.eof()){
out << "0x" << c;
}
else {
break;
}
if(!binIn.eof()){
out << ",";
};
if(c_count >= CHAR_LINE_MAX){
out << std::endl;
c_count = 0;
};
}
out << std::dec;
out << "};" << std::endl;
};
out.close();
return 0;
}; | 22.377193 | 95 | 0.457468 | omega-graphics |
43905339e20daf104fb8ad1aa63423c9a409019e | 7,832 | cpp | C++ | modules/unitest/core/test_perf_calculator.cpp | 7956968/CNStream | bcf746676c137bc6f21ab7ae3523c7ddf71737d0 | [
"Apache-2.0"
] | null | null | null | modules/unitest/core/test_perf_calculator.cpp | 7956968/CNStream | bcf746676c137bc6f21ab7ae3523c7ddf71737d0 | [
"Apache-2.0"
] | null | null | null | modules/unitest/core/test_perf_calculator.cpp | 7956968/CNStream | bcf746676c137bc6f21ab7ae3523c7ddf71737d0 | [
"Apache-2.0"
] | 1 | 2021-02-24T03:24:14.000Z | 2021-02-24T03:24:14.000Z | /*************************************************************************
* Copyright (C) [2019] by Cambricon, Inc. 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
*
* 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 <glog/logging.h>
#include <gtest/gtest.h>
#include <cmath>
#include <memory>
#include <string>
#include <vector>
#include "cnstream_time_utility.hpp"
#include "sqlite_db.hpp"
#include "perf_calculator.hpp"
#include "perf_manager.hpp"
namespace cnstream {
extern bool CreateDir(std::string path);
extern std::string gTestPerfDir;
extern std::string gTestPerfFile;
TEST(PerfCalculator, PrintLatency) {
PerfStats stats = {10100, 20010, 1600, 100.5};
PrintLatency(stats);
}
TEST(PerfCalculator, PrintThroughput) {
PerfStats stats = {10100, 20010, 1600, 100.5};
PrintThroughput(stats);
}
TEST(PerfCalculator, PrintPerfStats) {
PerfStats stats = {10123, 20001, 1600, 100.526};
PrintPerfStats(stats);
}
TEST(PerfCalculator, Construct) {
PerfCalculator perf_cal;
EXPECT_EQ(perf_cal.pre_time_, unsigned(0));
}
TEST(PerfCalculator, CalcLatency) {
CreateDir(gTestPerfDir);
remove(gTestPerfFile.c_str());
PerfCalculator perf_cal;
auto sql = std::make_shared<Sqlite>(gTestPerfFile);
std::string table_name = "TEST";
sql->Connect();
std::vector<std::string> keys = {"a", "b"};
sql->CreateTable(table_name, "ID", keys);
size_t total = 0;
size_t max = 0;
uint32_t data_num = 10;
for (uint32_t i = 0; i < data_num; i++) {
size_t start = TimeStamp::Current();
std::this_thread::sleep_for(std::chrono::microseconds(10 + i));
size_t end = TimeStamp::Current();
sql->Insert(table_name, "ID,a,b", std::to_string(i) + ","+ std::to_string(start) + "," + std::to_string(end));
size_t duration = end - start;
total += duration;
if (duration > max) max = duration;
}
PerfStats stats = perf_cal.CalcLatency(sql, table_name, keys[0], keys[1]);
#ifdef HAVE_SQLITE
EXPECT_EQ(stats.latency_avg, total / data_num);
EXPECT_EQ(stats.latency_max, max);
EXPECT_EQ(stats.frame_cnt, data_num);
EXPECT_EQ(perf_cal.GetLatency().latency_avg, total / data_num);
EXPECT_EQ(perf_cal.GetLatency().latency_max, max);
EXPECT_EQ(perf_cal.GetLatency().frame_cnt, data_num);
#else
EXPECT_EQ(stats.latency_avg, (unsigned)0);
EXPECT_EQ(stats.latency_max, (unsigned)0);
EXPECT_EQ(stats.frame_cnt, (unsigned)0);
#endif
remove(gTestPerfFile.c_str());
}
void CheckForZeroLatency(PerfStats stats, uint32_t line) {
EXPECT_EQ(stats.latency_avg, (unsigned)0) << "wrong line = " << line;
EXPECT_EQ(stats.latency_max, (unsigned)0) << "wrong line = " << line;
EXPECT_EQ(stats.frame_cnt, (unsigned)0) << "wrong line = " << line;
}
TEST(PerfCalculator, CalcLatencyFailedCase) {
CreateDir(gTestPerfDir);
remove(gTestPerfFile.c_str());
PerfCalculator perf_cal;
PerfStats stats = perf_cal.CalcLatency(nullptr, "", "", "");
CheckForZeroLatency(stats, __LINE__);
auto sql = std::make_shared<Sqlite>(gTestPerfFile);
std::string table_name = "TEST";
sql->Connect();
std::vector<std::string> keys = {"a", "b"};
sql->CreateTable(table_name, "ID", keys);
stats = perf_cal.CalcLatency(sql, "", "", "");
CheckForZeroLatency(stats, __LINE__);
// no start and end time
stats = perf_cal.CalcLatency(sql, table_name, keys[0], keys[1]);
CheckForZeroLatency(stats, __LINE__);
// no start, but only end time
size_t end = TimeStamp::Current();
sql->Insert(table_name, "ID,b", "0,"+ std::to_string(end));
stats = perf_cal.CalcLatency(sql, table_name, keys[0], keys[1]);
CheckForZeroLatency(stats, __LINE__);
std::this_thread::sleep_for(std::chrono::microseconds(10));
size_t start = TimeStamp::Current();
sql->Update(table_name, "a", std::to_string(start), "ID", "0");
// end - start is negtive
stats = perf_cal.CalcLatency(sql, table_name, keys[0], keys[1]);
CheckForZeroLatency(stats, __LINE__);
remove(gTestPerfFile.c_str());
}
TEST(PerfCalculator, CalcThroughputByTotalTime) {
CreateDir(gTestPerfDir);
remove(gTestPerfFile.c_str());
PerfCalculator perf_cal;
auto sql = std::make_shared<Sqlite>(gTestPerfFile);
std::string table_name = "TEST";
sql->Connect();
std::vector<std::string> keys = {"a", "b"};
sql->CreateTable(table_name, "ID", keys);
uint32_t data_num = 10;
size_t start = TimeStamp::Current();
sql->Insert(table_name, "ID,a,b", "0,"+ std::to_string(start) + "," + std::to_string(TimeStamp::Current()));
for (uint32_t i = 1; i < data_num - 1; i++) {
size_t s = TimeStamp::Current();
std::this_thread::sleep_for(std::chrono::microseconds(10 + i));
size_t e = TimeStamp::Current();
sql->Insert(table_name, "ID,a,b", std::to_string(i) + ","+ std::to_string(s) + "," + std::to_string(e));
}
size_t end = TimeStamp::Current();
sql->Insert(table_name, "ID,a,b", std::to_string(data_num - 1) + "," + std::to_string(TimeStamp::Current()) +
"," + std::to_string(end));
PerfStats stats = perf_cal.CalcThroughputByTotalTime(sql, table_name, keys[0], keys[1]);
#ifdef HAVE_SQLITE
EXPECT_EQ(stats.frame_cnt, data_num);
EXPECT_DOUBLE_EQ(stats.fps, ceil(static_cast<double>(data_num) * 1e7 / (end -start)) / 10.0);
#else
EXPECT_EQ(stats.frame_cnt, (unsigned)0);
EXPECT_DOUBLE_EQ(stats.fps, 0);
#endif
EXPECT_DOUBLE_EQ(stats.fps, perf_cal.GetThroughput().fps);
remove(gTestPerfFile.c_str());
}
TEST(PerfCalculator, CalcThroughputByTotalTimeFailedCase) {
CreateDir(gTestPerfDir);
remove(gTestPerfFile.c_str());
PerfCalculator perf_cal;
PerfStats stats = perf_cal.CalcThroughputByTotalTime(nullptr, "", "", "");
CheckForZeroLatency(stats, __LINE__);
auto sql = std::make_shared<Sqlite>(gTestPerfFile);
std::string table_name = "TEST";
sql->Connect();
std::vector<std::string> keys = {"a", "b"};
sql->CreateTable(table_name, "ID", keys);
stats = perf_cal.CalcThroughputByTotalTime(sql, "", "", "");
CheckForZeroLatency(stats, __LINE__);
// no start and end time
stats = perf_cal.CalcThroughputByTotalTime(sql, table_name, keys[0], keys[1]);
CheckForZeroLatency(stats, __LINE__);
// no start, but only end time
size_t end = TimeStamp::Current();
sql->Insert(table_name, "ID,b", "0,"+ std::to_string(end));
stats = perf_cal.CalcThroughputByTotalTime(sql, table_name, keys[0], keys[1]);
CheckForZeroLatency(stats, __LINE__);
std::this_thread::sleep_for(std::chrono::microseconds(10));
size_t start = TimeStamp::Current();
sql->Update(table_name, "a", std::to_string(start), "ID", "0");
// end - start is negtive
stats = perf_cal.CalcThroughputByTotalTime(sql, table_name, keys[0], keys[1]);
CheckForZeroLatency(stats, __LINE__);
// no end, but only start time
sql->Delete(table_name, "ID", "0");
sql->Insert(table_name, "ID,a", "0,"+ std::to_string(start));
stats = perf_cal.CalcThroughputByTotalTime(sql, table_name, keys[0], keys[1]);
CheckForZeroLatency(stats, __LINE__);
remove(gTestPerfFile.c_str());
}
} // namespace cnstream
| 36.943396 | 114 | 0.689479 | 7956968 |
43939f54f22cdeaf48879c39dcc06fe7c76f053f | 982 | hpp | C++ | src/stan/lang/ast/type/cholesky_factor_cov_block_type.hpp | ludkinm/stan | c318114f875266f22c98cf0bebfff928653727cb | [
"CC-BY-3.0",
"BSD-3-Clause"
] | null | null | null | src/stan/lang/ast/type/cholesky_factor_cov_block_type.hpp | ludkinm/stan | c318114f875266f22c98cf0bebfff928653727cb | [
"CC-BY-3.0",
"BSD-3-Clause"
] | null | null | null | src/stan/lang/ast/type/cholesky_factor_cov_block_type.hpp | ludkinm/stan | c318114f875266f22c98cf0bebfff928653727cb | [
"CC-BY-3.0",
"BSD-3-Clause"
] | null | null | null | #ifndef STAN_LANG_AST_CHOLESKY_FACTOR_COV_BLOCK_TYPE_HPP
#define STAN_LANG_AST_CHOLESKY_FACTOR_COV_BLOCK_TYPE_HPP
#include <stan/lang/ast/node/expression.hpp>
namespace stan {
namespace lang {
/**
* Cholesky factor for covariance matrix block var type.
*
* Note: no 1-arg constructor for square matrix;
* both row and column dimensions always required.
*/
struct cholesky_factor_cov_block_type {
/**
* Number of rows.
*/
expression M_;
/**
* Number of columns.
*/
expression N_;
/**
* Construct a block var type with default values.
*/
cholesky_factor_cov_block_type();
/**
* Construct a block var type with specified values.
*
* @param M num rows
* @param N num columns
*/
cholesky_factor_cov_block_type(const expression& M, const expression& N);
/**
* Get M (num rows).
*/
expression M() const;
/**
* Get N (num cols).
*/
expression N() const;
};
} // namespace lang
} // namespace stan
#endif
| 18.528302 | 75 | 0.675153 | ludkinm |
4395318524735808268a8d6502e3eaf914f4bf26 | 400 | hxx | C++ | sourceCode/dotNet4.6/wpf/src/Shared/inc/utils.hxx | csoap/csoap.github.io | 2a8db44eb63425deff147652b65c5912f065334e | [
"Apache-2.0"
] | 5 | 2017-03-03T02:13:16.000Z | 2021-08-18T09:59:56.000Z | sourceCode/dotNet4.6/wpf/src/Shared/inc/utils.hxx | 295007712/295007712.github.io | 25241dbf774427545c3ece6534be6667848a6faf | [
"Apache-2.0"
] | null | null | null | sourceCode/dotNet4.6/wpf/src/Shared/inc/utils.hxx | 295007712/295007712.github.io | 25241dbf774427545c3ece6534be6667848a6faf | [
"Apache-2.0"
] | 4 | 2016-11-15T05:20:12.000Z | 2021-11-13T16:32:11.000Z | #pragma once
#include <sal.h>
#include <codeanalysis/sourceannotations.h> // TEMPORARY INCLUDE
#include <Windows.h>
namespace WPFUtils {
LONG ReadRegistryString(__in HKEY rootKey, __in LPCWSTR keyName, __in LPCWSTR valueName,
__out LPWSTR value, size_t cchMax);
HRESULT GetWPFInstallPath(__out_ecount(cchMaxPath) LPWSTR pszPath, size_t cchMaxPath);
}
| 28.571429 | 92 | 0.71 | csoap |
4399b0c7d5ea94cc879f4d6cdfd02ef4c5ed5a9d | 6,283 | cpp | C++ | src/eepp/math/transform.cpp | jayrulez/eepp | 09c5c1b6b4c0306bb0a188474778c6949b5df3a7 | [
"MIT"
] | 37 | 2020-01-20T06:21:24.000Z | 2022-03-21T17:44:50.000Z | src/eepp/math/transform.cpp | jayrulez/eepp | 09c5c1b6b4c0306bb0a188474778c6949b5df3a7 | [
"MIT"
] | null | null | null | src/eepp/math/transform.cpp | jayrulez/eepp | 09c5c1b6b4c0306bb0a188474778c6949b5df3a7 | [
"MIT"
] | 9 | 2019-03-22T00:33:07.000Z | 2022-03-01T01:35:59.000Z | #include <cmath>
#include <eepp/math/transform.hpp>
namespace EE { namespace Math {
const Transform Transform::Identity;
Transform::Transform() {
// Identity matrix
mMatrix[0] = 1.f;
mMatrix[4] = 0.f;
mMatrix[8] = 0.f;
mMatrix[12] = 0.f;
mMatrix[1] = 0.f;
mMatrix[5] = 1.f;
mMatrix[9] = 0.f;
mMatrix[13] = 0.f;
mMatrix[2] = 0.f;
mMatrix[6] = 0.f;
mMatrix[10] = 1.f;
mMatrix[14] = 0.f;
mMatrix[3] = 0.f;
mMatrix[7] = 0.f;
mMatrix[11] = 0.f;
mMatrix[15] = 1.f;
}
Transform::Transform( float a00, float a01, float a02, float a10, float a11, float a12, float a20,
float a21, float a22 ) {
mMatrix[0] = a00;
mMatrix[4] = a01;
mMatrix[8] = 0.f;
mMatrix[12] = a02;
mMatrix[1] = a10;
mMatrix[5] = a11;
mMatrix[9] = 0.f;
mMatrix[13] = a12;
mMatrix[2] = 0.f;
mMatrix[6] = 0.f;
mMatrix[10] = 1.f;
mMatrix[14] = 0.f;
mMatrix[3] = a20;
mMatrix[7] = a21;
mMatrix[11] = 0.f;
mMatrix[15] = a22;
}
const float* Transform::getMatrix() const {
return mMatrix;
}
Transform Transform::getInverse() const {
// Compute the determinant
float det = mMatrix[0] * ( mMatrix[15] * mMatrix[5] - mMatrix[7] * mMatrix[13] ) -
mMatrix[1] * ( mMatrix[15] * mMatrix[4] - mMatrix[7] * mMatrix[12] ) +
mMatrix[3] * ( mMatrix[13] * mMatrix[4] - mMatrix[5] * mMatrix[12] );
// Compute the inverse if the determinant is not zero
// (don't use an epsilon because the determinant may *really* be tiny)
if ( det != 0.f ) {
return Transform( ( mMatrix[15] * mMatrix[5] - mMatrix[7] * mMatrix[13] ) / det,
-( mMatrix[15] * mMatrix[4] - mMatrix[7] * mMatrix[12] ) / det,
( mMatrix[13] * mMatrix[4] - mMatrix[5] * mMatrix[12] ) / det,
-( mMatrix[15] * mMatrix[1] - mMatrix[3] * mMatrix[13] ) / det,
( mMatrix[15] * mMatrix[0] - mMatrix[3] * mMatrix[12] ) / det,
-( mMatrix[13] * mMatrix[0] - mMatrix[1] * mMatrix[12] ) / det,
( mMatrix[7] * mMatrix[1] - mMatrix[3] * mMatrix[5] ) / det,
-( mMatrix[7] * mMatrix[0] - mMatrix[3] * mMatrix[4] ) / det,
( mMatrix[5] * mMatrix[0] - mMatrix[1] * mMatrix[4] ) / det );
} else {
return Identity;
}
}
Vector2f Transform::transformPoint( float x, float y ) const {
return Vector2f( mMatrix[0] * x + mMatrix[4] * y + mMatrix[12],
mMatrix[1] * x + mMatrix[5] * y + mMatrix[13] );
}
Vector2f Transform::transformPoint( const Vector2f& point ) const {
return transformPoint( point.x, point.y );
}
Rectf Transform::transformRect( const Rectf& rectangle ) const {
// Transform the 4 corners of the rectangle
const Vector2f points[] = {
transformPoint( rectangle.Left, rectangle.Top ),
transformPoint( rectangle.Left, rectangle.Top + rectangle.Bottom ),
transformPoint( rectangle.Left + rectangle.Right, rectangle.Top ),
transformPoint( rectangle.Left + rectangle.Right, rectangle.Top + rectangle.Bottom )};
// Compute the bounding rectangle of the transformed points
float left = points[0].x;
float top = points[0].y;
float right = points[0].x;
float bottom = points[0].y;
for ( int i = 1; i < 4; ++i ) {
if ( points[i].x < left )
left = points[i].x;
else if ( points[i].x > right )
right = points[i].x;
if ( points[i].y < top )
top = points[i].y;
else if ( points[i].y > bottom )
bottom = points[i].y;
}
return Rectf( left, top, right - left, bottom - top );
}
Transform& Transform::combine( const Transform& transform ) {
const float* a = mMatrix;
const float* b = transform.mMatrix;
*this = Transform(
a[0] * b[0] + a[4] * b[1] + a[12] * b[3], a[0] * b[4] + a[4] * b[5] + a[12] * b[7],
a[0] * b[12] + a[4] * b[13] + a[12] * b[15], a[1] * b[0] + a[5] * b[1] + a[13] * b[3],
a[1] * b[4] + a[5] * b[5] + a[13] * b[7], a[1] * b[12] + a[5] * b[13] + a[13] * b[15],
a[3] * b[0] + a[7] * b[1] + a[15] * b[3], a[3] * b[4] + a[7] * b[5] + a[15] * b[7],
a[3] * b[12] + a[7] * b[13] + a[15] * b[15] );
return *this;
}
Transform& Transform::translate( float x, float y ) {
Transform translation( 1, 0, x, 0, 1, y, 0, 0, 1 );
return combine( translation );
}
Transform& Transform::translate( const Vector2f& offset ) {
return translate( offset.x, offset.y );
}
Transform& Transform::rotate( float angle ) {
float rad = angle * 3.141592654f / 180.f;
float cos = std::cos( rad );
float sin = std::sin( rad );
Transform rotation( cos, -sin, 0, sin, cos, 0, 0, 0, 1 );
return combine( rotation );
}
Transform& Transform::rotate( float angle, float centerX, float centerY ) {
float rad = angle * 3.141592654f / 180.f;
float cos = std::cos( rad );
float sin = std::sin( rad );
Transform rotation( cos, -sin, centerX * ( 1 - cos ) + centerY * sin, sin, cos,
centerY * ( 1 - cos ) - centerX * sin, 0, 0, 1 );
return combine( rotation );
}
Transform& Transform::rotate( float angle, const Vector2f& center ) {
return rotate( angle, center.x, center.y );
}
Transform& Transform::scale( float scaleX, float scaleY ) {
Transform scaling( scaleX, 0, 0, 0, scaleY, 0, 0, 0, 1 );
return combine( scaling );
}
Transform& Transform::scale( float scaleX, float scaleY, float centerX, float centerY ) {
Transform scaling( scaleX, 0, centerX * ( 1 - scaleX ), 0, scaleY, centerY * ( 1 - scaleY ), 0,
0, 1 );
return combine( scaling );
}
Transform& Transform::scale( const Vector2f& factors ) {
return scale( factors.x, factors.y );
}
Transform& Transform::scale( const Vector2f& factors, const Vector2f& center ) {
return scale( factors.x, factors.y, center.x, center.y );
}
Transform operator*( const Transform& left, const Transform& right ) {
return Transform( left ).combine( right );
}
Transform& operator*=( Transform& left, const Transform& right ) {
return left.combine( right );
}
Vector2f operator*( const Transform& left, const Vector2f& right ) {
return left.transformPoint( right );
}
bool operator==( const Transform& left, const Transform& right ) {
const float* a = left.getMatrix();
const float* b = right.getMatrix();
return ( ( a[0] == b[0] ) && ( a[1] == b[1] ) && ( a[3] == b[3] ) && ( a[4] == b[4] ) &&
( a[5] == b[5] ) && ( a[7] == b[7] ) && ( a[12] == b[12] ) && ( a[13] == b[13] ) &&
( a[15] == b[15] ) );
}
bool operator!=( const Transform& left, const Transform& right ) {
return !( left == right );
}
}} // namespace EE::Math
| 30.352657 | 98 | 0.604488 | jayrulez |
439b2012e979640ea1aaa0bdaf7f644278b03299 | 10,721 | cpp | C++ | src/modules/processes/ImageIntegration/HDRCompositionParameters.cpp | GeorgViehoever/PCL | c4a4390185db3ccb04471f845d92917cc1bc1113 | [
"JasPer-2.0"
] | null | null | null | src/modules/processes/ImageIntegration/HDRCompositionParameters.cpp | GeorgViehoever/PCL | c4a4390185db3ccb04471f845d92917cc1bc1113 | [
"JasPer-2.0"
] | null | null | null | src/modules/processes/ImageIntegration/HDRCompositionParameters.cpp | GeorgViehoever/PCL | c4a4390185db3ccb04471f845d92917cc1bc1113 | [
"JasPer-2.0"
] | null | null | null | // ____ ______ __
// / __ \ / ____// /
// / /_/ // / / /
// / ____// /___ / /___ PixInsight Class Library
// /_/ \____//_____/ PCL 02.01.01.0784
// ----------------------------------------------------------------------------
// Standard ImageIntegration Process Module Version 01.09.04.0322
// ----------------------------------------------------------------------------
// HDRCompositionParameters.cpp - Released 2016/02/21 20:22:43 UTC
// ----------------------------------------------------------------------------
// This file is part of the standard ImageIntegration PixInsight module.
//
// Copyright (c) 2003-2016 Pleiades Astrophoto S.L. All Rights Reserved.
//
// Redistribution and use in both source and binary forms, with or without
// modification, is permitted provided that the following conditions are met:
//
// 1. All redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. All 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 names "PixInsight" and "Pleiades Astrophoto", nor the names
// of their contributors, may be used to endorse or promote products derived
// from this software without specific prior written permission. For written
// permission, please contact info@pixinsight.com.
//
// 4. All products derived from this software, in any form whatsoever, must
// reproduce the following acknowledgment in the end-user documentation
// and/or other materials provided with the product:
//
// "This product is based on software from the PixInsight project, developed
// by Pleiades Astrophoto and its contributors (http://pixinsight.com/)."
//
// Alternatively, if that is where third-party acknowledgments normally
// appear, this acknowledgment must be reproduced in the product itself.
//
// THIS SOFTWARE IS PROVIDED BY PLEIADES ASTROPHOTO AND ITS 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 PLEIADES ASTROPHOTO OR ITS
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, BUSINESS
// INTERRUPTION; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; AND LOSS OF USE,
// DATA OR PROFITS) 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 "HDRCompositionParameters.h"
namespace pcl
{
// ----------------------------------------------------------------------------
HCImages* TheHCImagesParameter = 0;
HCImageEnabled* TheHCImageEnabledParameter = 0;
HCImagePath* TheHCImagePathParameter = 0;
HCInputHints* TheHCInputHintsParameter = 0;
HCMaskBinarizingThreshold* TheHCMaskBinarizingThresholdParameter = 0;
HCMaskSmoothness* TheHCMaskSmoothnessParameter = 0;
HCMaskGrowth* TheHCMaskGrowthParameter = 0;
HCAutoExposures* TheHCAutoExposuresParameter = 0;
HCRejectBlack* TheHCRejectBlackParameter = 0;
HCUseFittingRegion* TheHCUseFittingRegionParameter = 0;
HCFittingRectX0* TheHCFittingRectX0Parameter = 0;
HCFittingRectY0* TheHCFittingRectY0Parameter = 0;
HCFittingRectX1* TheHCFittingRectX1Parameter = 0;
HCFittingRectY1* TheHCFittingRectY1Parameter = 0;
HCGenerate64BitResult* TheHCGenerate64BitResultParameter = 0;
HCOutputMasks* TheHCOutputMasksParameter = 0;
HCClosePreviousImages* TheHCClosePreviousImagesParameter = 0;
// ----------------------------------------------------------------------------
HCImages::HCImages( MetaProcess* P ) : MetaTable( P )
{
TheHCImagesParameter = this;
}
IsoString HCImages::Id() const
{
return "images";
}
// ----------------------------------------------------------------------------
HCImageEnabled::HCImageEnabled( MetaTable* T ) : MetaBoolean( T )
{
TheHCImageEnabledParameter = this;
}
IsoString HCImageEnabled::Id() const
{
return "enabled";
}
bool HCImageEnabled::DefaultValue() const
{
return true;
}
// ----------------------------------------------------------------------------
HCImagePath::HCImagePath( MetaTable* T ) : MetaString( T )
{
TheHCImagePathParameter = this;
}
IsoString HCImagePath::Id() const
{
return "path";
}
// ----------------------------------------------------------------------------
HCInputHints::HCInputHints( MetaProcess* P ) : MetaString( P )
{
TheHCInputHintsParameter = this;
}
IsoString HCInputHints::Id() const
{
return "inputHints";
}
// ----------------------------------------------------------------------------
HCMaskBinarizingThreshold::HCMaskBinarizingThreshold( MetaProcess* P ) : MetaFloat( P )
{
TheHCMaskBinarizingThresholdParameter = this;
}
IsoString HCMaskBinarizingThreshold::Id() const
{
return "maskBinarizingThreshold";
}
int HCMaskBinarizingThreshold::Precision() const
{
return 4;
}
double HCMaskBinarizingThreshold::DefaultValue() const
{
return 0.8;
}
double HCMaskBinarizingThreshold::MinimumValue() const
{
return 0;
}
double HCMaskBinarizingThreshold::MaximumValue() const
{
return 1;
}
// ----------------------------------------------------------------------------
HCMaskSmoothness::HCMaskSmoothness( MetaProcess* P ) : MetaInt32( P )
{
TheHCMaskSmoothnessParameter = this;
}
IsoString HCMaskSmoothness::Id() const
{
return "maskSmoothness";
}
double HCMaskSmoothness::DefaultValue() const
{
return 7;
}
double HCMaskSmoothness::MinimumValue() const
{
return 1;
}
double HCMaskSmoothness::MaximumValue() const
{
return 25;
}
// ----------------------------------------------------------------------------
HCMaskGrowth::HCMaskGrowth( MetaProcess* P ) : MetaInt32( P )
{
TheHCMaskGrowthParameter = this;
}
IsoString HCMaskGrowth::Id() const
{
return "maskGrowth";
}
double HCMaskGrowth::DefaultValue() const
{
return 1;
}
double HCMaskGrowth::MinimumValue() const
{
return 0;
}
double HCMaskGrowth::MaximumValue() const
{
return 15;
}
// ----------------------------------------------------------------------------
HCAutoExposures::HCAutoExposures( MetaProcess* P ) : MetaBoolean( P )
{
TheHCAutoExposuresParameter = this;
}
IsoString HCAutoExposures::Id() const
{
return "autoExposures";
}
bool HCAutoExposures::DefaultValue() const
{
return true;
}
// ----------------------------------------------------------------------------
HCRejectBlack::HCRejectBlack( MetaProcess* P ) : MetaBoolean( P )
{
TheHCRejectBlackParameter = this;
}
IsoString HCRejectBlack::Id() const
{
return "rejectBlack";
}
bool HCRejectBlack::DefaultValue() const
{
return true;
}
// ----------------------------------------------------------------------------
HCUseFittingRegion::HCUseFittingRegion( MetaProcess* P ) : MetaBoolean( P )
{
TheHCUseFittingRegionParameter = this;
}
IsoString HCUseFittingRegion::Id() const
{
return "useFittingRegion";
}
bool HCUseFittingRegion::DefaultValue() const
{
return false;
}
// ----------------------------------------------------------------------------
HCFittingRectX0::HCFittingRectX0( MetaProcess* P ) : MetaInt32( P )
{
TheHCFittingRectX0Parameter = this;
}
IsoString HCFittingRectX0::Id() const
{
return "fittingRectX0";
}
double HCFittingRectX0::DefaultValue() const
{
return 0;
}
double HCFittingRectX0::MinimumValue() const
{
return 0;
}
double HCFittingRectX0::MaximumValue() const
{
return int32_max;
}
// ----------------------------------------------------------------------------
HCFittingRectY0::HCFittingRectY0( MetaProcess* P ) : MetaInt32( P )
{
TheHCFittingRectY0Parameter = this;
}
IsoString HCFittingRectY0::Id() const
{
return "fittingRectY0";
}
double HCFittingRectY0::DefaultValue() const
{
return 0;
}
double HCFittingRectY0::MinimumValue() const
{
return 0;
}
double HCFittingRectY0::MaximumValue() const
{
return int32_max;
}
// ----------------------------------------------------------------------------
HCFittingRectX1::HCFittingRectX1( MetaProcess* P ) : MetaInt32( P )
{
TheHCFittingRectX1Parameter = this;
}
IsoString HCFittingRectX1::Id() const
{
return "fittingRectX1";
}
double HCFittingRectX1::DefaultValue() const
{
return 0;
}
double HCFittingRectX1::MinimumValue() const
{
return 0;
}
double HCFittingRectX1::MaximumValue() const
{
return int32_max;
}
// ----------------------------------------------------------------------------
HCFittingRectY1::HCFittingRectY1( MetaProcess* P ) : MetaInt32( P )
{
TheHCFittingRectY1Parameter = this;
}
IsoString HCFittingRectY1::Id() const
{
return "fittingRectY1";
}
double HCFittingRectY1::DefaultValue() const
{
return 0;
}
double HCFittingRectY1::MinimumValue() const
{
return 0;
}
double HCFittingRectY1::MaximumValue() const
{
return int32_max;
}
// ----------------------------------------------------------------------------
HCGenerate64BitResult::HCGenerate64BitResult( MetaProcess* P ) : MetaBoolean( P )
{
TheHCGenerate64BitResultParameter = this;
}
IsoString HCGenerate64BitResult::Id() const
{
return "generate64BitResult";
}
bool HCGenerate64BitResult::DefaultValue() const
{
return true;
}
// ----------------------------------------------------------------------------
HCOutputMasks::HCOutputMasks( MetaProcess* P ) : MetaBoolean( P )
{
TheHCOutputMasksParameter = this;
}
IsoString HCOutputMasks::Id() const
{
return "outputMasks";
}
bool HCOutputMasks::DefaultValue() const
{
return true;
}
// ----------------------------------------------------------------------------
HCClosePreviousImages::HCClosePreviousImages( MetaProcess* P ) : MetaBoolean( P )
{
TheHCClosePreviousImagesParameter = this;
}
IsoString HCClosePreviousImages::Id() const
{
return "closePreviousImages";
}
bool HCClosePreviousImages::DefaultValue() const
{
return false;
}
// ----------------------------------------------------------------------------
} // pcl
// ----------------------------------------------------------------------------
// EOF HDRCompositionParameters.cpp - Released 2016/02/21 20:22:43 UTC
| 24.759815 | 87 | 0.60125 | GeorgViehoever |
439b73ee9ce3bafe529940f35a3d499901dfd0ed | 3,468 | cpp | C++ | src/infra/Files.cpp | dim-lang/dim | 372c4f92030028621ddea9561364ea44a78b4671 | [
"Apache-2.0"
] | null | null | null | src/infra/Files.cpp | dim-lang/dim | 372c4f92030028621ddea9561364ea44a78b4671 | [
"Apache-2.0"
] | null | null | null | src/infra/Files.cpp | dim-lang/dim | 372c4f92030028621ddea9561364ea44a78b4671 | [
"Apache-2.0"
] | 4 | 2021-01-12T09:19:27.000Z | 2021-01-14T01:12:46.000Z | // Copyright 2019- <dim-lang>
// Apache License Version 2.0
#include "infra/Files.h"
#include "infra/Log.h"
#include <cerrno>
#include <cstdio>
#define BUF_SIZE 4096
namespace detail {
FileInfo::FileInfo(const Cowstr &fileName)
: fileName_(fileName), fp_(nullptr) {}
FileInfo::~FileInfo() {
if (fp_) {
std::fclose(fp_);
fp_ = nullptr;
}
}
const Cowstr &FileInfo::fileName() const { return fileName_; }
FileWriterImpl::FileWriterImpl(const Cowstr &fileName) : FileInfo(fileName) {}
FileWriterImpl::~FileWriterImpl() { flush(); }
void FileWriterImpl::reset(int offset) { std::fseek(fp_, offset, SEEK_SET); }
int FileWriterImpl::flush() {
if (buffer_.size() > 0) {
buffer_.writefile(fp_);
}
return std::fflush(fp_) ? errno : 0;
}
int FileWriterImpl::write(const Cowstr &buf) {
int r = buffer_.read(buf.rawstr(), buf.length());
if (buffer_.size() >= BUF_SIZE) {
buffer_.writefile(fp_, BUF_SIZE);
}
return r;
}
int FileWriterImpl::writeln(const Cowstr &buf) {
return write(buf) + write("\n");
}
} // namespace detail
FileReader::FileReader(const Cowstr &fileName) : detail::FileInfo(fileName) {
fp_ = std::fopen(fileName.rawstr(), "r");
LOG_ASSERT(fp_, "fp_ is null, open fileName {} failed", fileName);
}
FileMode FileReader::mode() const { return FileMode::Read; }
void FileReader::reset(int offset) { std::fseek(fp_, offset, SEEK_SET); }
void FileReader::prepareFor(int n) {
if (n <= 0) {
return;
}
if (buffer_.size() < n) {
int c = 0;
do {
c = buffer_.readfile(fp_, BUF_SIZE);
if (buffer_.size() >= n) {
break;
}
} while (c > 0);
}
}
Cowstr FileReader::read(int n) {
if (n <= 0) {
return "";
}
prepareFor(n);
char *buf = new char[n + 1];
std::memset(buf, 0, n + 1);
int c = buffer_.write(buf, n);
Cowstr r(buf, c);
delete[] buf;
return r;
}
Cowstr FileReader::readall() {
buffer_.readfile(fp_);
char *buf = new char[buffer_.size() + 1];
std::memset(buf, 0, buffer_.size() + 1);
int c = buffer_.write(buf, buffer_.size());
Cowstr r(buf, c);
delete[] buf;
return r;
}
Cowstr FileReader::readc() {
prepareFor(1);
char buf;
int c = buffer_.write(&buf, 1);
Cowstr r(&buf, c);
return r;
}
char *FileReader::prepareUntil(char c) {
char *linepos = nullptr;
int n = 0;
do {
n = buffer_.readfile(fp_, BUF_SIZE);
linepos = buffer_.search(c);
if (linepos) {
break;
}
} while (n > 0);
return linepos;
}
Cowstr FileReader::readln() {
char *linepos = prepareUntil('\n');
if (!linepos) {
return "";
}
int len = linepos - buffer_.begin() + 1;
char *buf = new char[len + 1];
std::memset(buf, 0, len + 1);
int c = buffer_.write(buf, len);
Cowstr r(buf, c);
delete[] buf;
return r;
}
FileWriter::FileWriter(const Cowstr &fileName)
: detail::FileWriterImpl(fileName) {
fp_ = std::fopen(fileName.rawstr(), "w");
ASSERT(fp_, "error: cannot open file {}", fileName);
}
FileMode FileWriter::mode() const { return FileMode::Write; }
void FileWriter::reset(int offset) { detail::FileWriterImpl::reset(offset); }
FileAppender::FileAppender(const Cowstr &fileName)
: detail::FileWriterImpl(fileName) {
fp_ = std::fopen(fileName.rawstr(), "a");
LOG_ASSERT(fp_, "fp_ is null, open fileName {} failed", fileName);
}
void FileAppender::reset(int offset) { detail::FileWriterImpl::reset(offset); }
FileMode FileAppender::mode() const { return FileMode::Append; }
| 22.666667 | 79 | 0.636678 | dim-lang |
439d92d2e90d24692e3cb3c3eb69ca9ee737fd66 | 6,303 | cpp | C++ | sdcard.cpp | dizcza/M5Core2_SDPSensorLogger | 6e9eca61642d365f2ec42a9d3b78f59d08a2ddfe | [
"MIT"
] | null | null | null | sdcard.cpp | dizcza/M5Core2_SDPSensorLogger | 6e9eca61642d365f2ec42a9d3b78f59d08a2ddfe | [
"MIT"
] | null | null | null | sdcard.cpp | dizcza/M5Core2_SDPSensorLogger | 6e9eca61642d365f2ec42a9d3b78f59d08a2ddfe | [
"MIT"
] | null | null | null | /*
* sdcard.c
*
* Created on: Sep 8, 2021
* Author: Danylo Ulianych
*/
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <sys/stat.h>
#include "esp_log.h"
#include "esp_err.h"
#include "esp32-hal-log.h"
#include "bsp_log.h"
#include "sdcard.h"
#include "record.h"
#define SDCARD_USE_SPI
#define SDCARD_ALLOCATION_UNIT_SIZE (16 * 1024)
static int m_record_id = 0;
const char *sdcard_mount_point = "/sd";
static char *m_sdcard_record_dir = NULL;
static const char *TAG = "sdcard";
static int sdcard_count_dirs(char *dirpath);
void sdcard_listdir(const char *name, int indent) {
DIR *dir;
struct dirent *entry;
struct stat fstat;
if (!(dir = opendir(name)))
return;
char path[512];
while ((entry = readdir(dir)) != NULL) {
snprintf(path, sizeof(path), "%s/%s", name, entry->d_name);
if (entry->d_type == DT_DIR) {
if (strcmp(entry->d_name, ".") == 0
|| strcmp(entry->d_name, "..") == 0)
continue;
printf("%*s[%s]\n", indent, "", entry->d_name);
sdcard_listdir(path, indent + 2);
} else {
stat(path, &fstat);
printf("%*s- %s: %ld bytes\n", indent, "", entry->d_name, fstat.st_size);
}
}
closedir(dir);
}
static int sdcard_count_dirs(char *dirpath) {
int dircnt = 0;
DIR *directory;
struct dirent *entry;
directory = opendir(dirpath);
if (directory == NULL) {
return 0;
}
while ((entry = readdir(directory)) != NULL) {
if (entry->d_type == DT_DIR) { /* a directory */
dircnt++;
}
}
closedir(directory);
return dircnt;
}
static int8_t sdcard_sdpfile_exists(uint32_t record_id) {
char dirpath[128];
DIR *directory;
struct dirent *entry;
if (record_id == -1) record_id = m_record_id - 1;
const char *sdp_pref = "SDP-";
snprintf(dirpath, sizeof(dirpath), "%s/RECORDS/%03d", sdcard_mount_point, record_id);
directory = opendir(dirpath);
if (directory == NULL) {
return 0;
}
int8_t sdp_exists = 0;
while ((entry = readdir(directory)) != NULL) {
if (entry->d_type == DT_REG /* a regular file */
&& strstr(entry->d_name, sdp_pref) == entry->d_name) { /* a prefix match */
sdp_exists = 1;
break;
}
}
closedir(directory);
return sdp_exists;
}
static void sdcard_remove_record_files(int record_id) {
char dirpath[300];
DIR *directory;
struct dirent *entry;
if (record_id == -1) record_id = m_record_id - 1;
snprintf(dirpath, sizeof(dirpath), "%s/RECORDS/%03d", sdcard_mount_point, record_id);
directory = opendir(dirpath);
if (directory == NULL) {
return;
}
while ((entry = readdir(directory)) != NULL) {
if (entry->d_type == DT_REG ) { /* a regular file */
snprintf(dirpath, sizeof(dirpath), "%s/RECORDS/%03d/%s", sdcard_mount_point, record_id, entry->d_name);
remove(dirpath);
}
}
closedir(directory);
BSP_LOGI(TAG, "Removed files in record %d", record_id);
}
static esp_err_t sdcard_get_sdpfile_path(char *path, int record_id) {
char dirpath[300];
DIR *directory;
struct dirent *entry;
if (record_id == -1) record_id = m_record_id - 1;
const char *sdp_pref = "SDP-";
snprintf(dirpath, sizeof(dirpath), "%s/RECORDS/%03d", sdcard_mount_point, record_id);
directory = opendir(dirpath);
if (directory == NULL) {
return ESP_ERR_NOT_FOUND;
}
int sdp_cnt = 0;
while ((entry = readdir(directory)) != NULL) {
if (entry->d_type == DT_REG /* a regular file */
&& strstr(entry->d_name, sdp_pref) == entry->d_name) { /* a prefix match */
// the files are sorted
sdp_cnt++;
}
}
if (sdp_cnt == 0) {
return ESP_ERR_NOT_FOUND;
}
sprintf(path, "%s/%s%03d.BIN", dirpath, sdp_pref, sdp_cnt - 1);
closedir(directory);
return ESP_OK;
}
int sdcard_get_record_id() {
return m_record_id;
}
void sdcard_create_record_dir() {
char rec_folder[128];
struct stat dstat = { 0 };
snprintf(rec_folder, sizeof(rec_folder), "%s/RECORDS", sdcard_mount_point);
if (stat(rec_folder, &dstat) == -1) {
mkdir(rec_folder, 0700);
}
m_record_id = sdcard_count_dirs(rec_folder);
if (m_record_id > 0) {
m_record_id--;
if (sdcard_sdpfile_exists(m_record_id)) {
// file exists; increment ID
m_record_id++;
}
sdcard_get_record_duration(-1);
// remove logs, BMP files, etc.
sdcard_remove_record_files(m_record_id);
if (m_record_id >= 1000) {
// SD cards don't like long paths
m_record_id = 0;
}
}
snprintf(rec_folder, sizeof(rec_folder), "%s/RECORDS/%03d", sdcard_mount_point, m_record_id);
if (stat(rec_folder, &dstat) == -1) {
mkdir(rec_folder, 0700);
}
char *rec_dir_heap = (char*) malloc(strlen(rec_folder));
strcpy(rec_dir_heap, rec_folder);
if (m_sdcard_record_dir != NULL) {
// clean-up from the previous call
free(m_sdcard_record_dir);
}
m_sdcard_record_dir = rec_dir_heap;
}
const char* sdcard_get_record_dir() {
return (const char*) m_sdcard_record_dir;
}
esp_err_t sdcard_print_content(const char *fpath) {
FILE *f = fopen(fpath, "r");
if (f == NULL) {
BSP_LOGW(TAG, "No such file: '%s'", fpath);
return ESP_ERR_NOT_FOUND;
}
printf("\n>>> BEGIN '%s'\n", fpath);
int c;
while ((c = fgetc(f)) != EOF) {
printf("%c", c);
}
fclose(f);
printf("<<< END '%s'\n\n", fpath);
return ESP_OK;
}
int64_t sdcard_get_record_duration(int record_id) {
char fpath[512];
if (record_id == -1) record_id = m_record_id - 1;
if (sdcard_get_sdpfile_path(fpath, record_id) != ESP_OK) {
return 0;
}
FILE *f = fopen(fpath, "r");
if (f == NULL) {
return 0;
}
fseek(f, 0L, SEEK_END);
long int fsize = ftell(f);
if (fsize % sizeof(SDPRecord) != 0) {
BSP_LOGW(TAG, "%s file is corrupted", fpath);
}
long int records_cnt = fsize / sizeof(SDPRecord);
fseek(f, (records_cnt - 1) * sizeof(SDPRecord), SEEK_SET);
SDPRecord record;
fread(&record, sizeof(SDPRecord), 1, f);
fclose(f);
time_t seconds = (time_t) (record.time / 1000000);
BSP_LOGI(TAG, "Record %d ended %s", record_id, ctime(&seconds));
return record.time;
}
esp_err_t sdcard_print_content_prev(char *fname) {
char fpath[128];
if (m_record_id == 0) {
return ESP_ERR_NOT_FOUND;
}
snprintf(fpath, sizeof(fpath), "%s/RECORDS/%03d/%s", sdcard_mount_point, m_record_id - 1, fname);
return sdcard_print_content(fpath);
}
| 23.606742 | 106 | 0.651436 | dizcza |
439ee7bad86587b44ef2f6ff6d4144a80ddd2af8 | 3,146 | cpp | C++ | src/forced-random-dither.cpp | GhostatSpirit/hdrview | 61596f8ba45554db23ae1b214354ab40da065638 | [
"MIT"
] | 94 | 2021-04-23T03:31:15.000Z | 2022-03-29T08:20:26.000Z | src/forced-random-dither.cpp | GhostatSpirit/hdrview | 61596f8ba45554db23ae1b214354ab40da065638 | [
"MIT"
] | 64 | 2021-05-05T21:51:15.000Z | 2022-02-08T17:06:52.000Z | src/forced-random-dither.cpp | GhostatSpirit/hdrview | 61596f8ba45554db23ae1b214354ab40da065638 | [
"MIT"
] | 3 | 2021-07-06T04:58:27.000Z | 2022-02-08T16:53:48.000Z | /*!
force-random-dither.cpp -- Generate a dither matrix using the force-random-dither method from:
W. Purgathofer, R. F. Tobler and M. Geiler.
"Forced random dithering: improved threshold matrices for ordered dithering"
Image Processing, 1994. Proceedings. ICIP-94., IEEE International Conference,
Austin, TX, 1994, pp. 1032-1035 vol.2.
doi: 10.1109/ICIP.1994.413512
*/
//
// Copyright (C) Wojciech Jarosz <wjarosz@gmail.com>. All rights reserved.
// Use of this source code is governed by a BSD-style license that can
// be found in the LICENSE.txt file.
//
#include <iostream>
#include "array2d.h"
#include <nanogui/vector.h>
#include <vector>
#include <random>
#include <algorithm> // std::random_shuffle
#include <ctime> // std::time
#include <cstdlib> // std::rand, std::srand
using nanogui::Vector2i;
using namespace std;
const int Sm = 128;
const int Smk = Sm*Sm;
double toroidalMinimumDistance(const Vector2i & a, const Vector2i & b)
{
int x0 = min(a.x(), b.x());
int x1 = max(a.x(), b.x());
int y0 = min(a.y(), b.y());
int y1 = max(a.y(), b.y());
double deltaX = min(x1-x0, x0+Sm-x1);
double deltaY = min(y1-y0, y0+Sm-y1);
return sqrt(deltaX*deltaX + deltaY*deltaY);
}
double force(double r)
{
return exp(-sqrt(2*r));
}
int main(int, char **)
{
srand(unsigned ( std::time(0) ) );
std::mt19937 g_rand(unsigned ( std::time(0) ) );
vector<Vector2i> freeLocations;
Array2Dd M = Array2Dd(Sm,Sm,0.0);
Array2Dd forceField = Array2Dd(Sm,Sm,0.0);
// initialize free locations
for (int y = 0; y < Sm; ++y)
for (int x = 0; x < Sm; ++x)
freeLocations.push_back(Vector2i(x,y));
for (int ditherValue = 0; ditherValue < Smk; ++ditherValue)
{
shuffle(freeLocations.begin(), freeLocations.end(), g_rand);
double minimum = 1e20f;
Vector2i minimumLocation(0,0);
// int halfP = freeLocations.size();
int halfP = min(max(1, (int)sqrt(freeLocations.size()*3/4)), (int)freeLocations.size());
// int halfP = min(10, (int)freeLocations.size());
for (int i = 0; i < halfP; ++i)
{
const Vector2i & location = freeLocations[i];
if (forceField(location.x(), location.y()) < minimum)
{
minimum = forceField(location.x(), location.y());
minimumLocation = location;
}
}
Vector2i cell(0,0);
for (cell.y() = 0; cell.y() < Sm; ++cell.y())
for (cell.x() = 0; cell.x() < Sm; ++cell.x())
{
double r = toroidalMinimumDistance(cell, minimumLocation);
forceField(cell.x(), cell.y()) += force(r);
}
freeLocations.erase(remove(freeLocations.begin(), freeLocations.end(), minimumLocation), freeLocations.end());
M(minimumLocation.x(), minimumLocation.y()) = ditherValue;
// if (ditherValue % 16 == 0)
// {
// std::stringstream ss;
// ss << ditherValue;
// writeEXR("forceField-" + ss.str() + ".exr", forceField/(ditherValue+1));
// }
}
// std::cout << M << std::endl;
cout << "unsigned dither_matrix[" << Smk << "] = \n{\n ";
printf("%5d", (int)M(0));
for (int i = 1; i < M.size(); ++i)
{
cout << ", ";
if (i % Sm == 0)
cout << endl << " ";
printf("%5d", (int)M(i));
}
cout << "\n};" << endl;
return 0;
} | 26.888889 | 112 | 0.625238 | GhostatSpirit |
439efd4836183372aa61c81b4f9b78f67cab60ba | 1,656 | cc | C++ | dcmdata/libsrc/dcrledrg.cc | trice-imaging/dcmtk | 60b158654dc7215d938a9ddba92ef5e93ded298d | [
"Apache-2.0"
] | 29 | 2020-02-13T17:40:16.000Z | 2022-03-12T14:58:22.000Z | dcmdata/libsrc/dcrledrg.cc | trice-imaging/dcmtk | 60b158654dc7215d938a9ddba92ef5e93ded298d | [
"Apache-2.0"
] | 20 | 2020-03-20T18:06:31.000Z | 2022-02-25T08:38:08.000Z | dcmdata/libsrc/dcrledrg.cc | trice-imaging/dcmtk | 60b158654dc7215d938a9ddba92ef5e93ded298d | [
"Apache-2.0"
] | 9 | 2020-03-20T17:29:55.000Z | 2022-02-14T10:15:33.000Z | /*
*
* Copyright (C) 1994-2010, OFFIS e.V.
* All rights reserved. See COPYRIGHT file for details.
*
* This software and supporting documentation were developed by
*
* OFFIS e.V.
* R&D Division Health
* Escherweg 2
* D-26121 Oldenburg, Germany
*
*
* Module: dcmdata
*
* Author: Marco Eichelberg
*
* Purpose: singleton class that registers RLE decoder.
*
*/
#include "dcmtk/config/osconfig.h"
#include "dcmtk/dcmdata/dcrledrg.h"
#include "dcmtk/dcmdata/dccodec.h" /* for DcmCodecStruct */
#include "dcmtk/dcmdata/dcrleccd.h" /* for class DcmRLECodecDecoder */
#include "dcmtk/dcmdata/dcrlecp.h" /* for class DcmRLECodecParameter */
// initialization of static members
OFBool DcmRLEDecoderRegistration::registered = OFFalse;
DcmRLECodecParameter *DcmRLEDecoderRegistration::cp = NULL;
DcmRLECodecDecoder *DcmRLEDecoderRegistration::codec = NULL;
void DcmRLEDecoderRegistration::registerCodecs(
OFBool pCreateSOPInstanceUID,
OFBool pReverseDecompressionByteOrder)
{
if (! registered)
{
cp = new DcmRLECodecParameter(
pCreateSOPInstanceUID,
0, OFTrue, OFFalse,
pReverseDecompressionByteOrder);
if (cp)
{
codec = new DcmRLECodecDecoder();
if (codec) DcmCodecList::registerCodec(codec, NULL, cp);
registered = OFTrue;
}
}
}
void DcmRLEDecoderRegistration::cleanup()
{
if (registered)
{
DcmCodecList::deregisterCodec(codec);
delete codec;
delete cp;
registered = OFFalse;
#ifdef DEBUG
// not needed but useful for debugging purposes
codec = NULL;
cp = NULL;
#endif
}
}
| 24 | 72 | 0.67814 | trice-imaging |
43a573f202ee17d44a7fddeeca7e8de732f2eada | 355 | cpp | C++ | source/slang/slang-emit-precedence.cpp | KostasAndrianos/slang | 6cbc3929a54d37bd23cb5efa8e3320ba02f78b2f | [
"MIT"
] | null | null | null | source/slang/slang-emit-precedence.cpp | KostasAndrianos/slang | 6cbc3929a54d37bd23cb5efa8e3320ba02f78b2f | [
"MIT"
] | null | null | null | source/slang/slang-emit-precedence.cpp | KostasAndrianos/slang | 6cbc3929a54d37bd23cb5efa8e3320ba02f78b2f | [
"MIT"
] | null | null | null | // slang-emit-precedence.cpp
#include "slang-emit-precedence.h"
namespace Slang {
#define SLANG_OP_INFO_EXPAND(op, name, precedence) {name, kEPrecedence_##precedence##_Left, kEPrecedence_##precedence##_Right, },
/* static */const EmitOpInfo EmitOpInfo::s_infos[int(EmitOp::CountOf)] =
{
SLANG_OP_INFO(SLANG_OP_INFO_EXPAND)
};
} // namespace Slang
| 25.357143 | 129 | 0.752113 | KostasAndrianos |
43a94cbb80e5f92ae7af3af3af7dbec74132d904 | 27 | cpp | C++ | rtcsupport/I2CBuffer.cpp | jakesays/raspberrypi | 99192a56c097a79f45e2291110ebaa0dcb464ba8 | [
"MIT"
] | null | null | null | rtcsupport/I2CBuffer.cpp | jakesays/raspberrypi | 99192a56c097a79f45e2291110ebaa0dcb464ba8 | [
"MIT"
] | null | null | null | rtcsupport/I2CBuffer.cpp | jakesays/raspberrypi | 99192a56c097a79f45e2291110ebaa0dcb464ba8 | [
"MIT"
] | null | null | null | #include "I2CBuffer.h"
| 9 | 24 | 0.62963 | jakesays |
43ac354d931e7287bd01efed1ba0c56709ae637f | 988 | cpp | C++ | core/runtime/binaryen/module/wasm_module_instance_impl.cpp | igor-egorov/kagome | b2a77061791aa7c1eea174246ddc02ef5be1b605 | [
"Apache-2.0"
] | null | null | null | core/runtime/binaryen/module/wasm_module_instance_impl.cpp | igor-egorov/kagome | b2a77061791aa7c1eea174246ddc02ef5be1b605 | [
"Apache-2.0"
] | null | null | null | core/runtime/binaryen/module/wasm_module_instance_impl.cpp | igor-egorov/kagome | b2a77061791aa7c1eea174246ddc02ef5be1b605 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#include "runtime/binaryen/module/wasm_module_instance_impl.hpp"
#include <binaryen/wasm.h>
namespace kagome::runtime::binaryen {
WasmModuleInstanceImpl::WasmModuleInstanceImpl(
std::shared_ptr<wasm::Module> parent,
const std::shared_ptr<RuntimeExternalInterface> &rei)
: parent_{std::move(parent)},
rei_{rei},
module_instance_{
std::make_unique<wasm::ModuleInstance>(*parent_, rei.get())} {
BOOST_ASSERT(parent_);
BOOST_ASSERT(rei_);
BOOST_ASSERT(module_instance_);
}
wasm::Literal WasmModuleInstanceImpl::callExportFunction(
wasm::Name name, const wasm::LiteralList &arguments) {
return module_instance_->callExport(name, arguments);
}
wasm::Literal WasmModuleInstanceImpl::getExportGlobal(wasm::Name name) {
return module_instance_->getExport(name);
}
} // namespace kagome::runtime::binaryen
| 29.939394 | 74 | 0.714575 | igor-egorov |
43ac64f6f5d0df2355e942b0ff46179e5ec85c7a | 575 | hpp | C++ | fileid/document/excel/records/ContinueRecord.hpp | DBHeise/fileid | 3e3bacf859445020999d0fc30301ac86973c3737 | [
"MIT"
] | 13 | 2016-03-13T17:57:46.000Z | 2021-12-21T12:11:41.000Z | fileid/document/excel/records/ContinueRecord.hpp | DBHeise/fileid | 3e3bacf859445020999d0fc30301ac86973c3737 | [
"MIT"
] | 9 | 2016-04-07T13:07:58.000Z | 2020-05-30T13:31:59.000Z | fileid/document/excel/records/ContinueRecord.hpp | DBHeise/fileid | 3e3bacf859445020999d0fc30301ac86973c3737 | [
"MIT"
] | 5 | 2017-04-20T14:47:55.000Z | 2021-03-08T03:27:17.000Z | #pragma once
#include "Record.hpp"
namespace oless {
namespace excel {
namespace records {
class ContinueRecord : public Record {
public:
ContinueRecord(IRecordParser* p, unsigned short type, std::vector<uint8_t> data) : Record(type, data) {
Record* r = p->GetPrevRecordNotOfType(type);
r->Data.insert(r->Data.end(), data.begin(), data.end());
//TODO: it is problematic to do this during parsing....need a better way
//if (IReParseable* pr = dynamic_cast<IReParseable*>(r)) {
// pr->ReParse(p);
//}
}
};
}
}
}
| 21.296296 | 107 | 0.626087 | DBHeise |
43ad4f10d88e55988d96738286fbc561964d48b8 | 140 | hxx | C++ | src/Providers/UNIXProviders/VLANEndpointSettingData/UNIX_VLANEndpointSettingData_AIX.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | 1 | 2020-10-12T09:00:09.000Z | 2020-10-12T09:00:09.000Z | src/Providers/UNIXProviders/VLANEndpointSettingData/UNIX_VLANEndpointSettingData_AIX.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | src/Providers/UNIXProviders/VLANEndpointSettingData/UNIX_VLANEndpointSettingData_AIX.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | #ifdef PEGASUS_OS_AIX
#ifndef __UNIX_VLANENDPOINTSETTINGDATA_PRIVATE_H
#define __UNIX_VLANENDPOINTSETTINGDATA_PRIVATE_H
#endif
#endif
| 11.666667 | 48 | 0.864286 | brunolauze |
43ade173a48bf93b83f4c3593768397894cfe511 | 11,814 | cpp | C++ | Library/DS3231/Tests/main.cpp | JVKran/IPASS | 721cf7d481319bf6bd42f4a6b992658591f8a036 | [
"BSL-1.0"
] | 4 | 2019-07-04T17:38:11.000Z | 2021-04-24T19:50:36.000Z | Library/DS3231/Tests/main.cpp | JVKran/IPASS | 721cf7d481319bf6bd42f4a6b992658591f8a036 | [
"BSL-1.0"
] | 2 | 2020-04-08T18:10:06.000Z | 2020-04-08T19:11:50.000Z | Library/DS3231/Tests/main.cpp | JVKran/IPASS | 721cf7d481319bf6bd42f4a6b992658591f8a036 | [
"BSL-1.0"
] | null | null | null | /// @file
#include "hwlib.hpp"
#include "DS3231.hpp"
/// \brief
/// Test
/// \details
/// This program tests most of the functionality of the DS3231 Real Time clock.
int main( void ){
namespace target = hwlib::target;
auto scl = target::pin_oc( target::pins::d8 );
auto sda = target::pin_oc( target::pins::d9 );
auto i2c_bus = hwlib::i2c_bus_bit_banged_scl_sda(scl, sda);
auto clock = DS3231(i2c_bus);
auto time = timeData(15, 20, 10);
auto lastTime = timeData(5, 30);
auto bigTime = timeData(50, 60, 80);
//Uncomment is time is allowed to get overwritten
//clock.setTime(14, 20);
//clock.setDate(5, 7, 7, 2019);
hwlib::wait_ms(1000);
hwlib::cout << "---------------------------------TIME------------------------------" << hwlib::endl << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::boolalpha << hwlib::setw(45) << "Initialization: " << ((time.getHours() == 15) && time.getMinutes() == 20 && time.getSeconds() == 10) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Too Large Initialization Handling: " << ((bigTime.getHours() == 0) && bigTime.getMinutes() == 0 && bigTime.getSeconds() == 0) << hwlib::endl;
time.setTime(11, 40, 55);
hwlib::cout << hwlib::left << hwlib::setw(45) << "Setting: " << ((time.getHours() == 11) && time.getMinutes() == 40 && time.getSeconds() == 55) << hwlib::endl;
time.setTime(80, 90, 100);
hwlib::cout << hwlib::left << hwlib::setw(45) << "Too Large Setting Handling: " << (time == timeData(0, 0, 0)) << hwlib::endl;
time.setTime(10, 30);
hwlib::cout << hwlib::endl << hwlib::left << hwlib::setw(45) << "Addition: " << time << " + " << lastTime << " = " << (time + lastTime) << hwlib::boolalpha << " " << ((time + lastTime) == timeData(16, 0, 0)) << hwlib::endl;
lastTime.setHours(18);
lastTime.setMinutes(15);
lastTime.setSeconds(55);
hwlib::cout << hwlib::left << hwlib::setw(45) << "Addition: " << time << " + " << lastTime << " = " << (time + lastTime) << hwlib::boolalpha << " " << ((time + lastTime) == timeData(4, 45, 55)) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Addition: " << timeData(0, 0) << " + " << timeData(0, 0) << " = " << (timeData(0+0, 0+0)) << " true" << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Addition: " << timeData(23, 59) << " + " << timeData(23, 59) << " = " << (timeData(23, 59) + timeData(23, 59)) << " true" << hwlib::endl;
lastTime.setTime(5, 30);
time.setTime(10, 30);
hwlib::cout << hwlib::endl << hwlib::left << hwlib::setw(45) << "Setting and Substraction: " << time << " - " << lastTime << " = " << (time - lastTime) << hwlib::boolalpha << " " << ((time - lastTime) == timeData(5, 0, 0)) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Substraction: " << lastTime << " - " << time << " = " << (lastTime - time) << hwlib::boolalpha << " " << ((lastTime - time) == timeData(19, 0, 0)) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Substraction: " << timeData(23, 59) << " - " << timeData(23, 59) << " = " << (timeData(23, 59) - timeData(23, 59)) << " true" << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Substraction: " << timeData(0, 15) << " - " << timeData(0, 30) << " = " << (timeData(0, 15) - timeData(0, 30)) << " true" << hwlib::endl;
lastTime.setTime(5, 30);
time.setTime(10, 30);
hwlib::cout << hwlib::endl << hwlib::left << hwlib::setw(45) << "Comparison: " << time << " < " << lastTime << " = " << (time < lastTime) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << timeData(11, 30) << " < " << timeData(11, 30, 10) << " = " << (timeData(11, 30) < timeData(11, 30, 10)) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << time << " <= " << lastTime << " = " << (time <= lastTime) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << time << " > " << lastTime << " = " << (time > lastTime) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << time << " >= " << lastTime << " = " << (time >= lastTime) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << timeData(11, 30) << " >= " << timeData(11, 30) << " = " << (timeData(11, 30) >= timeData(11, 30)) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << timeData(11, 30) << " <= " << timeData(11, 30) << " = " << (timeData(11, 30) <= timeData(11, 30)) << hwlib::endl;
hwlib::cout << hwlib::endl << hwlib::left << hwlib::setw(45) << "Equality: " << time << " == " << lastTime << " = " << (time == lastTime) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Unequality: " << lastTime << " != " << time << " = " << (lastTime != time) << hwlib::endl << hwlib::endl;
hwlib::cout << "---------------------------------DATE------------------------------" << hwlib::endl << hwlib::endl;
auto date = dateData(7, 30, 6, 2019);
auto lastDate = dateData(10, 35, 14, 2019);
hwlib::cout << hwlib::left << hwlib::setw(45) << "Initialization: " << (date.getWeekDay() == 7 && date.getMonthDay() == 30 && date.getMonth() == 6 && date.getYear() == 2019) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Too Large Initialization Handling: " << (lastDate.getWeekDay() == 1 && lastDate.getMonthDay() == 1 && lastDate.getMonth() == 1 && lastDate.getYear() == 2019) << hwlib::endl;
lastDate.setDate(7, 30, 6, 2019);
hwlib::cout << hwlib::left << hwlib::setw(45) << "Setting: " << (lastDate.getWeekDay() == 7 && lastDate.getMonthDay() == 30 && lastDate.getMonth() == 6 && lastDate.getYear() == 2019) << hwlib::endl;
lastDate.setDate(80, 90, 100, 2019);
hwlib::cout << hwlib::left << hwlib::setw(45) << "Too Large Setting Handling: " << (lastDate.getWeekDay() == 1 && lastDate.getMonthDay() == 1 && lastDate.getMonth() == 1 && lastDate.getYear() == 2019) << hwlib::endl;
date.setDate(1, 1, 1, 2019);
lastDate.setDate(7, 30, 6, 0);
hwlib::cout << hwlib::endl << hwlib::left << hwlib::setw(45) << "Addition: " << date.getWeekDay() << ", " << date << " + " << lastDate.getWeekDay() << ", " << lastDate << " = " << (date + lastDate) << hwlib::boolalpha << " " << ((date + lastDate) == dateData(1, 1, 8, 2019)) << hwlib::endl;
lastDate.setWeekDay(5);
lastDate.setMonthDay(15);
lastDate.setMonth(8);
lastDate.setYear(2000);
hwlib::cout << hwlib::left << hwlib::setw(45) << "Setting and Addition: " << date.getWeekDay() << ", " << date << " + " << lastDate.getWeekDay() << ", " << lastDate << " = " << (date + lastDate) << hwlib::boolalpha << " " << ((date + lastDate) == dateData(6, 16, 9, 4019)) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Addition: " << dateData(6, 20, 12, 2019) << " + " << dateData(6, 20, 5, 0) << " = " << (dateData(6, 20, 5, 0) + dateData(6, 20, 12, 2019)) << hwlib::boolalpha << " true" << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Addition: " << dateData(1, 1, 1, 2000) << " + " << dateData(1, 1, 1, 0) << " = " << (dateData(1, 1, 1, 2000) + dateData(1, 1, 1, 0)) << hwlib::boolalpha << " true" << hwlib::endl;
date.setDate(5, 8, 10, 2019);
lastDate.setDate(4, 30, 8, 2000);
hwlib::cout << hwlib::endl << hwlib::left << hwlib::setw(45) << "Setting and Substraction: " << date.getWeekDay() << ", " << date << " - " << lastDate.getWeekDay() << ", " << lastDate << " = " << (date - lastDate) << hwlib::boolalpha << " " << ((date - lastDate) == dateData(1, 8, 1, 19)) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Substraction: " << lastDate.getWeekDay() << ", " << lastDate << " - " << date.getWeekDay() << ", " << date << " = " << (lastDate - date) << hwlib::boolalpha << " " << ((lastDate - date) == dateData(6, 22, 10, 0)) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Substraction: " << dateData(6, 20, 12, 2019) << " - " << dateData(6, 20, 5, 0) << " = " << (dateData(6, 20, 12, 0) - dateData(6, 20, 5, 2019)) << hwlib::boolalpha << " true" << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Substraction: " << dateData(6, 1, 1, 2019) << " - " << dateData(6, 6, 6, 0) << " = " << (dateData(6, 1, 1, 2019) - dateData(6, 6, 6, 0)) << hwlib::boolalpha << " true" << hwlib::endl;
lastTime.setTime(5, 30);
time.setTime(10, 30);
hwlib::cout << hwlib::endl << hwlib::left << hwlib::setw(45) << "Comparison: " << date << " < " << lastDate << " = " << (date < lastDate) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << date << " <= " << lastDate << " = " << (date <= lastDate) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << dateData(1, 1, 12, 2019) << " <= " << dateData(1, 1, 12, 2019) << " = " << (dateData(1, 1, 12, 2019) <= dateData(1, 1, 12, 2019)) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << date << " > " << lastDate << " = " << (date > lastDate) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << dateData(1, 1, 12, 2019) << " > " << dateData(1, 1, 12, 2019) << " = " << (dateData(1, 1, 12, 2019) > dateData(1, 1, 12, 2019)) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << date << " >= " << lastDate << " = " << (date >= lastDate) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Comparison: " << dateData(1, 1, 12, 2019) << " > " << dateData(1, 1, 12, 2019) << " = " << (dateData(1, 1, 12, 2019) > dateData(1, 1, 12, 2019)) << hwlib::endl;
hwlib::cout << hwlib::endl << hwlib::left << hwlib::setw(45) << "Equality: " << date.getWeekDay() << ", " << date << " == " << lastDate.getWeekDay() << ", " << lastDate << " = " << (date == lastDate) << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Unequality: " << date.getWeekDay() << ", " << date << " != " << lastDate.getWeekDay() << ", " << lastDate << " = " << (date != lastDate) << hwlib::endl << hwlib::endl;
hwlib::cout << "-------------------------------DS3231--------------------------------" << hwlib::endl << hwlib::endl;
hwlib::cout << hwlib::left << hwlib::setw(45) << "Initialization: " << (clock.getAddress() == 0x68) << hwlib::endl;
hwlib::cout << hwlib::endl;
for(unsigned int i = 0; i < 3; i++){
time = clock.getTime();
date = clock.getDate();
hwlib::cout << "Time: " << clock.getTime() << hwlib::endl;
hwlib::cout << "Temperature: " << int(clock.getTemperature() * 10) << hwlib::endl;
hwlib::cout << "Date: " << clock.getDate() << hwlib::endl << hwlib::endl;
hwlib::wait_ms(3000);
}
hwlib::cout << hwlib::endl;
//Uncomment if time is allowed to get lost. You'll have to set it again later.
//hwlib::cout << hwlib::left << hwlib::setw(45) << "Set time to 0:0:0 : ";
//clock.setTime(0, 0, 0);
//hwlib::cout << (clock.getTime() == timeData(0, 0, 0)) << hwlib::endl;
auto curTime = timeData();
for(unsigned int i = 0; i < 3; i++){
hwlib::cout << "Time: " << clock.getTime() << hwlib::endl;
hwlib::cout << "Temperature: " << int(clock.getTemperature() * 10) << hwlib::endl;
hwlib::cout << "Date: " << clock.getDate() << hwlib::endl << hwlib::endl;
curTime = clock.getTime();
curTime.setSeconds(curTime.getSeconds() + 10);
hwlib::cout << "Time to Trigger: " << curTime << hwlib::endl;
clock.clearAlarm(1);
clock.changeFirstAlarm(curTime, dateData(0, 0, 1, 2019));
clock.setFirstAlarm(14);
hwlib::cout << "Alarm set, should go in 10 seconds: ";
hwlib::wait_ms(30);
while(clock.checkAlarms() == 0){
hwlib::wait_ms(1000);
hwlib::cout << clock.getTime() << hwlib::endl;
}
hwlib::cout << "Triggered!" << hwlib::endl;
}
}
| 71.6 | 308 | 0.543592 | JVKran |
43ae71157c2744dcfbb201ee8af41a1373cb3232 | 1,047 | cpp | C++ | PopSyn/IPF_Setup.cpp | kravitz/transims4 | ea0848bf3dc71440d54724bb3ecba3947b982215 | [
"NASA-1.3"
] | 2 | 2018-04-27T11:07:02.000Z | 2020-04-24T06:53:21.000Z | PopSyn/IPF_Setup.cpp | idkravitz/transims4 | ea0848bf3dc71440d54724bb3ecba3947b982215 | [
"NASA-1.3"
] | null | null | null | PopSyn/IPF_Setup.cpp | idkravitz/transims4 | ea0848bf3dc71440d54724bb3ecba3947b982215 | [
"NASA-1.3"
] | null | null | null | //*********************************************************
// IPF_Setup.cpp - initialize the IPF classes
//*********************************************************
#include "PopSyn.hpp"
//---------------------------------------------------------
// IPF_Setup
//---------------------------------------------------------
void PopSyn::IPF_Setup (Household_Model *model_ptr)
{
int i, attributes;
Attribute_Type *at_ptr;
//---- clear memory ----
ipf_data.Clear ();
//---- copy the attribute types ----
attributes = model_ptr->Num_Attributes ();
for (i=1; i <= attributes; i++) {
at_ptr = model_ptr->Attribute (i);
if (!ipf_data.Add_Attribute (at_ptr->Num_Types ())) {
Error ("Adding IPF Attribute");
}
}
//---- set data cells ----
if (!ipf_data.Set_Cells ()) {
Error ("Creating IPF Cells");
}
//---- initialize the stage2 process ----
if (!stage2_data.Set_Stage_Two (&ipf_data)) {
Error ("Creating Stage2 Data");
}
//---- sum the zone targets and normalize the weights ----
model_ptr->Sum_Targets ();
}
| 20.94 | 59 | 0.489016 | kravitz |
43b0da23ae953e9de1c7a2e8e22ee0f8fe18e17f | 2,799 | cpp | C++ | libs/utils/src/console.cpp | suilteam/spark-xy | d07dc98c12c8842af0f11bf27d59161cb80f99b0 | [
"MIT"
] | null | null | null | libs/utils/src/console.cpp | suilteam/spark-xy | d07dc98c12c8842af0f11bf27d59161cb80f99b0 | [
"MIT"
] | null | null | null | libs/utils/src/console.cpp | suilteam/spark-xy | d07dc98c12c8842af0f11bf27d59161cb80f99b0 | [
"MIT"
] | null | null | null | /**
* Copyright (c) 2022 Suilteam, Carter Mbotho
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the MIT license. See LICENSE for details.
*
* @author Carter
* @date 2022-03-12
*/
#include "suil/utils/console.hpp"
namespace suil::Console {
void cprint(uint8_t color, int bold, const char *str) {
if (color >= 0 && color <= CYAN)
printf("\033[%s3%dm", (bold ? "1;" : ""), color);
(void) printf("%s", str);
printf("\033[0m");
}
void cprintv(uint8_t color, int bold, const char *fmt, va_list args) {
if (color > 0 && color <= CYAN)
printf("\033[%s3%dm", (bold ? "1;" : ""), color);
(void) vprintf(fmt, args);
printf("\033[0m");
}
void cprintf(uint8_t color, int bold, const char *fmt, ...) {
va_list args;
va_start(args, fmt);
cprintv(color, bold, fmt, args);
va_end(args);
}
void println(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
printf("\n");
}
void red(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
cprintv(RED, 0, fmt, args);
va_end(args);
}
void blue(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
cprintv(BLUE, 0, fmt, args);
va_end(args);
}
void green(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
cprintv(GREEN, 0, fmt, args);
va_end(args);
}
void yellow(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
cprintv(YELLOW, 0, fmt, args);
va_end(args);
}
void magenta(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
cprintv(MAGENTA, 0, fmt, args);
va_end(args);
}
void cyan(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
cprintv(CYAN, 0, fmt, args);
va_end(args);
}
void log(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
printf(fmt, args);
printf("\n");
printf("\n");
va_end(args);
}
void info(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
cprintv(GREEN, 0, fmt, args);
printf("\n");
va_end(args);
}
void error(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
cprintv(RED, 0, fmt, args);
printf("\n");
va_end(args);
}
void warn(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
cprintv(YELLOW, 0, fmt, args);
printf("\n");
va_end(args);
}
} | 23.521008 | 74 | 0.503751 | suilteam |
43b16039b4319d712151e2520daa8dcf0a16ef89 | 297 | cpp | C++ | Source/JCSUE/JCSUEGameModeBase.cpp | jcs090218/JCSUE | 28297609bdafd15c0fb1808b48ffc0246a4485db | [
"MIT"
] | 1 | 2020-06-29T12:23:37.000Z | 2020-06-29T12:23:37.000Z | Source/JCSUE/JCSUEGameModeBase.cpp | jcs090218/JCSUE | 28297609bdafd15c0fb1808b48ffc0246a4485db | [
"MIT"
] | null | null | null | Source/JCSUE/JCSUEGameModeBase.cpp | jcs090218/JCSUE | 28297609bdafd15c0fb1808b48ffc0246a4485db | [
"MIT"
] | null | null | null | /**
* $File: JCSUEGameModeBase.cpp $
* $Date: 2017-03-01 $
* $Revision: $
* $Creator: Jen-Chieh Shen $
* $Notice: See LICENSE.txt for modification and distribution information
* Copyright (c) 2017 by Shen, Jen-Chieh $
*/
#include "JCSUEGameModeBase.h"
#include "JCSUE.h"
| 24.75 | 73 | 0.636364 | jcs090218 |
43b183193eb34b5d735128190ea64f3982c1a254 | 6,051 | cpp | C++ | pin-3.22-98547-g7a303a835-gcc-linux/source/tools/ToolUnitTests/internal_exception_handler_app.cpp | ArthasZhang007/15418FinalProject | a71f698ea48ebbc446111734c198f16a55633669 | [
"MIT"
] | null | null | null | pin-3.22-98547-g7a303a835-gcc-linux/source/tools/ToolUnitTests/internal_exception_handler_app.cpp | ArthasZhang007/15418FinalProject | a71f698ea48ebbc446111734c198f16a55633669 | [
"MIT"
] | null | null | null | pin-3.22-98547-g7a303a835-gcc-linux/source/tools/ToolUnitTests/internal_exception_handler_app.cpp | ArthasZhang007/15418FinalProject | a71f698ea48ebbc446111734c198f16a55633669 | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2009-2021 Intel Corporation.
* SPDX-License-Identifier: MIT
*/
/*! @file
* This application verifies that pin tool can correctly emulate exceptions on behalf of the application
*/
#include <string>
#include <iostream>
#include <fpieee.h>
#include <excpt.h>
#include <float.h>
#if defined(TARGET_WINDOWS)
#include "windows.h"
#define EXPORT_CSYM extern "C" __declspec(dllexport)
#else
#error Unsupported OS
#endif
using std::cout;
using std::endl;
using std::flush;
using std::hex;
using std::string;
//==========================================================================
// Printing utilities
//==========================================================================
string UnitTestName("internal_exception_handler_app");
string FunctionTestName;
static void StartFunctionTest(const string& functionTestName)
{
if (FunctionTestName != "")
{
cout << UnitTestName << "[" << FunctionTestName << "] Success" << endl << flush;
}
FunctionTestName = functionTestName;
}
static void ExitUnitTest()
{
if (FunctionTestName != "")
{
cout << UnitTestName << "[" << FunctionTestName << "] Success" << endl << flush;
}
cout << UnitTestName << " : Completed successfully" << endl << flush;
exit(0);
}
static void Abort(const string& msg)
{
cout << UnitTestName << "[" << FunctionTestName << "] Failure: " << msg << endl << flush;
exit(1);
}
//==========================================================================
// Exception handling utilities
//==========================================================================
/*!
* Exception filter for the ExecuteSafe function: copy the exception record
* to the specified structure.
* @param[in] exceptPtr pointers to the exception context and the exception
* record prepared by the system
* @param[in] pExceptRecord pointer to the structure that receives the
* exception record
* @return the exception disposition
*/
static int SafeExceptionFilter(LPEXCEPTION_POINTERS exceptPtr) { return EXCEPTION_EXECUTE_HANDLER; }
static int SafeExceptionFilterFloating(_FPIEEE_RECORD* pieee) { return EXCEPTION_EXECUTE_HANDLER; }
/*!
* Execute the specified function and return to the caller even if the function raises
* an exception.
* @param[in] pExceptRecord pointer to the structure that receives the
* exception record if the function raises an exception
* @return TRUE, if the function raised an exception
*/
template< typename FUNC > bool ExecuteSafe(FUNC fp, DWORD* pExceptCode)
{
__try
{
fp();
return false;
}
__except (*pExceptCode = GetExceptionCode(), SafeExceptionFilter(GetExceptionInformation()))
{
return true;
}
}
#pragma float_control(except, on)
template< typename FUNC > bool ExecuteSafeFloating(FUNC fp, DWORD* pExceptCode)
{
unsigned int currentControl;
errno_t err = _controlfp_s(¤tControl, ~_EM_ZERODIVIDE, _MCW_EM);
__try
{
fp();
return false;
}
__except (*pExceptCode = GetExceptionCode(), SafeExceptionFilter(GetExceptionInformation())
/*_fpieee_flt( GetExceptionCode(), GetExceptionInformation(), SafeExceptionFilterFloating )*/)
{
return true;
}
}
/*!
* The tool replaces this function and raises the EXCEPTION_INT_DIVIDE_BY_ZERO system exception.
*/
EXPORT_CSYM void RaiseIntDivideByZeroException()
{
volatile int zero = 0;
volatile int i = 1 / zero;
}
/*!
* The tool replaces this function and raises the EXCEPTION_FLT_DIVIDE_BY_ZERO system exception.
*/
EXPORT_CSYM void RaiseFltDivideByZeroException()
{
volatile float zero = 0.0;
volatile float i = 1.0 / zero;
}
EXPORT_CSYM void End() { return; }
/*!
* The tool replace this function and raises the specified system exception.
*/
EXPORT_CSYM void RaiseSystemException(unsigned int sysExceptCode) { RaiseException(sysExceptCode, 0, 0, NULL); }
/*!
* Check to see if the specified exception record represents an exception with the
* specified exception code.
*/
static bool CheckExceptionCode(DWORD exceptCode, DWORD expectedExceptCode)
{
if (exceptCode != expectedExceptCode)
{
cout << "Unexpected exception code " << hex << exceptCode << ". Should be " << hex << expectedExceptCode << endl << flush;
return false;
}
return true;
}
/*!
* Convert a pointer to <SRC> type into a pointer to <DST> type.
* Allows any combination of data/function types.
*/
#if defined(TARGET_IA32) || defined(TARGET_IA32E)
template< typename DST, typename SRC > DST* CastPtr(SRC* src)
{
union CAST
{
DST* dstPtr;
SRC* srcPtr;
} cast;
cast.srcPtr = src;
return cast.dstPtr;
}
#else
#error Unsupported architechture
#endif
typedef void FUNC_NOARGS();
/*!
* The main procedure of the application.
*/
int main(int argc, char* argv[])
{
DWORD exceptCode;
bool exceptionCaught;
// Raise int divide by zero exception in the tool
StartFunctionTest("Raise int divide by zero in the tool");
exceptionCaught = ExecuteSafe(RaiseIntDivideByZeroException, &exceptCode);
if (!exceptionCaught)
{
Abort("Unhandled exception");
}
if (!CheckExceptionCode(exceptCode, EXCEPTION_INT_DIVIDE_BY_ZERO))
{
Abort("Incorrect exception information (EXCEPTION_INT_DIVIDE_BY_ZERO)");
}
// Raise flt divide by zero exception in the tool
StartFunctionTest("Raise FP divide by zero in the tool");
exceptionCaught = ExecuteSafeFloating(RaiseFltDivideByZeroException, &exceptCode);
if (!exceptionCaught)
{
Abort("Unhandled exception");
}
if (EXCEPTION_FLT_DIVIDE_BY_ZERO != exceptCode && STATUS_FLOAT_MULTIPLE_TRAPS != exceptCode)
{
CheckExceptionCode(exceptCode, EXCEPTION_FLT_DIVIDE_BY_ZERO); // For reporting only
Abort("Incorrect exception information (EXCEPTION_FLT_DIVIDE_BY_ZERO)");
}
ExitUnitTest();
}
| 28.952153 | 130 | 0.65295 | ArthasZhang007 |
43b3b9423a191557cb0ae25d6443cbdaa270c3b2 | 734 | cpp | C++ | pronto/core/entities/cylinder.cpp | MgBag/pronto | c10827e094726d8dc285c3da68c9c03be42d9a32 | [
"MIT"
] | null | null | null | pronto/core/entities/cylinder.cpp | MgBag/pronto | c10827e094726d8dc285c3da68c9c03be42d9a32 | [
"MIT"
] | null | null | null | pronto/core/entities/cylinder.cpp | MgBag/pronto | c10827e094726d8dc285c3da68c9c03be42d9a32 | [
"MIT"
] | null | null | null | #include "Cylinder.h"
#include "core/world.h"
#include "core/application.h"
#include "core/components/model.h"
#include "platform/resource.h"
#include "platform/renderer.h"
#include "core/components/fps_controller.h"
#include "core/components/directional_light.h"
#include <glm/gtc/quaternion.hpp>
namespace pronto
{
//-----------------------------------------------------------------------------------------------
Cylinder::Cylinder(World* world) :
Entity(world),
model_(nullptr)
{
model_ = AddComponent<Model>();
model_->SetModel("resource/cylinder/scene.gltf");
transform()->SetScale(glm::vec3(0.05f));
AddComponent<DirectionalLight>();
}
void Cylinder::Update()
{
Entity::Update();
}
}
| 25.310345 | 99 | 0.606267 | MgBag |
43b45d490dc8f46536a41e44900bd1ae1d6369c2 | 7,086 | cpp | C++ | argus/samples/cudaBayerDemosaic/main.cpp | slovak194/tegra_multimedia_api | 6314d06fde5526769cae3ea31c027004e0b5e24d | [
"Unlicense"
] | 2 | 2021-07-16T15:23:14.000Z | 2022-02-07T09:04:39.000Z | argus/samples/cudaBayerDemosaic/main.cpp | slovak194/tegra_multimedia_api | 6314d06fde5526769cae3ea31c027004e0b5e24d | [
"Unlicense"
] | null | null | null | argus/samples/cudaBayerDemosaic/main.cpp | slovak194/tegra_multimedia_api | 6314d06fde5526769cae3ea31c027004e0b5e24d | [
"Unlicense"
] | null | null | null | /*
* Copyright (c) 2018, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <Argus/Argus.h>
#include "ArgusHelpers.h"
#include "CommonOptions.h"
#include "CudaBayerDemosaicConsumer.h"
namespace ArgusSamples
{
/**
* Main thread function opens connection to Argus driver, creates a capture session for
* a given camera device and sensor mode, then creates a RAW16 stream attached to a
* CudaBayerConsumer such that the CUDA consumer will acquire the outputs of capture
* results as raw Bayer data (which it then demosaics to RGBA for demonstration purposes).
*/
static bool execute(const CommonOptions& options)
{
EGLDisplayHolder eglDisplay;
// Initialize the preview window and EGL display.
Window &window = Window::getInstance();
window.setWindowRect(options.windowRect());
PROPAGATE_ERROR(eglDisplay.initialize(window.getEGLNativeDisplay()));
// Create the Argus CameraProvider object
UniqueObj<CameraProvider> cameraProvider(CameraProvider::create());
ICameraProvider *iCameraProvider = interface_cast<ICameraProvider>(cameraProvider);
if (!iCameraProvider)
{
ORIGINATE_ERROR("Failed to create CameraProvider");
}
printf("Argus Version: %s\n", iCameraProvider->getVersion().c_str());
// Get the selected camera device and sensor mode.
CameraDevice* cameraDevice = ArgusHelpers::getCameraDevice(
cameraProvider.get(), options.cameraDeviceIndex());
if (!cameraDevice)
ORIGINATE_ERROR("Selected camera device is not available");
SensorMode* sensorMode = ArgusHelpers::getSensorMode(cameraDevice, options.sensorModeIndex());
ISensorMode *iSensorMode = interface_cast<ISensorMode>(sensorMode);
if (!iSensorMode)
ORIGINATE_ERROR("Selected sensor mode not available");
// Create the capture session using the selected device.
UniqueObj<CaptureSession> captureSession(iCameraProvider->createCaptureSession(cameraDevice));
ICaptureSession *iCaptureSession = interface_cast<ICaptureSession>(captureSession);
if (!iCaptureSession)
{
ORIGINATE_ERROR("Failed to create CaptureSession");
}
// Create the RAW16 output EGLStream using the sensor mode resolution.
UniqueObj<OutputStreamSettings> streamSettings(
iCaptureSession->createOutputStreamSettings(STREAM_TYPE_EGL));
IEGLOutputStreamSettings *iEGLStreamSettings =
interface_cast<IEGLOutputStreamSettings>(streamSettings);
if (!iEGLStreamSettings)
{
ORIGINATE_ERROR("Failed to create OutputStreamSettings");
}
iEGLStreamSettings->setEGLDisplay(eglDisplay.get());
iEGLStreamSettings->setPixelFormat(PIXEL_FMT_RAW16);
iEGLStreamSettings->setResolution(iSensorMode->getResolution());
iEGLStreamSettings->setMode(EGL_STREAM_MODE_FIFO);
UniqueObj<OutputStream> outputStream(iCaptureSession->createOutputStream(streamSettings.get()));
IEGLOutputStream *iEGLOutputStream = interface_cast<IEGLOutputStream>(outputStream);
if (!iEGLOutputStream)
{
ORIGINATE_ERROR("Failed to create EGLOutputStream");
}
// Create capture request and enable output stream.
UniqueObj<Request> request(iCaptureSession->createRequest());
IRequest *iRequest = interface_cast<IRequest>(request);
if (!iRequest)
{
ORIGINATE_ERROR("Failed to create Request");
}
iRequest->enableOutputStream(outputStream.get());
// Set the sensor mode in the request.
ISourceSettings *iSourceSettings = interface_cast<ISourceSettings>(request);
if (!iSourceSettings)
ORIGINATE_ERROR("Failed to get source settings request interface");
iSourceSettings->setSensorMode(sensorMode);
// Create the CUDA Bayer consumer and connect it to the RAW16 output stream.
CudaBayerDemosaicConsumer cudaConsumer(iEGLOutputStream->getEGLDisplay(),
iEGLOutputStream->getEGLStream(),
iEGLStreamSettings->getResolution(),
options.frameCount());
PROPAGATE_ERROR(cudaConsumer.initialize());
PROPAGATE_ERROR(cudaConsumer.waitRunning());
// Submit the batch of capture requests.
for (unsigned int frame = 0; frame < options.frameCount(); ++frame)
{
Argus::Status status;
uint32_t result = iCaptureSession->capture(request.get(), TIMEOUT_INFINITE, &status);
if (result == 0)
{
ORIGINATE_ERROR("Failed to submit capture request (status %x)", status);
}
}
// Wait until all captures have completed.
iCaptureSession->waitForIdle();
// Shutdown the CUDA consumer.
PROPAGATE_ERROR(cudaConsumer.shutdown());
return true;
}
}; // namespace ArgusSamples
int main(int argc, char** argv)
{
printf("Executing Argus Sample: %s\n", basename(argv[0]));
ArgusSamples::CommonOptions options(basename(argv[0]),
ArgusSamples::CommonOptions::Option_D_CameraDevice |
ArgusSamples::CommonOptions::Option_M_SensorMode |
ArgusSamples::CommonOptions::Option_R_WindowRect |
ArgusSamples::CommonOptions::Option_F_FrameCount);
if (!options.parse(argc, argv))
return EXIT_FAILURE;
if (options.requestedExit())
return EXIT_SUCCESS;
if (!ArgusSamples::execute(options))
return EXIT_FAILURE;
printf("Argus sample '%s' completed successfully.\n", basename(argv[0]));
return EXIT_SUCCESS;
}
| 42.686747 | 100 | 0.710979 | slovak194 |
43b56f7d53d26c6d64609fc80f79bf135632d154 | 3,680 | hpp | C++ | src/tools/lvr2_dmc_reconstruction/Options.hpp | uos/lvr | 9bb03a30441b027c39db967318877e03725112d5 | [
"BSD-3-Clause"
] | 38 | 2019-06-19T15:10:35.000Z | 2022-02-16T03:08:24.000Z | src/tools/lvr2_dmc_reconstruction/Options.hpp | uos/lvr | 9bb03a30441b027c39db967318877e03725112d5 | [
"BSD-3-Clause"
] | 9 | 2019-06-19T16:19:51.000Z | 2021-09-17T08:31:25.000Z | src/tools/lvr2_dmc_reconstruction/Options.hpp | uos/lvr | 9bb03a30441b027c39db967318877e03725112d5 | [
"BSD-3-Clause"
] | 13 | 2019-04-16T11:50:32.000Z | 2020-11-26T07:47:44.000Z | /**
* Copyright (c) 2018, University Osnabrück
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the University Osnabrück nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL University Osnabrück 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.
*/
/*
* OptionsDMC.hpp
*
* Created on: May 13, 2020
* Author: Benedikt SChumacher
*/
#ifndef OPTIONSDMC_H_
#define OPTIONSDMC_H_
#include "lvr2/config/BaseOption.hpp"
#include <boost/program_options.hpp>
#include <float.h>
#include <iostream>
#include <string>
#include <vector>
using std::cout;
using std::endl;
using std::ostream;
using std::string;
using std::vector;
using namespace lvr2;
namespace dmc_reconstruction
{
class Options : public BaseOption
{
public:
Options(int argc, char** argv);
virtual ~Options();
string getInputFileName() const;
int getMaxLevel() const;
float getMaxError() const;
/*
* prints information about needed command-line-inputs e.g: input-file (ply)
*/
bool printUsage() const;
int getKd() const;
int getKn() const;
int getKi() const;
int getNumThreads() const;
string getPCM() const;
bool useRansac() const;
string getScanPoseFile() const;
private:
/// The maximum allows octree level
int m_maxLevel;
/// The max allowed error between points and surfaces in an octree cell
float m_maxError;
/// The number of neighbors for distance function evaluation
int m_kd;
/// The number of neighbors for normal estimation
int m_kn;
/// The number of neighbors for normal interpolation
int m_ki;
/// The number of threads to use
int m_numThreads;
/// The used point cloud manager
string m_pcm;
};
/// Output the Options - overloaded output Operator
inline ostream& operator<<(ostream& os, const Options& o)
{
// o.printTransformation(os);
cout << "##### InputFile-Name: " << o.getInputFileName() << endl;
cout << "##### Max Level: " << o.getMaxLevel() << endl;
cout << "##### Max Error: " << o.getMaxError() << endl;
cout << "##### PCM: " << o.getPCM() << endl;
cout << "##### KD: " << o.getKd() << endl;
cout << "##### KI: " << o.getKi() << endl;
cout << "##### KN: " << o.getKn() << endl;
return os;
}
} // namespace dmc_reconstruction
#endif // OPTIONSDMC_H_
| 28.307692 | 82 | 0.685598 | uos |
43b696e347eb74bffb556bdda893267b36551bae | 2,558 | cpp | C++ | archived/polint.cpp | HiTMonitor/ginan | f348e2683507cfeca65bb58880b3abc2f9c36bcf | [
"Apache-2.0"
] | 1 | 2022-03-31T15:16:19.000Z | 2022-03-31T15:16:19.000Z | archived/polint.cpp | hqy123-cmyk/ginan | b69593b584f75e03238c1c667796e2030391fbed | [
"Apache-2.0"
] | null | null | null | archived/polint.cpp | hqy123-cmyk/ginan | b69593b584f75e03238c1c667796e2030391fbed | [
"Apache-2.0"
] | null | null | null | // /* Slightly modified versions of the "polint" routine from
// * Press, William H., Brian P. Flannery, Saul A. Teukolsky and
// * William T. Vetterling, 1986, "Numerical Recipes: The Art of
// * Scientific Computing" (Fortran), Cambrigde University Press,
// * pp. 80-82.
// */
//
// #include <stdio.h>
// #include <malloc.h>
// #include <math.h>
//
// void polint( double *xa, double *ya, int n, double x, double *y, double *dy );
//
// void polint( double *xa, double *ya, int n, double x, double *y, double *dy )
// {
// double *c = NULL;
// double *d = NULL;
// double den;
// double dif;
// double dift;
// double ho;
// double hp;
// double w;
//
// int i;
// int m;
// int ns;
//
// if( (c = (double *)malloc( n * sizeof( double ) )) == NULL ||
// (d = (double *)malloc( n * sizeof( double ) )) == NULL ) {
// fprintf( stderr, "polint error: allocating workspace\n" );
// fprintf( stderr, "polint error: setting y = 0 and dy = 1e9\n" );
// *y = 0.0;
// *dy = 1.e9;
//
// if( c != NULL )
// free( c );
// if( d != NULL )
// free( d );
// return;
// }
//
// ns = 0;
// dif = fabs(x-xa[0]);
// for( i = 0; i < n; ++i ) {
// dift = fabs( x-xa[i] );
// if( dift < dif ) {
// ns = i;
// dif = dift;
// }
// c[i] = ya[i];
// d[i] = ya[i];
// }
// *y = ya[ns];
// ns = ns-1;
// for( m = 0; m < n-1; ++m ) {
// for( i = 0; i < n-m-1; ++i ) {
// ho = xa[i]-x;
// hp = xa[i+m+1]-x;
// w = c[i+1]-d[i];
// den = ho-hp;
// if( den == 0 ) {
// fprintf( stderr, "polint error: den = 0\n" );
// fprintf( stderr, "polint error: setting y = 0 and dy = 1e9\n" );
// *y = 0.0;
// *dy = 1.e9;
//
// if( c != NULL )
// free( c );
// if( d != NULL )
// free( d );
// return;
// }
// den = w/den;
// d[i] = hp*den;
// c[i] = ho*den;
// }
// if( 2*(ns+1) < n-m-1 ) {
// *dy = c[ns+1];
// } else {
// *dy = d[ns];
// ns = ns-1;
// }
// *y = (*y)+(*dy);
// }
//
//
// if( c != NULL )
// free( c );
// if( d != NULL )
// free( d );
// return;
// }
| 27.212766 | 83 | 0.361611 | HiTMonitor |
43b90a24093499049a92827db81d519729ac9c1e | 3,991 | hpp | C++ | neventGenerator/serialiser.hpp | ess-dmsc/sinq-amor | 1868ffef90e4e9192ac8ac928a33111cb67af315 | [
"BSD-2-Clause"
] | null | null | null | neventGenerator/serialiser.hpp | ess-dmsc/sinq-amor | 1868ffef90e4e9192ac8ac928a33111cb67af315 | [
"BSD-2-Clause"
] | 6 | 2017-08-04T07:09:35.000Z | 2017-11-07T14:23:51.000Z | neventGenerator/serialiser.hpp | ess-dmsc/sinq-amorsim | 1868ffef90e4e9192ac8ac928a33111cb67af315 | [
"BSD-2-Clause"
] | null | null | null | #pragma once
#include "schemas/ev42_events_generated.h"
// WARNING:
// the schema has to match to the serialise template type
// this must change
namespace SINQAmorSim {
/// \author Michele Brambilla <mib.mic@gmail.com>
/// \date Thu Jul 28 14:32:29 2016
class FlatBufferSerialiser {
public:
FlatBufferSerialiser(const std::string &source_name = "AMOR.event.stream")
: source{source_name} {}
FlatBufferSerialiser(const FlatBufferSerialiser &other) = default;
FlatBufferSerialiser(FlatBufferSerialiser &&other) = default;
~FlatBufferSerialiser() = default;
// WARNING: template parameter has to match schema data type
template <class T>
std::vector<char> &serialise(const int &message_id,
const std::chrono::nanoseconds &pulse_time,
const std::vector<T> &message = {}) {
auto nev = message.size() / 2;
flatbuffers::FlatBufferBuilder builder;
auto source_name = builder.CreateString(source);
auto time_of_flight = builder.CreateVector(&message[0], nev);
auto detector_id = builder.CreateVector(&message[nev], nev);
auto event =
CreateEventMessage(builder, source_name, message_id, pulse_time.count(),
time_of_flight, detector_id);
FinishEventMessageBuffer(builder, event);
buffer_.resize(builder.GetSize());
buffer_.assign(builder.GetBufferPointer(),
builder.GetBufferPointer() + builder.GetSize());
return buffer_;
}
template <class T>
void extract(const std::vector<char> &message, std::vector<T> &data,
uint64_t &pid, std::chrono::nanoseconds &pulse_time,
std::string &source_name) {
extract_impl<T>(static_cast<const void *>(&message[0]), data, pid,
pulse_time, source_name);
}
template <class T>
void extract(const char *msg, std::vector<T> &data, uint64_t &pid,
std::chrono::nanoseconds &pulse_time, std::string &source_name) {
extract_impl<T>(static_cast<const void *>(msg), data, pid, pulse_time,
source_name);
}
char *get() { return &buffer_[0]; }
size_t size() { return buffer_.size(); }
const std::vector<char> &buffer() { return buffer_; }
bool verify() {
auto p = const_cast<const char *>(&buffer_[0]);
flatbuffers::Verifier verifier(reinterpret_cast<const unsigned char *>(p),
buffer_.size());
return VerifyEventMessageBuffer(verifier);
}
bool verify(const std::vector<char> &other) {
auto p = const_cast<const char *>(&other[0]);
flatbuffers::Verifier verifier(reinterpret_cast<const unsigned char *>(p),
buffer_.size());
return VerifyEventMessageBuffer(verifier);
}
private:
template <class T>
void extract_impl(const void *msg, std::vector<T> &data, uint64_t &pid,
std::chrono::nanoseconds &pulse_time,
std::string &source_name) {
auto event = GetEventMessage(msg);
data.resize(2 * event->time_of_flight()->size());
std::copy(event->time_of_flight()->begin(), event->time_of_flight()->end(),
data.begin());
std::copy(event->detector_id()->begin(), event->detector_id()->end(),
data.begin() + event->time_of_flight()->size());
pid = event->message_id();
size_t timestamp = event->pulse_time();
pulse_time = std::chrono::nanoseconds(timestamp);
source_name = std::string{event->source_name()->c_str()};
}
std::vector<char> buffer_;
std::string source;
};
/// \author Michele Brambilla <mib.mic@gmail.com>
/// \date Fri Jun 17 12:22:01 2016
class NoSerialiser {
public:
NoSerialiser(const std::string & = "") {}
NoSerialiser(const NoSerialiser &other) = default;
NoSerialiser(NoSerialiser &&other) = default;
~NoSerialiser() = default;
NoSerialiser() = default;
char *get() { return nullptr; }
const int size() { return 0; }
};
} // serialiser
| 35.954955 | 80 | 0.642947 | ess-dmsc |
43b95c45f8b50309059b953bb60226a52c18dc93 | 910 | hpp | C++ | testsuite/src/MacroCommandTestVO.hpp | roversun/puremvc-cpp-multicore-framework | 3e80412d5049a427637c6130a9bf6dbf029bf4bb | [
"CC-BY-3.0",
"BSD-3-Clause"
] | 2 | 2019-09-04T09:34:13.000Z | 2019-09-04T09:34:16.000Z | testsuite/src/MacroCommandTestVO.hpp | roversun/puremvc-cpp-multicore-framework | 3e80412d5049a427637c6130a9bf6dbf029bf4bb | [
"CC-BY-3.0",
"BSD-3-Clause"
] | null | null | null | testsuite/src/MacroCommandTestVO.hpp | roversun/puremvc-cpp-multicore-framework | 3e80412d5049a427637c6130a9bf6dbf029bf4bb | [
"CC-BY-3.0",
"BSD-3-Clause"
] | null | null | null | // MacroCommandTestVO.hpp
// PureMVC_C++ Test suite
//
// PureMVC Port to C++ by Tang Khai Phuong <phuong.tang@puremvc.org>
// PureMVC - Copyright(c) 2006-2011 Futurescale, Inc., Some rights reserved.
// Your reuse is governed by the Creative Commons Attribution 3.0 License
//
#if !defined(MACRO_COMMAND_TEST_VO_HPP)
#define MACRO_COMMAND_TEST_VO_HPP
namespace data
{
/**
* A utility class used by MacroCommandTest.
*/
struct MacroCommandTestVO
{
int input;
int result1;
int result2;
/**
* Constructor.
*
* @param input the number to be fed to the MacroCommandTestCommand
*/
MacroCommandTestVO(int input)
{
this->input = input;
this->result1 = 0;
this->result2 = 0;
}
};
}
#endif /* MACRO_COMMAND_TEST_VO_HPP */
| 24.594595 | 78 | 0.581319 | roversun |
43b98881dd151dc94f5df25db154a16941658a82 | 3,289 | cpp | C++ | problems18apr/scootchhop/correct.cpp | Gomango999/codebreaker | 407c4ac7a69c8db52cc7d2a57034cdda243c9134 | [
"MIT"
] | 1 | 2021-12-11T01:43:27.000Z | 2021-12-11T01:43:27.000Z | problems18apr/scootchhop/correct.cpp | Gomango999/codebreaker | 407c4ac7a69c8db52cc7d2a57034cdda243c9134 | [
"MIT"
] | null | null | null | problems18apr/scootchhop/correct.cpp | Gomango999/codebreaker | 407c4ac7a69c8db52cc7d2a57034cdda243c9134 | [
"MIT"
] | 1 | 2021-12-15T07:04:29.000Z | 2021-12-15T07:04:29.000Z | #include <bits/stdc++.h>
using namespace std;
template <typename T>
using V = vector<T>;
typedef long double ld;
typedef long long ll;
#define FO(i, N) for (int (i) = 0; (i) < (N); ++(i))
#define FOll(i, N) for (ll (i) = 0; (i) < (N); ++(i))
#define READALL(c) for (auto &e : c) { cin >> e; }
#define PRINTALL(c) for (const auto &e : c) { cout << e << " "; } cout << "\n";
#define MP(x, y) (make_pair((x), (y)))
#define MT(...) make_tuple(__VA_ARGS__)
#define ALL(x) begin(x), end(x)
#define D(x...) fprintf(stderr, x)
const int MAXN = 500, MAXQ = 1e7;
int R, C, Q;
ll DPul[MAXN+5][MAXN+5], DPbr[MAXN+5][MAXN+5], G[MAXN+5][MAXN+5], GG[MAXN+5][MAXN+5], ans[MAXQ];
tuple<int,int,int,int> Qs[MAXQ];
void fill_dp(int r, int c, int minr, int minc, int maxr, int maxc) {
for (int i = minr-1; i <= maxr+1; ++i)
for (int j = minc-1; j <= maxc+1; ++j)
DPul[i][j] = DPbr[i][j] = -1e18;
DPul[r+1][c]=0;
for (int i = r; i >= minr; --i)
for (int j = c; j >= minc; --j)
DPul[i][j] = max(DPul[i+1][j],DPul[i][j+1])+G[i][j];
DPbr[r-1][c]=0;
for (int i = r; i <= maxr; ++i)
for (int j = c; j <= maxc; ++j)
DPbr[i][j] = max(DPbr[i-1][j],DPbr[i][j-1])+G[i][j];
}
void dc(int minr, int minc, int maxr, int maxc, vector<int> query_inds) {
if (minr > maxr || minc > maxc)
return;
int r, c = (maxc+minc)/2;
vector<int> query_inds_tmp;
for (int i : query_inds) {
int qr, qc, qrr, qcc;
tie(qr, qc, qrr, qcc) = Qs[i];
if (qr < minr || qc < minc || qr > maxr || qc > maxc)
continue;
if (qrr < minr || qcc < minc || qrr > maxr || qcc > maxc)
continue;
query_inds_tmp.push_back(i);
}
query_inds = query_inds_tmp;
if (query_inds.size() == 0)
return;
for (r = minr; r <= maxr; ++r) {
fill_dp(r, c, minr, minc, maxr, maxc);
for (int i : query_inds) {
int qr, qc, qrr, qcc;
tie(qr, qc, qrr, qcc) = Qs[i];
if (qr <= r && qrr >= r && qc <= c && qcc >= c) {
ans[i] = max(ans[i], DPul[qr][qc]+DPbr[qrr][qcc]-G[r][c]);
}
}
}
r = (minr+maxr)/2;
for (c = minc; c <= maxc; ++c) if (c != (maxc+minc)/2 && G[r][c] != '1') {
fill_dp(r, c, minr, minc, maxr, maxc);
for (int i : query_inds) {
int qr, qc, qrr, qcc;
tie(qr, qc, qrr, qcc) = Qs[i];
if (qr <= r && qrr >= r && qc <= c && qcc >= c) {
ans[i] = max(ans[i], DPul[qr][qc]+DPbr[qrr][qcc]-G[r][c]);
}
}
}
dc(minr, minc, (maxr+minr)/2-1, (maxc+minc)/2-1, query_inds);
dc(minr, (maxc+minc)/2+1, (maxr+minr)/2-1, maxc, query_inds);
dc((maxr+minr)/2+1, minc, maxr, (maxc+minc)/2-1, query_inds);
dc((maxr+minr)/2+1, (maxc+minc)/2+1, maxr, maxc, query_inds);
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> R >> C;
FO(i,R) FO(j,C) {
cin >> GG[i+1][j+1];
G[i+1][j+1] = max(GG[i+1][j+1],0ll);
}
cin >> Q;
V<int> all_inds;
FO(i,Q) {
int x,y,xx,yy;
cin>>x>>y>>xx>>yy;
Qs[i] = make_tuple(x,y,xx,yy);
all_inds.push_back(i);
}
if(Q == 0) {
Q++;
Qs[0] = make_tuple(1, 1, R, C);
all_inds.push_back(0);
}
fill(ans,ans+Q,-1e18);
dc(1,1,R,C,all_inds);
for(int i = 0; i < Q; i++) {
int x,y,xx,yy;
tie(x, y, xx, yy) = Qs[i];
if (GG[x][y] < 0) {
ans[i] += GG[x][y];
}
if (GG[xx][yy] < 0) {
ans[i] += GG[xx][yy];
}
}
FO(i,Q) cout << ans[i] << "\n";
}
| 26.739837 | 96 | 0.512618 | Gomango999 |
43be1349dd39e6f7f2f7117e39ae70ec276c8839 | 1,413 | cpp | C++ | kafka_configuration.cpp | mexicowilly/Chucho | f4235420437eb2078ab592540c0d729b7b9a3c10 | [
"Apache-2.0"
] | 4 | 2016-12-06T05:33:29.000Z | 2017-12-17T17:04:25.000Z | kafka_configuration.cpp | mexicowilly/Chucho | f4235420437eb2078ab592540c0d729b7b9a3c10 | [
"Apache-2.0"
] | 147 | 2016-09-05T14:00:46.000Z | 2021-08-24T14:43:07.000Z | kafka_configuration.cpp | mexicowilly/Chucho | f4235420437eb2078ab592540c0d729b7b9a3c10 | [
"Apache-2.0"
] | 4 | 2017-11-08T04:12:39.000Z | 2022-01-04T06:40:16.000Z | /*
* Copyright 2013-2021 Will Mason
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <chucho/kafka_configuration.hpp>
#include <chucho/exception.hpp>
namespace chucho
{
kafka_configuration::kafka_configuration(const std::map<std::string, std::string>& key_values)
: conf_(rd_kafka_conf_new())
{
char msg[1024];
for (auto& p : key_values)
{
auto rc = rd_kafka_conf_set(conf_, p.first.c_str(), p.second.c_str(), msg, sizeof(msg));
if (rc != RD_KAFKA_CONF_OK)
throw exception("kafka_writer_factory: Error setting Kafka configuration (" + p.first + ", " + p.second + "): " + msg);
}
}
kafka_configuration::~kafka_configuration()
{
if (conf_ != nullptr)
rd_kafka_conf_destroy(conf_);
}
rd_kafka_conf_t* kafka_configuration::get_conf()
{
auto local = conf_;
conf_ = nullptr;
return local;
}
}
| 28.836735 | 131 | 0.682944 | mexicowilly |
43c0d87b57b5254bb67462e977d11d0d4644067f | 1,995 | hpp | C++ | cpp/godot-cpp/include/gen/TextureLayered.hpp | GDNative-Gradle/proof-of-concept | 162f467430760cf959f68f1638adc663fd05c5fd | [
"MIT"
] | 1 | 2021-03-16T09:51:00.000Z | 2021-03-16T09:51:00.000Z | cpp/godot-cpp/include/gen/TextureLayered.hpp | GDNative-Gradle/proof-of-concept | 162f467430760cf959f68f1638adc663fd05c5fd | [
"MIT"
] | null | null | null | cpp/godot-cpp/include/gen/TextureLayered.hpp | GDNative-Gradle/proof-of-concept | 162f467430760cf959f68f1638adc663fd05c5fd | [
"MIT"
] | null | null | null | #ifndef GODOT_CPP_TEXTURELAYERED_HPP
#define GODOT_CPP_TEXTURELAYERED_HPP
#include <gdnative_api_struct.gen.h>
#include <stdint.h>
#include <core/CoreTypes.hpp>
#include <core/Ref.hpp>
#include "Image.hpp"
#include "Resource.hpp"
namespace godot {
class Image;
class TextureLayered : public Resource {
struct ___method_bindings {
godot_method_bind *mb__get_data;
godot_method_bind *mb__set_data;
godot_method_bind *mb_create;
godot_method_bind *mb_get_depth;
godot_method_bind *mb_get_flags;
godot_method_bind *mb_get_format;
godot_method_bind *mb_get_height;
godot_method_bind *mb_get_layer_data;
godot_method_bind *mb_get_width;
godot_method_bind *mb_set_data_partial;
godot_method_bind *mb_set_flags;
godot_method_bind *mb_set_layer_data;
};
static ___method_bindings ___mb;
public:
static void ___init_method_bindings();
static inline const char *___get_class_name() { return (const char *) "TextureLayered"; }
static inline Object *___get_from_variant(Variant a) { godot_object *o = (godot_object*) a; return (o) ? (Object *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, o) : nullptr; }
// enums
enum Flags {
FLAG_MIPMAPS = 1,
FLAG_REPEAT = 2,
FLAG_FILTER = 4,
FLAGS_DEFAULT = 4,
};
// constants
// methods
Dictionary _get_data() const;
void _set_data(const Dictionary data);
void create(const int64_t width, const int64_t height, const int64_t depth, const int64_t format, const int64_t flags = 4);
int64_t get_depth() const;
int64_t get_flags() const;
Image::Format get_format() const;
int64_t get_height() const;
Ref<Image> get_layer_data(const int64_t layer) const;
int64_t get_width() const;
void set_data_partial(const Ref<Image> image, const int64_t x_offset, const int64_t y_offset, const int64_t layer, const int64_t mipmap = 0);
void set_flags(const int64_t flags);
void set_layer_data(const Ref<Image> image, const int64_t layer);
};
}
#endif | 29.338235 | 245 | 0.777444 | GDNative-Gradle |
43c261199e50810e5a13b05fa96694b0dac32d1d | 1,273 | cpp | C++ | src/ProgramState.cpp | tsehon/basic.cpp | 39c93f174b09e92ff3d7561165aa3fb8ab42a82b | [
"MIT"
] | null | null | null | src/ProgramState.cpp | tsehon/basic.cpp | 39c93f174b09e92ff3d7561165aa3fb8ab42a82b | [
"MIT"
] | null | null | null | src/ProgramState.cpp | tsehon/basic.cpp | 39c93f174b09e92ff3d7561165aa3fb8ab42a82b | [
"MIT"
] | null | null | null | #include "ProgramState.h"
using namespace std;
ProgramState::ProgramState(int numLines){
m_numLines = numLines;
m_nextLine = 1;
m_line = 0;
m_over = 0;
}
void ProgramState::updateVal(std::string var, int val){
if (m_varMap.count(var) > 0){
m_varMap[var] = val;
} else {
m_varMap.insert(std::pair<string, int>(var, val));
}
}
int ProgramState::getVal(std::string var){
return m_varMap.at(var);
}
void ProgramState::toStream(std::string var, std::ostream& outf){
map<std::string, int>::iterator it = m_varMap.find(var);
outf << it->first << " : " << it->second << std::endl;
}
void ProgramState::toStreamAll(std::ostream &outf){
map<std::string, int>::iterator it;
for (it = m_varMap.begin(); it != m_varMap.end(); it++){
outf << it->first << " : " << it->second << std::endl;
}
}
int ProgramState::getCurrLine(){
return m_line;
}
void ProgramState::goNextLine(){
m_line = m_nextLine;
}
void ProgramState::updateNextLine(int val){
m_nextLine = val;
}
int ProgramState::getReturnLine(){
int temp = m_stack.top();
m_stack.pop();
return temp;
}
void ProgramState::addReturnLine(int val){
m_stack.push(val);
}
void ProgramState::endProgram(){
m_over = 1;
}
bool ProgramState::isOver(){
if (m_over) {
return true;
}
return false;
}
| 18.720588 | 65 | 0.6685 | tsehon |
43c2b4114ff84dd0e8d6a3a8c442b2ce1e70021e | 1,336 | cpp | C++ | Aurora/Aurora/sysserv/sysmem.cpp | manaskamal/aurora-xeneva | fe277f7ac155a40465c70f1db3c27046e4d0f7b5 | [
"BSD-2-Clause"
] | 8 | 2021-07-19T04:46:35.000Z | 2022-03-12T17:56:00.000Z | Aurora/Aurora/sysserv/sysmem.cpp | manaskamal/aurora-xeneva | fe277f7ac155a40465c70f1db3c27046e4d0f7b5 | [
"BSD-2-Clause"
] | null | null | null | Aurora/Aurora/sysserv/sysmem.cpp | manaskamal/aurora-xeneva | fe277f7ac155a40465c70f1db3c27046e4d0f7b5 | [
"BSD-2-Clause"
] | null | null | null | /**
** Copyright (C) Manas Kamal Choudhury 2021
**
** sysmem.cpp -- System Memory Callbacks
**
** /PORJECT - Aurora {Xeneva}
** /AUTHOR - Manas Kamal Choudhury
**
**/
#ifdef ARCH_X64
#include <arch\x86_64\mmngr\vmmngr.h>
#include <arch\x86_64\thread.h>
#include <_null.h>
#include <stdio.h>
#endif
void map_shared_memory (uint16_t dest_id,uint64_t pos, size_t size) {
x64_cli ();
thread_t* t = thread_iterate_ready_list (dest_id);
if (t == NULL) {
t = thread_iterate_block_list(dest_id);
}
uint64_t *current_cr3 = (uint64_t*)get_current_thread()->cr3;
uint64_t *cr3 = (uint64_t*)t->cr3;
for (int i = 0; i < size/4096; i++) {
if (map_page ((uint64_t)pmmngr_alloc(),pos + i * 4096, PAGING_USER)) {
cr3[pml4_index(pos + i * 4096)] = current_cr3[pml4_index(pos + i * 4096)];
}
}
}
void unmap_shared_memory (uint16_t dest_id, uint64_t pos, size_t size) {
x64_cli ();
thread_t* t = thread_iterate_ready_list (dest_id);
if (t == NULL) {
t = thread_iterate_block_list(dest_id);
}
uint64_t *cr3 = (uint64_t*)t->cr3;
for (int i = 0; i < size/4096; i++) {
unmap_page (pos + i * 4096);
unmap_page_ex(cr3,pos + i * 4096, false);
}
}
uint64_t sys_get_used_ram () {
x64_cli ();
return pmmngr_get_used_ram ();
}
uint64_t sys_get_free_ram () {
x64_cli ();
return pmmngr_get_free_ram ();
} | 21.901639 | 79 | 0.661677 | manaskamal |
43c3499000af85858b48bd324d3de23b91175e17 | 2,335 | cc | C++ | ns-allinone-3.22/ns-3.22/src/network/utils/llc-snap-header.cc | gustavo978/helpful | 59e3fd062cff4451c9bf8268df78a24f93ff67b7 | [
"Unlicense"
] | null | null | null | ns-allinone-3.22/ns-3.22/src/network/utils/llc-snap-header.cc | gustavo978/helpful | 59e3fd062cff4451c9bf8268df78a24f93ff67b7 | [
"Unlicense"
] | null | null | null | ns-allinone-3.22/ns-3.22/src/network/utils/llc-snap-header.cc | gustavo978/helpful | 59e3fd062cff4451c9bf8268df78a24f93ff67b7 | [
"Unlicense"
] | 2 | 2018-06-06T14:10:23.000Z | 2020-04-07T17:20:55.000Z | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2005 INRIA
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* 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
*
* Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr>
*/
#include "llc-snap-header.h"
#include "ns3/assert.h"
#include "ns3/log.h"
#include <string>
namespace ns3 {
NS_LOG_COMPONENT_DEFINE ("LlcSnalHeader");
NS_OBJECT_ENSURE_REGISTERED (LlcSnapHeader);
LlcSnapHeader::LlcSnapHeader ()
{
NS_LOG_FUNCTION (this);
}
void
LlcSnapHeader::SetType (uint16_t type)
{
NS_LOG_FUNCTION (this);
m_etherType = type;
}
uint16_t
LlcSnapHeader::GetType (void)
{
NS_LOG_FUNCTION (this);
return m_etherType;
}
uint32_t
LlcSnapHeader::GetSerializedSize (void) const
{
NS_LOG_FUNCTION (this);
return LLC_SNAP_HEADER_LENGTH;
}
TypeId
LlcSnapHeader::GetTypeId (void)
{
static TypeId tid = TypeId ("ns3::LlcSnapHeader")
.SetParent<Header> ()
.AddConstructor<LlcSnapHeader> ()
;
return tid;
}
TypeId
LlcSnapHeader::GetInstanceTypeId (void) const
{
return GetTypeId ();
}
void
LlcSnapHeader::Print (std::ostream &os) const
{
NS_LOG_FUNCTION (this << &os);
os << "type 0x";
os.setf (std::ios::hex, std::ios::basefield);
os << m_etherType;
os.setf (std::ios::dec, std::ios::basefield);
}
void
LlcSnapHeader::Serialize (Buffer::Iterator start) const
{
NS_LOG_FUNCTION (this << &start);
Buffer::Iterator i = start;
uint8_t buf[] = { 0xaa, 0xaa, 0x03, 0, 0, 0};
i.Write (buf, 6);
i.WriteHtonU16 (m_etherType);
}
uint32_t
LlcSnapHeader::Deserialize (Buffer::Iterator start)
{
NS_LOG_FUNCTION (this << &start);
Buffer::Iterator i = start;
i.Next (5+1);
m_etherType = i.ReadNtohU16 ();
return GetSerializedSize ();
}
} // namespace ns3
| 22.892157 | 76 | 0.708351 | gustavo978 |
43c3c4a9e6da8bd65ee7a0b6e3671c485158c31c | 662 | cpp | C++ | C++/ponteiros/MyStrCat.cpp | henrique-tavares/Coisas | f740518b1bedec5b0ea8c12ae07a2cac21eb51ae | [
"MIT"
] | 1 | 2020-02-07T20:39:26.000Z | 2020-02-07T20:39:26.000Z | C++/ponteiros/MyStrCat.cpp | neptune076/Coisas | 85c064cc0e134465aaf6ef41acf747d47f108fc9 | [
"MIT"
] | null | null | null | C++/ponteiros/MyStrCat.cpp | neptune076/Coisas | 85c064cc0e134465aaf6ef41acf747d47f108fc9 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int myStrLen(const char *str)
{
int tam;
for (tam = 0; str[tam] != '\0'; tam++);
return tam;
}
char* myStrCat(const char *dest, const char *orig)
{
char *resultado = new char[myStrLen(dest) + myStrLen(orig) + 1];
int i = 0;
for (int j = 0; dest[j] != '\0'; j++, i++)
{
resultado[i] = dest[j];
}
for (int j = 0; orig[j] != '\0'; j++, i++)
{
resultado[i] = orig[j];
}
resultado[i] = '\0';
return resultado;
}
int main()
{
const char *str1 = "abra";
const char *str2 = "cadabra";
char *str3 = myStrCat(str1, str2);
cout << str1 << endl << str2 << endl << str3 << endl << endl;
return 0;
} | 14.711111 | 65 | 0.558912 | henrique-tavares |
43c7cc25c6446ea2501d0df1085f5e9efca7614e | 1,424 | cpp | C++ | code/binary-tests/binary/converters/little_endian_converter_tests.cpp | afxres/binary-cxx | ef84b0d5324c5add5ea8a09340471efc6221f91f | [
"MIT"
] | 1 | 2019-11-21T06:37:04.000Z | 2019-11-21T06:37:04.000Z | code/binary-tests/binary/converters/little_endian_converter_tests.cpp | afxres/binary-cxx | ef84b0d5324c5add5ea8a09340471efc6221f91f | [
"MIT"
] | null | null | null | code/binary-tests/binary/converters/little_endian_converter_tests.cpp | afxres/binary-cxx | ef84b0d5324c5add5ea8a09340471efc6221f91f | [
"MIT"
] | 1 | 2019-11-26T16:47:56.000Z | 2019-11-26T16:47:56.000Z | #include <boost/test/unit_test.hpp>
#include <boost/test/data/test_case.hpp>
#include <boost/mpl/list.hpp>
#include <binary/converters/little_endian_converter.hpp>
namespace mikodev::binary::tests::converters::little_endian_converter_tests
{
namespace mk = mikodev::binary;
namespace mkc = mikodev::binary::converters;
using __test_types = boost::mpl::list<int8_t, int32_t, uint16_t, uint64_t>;
BOOST_AUTO_TEST_CASE_TEMPLATE(little_endian_converter__length, T, __test_types)
{
auto converter = mkc::little_endian_converter<T>();
BOOST_REQUIRE_EQUAL(sizeof(T), converter.length());
}
template <typename TArgs>
void __test_encode_decode(TArgs source)
{
byte_t buffer[16] = { static_cast<byte_t>(0) };
auto converter = mkc::little_endian_converter<TArgs>();
auto allocator = mk::allocator(buffer, sizeof(buffer));
converter.encode(allocator, source);
BOOST_REQUIRE_EQUAL(sizeof(TArgs), allocator.length());
auto span = allocator.as_span();
auto result = converter.decode(span);
BOOST_REQUIRE_EQUAL(source, result);
BOOST_REQUIRE_EQUAL(sizeof(TArgs), span.length());
}
auto __int64_data = std::vector<int64_t>{ -65536, 0x11223344AABBCCDD };
BOOST_DATA_TEST_CASE(little_endian_converter__encode_decode__int64, __int64_data)
{
__test_encode_decode<int64_t>(sample);
}
}
| 33.904762 | 85 | 0.706461 | afxres |