text string | size int64 | token_count int64 |
|---|---|---|
#include <QApplication>
#include "buttons.h"
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
Buttons window;
window.resize(290, 170);
window.setWindowTitle("Buttons");
window.show();
return app.exec();
}
| 238 | 94 |
/*
* Copyright (C) 2009 Ericsson AB
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name of Ericsson nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#if ENABLE(EVENTSOURCE)
#include "JSEventSourceConstructor.h"
#include "EventSource.h"
#include "ExceptionCode.h"
#include "JSEventSource.h"
#include "ScriptExecutionContext.h"
#include <runtime/Error.h>
using namespace JSC;
namespace WebCore {
ASSERT_CLASS_FITS_IN_CELL(JSEventSourceConstructor);
const ClassInfo JSEventSourceConstructor::s_info = { "EventSourceContructor", 0, 0, 0 };
JSEventSourceConstructor::JSEventSourceConstructor(ExecState* exec, JSDOMGlobalObject* globalObject)
: DOMConstructorObject(JSEventSourceConstructor::createStructure(globalObject->objectPrototype()), globalObject)
{
putDirect(exec->propertyNames().prototype, JSEventSourcePrototype::self(exec, globalObject), None);
putDirect(exec->propertyNames().length, jsNumber(exec, 1), ReadOnly|DontDelete|DontEnum);
}
static JSObject* constructEventSource(ExecState* exec, JSObject* constructor, const ArgList& args)
{
if (args.size() < 1)
return throwError(exec, SyntaxError, "Not enough arguments");
UString url = args.at(0).toString(exec);
if (exec->hadException())
return 0;
JSEventSourceConstructor* jsConstructor = static_cast<JSEventSourceConstructor*>(constructor);
ScriptExecutionContext* context = jsConstructor->scriptExecutionContext();
if (!context)
return throwError(exec, ReferenceError, "EventSource constructor associated document is unavailable");
ExceptionCode ec = 0;
RefPtr<EventSource> eventSource = EventSource::create(url, context, ec);
if (ec) {
setDOMException(exec, ec);
return 0;
}
return asObject(toJS(exec, jsConstructor->globalObject(), eventSource.release()));
}
ConstructType JSEventSourceConstructor::getConstructData(ConstructData& constructData)
{
constructData.native.function = constructEventSource;
return ConstructTypeHost;
}
} // namespace WebCore
#endif // ENABLE(EVENTSOURCE)
| 3,510 | 1,116 |
#include "ns.h"
extern int func();
// Note: the following function must be before the using.
void test_lookup_before_using_directive()
{
// BP_before_using_directive
std::printf("before using directive: func() = %d\n", func()); // eval func(), exp: 1
}
using namespace A;
void test_lookup_after_using_directive()
{
// BP_after_using_directive
//printf("func() = %d\n", func()); // eval func(), exp: error, amiguous
std::printf("after using directive: func2() = %d\n", func2()); // eval func2(), exp: 3
std::printf("after using directive: ::func() = %d\n", ::func()); // eval ::func(), exp: 1
std::printf("after using directive: B::func() = %d\n", B::func()); // eval B::func(), exp: 4
}
| 702 | 242 |
/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkRecordDraw.h"
namespace {
// This is an SkRecord visitor that will draw that SkRecord to an SkCanvas.
class Draw : SkNoncopyable {
public:
explicit Draw(SkCanvas* canvas) : fCanvas(canvas), fIndex(0), fClipEmpty(false) {}
unsigned index() const { return fIndex; }
void next() { ++fIndex; }
template <typename T> void operator()(const T& r) {
if (!this->canSkip(r)) {
this->draw(r);
this->updateClip<T>();
}
}
private:
// Can we skip this command right now?
template <typename T> bool canSkip(const T&) const {
// We can skip most commands if the clip is empty. Exceptions are specialized below.
return fClipEmpty;
}
// No base case, so we'll be compile-time checked that we implemented all possibilities below.
template <typename T> void draw(const T&);
// Update fClipEmpty if necessary.
template <typename T> void updateClip() {
// Most commands don't change the clip. Exceptions are specialized below.
}
SkCanvas* fCanvas;
unsigned fIndex;
bool fClipEmpty;
};
// These commands may change the clip.
#define UPDATE_CLIP(T) template <> void Draw::updateClip<SkRecords::T>() \
{ fClipEmpty = fCanvas->isClipEmpty(); }
UPDATE_CLIP(Restore);
UPDATE_CLIP(SaveLayer);
UPDATE_CLIP(ClipPath);
UPDATE_CLIP(ClipRRect);
UPDATE_CLIP(ClipRect);
UPDATE_CLIP(ClipRegion);
#undef UPDATE_CLIP
// These commands must always run.
#define CAN_SKIP(T) template <> bool Draw::canSkip(const SkRecords::T&) const { return false; }
CAN_SKIP(Restore);
CAN_SKIP(Save);
CAN_SKIP(SaveLayer);
CAN_SKIP(Clear);
CAN_SKIP(PushCull);
CAN_SKIP(PopCull);
#undef CAN_SKIP
// We can skip these commands if they're intersecting with a clip that's already empty.
#define CAN_SKIP(T) template <> bool Draw::canSkip(const SkRecords::T& r) const \
{ return fClipEmpty && SkRegion::kIntersect_Op == r.op; }
CAN_SKIP(ClipPath);
CAN_SKIP(ClipRRect);
CAN_SKIP(ClipRect);
CAN_SKIP(ClipRegion);
#undef CAN_SKIP
static bool can_skip_text(const SkCanvas& c, const SkPaint& p, SkScalar minY, SkScalar maxY) {
// If we're drawing vertical text, none of the checks we're about to do make any sense.
// We'll need to call SkPaint::computeFastBounds() later, so bail out if that's not possible.
if (p.isVerticalText() || !p.canComputeFastBounds()) {
return false;
}
// Rather than checking the top and bottom font metrics, we guess. Actually looking up the top
// and bottom metrics is slow, and this overapproximation should be good enough.
const SkScalar buffer = p.getTextSize() * 1.5f;
SkDEBUGCODE(SkPaint::FontMetrics metrics;)
SkDEBUGCODE(p.getFontMetrics(&metrics);)
SkASSERT(-buffer <= metrics.fTop);
SkASSERT(+buffer >= metrics.fBottom);
// Let the paint adjust the text bounds. We don't care about left and right here, so we use
// 0 and 1 respectively just so the bounds rectangle isn't empty.
SkRect bounds;
bounds.set(0, -buffer, SK_Scalar1, buffer);
SkRect adjusted = p.computeFastBounds(bounds, &bounds);
return c.quickRejectY(minY + adjusted.fTop, maxY + adjusted.fBottom);
}
template <> bool Draw::canSkip(const SkRecords::DrawPosTextH& r) const {
return fClipEmpty || can_skip_text(*fCanvas, r.paint, r.y, r.y);
}
template <> bool Draw::canSkip(const SkRecords::DrawPosText& r) const {
if (fClipEmpty) {
return true;
}
// TODO(mtklein): may want to move this minY/maxY calculation into a one-time pass
const unsigned points = r.paint.countText(r.text, r.byteLength);
if (points == 0) {
return true;
}
SkScalar minY = SK_ScalarInfinity, maxY = SK_ScalarNegativeInfinity;
for (unsigned i = 0; i < points; i++) {
minY = SkTMin(minY, r.pos[i].fY);
maxY = SkTMax(maxY, r.pos[i].fY);
}
return can_skip_text(*fCanvas, r.paint, minY, maxY);
}
#define DRAW(T, call) template <> void Draw::draw(const SkRecords::T& r) { fCanvas->call; }
DRAW(Restore, restore());
DRAW(Save, save(r.flags));
DRAW(SaveLayer, saveLayer(r.bounds, r.paint, r.flags));
DRAW(PopCull, popCull());
DRAW(Clear, clear(r.color));
DRAW(Concat, concat(r.matrix));
DRAW(SetMatrix, setMatrix(r.matrix));
DRAW(ClipPath, clipPath(r.path, r.op, r.doAA));
DRAW(ClipRRect, clipRRect(r.rrect, r.op, r.doAA));
DRAW(ClipRect, clipRect(r.rect, r.op, r.doAA));
DRAW(ClipRegion, clipRegion(r.region, r.op));
DRAW(DrawBitmap, drawBitmap(r.bitmap, r.left, r.top, r.paint));
DRAW(DrawBitmapMatrix, drawBitmapMatrix(r.bitmap, r.matrix, r.paint));
DRAW(DrawBitmapNine, drawBitmapNine(r.bitmap, r.center, r.dst, r.paint));
DRAW(DrawBitmapRectToRect, drawBitmapRectToRect(r.bitmap, r.src, r.dst, r.paint, r.flags));
DRAW(DrawDRRect, drawDRRect(r.outer, r.inner, r.paint));
DRAW(DrawOval, drawOval(r.oval, r.paint));
DRAW(DrawPaint, drawPaint(r.paint));
DRAW(DrawPath, drawPath(r.path, r.paint));
DRAW(DrawPoints, drawPoints(r.mode, r.count, r.pts, r.paint));
DRAW(DrawPosText, drawPosText(r.text, r.byteLength, r.pos, r.paint));
DRAW(DrawPosTextH, drawPosTextH(r.text, r.byteLength, r.xpos, r.y, r.paint));
DRAW(DrawRRect, drawRRect(r.rrect, r.paint));
DRAW(DrawRect, drawRect(r.rect, r.paint));
DRAW(DrawSprite, drawSprite(r.bitmap, r.left, r.top, r.paint));
DRAW(DrawText, drawText(r.text, r.byteLength, r.x, r.y, r.paint));
DRAW(DrawTextOnPath, drawTextOnPath(r.text, r.byteLength, r.path, r.matrix, r.paint));
DRAW(DrawVertices, drawVertices(r.vmode, r.vertexCount, r.vertices, r.texs, r.colors,
r.xmode.get(), r.indices, r.indexCount, r.paint));
#undef DRAW
// PushCull is a bit of a oddball. We might be able to just skip until just past its popCull.
template <> void Draw::draw(const SkRecords::PushCull& r) {
if (r.popOffset != SkRecords::kUnsetPopOffset && fCanvas->quickReject(r.rect)) {
fIndex += r.popOffset;
} else {
fCanvas->pushCull(r.rect);
}
}
} // namespace
void SkRecordDraw(const SkRecord& record, SkCanvas* canvas) {
for (Draw draw(canvas); draw.index() < record.count(); draw.next()) {
record.visit(draw.index(), draw);
}
}
| 6,300 | 2,337 |
/*
* Copyright 2018 The Polycube Authors
*
* 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 "AbstractFactory.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "CaseResource.h"
#include "ChoiceResource.h"
#include "JsonNodeField.h"
#include "JsonValueField.h"
#include "LeafListResource.h"
#include "LeafResource.h"
#include "ListKey.h"
#include "ListResource.h"
#include "ParentResource.h"
namespace polycube::polycubed::Rest::Resources::Body {
std::unique_ptr<Body::JsonValueField> AbstractFactory::JsonValueField() const {
return std::make_unique<Body::JsonValueField>();
}
std::unique_ptr<Body::JsonValueField> AbstractFactory::JsonValueField(
LY_DATA_TYPE type,
std::vector<std::shared_ptr<Validators::ValueValidator>> &&validators)
const {
return std::make_unique<Body::JsonValueField>(type, std::move(validators));
}
std::unique_ptr<CaseResource> AbstractFactory::BodyCase(
const std::string &name, const std::string &description,
const std::string &cli_example, const Body::ParentResource *parent) const {
return std::make_unique<CaseResource>(name, description, cli_example, parent,
core_);
}
std::unique_ptr<ChoiceResource> AbstractFactory::BodyChoice(
const std::string &name, const std::string &description,
const std::string &cli_example, const Body::ParentResource *parent,
bool mandatory, std::unique_ptr<const std::string> &&default_case) const {
return std::make_unique<ChoiceResource>(name, description, cli_example,
parent, core_, mandatory,
std::move(default_case));
}
std::unique_ptr<LeafResource> AbstractFactory::BodyLeaf(
const std::string &name, const std::string &description,
const std::string &cli_example, const Body::ParentResource *parent,
std::unique_ptr<Body::JsonValueField> &&value_field,
const std::vector<Body::JsonNodeField> &node_fields, bool configuration,
bool init_only_config, bool mandatory, Types::Scalar type,
std::unique_ptr<const std::string> &&default_value) const {
return std::make_unique<LeafResource>(
name, description, cli_example, parent, core_, std::move(value_field),
node_fields, configuration, init_only_config, mandatory, type,
std::move(default_value));
}
std::unique_ptr<LeafListResource> AbstractFactory::BodyLeafList(
const std::string &name, const std::string &description,
const std::string &cli_example, const Body::ParentResource *parent,
std::unique_ptr<Body::JsonValueField> &&value_field,
const std::vector<JsonNodeField> &node_fields, bool configuration,
bool init_only_config, bool mandatory, Types::Scalar type,
std::vector<std::string> &&default_value) const {
return std::make_unique<LeafListResource>(
name, description, cli_example, parent, core_, std::move(value_field),
node_fields, configuration, init_only_config, mandatory, type,
std::move(default_value));
}
std::unique_ptr<ListResource> AbstractFactory::BodyList(
const std::string &name, const std::string &description,
const std::string &cli_example, const Body::ParentResource *parent,
std::vector<Resources::Body::ListKey> &&keys,
const std::vector<JsonNodeField> &node_fields, bool configuration,
bool init_only_config) const {
return std::make_unique<ListResource>(name, description, cli_example, parent,
core_, std::move(keys), node_fields,
configuration, init_only_config);
}
std::unique_ptr<ParentResource> AbstractFactory::BodyGeneric(
const std::string &name, const std::string &description,
const std::string &cli_example, const Body::ParentResource *parent,
const std::vector<JsonNodeField> &node_fields, bool configuration,
bool init_only_config, bool container_presence) const {
return std::make_unique<ParentResource>(
name, description, cli_example, parent, core_, node_fields, configuration,
init_only_config, container_presence);
}
AbstractFactory::AbstractFactory(PolycubedCore *core) : core_(core) {}
} // namespace polycube::polycubed::Rest::Resources::Body
| 4,763 | 1,364 |
#include <string>
#include <iostream>
int main(int argc, char *argv[])
{
std::string phrase;
std::cout << "Enter a phrase: ";
std::getline(std::cin, phrase);
std::cout << phrase.size() << std::endl;
int word_start = 0, temp_end = 0, word_end = 0, words = 0, proper = 0, repeat = 0;
while (word_end != std::string::npos) {
word_end = phrase.find(" ", word_start);
if(word_end == std::string::npos)
{
temp_end = phrase.size();
}
else
{
temp_end = word_end;
}
std::cout << phrase.substr(word_start, temp_end - word_start) << std::endl;
words++;
bool is_proper = true;
bool is_repeat = false;
char previous_letter = phrase[word_start];
for(int i = 0; i < (temp_end - word_start); i++)
{
if (!is_repeat)
{
if (i > 0)
{
if (phrase[word_start + i] == previous_letter)
{
is_repeat = true;
}
}
}
if (is_proper)
{
if (i == 0)
{
if (!(phrase[word_start + i] >= 'A' && phrase[word_start + i] <= 'Z'))
{
is_proper = false;
}
}
else // i > 1
{
if (!(phrase[word_start + i] >= 'a' && phrase[word_start + i] <= 'z'))
{
is_proper = false;
}
}
}
previous_letter = phrase[word_start + i];
}
if(is_proper)
{
proper++;
}
if(is_repeat)
{
repeat++;
}
word_start = word_end + 1;
}
std::cout << words << std::endl;
std::cout << proper << std::endl;
std::cout << repeat << std::endl;
} | 2,009 | 601 |
//==========================================================================
// ObTools::ObCache::SQL: storage.cc
//
// Implementation of SQL storage manager
//
// Copyright (c) 2008 Paul Clark. All rights reserved
// This code comes with NO WARRANTY and is subject to licence agreement
//==========================================================================
#include "ot-obcache-sql.h"
#include "ot-log.h"
#include "ot-text.h"
namespace ObTools { namespace ObCache { namespace SQL {
//--------------------------------------------------------------------------
// Load an object
Object *Storage::load(object_id_t id)
{
// Get DB connection
DB::AutoConnection db(db_pool);
// Look up ID in main object table, to get type ref
string types = db.select_value_by_id64("root", "_type", id, "_id");
if (types.empty())
throw Exception("Attempt to load non-existent object "+Text::i64tos(id));
type_id_t type = Text::stoi64(types);
// Look up storer interface by type ref
map<type_id_t, Storer *>::iterator p = storers.find(type);
if (p == storers.end())
throw Exception("Attempt to load unknown type "+Text::i64tos(type));
Storer *storer = p->second;
// Get storer to load it, using the same DB connection
return storer->load(id, db);
}
//--------------------------------------------------------------------------
// Save an object
void Storage::save(Object * /*ob*/)
{
// !!! Get type name from object get_name
// !!! Look up storer interface
// !!! Get DB connection
// !!! Get storer to save it
throw Exception("Not yet implemented!");
}
}}} // namespaces
| 1,614 | 472 |
/* Copyright 2001, 2019 IBM Corporation
*
* 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 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.
*/
//
// IBM T.J.W R.C.
// Date : 24/01/2003
// Name : Maria Eleftheriou
// Last Modified on: 09/24/03 by Maria Eleftheriou
// fftmain.hpp
// tests the 3D fft using MPI and fftw
#if defined(USE_PK_ACTORS)
#include <BonB/BGL_PartitionSPI.h>
#include <rts.h>
#include <Pk/API.hpp>
#include <Pk/Compatibility.hpp>
#include <stdio.h>
#include <BonB/BGLTorusAppSupport.h>
#include <BonB/BGLTorusAppSupport.c>
#else
#include <pk/platform.hpp>
#include <pk/fxlogger.hpp>
#endif
#include <BlueMatter/complex.hpp>
#include <fft3Dlib.hpp>
#include <math.h>
#define TYPE float
#define FFT3D_STUCT_ALIGNMENT __attribute__ (( aligned( (0x01 << 6) ) ))
#define FFT3D_STRUCT_ALIGNMENT __attribute__ (( aligned( (0x01 << 6) ) ))
#define TOLERANCE (1./1000.)
#define N_SIZE 128
#define MESS_SIZE 8
#define ITERATIONS 10
#define REGRESS_REVERSE
#ifndef PKFXLOG_FFTMAIN
#define PKFXLOG_FFTMAIN (0)
#endif
#ifndef PKFXLOG_FFTINTER
#define PKFXLOG_FFTINTER (0)
#endif
#ifndef PKFXLOG_FFTITERATION
#define PKFXLOG_FFTITERATION (0)
#endif
#ifndef PKFXLOG_FFTBENCHMARK
#define PKFXLOG_FFTBENCHMARK (0)
#endif
struct FFT_PLAN
{
enum
{
P_X = MESS_SIZE,
P_Y = MESS_SIZE,
P_Z = MESS_SIZE
};
enum
{
GLOBAL_SIZE_X = N_SIZE,
GLOBAL_SIZE_Y = N_SIZE,
GLOBAL_SIZE_Z = N_SIZE
};
};
// CHECK needs to be removed
#define FORWARD -1
#define REVERSE 1
typedef BGL3DFFT< FFT_PLAN, FORWARD, TYPE ,TYPE complex > FFT_FORWARD FFT3D_STRUCT_ALIGNMENT;
typedef BGL3DFFT< FFT_PLAN, REVERSE, TYPE ,TYPE complex > FFT_REVERSE FFT3D_STRUCT_ALIGNMENT;
static int compare ( TYPE complex* in,
TYPE complex* rev,
int localNx, int localNy, int localNz,
double fftSz)
{
for(int i=0; i<localNx; i++)
for(int j=0; j<localNy; j++)
for(int k=0; k<localNz; k++)
{
int myIndex = i*localNy*localNz+j*localNz+k;
if ( fabs(creal(in[myIndex])-creal(rev[myIndex])*fftSz) > TOLERANCE
|| fabs(cimag(in[myIndex])-cimag(rev[myIndex])*fftSz) > TOLERANCE ) {
BegLogLine(1)
<< "[" << i
<< "," << j
<< "," << k
<< "] in=(" << creal(in[myIndex])
<< "," << cimag(in[myIndex])
<< ") rev*fftSz=(" << creal(rev[myIndex]*fftSz)
<< "," << cimag(rev[myIndex]*fftSz)
<< ")"
<< EndLogLine ;
return 1;
}
}
return 0;
}
// get processor mesh and fft size
static void init( int argc, char*argv[], int& globalNx, int& globalNy, int& globalNz,
int& pX, int& pY, int& pZ,
int& subPx, int& subPy, int& subPz,
int& iterations ,
int& markrank ,
int& markindex )
{
BegLogLine(PKFXLOG_FFTMAIN)
<< "init argc=" << argc
<< EndLogLine ;
for(int i=0; i<argc; i++)
{
BegLogLine(PKFXLOG_FFTMAIN)
<< "i=" << i
<< " argv[i]=" << argv[i]
<< EndLogLine ;
if (!strcmp(argv[i],"-procmesh"))
{
pX = atoi(argv[++i]);
pY = atoi(argv[++i]);
pZ = atoi(argv[++i]);
}
if (!strcmp(argv[i],"-subprocmesh"))
{
subPx = atoi(argv[++i]);
subPy = atoi(argv[++i]);
subPz = atoi(argv[++i]);
}
if (!strcmp(argv[i],"-fftsize"))
{
globalNx = atoi(argv[++i]);
globalNy = atoi(argv[++i]);
globalNz = atoi(argv[++i]);
}
if (!strcmp(argv[i],"-iterations"))
{
iterations = atoi(argv[++i]) ;
}
if (!strcmp(argv[i],"-mark"))
{
markrank = atoi(argv[++i]) ;
markindex = atoi(argv[++i]) ;
}
}
}
#if !defined(USE_PK_ACTORS)
extern "C" {
void *
PkMain(int argc, char** argv, char** envp) ;
} ;
#endif
static FFT_FORWARD fftForward;
static FFT_REVERSE fftReverse;
#if defined(USE_PK_ACTORS)
int
#else
void *
#endif
PkMain(int argc, char** argv, char** envp)
{
#pragma execution_frequency(very_low)
// complex ***in, ***tmp, ***out;
// complex ***localOut;
// int pX = FFT_PLAN::P_X ;
// int pY = FFT_PLAN::P_Y ;
// int pZ = FFT_PLAN::P_Z ;
#if defined(USE_PK_ACTORS)
int pX ;
int pY ;
int pZ ;
if ( Platform::Thread::GetId() != 0 )
{
for(;;) ; // hang here if on the IOP
}
Platform::Topology::GetDimensions(&pX, &pY, &pZ) ;
#else
int pX = Platform::Topology::mDimX ;
int pY = Platform::Topology::mDimY ;
int pZ = Platform::Topology::mDimZ ;
#endif
int globalNx = FFT_PLAN::GLOBAL_SIZE_X ;
int globalNy = FFT_PLAN::GLOBAL_SIZE_Y ;
int globalNz = FFT_PLAN::GLOBAL_SIZE_Z ;
int iterations = ITERATIONS ;
int markrank = 0 ;
int markindex = 0 ;
int subPx = -1 ;
int subPy = -1 ;
int subPz = -1 ;
init(argc, argv, globalNx,globalNy,globalNz, pX, pY, pZ, subPx, subPy, subPz, iterations, markrank, markindex );
if ( -1 == subPx ) subPx = pX ;
if ( -1 == subPy ) subPy = pY ;
if ( -1 == subPz ) subPz = pZ ;
int localNx = globalNx / pX ;
int localNy = globalNy / pY ;
int localNz = globalNz / pZ ;
#if defined(USE_PK_ACTORS)
int myRank = PkNodeGetId() ;
// #if defined(PKTRACE)
// pkTraceServer::Init() ;
// #endif
#else
int myRank = Platform::Topology::GetAddressSpaceId();
#endif
// if (myRank == 0)
// {
// printf( " proc mesh GLOBAL_SIZE_X = %d GLOBAL_SIZE_Y = %d GLOBAL_SIZE_Z = %d\n",
// FFT_PLAN::GLOBAL_SIZE_X,
// FFT_PLAN::GLOBAL_SIZE_Y,
// FFT_PLAN::GLOBAL_SIZE_Z);
//
// printf(" 3D FFT of size [%d %d %d] on [%d %d %d] \n",
// localNx, localNy, localNz,
// FFT_PLAN::P_X, FFT_PLAN::P_Y, FFT_PLAN::P_Z);
// }
int arraySz= (globalNx*globalNy*globalNz)/(pX*pY*pZ);
BegLogLine(PKFXLOG_FFTMAIN)
<< "PkMain"
// << " FFT_PLAN::GLOBAL_SIZE_X=" << FFT_PLAN::GLOBAL_SIZE_X
// << " FFT_PLAN::GLOBAL_SIZE_Y=" << FFT_PLAN::GLOBAL_SIZE_Y
// << " FFT_PLAN::GLOBAL_SIZE_Z=" << FFT_PLAN::GLOBAL_SIZE_Z
// << " FFT_PLAN::P_X=" << FFT_PLAN::P_X
// << " FFT_PLAN::P_Y=" << FFT_PLAN::P_Y
// << " FFT_PLAN::P_Z=" << FFT_PLAN::P_Z
<< " globalNx=" << globalNx
<< " globalNy=" << globalNy
<< " globalNz=" << globalNz
<< " pX=" << pX
<< " pY=" << pY
<< " pZ=" << pZ
<< " localNx=" << localNx
<< " localNy=" << localNy
<< " localNz=" << localNz
<< " arraySz=" << arraySz
<< EndLogLine ;
TYPE complex * in = new TYPE complex[arraySz] ;
TYPE complex * out = new TYPE complex[arraySz] ;
TYPE complex * rev = new TYPE complex[arraySz] ;
(fftReverse).Init(globalNx,globalNy,globalNz
,pX,pY,pZ
,subPx, subPy, subPz, 1 );
(fftForward).Init(globalNx,globalNy,globalNz
,pX,pY,pZ
,subPx, subPy, subPz, 1 );
#ifndef FFT_FIX_DATA
srand48(myRank) ; // Arrange that different nodes get different seed data
#endif
for(unsigned int i=0; i<localNx; i++)
for(unsigned int j=0; j<localNy; j++)
for(unsigned int k=0; k<localNz; k++)
{
#ifdef FFT_FIX_DATA
double rdata = 0.0 ;
double idata = 0.0 ;
#else
double rdata = drand48();
double idata = drand48();
#endif
int myIndex = i*localNy*localNz+j*localNz+k;
in[myIndex] = rdata + I * idata ;
}
#ifdef FFT_FIX_DATA
if ( markrank == myRank && markindex >= 0 && markindex < arraySz )
{
in[markindex] = 1.0 ;
}
#endif
// int iter =20;
BegLogLine(PKFXLOG_FFTMAIN)
<< "Iterations starting"
<< EndLogLine ;
// Do one forward and one reverse, to separate out initialisation effects
(fftForward).DoFFT(in,out);
(fftReverse).DoFFT(out, rev);
// Main run
long long oscillatorAtStart =
#if defined(USE_PK_ACTORS)
PkTimeGetRaw()
#else
Platform::Clock::Oscillator()
#endif
;
{
BegLogLine(PKFXLOG_FFTINTER)
<< "Starting forwards FFT"
<< EndLogLine ;
int nextlogiteration = 1 ;
for(int i=0; i<iterations; i++)
{
if ( i >= nextlogiteration )
{
BegLogLine(PKFXLOG_FFTITERATION)
<< "Forward iteration=" << i
<< EndLogLine ;
nextlogiteration *= 2 ;
}
(fftForward).DoFFT(in,out);
}
BegLogLine(PKFXLOG_FFTINTER)
<< "Ending forwards FFT"
<< EndLogLine ;
}
// if(myRank==0)
// for(unsigned int i=0; i<localNx; i++)
// for(unsigned int j=0; j<localNy; j++)
// for(unsigned int k=0; k<localNz; k++)
// {
// printf(" proc = %d out_forward[%d %d %d] = %f\n",
// myRank, i, j, k, tmp[i][j][k].re, tmp[i][j][k].im );
// }
// (fftReverse).Init(FFT_PLAN::GLOBAL_SIZE_X,FFT_PLAN::GLOBAL_SIZE_Y,FFT_PLAN::GLOBAL_SIZE_Z
// ,FFT_PLAN::P_X,FFT_PLAN::P_Y,FFT_PLAN::P_Z);
// for( int i=0; i<localNx; i++)
// for( int j=0; j<localNy; j++)
// for( int k=0; k<localNz; k++)
// {
// fftReverse.PutRecipSpaceElement(i, j, k,
// fftForward.GetRecipSpaceElement( i, j, k ) );
// }
long long oscillatorAtMid =
#if defined(USE_PK_ACTORS)
PkTimeGetRaw()
#else
Platform::Clock::Oscillator()
#endif
;
{
BegLogLine(PKFXLOG_FFTINTER)
<< "Starting reverse FFT"
<< EndLogLine ;
int nextlogiteration = 1 ;
for(int i=0; i<iterations; i++)
{
if ( i >= nextlogiteration )
{
BegLogLine(PKFXLOG_FFTITERATION)
<< "Reverse iteration=" << i
<< EndLogLine ;
nextlogiteration *= 2 ;
}
(fftReverse).DoFFT(out, rev);
}
BegLogLine(PKFXLOG_FFTINTER)
<< "Ending reverse FFT"
<< EndLogLine ;
}
long long oscillatorAtEnd =
#if defined(USE_PK_ACTORS)
PkTimeGetRaw()
#else
Platform::Clock::Oscillator()
#endif
;
BegLogLine(PKFXLOG_FFTBENCHMARK)
<< "Benchmark sizeof(TYPE)=" << sizeof(TYPE)
<< " globalNx=" << globalNx
<< " globalNy=" << globalNy
<< " globalNz=" << globalNz
<< " pX=" << pX
<< " pY=" << pY
<< " pZ=" << pZ
<< " iterations=" << iterations
<< " forward_clocks=" << oscillatorAtMid-oscillatorAtStart
<< " reverse_clocks=" << oscillatorAtEnd-oscillatorAtMid
<< " forward_time_per_iter_ns=" << (oscillatorAtMid-oscillatorAtStart)*(1000.0/700.0)/iterations
<< " reverse_time_per_iter_ns=" << (oscillatorAtEnd-oscillatorAtMid)*(1000.0/700.0)/iterations
<< EndLogLine ;
double fftSz = 1.0/(double)(localNx*pX*localNy*pY*localNz*pZ);
// for( int i=0; i<localNx; i++)
// for( int j=0; j<localNy; j++)
// for( int k=0; k<localNz; k++)
// {
// out[i][j][k] = (fftReverse.GetRealSpaceElement(i, j, k ));
// out[i][j][k].re = fftSz*out[i][j][k].re;
// out[i][j][k].im = fftSz*out[i][j][k].im;
// // cout<<"OUT["<<i<<"]["<<j<<"][" <<k<< "] =" << out[i][j][k] <<endl;
// }
//#define PRINT_OUTPUT
#ifdef PRINT_OUTPUT
for(unsigned int i=0; i<localNx; i++)
for(unsigned int j=0; j<localNy; j++)
for(unsigned int k=0; k<localNz; k++)
{
int myIndex = i*localNy*localNz+j*localNz+k;
BegLogLine(1)
<< "[" << i
<< "," << j
<< "," << k
<< "] in=(" << in[myIndex].re
<< "," << in[myIndex].im
<< ") out=(" << out[myIndex].re
<< "," << out[myIndex].im
<< ") rev=(" << rev[myIndex].re
<< "," << rev[myIndex].im
<< ")"
<< EndLogLine ;
// tmp[i][j][k] = fftForward.GetRecipSpaceElement( i, j, k );
// BegLogLine(1)
// << "[" << i
// << "," << j
// << "," << k
// << "] in=(" << in[i][j][k].re
// << "," << in[i][j][k].im
// << ") out_forward=(" << tmp[i][j][k].re
// << "," << tmp[i][j][k].im
// << ") out=(" << out[i][j][k].re
// << "," << out[i][j][k].im
// << ")"
// << EndLogLine ;
// printf(" proc = %d out_forward[%d %d %d] = %f\n",
// myRank, i, j, k, tmp[i][j][k].re, tmp[i][j][k].im );
// printf(" proc %d out_reverse[%d %d %d] = %f\n",
// myRank, i, j, k, out[i][j][k].re, tmp[i][j][k].im );
}
#endif
#if defined(A2A_WITH_ACTORS)
#if defined(USE_PK_ACTORS)
PacketAlltoAllv_PkActors::ReportFifoHistogram() ;
#else
PacketAlltoAllv_Actors::ReportFifoHistogram() ;
#endif
#else
PacketAlltoAllv::ReportFifoHistogram() ;
#endif
#ifdef REGRESS_REVERSE
if(compare(in, rev, localNx, localNy, localNz, fftSz) == 1) {
BegLogLine(1)
<< "FAILED FFT-REVERSE TEST :-( "
<< EndLogLine ;
// printf( "FAILED FFT-REVERSE TEST :-( \n" );
}
else {
BegLogLine(1)
<< "PASSED FFT-REVERSE TEST :-) "
<< EndLogLine ;
// printf( "PASSED FFT-REVERSE TEST :-) \n" );
}
#endif
BegLogLine(PKFXLOG_FFTMAIN)
<< "PkMain complete"
<< EndLogLine ;
#if defined(USE_PK_ACTORS)
// 'Barrier' here spins until all nodes have finshed their last FFT; otherwise some nodes
// can exit before emptying their transmit FIFOs
PkCo_Barrier() ;
#if defined(PKTRACE)
pkTraceServer::FlushBuffer() ;
#endif
exit(0) ; // Bring 'Pk' down explicitly
return 0 ;
#else
return NULL ;
#endif
}
| 14,375 | 6,185 |
#include <iostream>
using std::cout;
using std::endl;
// author: https://github.com/AnotherGithubDude, 2022
int main(){
int valueOne = 15, valueTwo = 8;
cout << "valueOne original:" << valueOne << endl;
cout << "valueTwo original:" << valueTwo << endl;
valueOne += valueTwo; // 15 + 8 = 23
valueTwo = valueOne - valueTwo; // 23 - 8 = 15
valueOne -= valueTwo; // 23 - 15 = 8
cout << "valueOne after manipulation:" << valueOne << endl;
cout << "valueTwo after manipulation:" << valueTwo << endl;
return 0;
} | 571 | 200 |
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#include "test_precomp.hpp"
#include "test_intrin_utils.hpp"
#define CV_CPU_SIMD_FILENAME "test_intrin_utils.hpp"
#define CV_CPU_DISPATCH_MODE FP16
#include "opencv2/core/private/cv_cpu_include_simd_declarations.hpp"
using namespace cv;
namespace opencv_test { namespace hal {
using namespace CV_CPU_OPTIMIZATION_NAMESPACE;
//============= 8-bit integer =====================================================================
TEST(hal_intrin, uint8x16) {
TheTest<v_uint8x16>()
.test_loadstore()
.test_interleave()
.test_expand()
.test_expand_q()
.test_addsub()
.test_addsub_wrap()
.test_cmp()
.test_logic()
.test_min_max()
.test_absdiff()
.test_mask()
.test_popcount()
.test_pack<1>().test_pack<2>().test_pack<3>().test_pack<8>()
.test_pack_u<1>().test_pack_u<2>().test_pack_u<3>().test_pack_u<8>()
.test_unpack()
.test_extract<0>().test_extract<1>().test_extract<8>().test_extract<15>()
.test_rotate<0>().test_rotate<1>().test_rotate<8>().test_rotate<15>()
;
}
TEST(hal_intrin, int8x16) {
TheTest<v_int8x16>()
.test_loadstore()
.test_interleave()
.test_expand()
.test_expand_q()
.test_addsub()
.test_addsub_wrap()
.test_cmp()
.test_logic()
.test_min_max()
.test_absdiff()
.test_abs()
.test_mask()
.test_popcount()
.test_pack<1>().test_pack<2>().test_pack<3>().test_pack<8>()
.test_unpack()
.test_extract<0>().test_extract<1>().test_extract<8>().test_extract<15>()
.test_rotate<0>().test_rotate<1>().test_rotate<8>().test_rotate<15>()
;
}
//============= 16-bit integer =====================================================================
TEST(hal_intrin, uint16x8) {
TheTest<v_uint16x8>()
.test_loadstore()
.test_interleave()
.test_expand()
.test_addsub()
.test_addsub_wrap()
.test_mul()
.test_mul_expand()
.test_cmp()
.test_shift<1>()
.test_shift<8>()
.test_logic()
.test_min_max()
.test_absdiff()
.test_reduce()
.test_mask()
.test_popcount()
.test_pack<1>().test_pack<2>().test_pack<7>().test_pack<16>()
.test_pack_u<1>().test_pack_u<2>().test_pack_u<7>().test_pack_u<16>()
.test_unpack()
.test_extract<0>().test_extract<1>().test_extract<4>().test_extract<7>()
.test_rotate<0>().test_rotate<1>().test_rotate<4>().test_rotate<7>()
;
}
TEST(hal_intrin, int16x8) {
TheTest<v_int16x8>()
.test_loadstore()
.test_interleave()
.test_expand()
.test_addsub()
.test_addsub_wrap()
.test_mul()
.test_mul_expand()
.test_cmp()
.test_shift<1>()
.test_shift<8>()
.test_dot_prod()
.test_logic()
.test_min_max()
.test_absdiff()
.test_abs()
.test_reduce()
.test_mask()
.test_popcount()
.test_pack<1>().test_pack<2>().test_pack<7>().test_pack<16>()
.test_unpack()
.test_extract<0>().test_extract<1>().test_extract<4>().test_extract<7>()
.test_rotate<0>().test_rotate<1>().test_rotate<4>().test_rotate<7>()
;
}
//============= 32-bit integer =====================================================================
TEST(hal_intrin, uint32x4) {
TheTest<v_uint32x4>()
.test_loadstore()
.test_interleave()
.test_expand()
.test_addsub()
.test_mul()
.test_mul_expand()
.test_cmp()
.test_shift<1>()
.test_shift<8>()
.test_logic()
.test_min_max()
.test_absdiff()
.test_reduce()
.test_mask()
.test_popcount()
.test_pack<1>().test_pack<2>().test_pack<15>().test_pack<32>()
.test_unpack()
.test_extract<0>().test_extract<1>().test_extract<2>().test_extract<3>()
.test_rotate<0>().test_rotate<1>().test_rotate<2>().test_rotate<3>()
.test_transpose()
;
}
TEST(hal_intrin, int32x4) {
TheTest<v_int32x4>()
.test_loadstore()
.test_interleave()
.test_expand()
.test_addsub()
.test_mul()
.test_abs()
.test_cmp()
.test_popcount()
.test_shift<1>().test_shift<8>()
.test_logic()
.test_min_max()
.test_absdiff()
.test_reduce()
.test_mask()
.test_pack<1>().test_pack<2>().test_pack<15>().test_pack<32>()
.test_unpack()
.test_extract<0>().test_extract<1>().test_extract<2>().test_extract<3>()
.test_rotate<0>().test_rotate<1>().test_rotate<2>().test_rotate<3>()
.test_float_cvt32()
.test_float_cvt64()
.test_transpose()
;
}
//============= 64-bit integer =====================================================================
TEST(hal_intrin, uint64x2) {
TheTest<v_uint64x2>()
.test_loadstore()
.test_addsub()
.test_shift<1>().test_shift<8>()
.test_logic()
.test_extract<0>().test_extract<1>()
.test_rotate<0>().test_rotate<1>()
;
}
TEST(hal_intrin, int64x2) {
TheTest<v_int64x2>()
.test_loadstore()
.test_addsub()
.test_shift<1>().test_shift<8>()
.test_logic()
.test_extract<0>().test_extract<1>()
.test_rotate<0>().test_rotate<1>()
;
}
//============= Floating point =====================================================================
TEST(hal_intrin, float32x4) {
TheTest<v_float32x4>()
.test_loadstore()
.test_interleave()
.test_interleave_2channel()
.test_addsub()
.test_mul()
.test_div()
.test_cmp()
.test_sqrt_abs()
.test_min_max()
.test_float_absdiff()
.test_reduce()
.test_mask()
.test_unpack()
.test_float_math()
.test_float_cvt64()
.test_matmul()
.test_transpose()
.test_reduce_sum4()
;
}
#if CV_SIMD128_64F
TEST(hal_intrin, float64x2) {
TheTest<v_float64x2>()
.test_loadstore()
.test_addsub()
.test_mul()
.test_div()
.test_cmp()
.test_sqrt_abs()
.test_min_max()
.test_float_absdiff()
.test_mask()
.test_unpack()
.test_float_math()
.test_float_cvt32()
;
}
#endif
TEST(hal_intrin,float16x4)
{
CV_CPU_CALL_FP16(test_hal_intrin_float16x4, ());
throw SkipTestException("Unsupported hardware: FP16 is not available");
}
}}
| 6,911 | 2,542 |
//
// LineSegment.hpp
// CPP_2.3
//
// Created by Zhehao Li on 2020/2/26.
// Copyright © 2020 Zhehao Li. All rights reserved.
//
#ifndef LineSegment_hpp
#define LineSegment_hpp
#include "Point.hpp"
#include <iostream>
using namespace std;
class LineSegment {
private:
Point startPoint; // e1
Point endPoint; // e2
public:
// Constructor
LineSegment(); // Default constructor
LineSegment(const Point &p1, const Point &p2); // Initialize with two points
LineSegment(const LineSegment &l); // Copy constructor
// Destructor
virtual ~LineSegment();
// Accessing functions
Point Start() const; // May not change the data member
Point End() const; // May not change the data member
// Modifers
void Start(const Point &pt); // Call by reference, may not change the original object
void End(const Point &pt); // Overloading function name
};
#endif /* LineSegment_hpp */
| 1,150 | 325 |
//
// Created by Icyblazek on 2021/5/27.
// Github https://github.com/icyblazek
//
#include <cstdio>
#include <uv.h>
#include <httplib.h>
#include <nlohmann/json.hpp>
#include "args.hxx"
#include <spdlog/spdlog.h>
#ifdef _WIN32
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "IPHLPAPI.lib")
#pragma comment(lib, "Psapi.lib")
#pragma comment(lib, "Userenv.lib")
#pragma comment(lib, "uv.lib")
#else
#endif // _WIN32
using namespace std;
string g_version = "beta v1.0";
string g_host = "localhost";
int g_debug_port = 1635;
string g_gateway = "api.eth-swarm.io";
string g_nodeId = "";
int g_gateway_port = 80;
bool g_auto_cashout = false;
int g_upload_interval = 1000 * 60;
bool g_auto_upload = true;
httplib::Client *g_httpClient = nullptr;
std::set<string> *g_tx_upload_queue = new set<string>();
std::set<string> *g_tx_uploaded_queue = new set<string>();
std::tuple<int, string> bee_health() {
int res_code = -1;
string version = "unknown";
if (auto res = g_httpClient->Get("/health")) {
if (res->status == 200) {
auto json = nlohmann::json::parse(res->body);
if (json.contains("status") && json.at("status").get<string>() == "ok") {
res_code = 0;
version = json.at("version").get<string>();
}
}
} else {
res_code = static_cast<int>(res.error());
}
return std::tuple<int, string>(res_code, version);
}
int bee_peers() {
int peerCount = 0;
if (auto res = g_httpClient->Get("/peers")) {
if (res->status == 200) {
auto json = nlohmann::json::parse(res->body);
peerCount = json.at("peers").size();
}
}
return peerCount;
}
string bee_address() {
string address;
if (auto res = g_httpClient->Get("/addresses")) {
if (res->status == 200) {
auto json = nlohmann::json::parse(res->body);
if (json.contains("ethereum")) {
address = json.at("ethereum").get<string>();
}
}
}
return address;
}
string bee_chequebook_address() {
string address;
if (auto res = g_httpClient->Get("/chequebook/address")) {
if (res->status == 200) {
/**
* after bee 0.6.0, chequebookaddress change to chequebookAddress
*/
auto json = nlohmann::json::parse(res->body);
if (json.contains("chequebookaddress")) {
address = json.at("chequebookaddress").get<string>();
} else if (json.contains("chequebookAddress")) {
address = json.at("chequebookAddress").get<string>();
}
}
}
return address;
}
std::tuple<int, std::list<nlohmann::json>> bee_lastcheques() {
int res_code = -1;
string body;
std::list<nlohmann::json> peers;
if (auto res = g_httpClient->Get("/chequebook/cheque")) {
if (res->status == 200) {
res_code = 0;
auto json = nlohmann::json::parse(res->body);
if (json.contains("lastcheques")) {
nlohmann::json::array_t lastcheques = json.at("lastcheques");
for (auto &lastcheque : lastcheques) {
auto lastReceived = lastcheque.at("lastreceived");
if (lastReceived != nullptr) {
peers.push_back(lastcheque);
}
}
}
}
} else {
res_code = static_cast<int>(res.error());
}
return std::tuple<int, std::list<nlohmann::json>>(res_code, peers);
}
double bee_get_cumulative_payout(const string &peer) {
double payout = 0;
if (auto res = g_httpClient->Get(("/chequebook/cheque/" + peer).c_str())) {
if (res->status == 200) {
auto json = nlohmann::json::parse(res->body);
if (json.contains("lastreceived")) {
auto lastReceived = json.at("lastreceived");
if (lastReceived != nullptr && lastReceived.contains("payout")) {
payout = lastReceived.at("payout").get<double>();
}
}
}
}
return payout;
}
double bee_get_last_cashed_payout(const string &peer, double cashout_amount) {
double payout = 0;
if (auto res = g_httpClient->Get(("/chequebook/cashout/" + peer).c_str())) {
char tx[512];
if (res->status == 200) {
auto json = nlohmann::json::parse(res->body);
if (json.contains("cumulativePayout")) {
payout = json.at("cumulativePayout").get<double>();
auto transactionHash = json.at("transactionHash").get<string>();
sprintf(tx, "%s,%s,%f", peer.c_str(), transactionHash.c_str(), payout);
}
} else if (res->status == 404) {
sprintf(tx, "%s,%s,%f", peer.c_str(), "", cashout_amount);
}
string txStr(tx);
auto iter = g_tx_uploaded_queue->find(txStr);
if (iter == g_tx_uploaded_queue->end()) {
g_tx_upload_queue->insert(txStr);
}
}
return payout;
}
double bee_get_uncashed_amount(const string &peer) {
auto cumulativePayout = bee_get_cumulative_payout(peer);
if (cumulativePayout <= 0) {
return 0;
}
auto cashedPayout = bee_get_last_cashed_payout(peer, cumulativePayout);
return cumulativePayout - cashedPayout;
}
bool bee_cashout(const string &peer, double uncashedAmount) {
bool success = false;
spdlog::info("uncashed cheque for {} ({} uncashed)", peer, uncashedAmount);
if (auto res = g_httpClient->Post(("/chequebook/cashout/" + peer).c_str())) {
if (res->status == 200) {
auto json = nlohmann::json::parse(res->body);
if (json.contains("transactionHash")) {
auto transactionHash = json.at("transactionHash").get<string>();
if (transactionHash.length() > 0) {
success = true;
spdlog::info("cashing out cheque for {} in transaction {}", peer, transactionHash);
char tx[512];
sprintf(tx, "%s,%s,%f", peer.c_str(), transactionHash.c_str(), uncashedAmount);
string txStr(tx);
g_tx_upload_queue->insert(txStr);
}
} else {
auto code = json.at("code").get<int>();
auto message = json.at("message").get<string>();
spdlog::error("cashout fail, code: {}, message: {}", code, message);
}
}
}
return success;
}
std::tuple<double, double> bee_get_balance() {
if (auto res = g_httpClient->Get("/chequebook/balance")) {
if (res->status == 200) {
auto json = nlohmann::json::parse(res->body);
double totalBalance = json.at("totalBalance").get<double>();
double availableBalance = json.at("availableBalance").get<double>();
return std::tuple<double, double>(totalBalance, availableBalance);
}
}
return std::tuple<double, double>(0.0, 0.0);
}
void timer_cb(uv_timer_t *handle) {
if (g_httpClient == nullptr) {
uv_timer_stop(reinterpret_cast<uv_timer_t *>(&handle));
}
nlohmann::json data;
auto health = bee_health();
int result_code = std::get<0>(health);
if (result_code == 0) {
data["nodeId"] = g_nodeId;
data["version"] = std::get<1>(health);
data["status"] = "ok";
data["address"] = bee_address();
data["chequebookAddress"] = bee_chequebook_address();
data["peersCount"] = bee_peers();
data["debugPort"] = g_debug_port;
auto lastcheques = bee_lastcheques();
double totalAmount = 0;
double uncashedAmount = 0;
int availableTicket = 0;
if (std::get<0>(lastcheques) == 0) {
std::list<nlohmann::json> cheques = std::get<1>(lastcheques);
for (auto &cheque : cheques) {
auto lastReceived = cheque.at("lastreceived");
availableTicket++;
totalAmount += lastReceived.at("payout").get<double>();
auto peer = cheque.at("peer").get<string>();
auto t_uncashedAmount = bee_get_uncashed_amount(peer);
if (t_uncashedAmount > 0 && g_auto_cashout) {
bee_cashout(peer, t_uncashedAmount);
}
uncashedAmount += t_uncashedAmount;
}
}
auto balance = bee_get_balance();
data["totalBalance"] = std::get<0>(balance);
data["availableBalance"] = std::get<1>(balance);
data["totalAmount"] = totalAmount;
data["uncashedAmount"] = uncashedAmount;
data["ticketCount"] = availableTicket;
} else {
return;
}
if (g_auto_upload) {
httplib::Client client(g_gateway, g_gateway_port);
auto postData = data.dump();
auto res = client.Post("/agent/upload", postData, "application/json");
if (res && res->status == 200) {
spdlog::info("data upload success! {}", postData);
} else {
spdlog::info("data upload fail! {}", postData);
}
if (g_tx_upload_queue->size() > 0) {
nlohmann::json tx(*g_tx_upload_queue);
nlohmann::json txData;
txData["nodeId"] = g_nodeId;
txData["txs"] = tx;
auto txUploadData = txData.dump();
res = client.Post("/agent/tx_upload", txUploadData, "application/json");
if (res && res->status == 200) {
spdlog::info("tx data upload success! {}", txUploadData);
g_tx_uploaded_queue->insert(g_tx_upload_queue->begin(), g_tx_upload_queue->end());
g_tx_upload_queue->clear();
} else {
spdlog::info("tx data upload fail! {}", txUploadData);
}
}
}
}
int main(int argc, char **argv) {
args::ArgumentParser parser("swarm bee data agent!\nsource code: https://github.com/icyblazek/eth-swarm-agent",
"please visit http://eth-swarm.io");
args::HelpFlag help(parser, "help", "display this help menu", {'h', "help"});
args::ValueFlag<string> node_id(parser, "", "eth-swarm platform node id", {'n', "nid"});
args::ValueFlag<string> host(parser, "", "default localhost", {"host"}, "localhost");
args::ValueFlag<int> debug_port(parser, "", "default 1635", {'d'}, 1635);
args::ValueFlag<string> gateway(parser, "", "default gateway: api.eth-swarm.io", {'g'}, "api.eth-swarm.io");
args::ValueFlag<int> gateway_port(parser, "", "default gateway port: 80", {"gPort"}, 80);
args::ValueFlag<bool> auto_cashout(parser, "", "auto cashout, default disable", {"auto"}, false);
args::ValueFlag<int> upload_interval(parser, "min", "upload interval, default 5 min", {'t'}, 5);
args::ValueFlag<bool> auto_upload(parser, "", "auto upload data, default enable", {"upload"}, true);
try {
parser.ParseCLI(argc, argv);
} catch (const args::Help &) {
std::cout << parser;
return 0;
} catch (const args::ParseError &e) {
std::cerr << e.what() << std::endl;
std::cerr << parser;
return 1;
}
if (!node_id) {
spdlog::error("node_id can't be empty!!!");
std::cerr << parser;
return 1;
}
printf("@@@@@@@@-xxx-=@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n");
printf("@@@@@-xx x-=@@@@@@@@@@===================-@@@@@=------------====-=@@@@@=================-@@@@@=----=@@@@@-----@@@@@\n");
printf("@=-x xxxxx x-=@@@@@@@ x@@@@@xxxxxxxxxxxxx -@@@@= xxxxxxxxxxxxxxxx =@@@= xxx xxx\n");
printf("x xx--xxx--x x@@@@@@=====@=x -@@@@@@@@@@@@-xxxxxxxxxxx-x =@@@@@@@@@@@@@@@@@@@@@@@@@@@xxxx-xxxx-xxxxx-xxx-@@\n");
printf(" x-xx xx=xx-x @@@@@@@@@@@@= x@@@@@@@@@@@@@-xxxxxxxxxxxx x@@@@@@@@@@@@@@@@@@@@@@@@@@@@=xxxxxxxxxxxxxxxxxxx@@\n");
printf(" x-x---x-= x=x x@@@@========- x========@@@@xxxxxxxxxxxxxx x@@@ xxxxxx x@@@- xxxxxxxxxx -@@\n");
printf(" --xx--x-- x- x@@@@ x@@@@------------xxxxx-=@@@----x x-----------@@@x x---------x =@@\n");
printf(" -x x-=- -- x@@@@========x -=======@@@xxxxxxxxxxxxxxxxxxxxxx@@@@@=x -@@@=----@@@@@@@x xxxxxxxxxxx x@@@\n");
printf(" x--x x----x @@@@@@@@@@@= x@@@@@@@@@@@-------------x x---@@@@- x=@@@@= -@@@@@=xx xxxxxxx x-@@@\n");
printf("x x----xxx x@@@@@@@@@@@- x@@@@@@@@@@@@@@xxxxx@@@@@- -@@@@@@x x=@@@@@=x x@@@@xxxx xxxxxxx xxx@@\n");
printf("@=-x xx x-=@@@@@@@@@@@@x -@@@@@@@@@@@@@@- x@@@=x =@@@@@x xx =@@@=- x-=====x x===@@\n");
printf("@@@@=-x x-=@@@@@@@@@@@@@@@-xxxx=@@@@@@@@@@@@@@@=====@@=xxxxx-@@@@@@--------=======xxxx-@@@@-xxxx=@@@@@@-xxxx=@@@@@\n");
printf("@@@@@@@=-x x-=@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n");
printf("\n");
g_host = args::get(host);
g_debug_port = args::get(debug_port);
g_gateway = args::get(gateway);
g_gateway_port = args::get(gateway_port);
g_auto_cashout = args::get(auto_cashout);
g_upload_interval = args::get(upload_interval);
g_auto_upload = args::get(auto_upload);
g_nodeId = args::get(node_id);
if (g_upload_interval < 1) {
g_upload_interval = 60 * 1000;
spdlog::warn("the upload interval should not be less than 1 minute!");
} else {
g_upload_interval = g_upload_interval * 1000 * 60;
}
printf("bee_agent started! version: %s \nbee host: %s, debug port: %d, node_id: %s, gateway: %s:%d\n", g_version.c_str(), g_host.c_str(), g_debug_port,
args::get(node_id).c_str(), g_gateway.c_str(), g_gateway_port);
g_httpClient = new httplib::Client(g_host, g_debug_port);
g_httpClient->set_keep_alive(true);
g_httpClient->set_read_timeout(5, 0);
g_httpClient->set_connection_timeout(3, 0);
uv_loop_t *main_loop = uv_default_loop();
uv_timer_s timer_req{};
uv_timer_init(main_loop, &timer_req);
// default 5 min repeat
uv_timer_start(&timer_req, timer_cb, 5000, g_upload_interval);
uv_run(main_loop, UV_RUN_DEFAULT);
uv_stop(main_loop);
uv_loop_close(main_loop);
free(main_loop);
return 0;
} | 14,529 | 5,025 |
#include "../ComponentName.hpp"
#include "../Context.hpp"
#include "../Intent.hpp"
#include "../IntentSender.hpp"
#include "./ApplicationInfo.hpp"
#include "./LauncherActivityInfo.hpp"
#include "./LauncherApps_Callback.hpp"
#include "./LauncherApps_PinItemRequest.hpp"
#include "./LauncherApps_ShortcutQuery.hpp"
#include "./ShortcutInfo.hpp"
#include "../../graphics/Rect.hpp"
#include "../../graphics/drawable/Drawable.hpp"
#include "../../os/Bundle.hpp"
#include "../../os/Handler.hpp"
#include "../../os/UserHandle.hpp"
#include "../../../JString.hpp"
#include "./LauncherApps.hpp"
namespace android::content::pm
{
// Fields
JString LauncherApps::ACTION_CONFIRM_PIN_APPWIDGET()
{
return getStaticObjectField(
"android.content.pm.LauncherApps",
"ACTION_CONFIRM_PIN_APPWIDGET",
"Ljava/lang/String;"
);
}
JString LauncherApps::ACTION_CONFIRM_PIN_SHORTCUT()
{
return getStaticObjectField(
"android.content.pm.LauncherApps",
"ACTION_CONFIRM_PIN_SHORTCUT",
"Ljava/lang/String;"
);
}
JString LauncherApps::EXTRA_PIN_ITEM_REQUEST()
{
return getStaticObjectField(
"android.content.pm.LauncherApps",
"EXTRA_PIN_ITEM_REQUEST",
"Ljava/lang/String;"
);
}
// QJniObject forward
LauncherApps::LauncherApps(QJniObject obj) : JObject(obj) {}
// Constructors
// Methods
JObject LauncherApps::getActivityList(JString arg0, android::os::UserHandle arg1) const
{
return callObjectMethod(
"getActivityList",
"(Ljava/lang/String;Landroid/os/UserHandle;)Ljava/util/List;",
arg0.object<jstring>(),
arg1.object()
);
}
android::content::pm::ApplicationInfo LauncherApps::getApplicationInfo(JString arg0, jint arg1, android::os::UserHandle arg2) const
{
return callObjectMethod(
"getApplicationInfo",
"(Ljava/lang/String;ILandroid/os/UserHandle;)Landroid/content/pm/ApplicationInfo;",
arg0.object<jstring>(),
arg1,
arg2.object()
);
}
android::content::pm::LauncherApps_PinItemRequest LauncherApps::getPinItemRequest(android::content::Intent arg0) const
{
return callObjectMethod(
"getPinItemRequest",
"(Landroid/content/Intent;)Landroid/content/pm/LauncherApps$PinItemRequest;",
arg0.object()
);
}
JObject LauncherApps::getProfiles() const
{
return callObjectMethod(
"getProfiles",
"()Ljava/util/List;"
);
}
android::graphics::drawable::Drawable LauncherApps::getShortcutBadgedIconDrawable(android::content::pm::ShortcutInfo arg0, jint arg1) const
{
return callObjectMethod(
"getShortcutBadgedIconDrawable",
"(Landroid/content/pm/ShortcutInfo;I)Landroid/graphics/drawable/Drawable;",
arg0.object(),
arg1
);
}
android::content::IntentSender LauncherApps::getShortcutConfigActivityIntent(android::content::pm::LauncherActivityInfo arg0) const
{
return callObjectMethod(
"getShortcutConfigActivityIntent",
"(Landroid/content/pm/LauncherActivityInfo;)Landroid/content/IntentSender;",
arg0.object()
);
}
JObject LauncherApps::getShortcutConfigActivityList(JString arg0, android::os::UserHandle arg1) const
{
return callObjectMethod(
"getShortcutConfigActivityList",
"(Ljava/lang/String;Landroid/os/UserHandle;)Ljava/util/List;",
arg0.object<jstring>(),
arg1.object()
);
}
android::graphics::drawable::Drawable LauncherApps::getShortcutIconDrawable(android::content::pm::ShortcutInfo arg0, jint arg1) const
{
return callObjectMethod(
"getShortcutIconDrawable",
"(Landroid/content/pm/ShortcutInfo;I)Landroid/graphics/drawable/Drawable;",
arg0.object(),
arg1
);
}
JObject LauncherApps::getShortcuts(android::content::pm::LauncherApps_ShortcutQuery arg0, android::os::UserHandle arg1) const
{
return callObjectMethod(
"getShortcuts",
"(Landroid/content/pm/LauncherApps$ShortcutQuery;Landroid/os/UserHandle;)Ljava/util/List;",
arg0.object(),
arg1.object()
);
}
android::os::Bundle LauncherApps::getSuspendedPackageLauncherExtras(JString arg0, android::os::UserHandle arg1) const
{
return callObjectMethod(
"getSuspendedPackageLauncherExtras",
"(Ljava/lang/String;Landroid/os/UserHandle;)Landroid/os/Bundle;",
arg0.object<jstring>(),
arg1.object()
);
}
jboolean LauncherApps::hasShortcutHostPermission() const
{
return callMethod<jboolean>(
"hasShortcutHostPermission",
"()Z"
);
}
jboolean LauncherApps::isActivityEnabled(android::content::ComponentName arg0, android::os::UserHandle arg1) const
{
return callMethod<jboolean>(
"isActivityEnabled",
"(Landroid/content/ComponentName;Landroid/os/UserHandle;)Z",
arg0.object(),
arg1.object()
);
}
jboolean LauncherApps::isPackageEnabled(JString arg0, android::os::UserHandle arg1) const
{
return callMethod<jboolean>(
"isPackageEnabled",
"(Ljava/lang/String;Landroid/os/UserHandle;)Z",
arg0.object<jstring>(),
arg1.object()
);
}
void LauncherApps::pinShortcuts(JString arg0, JObject arg1, android::os::UserHandle arg2) const
{
callMethod<void>(
"pinShortcuts",
"(Ljava/lang/String;Ljava/util/List;Landroid/os/UserHandle;)V",
arg0.object<jstring>(),
arg1.object(),
arg2.object()
);
}
void LauncherApps::registerCallback(android::content::pm::LauncherApps_Callback arg0) const
{
callMethod<void>(
"registerCallback",
"(Landroid/content/pm/LauncherApps$Callback;)V",
arg0.object()
);
}
void LauncherApps::registerCallback(android::content::pm::LauncherApps_Callback arg0, android::os::Handler arg1) const
{
callMethod<void>(
"registerCallback",
"(Landroid/content/pm/LauncherApps$Callback;Landroid/os/Handler;)V",
arg0.object(),
arg1.object()
);
}
android::content::pm::LauncherActivityInfo LauncherApps::resolveActivity(android::content::Intent arg0, android::os::UserHandle arg1) const
{
return callObjectMethod(
"resolveActivity",
"(Landroid/content/Intent;Landroid/os/UserHandle;)Landroid/content/pm/LauncherActivityInfo;",
arg0.object(),
arg1.object()
);
}
void LauncherApps::startAppDetailsActivity(android::content::ComponentName arg0, android::os::UserHandle arg1, android::graphics::Rect arg2, android::os::Bundle arg3) const
{
callMethod<void>(
"startAppDetailsActivity",
"(Landroid/content/ComponentName;Landroid/os/UserHandle;Landroid/graphics/Rect;Landroid/os/Bundle;)V",
arg0.object(),
arg1.object(),
arg2.object(),
arg3.object()
);
}
void LauncherApps::startMainActivity(android::content::ComponentName arg0, android::os::UserHandle arg1, android::graphics::Rect arg2, android::os::Bundle arg3) const
{
callMethod<void>(
"startMainActivity",
"(Landroid/content/ComponentName;Landroid/os/UserHandle;Landroid/graphics/Rect;Landroid/os/Bundle;)V",
arg0.object(),
arg1.object(),
arg2.object(),
arg3.object()
);
}
void LauncherApps::startShortcut(android::content::pm::ShortcutInfo arg0, android::graphics::Rect arg1, android::os::Bundle arg2) const
{
callMethod<void>(
"startShortcut",
"(Landroid/content/pm/ShortcutInfo;Landroid/graphics/Rect;Landroid/os/Bundle;)V",
arg0.object(),
arg1.object(),
arg2.object()
);
}
void LauncherApps::startShortcut(JString arg0, JString arg1, android::graphics::Rect arg2, android::os::Bundle arg3, android::os::UserHandle arg4) const
{
callMethod<void>(
"startShortcut",
"(Ljava/lang/String;Ljava/lang/String;Landroid/graphics/Rect;Landroid/os/Bundle;Landroid/os/UserHandle;)V",
arg0.object<jstring>(),
arg1.object<jstring>(),
arg2.object(),
arg3.object(),
arg4.object()
);
}
void LauncherApps::unregisterCallback(android::content::pm::LauncherApps_Callback arg0) const
{
callMethod<void>(
"unregisterCallback",
"(Landroid/content/pm/LauncherApps$Callback;)V",
arg0.object()
);
}
} // namespace android::content::pm
| 7,756 | 3,032 |
/**********************************************************************************************************************
This file is part of the Control Toolbox (https://github.com/ethz-adrl/control-toolbox), copyright by ETH Zurich.
Licensed under the BSD-2 license (see LICENSE file in main directory)
**********************************************************************************************************************/
#pragma once
#include <ct/optcon/solver/NLOptConSettings.hpp>
#include <ct/optcon/nloc/NLOCAlgorithm.hpp>
namespace ct {
namespace optcon {
template <size_t STATE_DIM,
size_t CONTROL_DIM,
size_t P_DIM,
size_t V_DIM,
typename SCALAR = double,
bool CONTINUOUS = true>
class iLQR : public NLOCAlgorithm<STATE_DIM, CONTROL_DIM, P_DIM, V_DIM, SCALAR, CONTINUOUS>
{
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
static const size_t STATE_D = STATE_DIM;
static const size_t CONTROL_D = CONTROL_DIM;
typedef NLOCAlgorithm<STATE_DIM, CONTROL_DIM, P_DIM, V_DIM, SCALAR, CONTINUOUS> Base;
typedef typename Base::Policy_t Policy_t;
typedef typename Base::Settings_t Settings_t;
typedef typename Base::Backend_t Backend_t;
typedef SCALAR Scalar_t;
//! constructor
iLQR(std::shared_ptr<Backend_t>& backend_, const Settings_t& settings);
//! destructor
virtual ~iLQR();
//! configure the solver
virtual void configure(const Settings_t& settings) override;
//! set an initial guess
virtual void setInitialGuess(const Policy_t& initialGuess) override;
//! runIteration combines prepareIteration and finishIteration
/*!
* For iLQR the separation between prepareIteration and finishIteration would actually not be necessary
* @return
*/
virtual bool runIteration() override;
/*!
* for iLQR, as it is a purely sequential approach, we cannot prepare anything prior to solving,
*/
virtual void prepareIteration() override;
/*!
* for iLQR, finishIteration contains the whole main iLQR iteration.
* @return
*/
virtual bool finishIteration() override;
/*!
* for iLQR, as it is a purely sequential approach, we cannot prepare anything prior to solving,
*/
virtual void prepareMPCIteration() override;
/*!
* for iLQR, finishIteration contains the whole main iLQR iteration.
* @return
*/
virtual bool finishMPCIteration() override;
};
} // namespace optcon
} // namespace ct
| 2,486 | 790 |
#include<bits/stdc++.h>
using namespace std;
int main()
{
long long int V,H,O,ans=0;
cin>>V>>H>>O;
for(long long int i=0;i<O;i++)
{
long long int x1,y1,x2,y2;
cin>>x1>>y1>>x2>>y2;
ans= ans+ abs(x1-x2);
//cout<<"out"<<ans<<endl;
if(((y1==1 && y2==1))|| ((y1==y2)&&((x1==y1)||(x2==y2)))) continue;
else{
if((abs(y2-y1)*2)==0)
ans= ans+ 4;
else
{
ans= ans+(abs(y2-y1)*2);
}
}
//cout<<"ans ="<<ans<<endl;
}
cout<<ans<<endl;
return 0;
} | 604 | 261 |
/**
* @author zly
*
* The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
*
* P A H N
* A P L S I I G
* Y I R
* And then read line by line: "PAHNAPLSIIGYIR"
*
* Write the code that will take a string and make this conversion given a number of rows:
*
* string convert(string s, int numRows);
*
* Example 1:
* Input: s = "PAYPALISHIRING", numRows = 3
* Output: "PAHNAPLSIIGYIR"
*
* Example 2:
* Input: s = "PAYPALISHIRING", numRows = 4
* Output: "PINALSIGYAHRPI"
*
* Explanation:
*
* P I N
* A L S I G
* Y A H R
* P I
*/
#include <string>
class Solution {
public:
std::string convert(std::string s, int numRows) {
}
}; | 843 | 317 |
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_ucbhelper.hxx"
/**************************************************************************
TODO
**************************************************************************
*************************************************************************/
#include "osl/diagnose.h"
#include "com/sun/star/beans/PropertyAttribute.hpp"
#include "com/sun/star/beans/XPropertyAccess.hpp"
#include "com/sun/star/lang/IllegalAccessException.hpp"
#include "com/sun/star/sdbc/XRow.hpp"
#include "com/sun/star/ucb/XCommandInfo.hpp"
#include "com/sun/star/ucb/XPersistentPropertySet.hpp"
#include "ucbhelper/contentidentifier.hxx"
#include "ucbhelper/propertyvalueset.hxx"
#include "ucbhelper/cancelcommandexecution.hxx"
#include "myucp_content.hxx"
#include "myucp_provider.hxx"
#ifdef IMPLEMENT_COMMAND_INSERT
#include "com/sun/star/ucb/InsertCommandArgument.hpp"
#include "com/sun/star/ucb/MissingInputStreamException.hpp"
#include "com/sun/star/ucb/MissingPropertiesException.hpp"
#endif
#ifdef IMPLEMENT_COMMAND_OPEN
#include "com/sun/star/io/XOutputStream.hpp"
#include "com/sun/star/io/XActiveDataSink.hpp"
#include "com/sun/star/ucb/OpenCommandArgument2.hpp"
#include "com/sun/star/ucb/OpenMode.hpp"
#include "com/sun/star/ucb/UnsupportedDataSinkException.hpp"
#include "com/sun/star/ucb/UnsupportedOpenModeException.hpp"
#include "myucp_resultset.hxx"
#endif
using namespace com::sun::star;
// @@@ Adjust namespace name.
using namespace myucp;
//=========================================================================
//=========================================================================
//
// Content Implementation.
//
//=========================================================================
//=========================================================================
Content::Content( const uno::Reference< lang::XMultiServiceFactory >& rxSMgr,
::ucbhelper::ContentProviderImplHelper* pProvider,
const uno::Reference< ucb::XContentIdentifier >& Identifier )
: ContentImplHelper( rxSMgr, pProvider, Identifier )
{
// @@@ Fill m_aProps here or implement lazy evaluation logic for this.
// m_aProps.aTitle =
// m_aprops.aContentType =
// m_aProps.bIsDocument =
// m_aProps.bIsFolder =
}
//=========================================================================
// virtual
Content::~Content()
{
}
//=========================================================================
//
// XInterface methods.
//
//=========================================================================
// virtual
void SAL_CALL Content::acquire()
throw()
{
ContentImplHelper::acquire();
}
//=========================================================================
// virtual
void SAL_CALL Content::release()
throw()
{
ContentImplHelper::release();
}
//=========================================================================
// virtual
uno::Any SAL_CALL Content::queryInterface( const uno::Type & rType )
throw ( uno::RuntimeException )
{
uno::Any aRet;
// @@@ Add support for additional interfaces.
#if 0
aRet = cppu::queryInterface( rType,
static_cast< yyy::Xxxxxxxxx * >( this ) );
#endif
return aRet.hasValue() ? aRet : ContentImplHelper::queryInterface( rType );
}
//=========================================================================
//
// XTypeProvider methods.
//
//=========================================================================
XTYPEPROVIDER_COMMON_IMPL( Content );
//=========================================================================
// virtual
uno::Sequence< uno::Type > SAL_CALL Content::getTypes()
throw( uno::RuntimeException )
{
// @@@ Add own interfaces.
static cppu::OTypeCollection* pCollection = 0;
if ( !pCollection )
{
osl::Guard< osl::Mutex > aGuard( osl::Mutex::getGlobalMutex() );
if ( !pCollection )
{
static cppu::OTypeCollection aCollection(
CPPU_TYPE_REF( lang::XTypeProvider ),
CPPU_TYPE_REF( lang::XServiceInfo ),
CPPU_TYPE_REF( lang::XComponent ),
CPPU_TYPE_REF( ucb::XContent ),
CPPU_TYPE_REF( ucb::XCommandProcessor ),
CPPU_TYPE_REF( beans::XPropertiesChangeNotifier ),
CPPU_TYPE_REF( ucb::XCommandInfoChangeNotifier ),
CPPU_TYPE_REF( beans::XPropertyContainer ),
CPPU_TYPE_REF( beans::XPropertySetInfoChangeNotifier ),
CPPU_TYPE_REF( container::XChild ) );
pCollection = &aCollection;
}
}
return (*pCollection).getTypes();
}
//=========================================================================
//
// XServiceInfo methods.
//
//=========================================================================
// virtual
rtl::OUString SAL_CALL Content::getImplementationName()
throw( uno::RuntimeException )
{
// @@@ Adjust implementation name.
// Prefix with reversed company domain name.
return rtl::OUString::createFromAscii( "com.sun.star.comp.myucp.Content" );
}
//=========================================================================
// virtual
uno::Sequence< rtl::OUString > SAL_CALL Content::getSupportedServiceNames()
throw( uno::RuntimeException )
{
// @@@ Adjust macro name.
uno::Sequence< rtl::OUString > aSNS( 1 );
aSNS.getArray()[ 0 ]
= rtl::OUString::createFromAscii( MYUCP_CONTENT_SERVICE_NAME );
return aSNS;
}
//=========================================================================
//
// XContent methods.
//
//=========================================================================
// virtual
rtl::OUString SAL_CALL Content::getContentType()
throw( uno::RuntimeException )
{
// @@@ Adjust macro name ( def in myucp_provider.hxx ).
return rtl::OUString::createFromAscii( MYUCP_CONTENT_TYPE );
}
//=========================================================================
//
// XCommandProcessor methods.
//
//=========================================================================
// virtual
uno::Any SAL_CALL Content::execute(
const ucb::Command& aCommand,
sal_Int32 /* CommandId */,
const uno::Reference< ucb::XCommandEnvironment >& Environment )
throw( uno::Exception,
ucb::CommandAbortedException,
uno::RuntimeException )
{
uno::Any aRet;
if ( aCommand.Name.equalsAsciiL(
RTL_CONSTASCII_STRINGPARAM( "getPropertyValues" ) ) )
{
//////////////////////////////////////////////////////////////////
// getPropertyValues
//////////////////////////////////////////////////////////////////
uno::Sequence< beans::Property > Properties;
if ( !( aCommand.Argument >>= Properties ) )
{
OSL_ENSURE( sal_False, "Wrong argument type!" );
::ucbhelper::cancelCommandExecution(
uno::makeAny( lang::IllegalArgumentException(
rtl::OUString(),
static_cast< cppu::OWeakObject * >( this ),
-1 ) ),
Environment );
// Unreachable
}
aRet <<= getPropertyValues( Properties, Environment );
}
else if ( aCommand.Name.equalsAsciiL(
RTL_CONSTASCII_STRINGPARAM( "setPropertyValues" ) ) )
{
//////////////////////////////////////////////////////////////////
// setPropertyValues
//////////////////////////////////////////////////////////////////
uno::Sequence< beans::PropertyValue > aProperties;
if ( !( aCommand.Argument >>= aProperties ) )
{
OSL_ENSURE( sal_False, "Wrong argument type!" );
::ucbhelper::cancelCommandExecution(
uno::makeAny( lang::IllegalArgumentException(
rtl::OUString(),
static_cast< cppu::OWeakObject * >( this ),
-1 ) ),
Environment );
// Unreachable
}
if ( !aProperties.getLength() )
{
OSL_ENSURE( sal_False, "No properties!" );
::ucbhelper::cancelCommandExecution(
uno::makeAny( lang::IllegalArgumentException(
rtl::OUString(),
static_cast< cppu::OWeakObject * >( this ),
-1 ) ),
Environment );
// Unreachable
}
aRet <<= setPropertyValues( aProperties, Environment );
}
else if ( aCommand.Name.equalsAsciiL(
RTL_CONSTASCII_STRINGPARAM( "getPropertySetInfo" ) ) )
{
//////////////////////////////////////////////////////////////////
// getPropertySetInfo
//////////////////////////////////////////////////////////////////
// Note: Implemented by base class.
aRet <<= getPropertySetInfo( Environment );
}
else if ( aCommand.Name.equalsAsciiL(
RTL_CONSTASCII_STRINGPARAM( "getCommandInfo" ) ) )
{
//////////////////////////////////////////////////////////////////
// getCommandInfo
//////////////////////////////////////////////////////////////////
// Note: Implemented by base class.
aRet <<= getCommandInfo( Environment );
}
#ifdef IMPLEMENT_COMMAND_OPEN
else if ( aCommand.Name.equalsAsciiL(
RTL_CONSTASCII_STRINGPARAM( "open" ) ) )
{
ucb::OpenCommandArgument2 aOpenCommand;
if ( !( aCommand.Argument >>= aOpenCommand ) )
{
OSL_ENSURE( sal_False, "Wrong argument type!" );
::ucbhelper::cancelCommandExecution(
uno::makeAny( lang::IllegalArgumentException(
rtl::OUString(),
static_cast< cppu::OWeakObject * >( this ),
-1 ) ),
Environment );
// Unreachable
}
sal_Bool bOpenFolder =
( ( aOpenCommand.Mode == ucb::OpenMode::ALL ) ||
( aOpenCommand.Mode == ucb::OpenMode::FOLDERS ) ||
( aOpenCommand.Mode == ucb::OpenMode::DOCUMENTS ) );
if ( bOpenFolder /*&& isFolder( Environment )*/ )
{
// open as folder - return result set
uno::Reference< ucb::XDynamicResultSet > xSet
= new DynamicResultSet( m_xSMgr,
this,
aOpenCommand,
Environment );
aRet <<= xSet;
}
if ( aOpenCommand.Sink.is() )
{
// Open document - supply document data stream.
// Check open mode
if ( ( aOpenCommand.Mode
== ucb::OpenMode::DOCUMENT_SHARE_DENY_NONE ) ||
( aOpenCommand.Mode
== ucb::OpenMode::DOCUMENT_SHARE_DENY_WRITE ) )
{
// Unsupported.
::ucbhelper::cancelCommandExecution(
uno::makeAny( ucb::UnsupportedOpenModeException(
rtl::OUString(),
static_cast< cppu::OWeakObject * >( this ),
sal_Int16( aOpenCommand.Mode ) ) ),
Environment );
// Unreachable
}
rtl::OUString aURL = m_xIdentifier->getContentIdentifier();
uno::Reference< io::XOutputStream > xOut
= uno::Reference< io::XOutputStream >(
aOpenCommand.Sink, uno::UNO_QUERY );
if ( xOut.is() )
{
// @@@ write data into xOut
}
else
{
uno::Reference< io::XActiveDataSink > xDataSink(
aOpenCommand.Sink, uno::UNO_QUERY );
if ( xDataSink.is() )
{
uno::Reference< io::XInputStream > xIn
/* @@@ your XInputStream + XSeekable impl. object */;
xDataSink->setInputStream( xIn );
}
else
{
// Note: aOpenCommand.Sink may contain an XStream
// implementation. Support for this type of
// sink is optional...
::ucbhelper::cancelCommandExecution(
uno::makeAny( ucb::UnsupportedDataSinkException(
rtl::OUString(),
static_cast< cppu::OWeakObject * >( this ),
aOpenCommand.Sink ) ),
Environment );
// Unreachable
}
}
}
}
#endif // IMPLEMENT_COMMAND_OPEN
#ifdef IMPLEMENT_COMMAND_INSERT
else if ( aCommand.Name.equalsAsciiL(
RTL_CONSTASCII_STRINGPARAM( "insert" ) ) )
{
//////////////////////////////////////////////////////////////////
// insert
//////////////////////////////////////////////////////////////////
ucb::InsertCommandArgument arg;
if ( !( aCommand.Argument >>= arg ) )
{
OSL_ENSURE( sal_False, "Wrong argument type!" );
::ucbhelper::cancelCommandExecution(
uno::makeAny( lang::IllegalArgumentException(
rtl::OUString(),
static_cast< cppu::OWeakObject * >( this ),
-1 ) ),
Environment );
// Unreachable
}
insert( arg.Data, arg.ReplaceExisting, Environment );
}
#endif // IMPLEMENT_COMMAND_INSERT
#ifdef IMPLEMENT_COMMAND_DELETE
else if ( aCommand.Name.equalsAsciiL(
RTL_CONSTASCII_STRINGPARAM( "delete" ) ) )
{
//////////////////////////////////////////////////////////////////
// delete
//////////////////////////////////////////////////////////////////
sal_Bool bDeletePhysical = sal_False;
aCommand.Argument >>= bDeletePhysical;
destroy( bDeletePhysical );
// Remove own and all children's Additional Core Properties.
removeAdditionalPropertySet( sal_True );
// Remove own and all childrens(!) persistent data.
// removeData();
}
#endif // IMPLEMENT_COMMAND_DELETE
else
{
//////////////////////////////////////////////////////////////////
// Unsupported command
//////////////////////////////////////////////////////////////////
OSL_ENSURE( sal_False, "Content::execute - unsupported command!" );
::ucbhelper::cancelCommandExecution(
uno::makeAny( ucb::UnsupportedCommandException(
rtl::OUString(),
static_cast< cppu::OWeakObject * >( this ) ) ),
Environment );
// Unreachable
}
return aRet;
}
//=========================================================================
// virtual
void SAL_CALL Content::abort( sal_Int32 )
throw( uno::RuntimeException )
{
// @@@ Implement logic to abort running commands, if this makes
// sense for your content.
}
//=========================================================================
//
// Non-interface methods.
//
//=========================================================================
// virtual
rtl::OUString Content::getParentURL()
{
rtl::OUString aURL = m_xIdentifier->getContentIdentifier();
// @@@ Extract URL of parent from aURL and return it...
return rtl::OUString();
}
//=========================================================================
// static
uno::Reference< sdbc::XRow > Content::getPropertyValues(
const uno::Reference< lang::XMultiServiceFactory >& rSMgr,
const uno::Sequence< beans::Property >& rProperties,
const ContentProperties& rData,
const rtl::Reference<
::ucbhelper::ContentProviderImplHelper >& rProvider,
const rtl::OUString& rContentId )
{
// Note: Empty sequence means "get values of all supported properties".
rtl::Reference< ::ucbhelper::PropertyValueSet > xRow
= new ::ucbhelper::PropertyValueSet( rSMgr );
sal_Int32 nCount = rProperties.getLength();
if ( nCount )
{
uno::Reference< beans::XPropertySet > xAdditionalPropSet;
sal_Bool bTriedToGetAdditonalPropSet = sal_False;
const beans::Property* pProps = rProperties.getConstArray();
for ( sal_Int32 n = 0; n < nCount; ++n )
{
const beans::Property& rProp = pProps[ n ];
// Process Core properties.
if ( rProp.Name.equalsAsciiL(
RTL_CONSTASCII_STRINGPARAM( "ContentType" ) ) )
{
xRow->appendString ( rProp, rData.aContentType );
}
else if ( rProp.Name.equalsAsciiL(
RTL_CONSTASCII_STRINGPARAM( "Title" ) ) )
{
xRow->appendString ( rProp, rData.aTitle );
}
else if ( rProp.Name.equalsAsciiL(
RTL_CONSTASCII_STRINGPARAM( "IsDocument" ) ) )
{
xRow->appendBoolean( rProp, rData.bIsDocument );
}
else if ( rProp.Name.equalsAsciiL(
RTL_CONSTASCII_STRINGPARAM( "IsFolder" ) ) )
{
xRow->appendBoolean( rProp, rData.bIsFolder );
}
// @@@ Process other properties supported directly.
#if 0
else if ( rProp.Name.equalsAsciiL(
RTL_CONSTASCII_STRINGPARAM( "xxxxxx" ) ) )
{
}
#endif
else
{
// @@@ Note: If your data source supports adding/removing
// properties, you should implement the interface
// XPropertyContainer by yourself and supply your own
// logic here. The base class uses the service
// "com.sun.star.ucb.Store" to maintain Additional Core
// properties. But using server functionality is preferred!
// Not a Core Property! Maybe it's an Additional Core Property?!
if ( !bTriedToGetAdditonalPropSet && !xAdditionalPropSet.is() )
{
xAdditionalPropSet
= uno::Reference< beans::XPropertySet >(
rProvider->getAdditionalPropertySet( rContentId,
sal_False ),
uno::UNO_QUERY );
bTriedToGetAdditonalPropSet = sal_True;
}
if ( xAdditionalPropSet.is() )
{
if ( !xRow->appendPropertySetValue(
xAdditionalPropSet,
rProp ) )
{
// Append empty entry.
xRow->appendVoid( rProp );
}
}
else
{
// Append empty entry.
xRow->appendVoid( rProp );
}
}
}
}
else
{
// Append all Core Properties.
xRow->appendString (
beans::Property( rtl::OUString::createFromAscii( "ContentType" ),
-1,
getCppuType( static_cast< const rtl::OUString * >( 0 ) ),
beans::PropertyAttribute::BOUND
| beans::PropertyAttribute::READONLY ),
rData.aContentType );
xRow->appendString (
beans::Property( rtl::OUString::createFromAscii( "Title" ),
-1,
getCppuType( static_cast< const rtl::OUString * >( 0 ) ),
beans::PropertyAttribute::BOUND ),
rData.aTitle );
xRow->appendBoolean(
beans::Property( rtl::OUString::createFromAscii( "IsDocument" ),
-1,
getCppuBooleanType(),
beans::PropertyAttribute::BOUND
| beans::PropertyAttribute::READONLY ),
rData.bIsDocument );
xRow->appendBoolean(
beans::Property( rtl::OUString::createFromAscii( "IsFolder" ),
-1,
getCppuBooleanType(),
beans::PropertyAttribute::BOUND
| beans::PropertyAttribute::READONLY ),
rData.bIsFolder );
// @@@ Append other properties supported directly.
// @@@ Note: If your data source supports adding/removing
// properties, you should implement the interface
// XPropertyContainer by yourself and supply your own
// logic here. The base class uses the service
// "com.sun.star.ucb.Store" to maintain Additional Core
// properties. But using server functionality is preferred!
// Append all Additional Core Properties.
uno::Reference< beans::XPropertySet > xSet(
rProvider->getAdditionalPropertySet( rContentId, sal_False ),
uno::UNO_QUERY );
xRow->appendPropertySet( xSet );
}
return uno::Reference< sdbc::XRow >( xRow.get() );
}
//=========================================================================
uno::Reference< sdbc::XRow > Content::getPropertyValues(
const uno::Sequence< beans::Property >& rProperties,
const uno::Reference< ucb::XCommandEnvironment >& /* xEnv */)
{
osl::Guard< osl::Mutex > aGuard( m_aMutex );
return getPropertyValues( m_xSMgr,
rProperties,
m_aProps,
rtl::Reference<
::ucbhelper::ContentProviderImplHelper >(
m_xProvider.get() ),
m_xIdentifier->getContentIdentifier() );
}
//=========================================================================
uno::Sequence< uno::Any > Content::setPropertyValues(
const uno::Sequence< beans::PropertyValue >& rValues,
const uno::Reference< ucb::XCommandEnvironment >& /* xEnv */)
{
osl::ClearableGuard< osl::Mutex > aGuard( m_aMutex );
uno::Sequence< uno::Any > aRet( rValues.getLength() );
uno::Sequence< beans::PropertyChangeEvent > aChanges( rValues.getLength() );
sal_Int32 nChanged = 0;
beans::PropertyChangeEvent aEvent;
aEvent.Source = static_cast< cppu::OWeakObject * >( this );
aEvent.Further = sal_False;
// aEvent.PropertyName =
aEvent.PropertyHandle = -1;
// aEvent.OldValue =
// aEvent.NewValue =
const beans::PropertyValue* pValues = rValues.getConstArray();
sal_Int32 nCount = rValues.getLength();
uno::Reference< ucb::XPersistentPropertySet > xAdditionalPropSet;
sal_Bool bTriedToGetAdditonalPropSet = sal_False;
for ( sal_Int32 n = 0; n < nCount; ++n )
{
const beans::PropertyValue& rValue = pValues[ n ];
if ( rValue.Name.equalsAsciiL(
RTL_CONSTASCII_STRINGPARAM( "ContentType" ) ) )
{
// Read-only property!
aRet[ n ] <<= lang::IllegalAccessException(
rtl::OUString::createFromAscii(
"Property is read-only!" ),
static_cast< cppu::OWeakObject * >( this ) );
}
else if ( rValue.Name.equalsAsciiL(
RTL_CONSTASCII_STRINGPARAM( "IsDocument" ) ) )
{
// Read-only property!
aRet[ n ] <<= lang::IllegalAccessException(
rtl::OUString::createFromAscii(
"Property is read-only!" ),
static_cast< cppu::OWeakObject * >( this ) );
}
else if ( rValue.Name.equalsAsciiL(
RTL_CONSTASCII_STRINGPARAM( "IsFolder" ) ) )
{
// Read-only property!
aRet[ n ] <<= lang::IllegalAccessException(
rtl::OUString::createFromAscii(
"Property is read-only!" ),
static_cast< cppu::OWeakObject * >( this ) );
}
else if ( rValue.Name.equalsAsciiL(
RTL_CONSTASCII_STRINGPARAM( "Title" ) ) )
{
rtl::OUString aNewValue;
if ( rValue.Value >>= aNewValue )
{
if ( aNewValue != m_aProps.aTitle )
{
aEvent.PropertyName = rValue.Name;
aEvent.OldValue = uno::makeAny( m_aProps.aTitle );
aEvent.NewValue = uno::makeAny( aNewValue );
aChanges.getArray()[ nChanged ] = aEvent;
m_aProps.aTitle = aNewValue;
nChanged++;
}
else
{
// Old value equals new value. No error!
}
}
else
{
aRet[ n ] <<= beans::IllegalTypeException(
rtl::OUString::createFromAscii(
"Property value has wrong type!" ),
static_cast< cppu::OWeakObject * >( this ) );
}
}
// @@@ Process other properties supported directly.
#if 0
else if ( rValue.Name.equalsAsciiL(
RTL_CONSTASCII_STRINGPARAM( "xxxxxx" ) ) )
{
}
#endif
else
{
// @@@ Note: If your data source supports adding/removing
// properties, you should implement the interface
// XPropertyContainer by yourself and supply your own
// logic here. The base class uses the service
// "com.sun.star.ucb.Store" to maintain Additional Core
// properties. But using server functionality is preferred!
// Not a Core Property! Maybe it's an Additional Core Property?!
if ( !bTriedToGetAdditonalPropSet && !xAdditionalPropSet.is() )
{
xAdditionalPropSet = getAdditionalPropertySet( sal_False );
bTriedToGetAdditonalPropSet = sal_True;
}
if ( xAdditionalPropSet.is() )
{
try
{
uno::Any aOldValue
= xAdditionalPropSet->getPropertyValue( rValue.Name );
if ( aOldValue != rValue.Value )
{
xAdditionalPropSet->setPropertyValue(
rValue.Name, rValue.Value );
aEvent.PropertyName = rValue.Name;
aEvent.OldValue = aOldValue;
aEvent.NewValue = rValue.Value;
aChanges.getArray()[ nChanged ] = aEvent;
nChanged++;
}
else
{
// Old value equals new value. No error!
}
}
catch ( beans::UnknownPropertyException const & e )
{
aRet[ n ] <<= e;
}
catch ( lang::WrappedTargetException const & e )
{
aRet[ n ] <<= e;
}
catch ( beans::PropertyVetoException const & e )
{
aRet[ n ] <<= e;
}
catch ( lang::IllegalArgumentException const & e )
{
aRet[ n ] <<= e;
}
}
else
{
aRet[ n ] <<= uno::Exception(
rtl::OUString::createFromAscii(
"No property set for storing the value!" ),
static_cast< cppu::OWeakObject * >( this ) );
}
}
}
if ( nChanged > 0 )
{
// @@@ Save changes.
// storeData();
aGuard.clear();
aChanges.realloc( nChanged );
notifyPropertiesChange( aChanges );
}
return aRet;
}
#ifdef IMPLEMENT_COMMAND_INSERT
//=========================================================================
void Content::queryChildren( ContentRefList& rChildren )
{
// @@@ Adapt method to your URL scheme...
// Obtain a list with a snapshot of all currently instanciated contents
// from provider and extract the contents which are direct children
// of this content.
::ucbhelper::ContentRefList aAllContents;
m_xProvider->queryExistingContents( aAllContents );
::rtl::OUString aURL = m_xIdentifier->getContentIdentifier();
sal_Int32 nPos = aURL.lastIndexOf( '/' );
if ( nPos != ( aURL.getLength() - 1 ) )
{
// No trailing slash found. Append.
aURL += ::rtl::OUString::createFromAscii( "/" );
}
sal_Int32 nLen = aURL.getLength();
::ucbhelper::ContentRefList::const_iterator it = aAllContents.begin();
::ucbhelper::ContentRefList::const_iterator end = aAllContents.end();
while ( it != end )
{
::ucbhelper::ContentImplHelperRef xChild = (*it);
::rtl::OUString aChildURL
= xChild->getIdentifier()->getContentIdentifier();
// Is aURL a prefix of aChildURL?
if ( ( aChildURL.getLength() > nLen ) &&
( aChildURL.compareTo( aURL, nLen ) == 0 ) )
{
nPos = aChildURL.indexOf( '/', nLen );
if ( ( nPos == -1 ) ||
( nPos == ( aChildURL.getLength() - 1 ) ) )
{
// No further slashes / only a final slash. It's a child!
rChildren.push_back(
ContentRef(
static_cast< Content * >( xChild.get() ) ) );
}
}
++it;
}
}
//=========================================================================
void Content::insert(
const uno::Reference< io::XInputStream > & xInputStream,
sal_Bool bReplaceExisting,
const uno::Reference< ucb::XCommandEnvironment >& Environment )
throw( uno::Exception )
{
osl::ClearableGuard< osl::Mutex > aGuard( m_aMutex );
// Check, if all required properties were set.
#if 0
// @@@ add checks for property presence
if ( m_aProps.xxxx == yyyyy )
{
OSL_ENSURE( sal_False, "Content::insert - property value missing!" );
uno::Sequence< rtl::OUString > aProps( 1 );
aProps[ 0 ] = rtl::OUString::createFromAscii( "zzzz" );
::ucbhelper::cancelCommandExecution(
uno::makeAny( ucb::MissingPropertiesException(
rtl::OUString(),
static_cast< cppu::OWeakObject * >( this ),
aProps ) ),
Environment );
// Unreachable
}
#endif
bool bNeedInputStream = true; // @@@ adjust to real requirements
if ( bNeedInputStream && !xInputStream.is() )
{
OSL_ENSURE( sal_False, "Content::insert - No data stream!" );
::ucbhelper::cancelCommandExecution(
uno::makeAny( ucb::MissingInputStreamException(
rtl::OUString(),
static_cast< cppu::OWeakObject * >( this ) ) ),
Environment );
// Unreachable
}
// Assemble new content identifier...
uno::Reference< ucb::XContentIdentifier > xId /* @@@ create content identifier */;
// Fail, if a resource with given id already exists.
if ( !bReplaceExisting /*&& hasData( xId ) @@@ impl for hasData() */ )
{
uno::Any aProps
= uno::makeAny( beans::PropertyValue(
rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM( "Uri" ) ),
-1,
uno::makeAny( xId->getContentIdentifier() ),
beans::PropertyState_DIRECT_VALUE ) );
ucbhelper::cancelCommandExecution(
ucb::IOErrorCode_ALREADY_EXISTING,
uno::Sequence< uno::Any >(&aProps, 1),
Environment,
rtl::OUString::createFromAscii( "content already existing!!" ),
this );
// Unreachable
}
m_xIdentifier = xId;
// @@@
// storeData();
aGuard.clear();
inserted();
}
#endif // IMPLEMENT_COMMAND_INSERT
#ifdef IMPLEMENT_COMMAND_DELETE
//=========================================================================
void Content::destroy( sal_Bool bDeletePhysical )
throw( uno::Exception )
{
// @@@ take care about bDeletePhysical -> trashcan support
uno::Reference< ucb::XContent > xThis = this;
deleted();
osl::Guard< osl::Mutex > aGuard( m_aMutex );
// Process instanciated children...
ContentRefList aChildren;
queryChildren( aChildren );
ContentRefList::const_iterator it = aChildren.begin();
ContentRefList::const_iterator end = aChildren.end();
while ( it != end )
{
(*it)->destroy( bDeletePhysical );
++it;
}
}
#endif // IMPLEMENT_COMMAND_DELETE
| 32,257 | 9,805 |
#include "POLYParser.h"
#include "IOUtils.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <Core/EigenTypedef.h>
#include <Core/Exception.h>
using namespace PyMesh;
bool POLYParser::parse(const std::string& filename) {
std::ifstream fin(filename.c_str());
if (!fin.good()) {
std::stringstream err_msg;
err_msg << "Unable to read file " << filename;
throw IOError(err_msg.str());
}
parse_vertices(fin);
parse_faces(fin);
fin.close();
return true;
}
POLYParser::AttrNames POLYParser::get_attribute_names() const {
return AttrNames();
}
void POLYParser::export_vertices(Float* buffer) {
std::copy(m_vertices.begin(), m_vertices.end(), buffer);
}
void POLYParser::export_faces(int* buffer) {
std::copy(m_faces.begin(), m_faces.end(), buffer);
}
void POLYParser::export_voxels(int* buffer) {
std::copy(m_voxels.begin(), m_voxels.end(), buffer);
}
void POLYParser::export_attribute(const std::string& name, Float* buffer) {
std::cerr << "Warning: attribute " << name << " does not exist." <<
std::endl;
}
void POLYParser::parse_vertices(std::ifstream& fin) {
std::string header = IOUtils::next_line(fin);
size_t num_vertices, dim, num_attributes, bd_marker;
sscanf(header.c_str(), "%zi %zi %zi %zi",
&num_vertices, &dim, &num_attributes, &bd_marker);
if (dim != 3) {
throw IOError("Dim is not 3!");
}
m_vertices.resize(num_vertices * dim);
for (size_t i=0; i<num_vertices; i++) {
assert(fin.good());
size_t index;
Float x,y,z;
fin >> index >> x >> y >> z;
assert(index >= 0);
assert(index < num_vertices);
m_vertices[index*3 ] = x;
m_vertices[index*3+1] = y;
m_vertices[index*3+2] = z;
for (size_t j=0; j<num_attributes; j++) {
Float attr;
fin >> attr;
}
if (bd_marker == 1) {
Float bd;
fin >> bd;
}
}
}
void POLYParser::parse_faces(std::ifstream& fin) {
size_t num_faces, bd_marker;
fin >> num_faces >> bd_marker;
for (size_t i=0; i<num_faces; i++) {
assert(fin.good());
std::string line = IOUtils::next_line(fin);
size_t num_poly=0, num_holes=0, bd=0;
size_t n = sscanf(line.c_str(), "%zi %zi %zi",
&num_poly, &num_holes, &bd);
assert(n >= 1);
for (size_t j=0; j<num_poly; j++) {
size_t num_corners;
fin >> num_corners;
if (i == 0 && j == 0) {
m_vertex_per_face = num_corners;
} else if (num_corners != m_vertex_per_face) {
throw NotImplementedError("Mixed faces is not supported!");
}
for (size_t k=0; k<num_corners; k++) {
size_t corner;
fin >> corner;
m_faces.push_back(corner);
}
}
assert(fin.good());
for (size_t j=0; j<num_holes; j++) {
size_t hole_index;
float x,y,z;
fin >> hole_index >> x >> y >> z;
}
}
}
| 3,148 | 1,137 |
//
// Copyright (c) 2016, Scientific Toolworks, Inc.
//
// This software is licensed under the MIT License. The LICENSE.md file
// describes the conditions under which this software may be distributed.
//
// Author: Jason Haslam
//
#include "StartDialog.h"
#include "AccountDialog.h"
#include "CloneDialog.h"
#include "IconLabel.h"
#include "app/Application.h"
#include "conf/RecentRepositories.h"
#include "conf/RecentRepository.h"
#include "host/Accounts.h"
#include "host/Repository.h"
#include "ui/Footer.h"
#include "ui/MainWindow.h"
#include "ui/ProgressIndicator.h"
#include "ui/RepoView.h"
#include "ui/TabWidget.h"
#include <QAbstractItemModel>
#include <QAbstractListModel>
#include <QApplication>
#include <QComboBox>
#include <QDesktopServices>
#include <QDialogButtonBox>
#include <QFileDialog>
#include <QHBoxLayout>
#include <QIcon>
#include <QLabel>
#include <QLineEdit>
#include <QListView>
#include <QMessageBox>
#include <QMenu>
#include <QMultiMap>
#include <QPushButton>
#include <QPointer>
#include <QSettings>
#include <QStyledItemDelegate>
#include <QTimer>
#include <QTreeView>
#include <QVBoxLayout>
namespace {
const QString kSubtitleFmt = "<h4 style='margin-top: 0px; color: gray'>%2</h4>";
const QString kGeometryKey = "geometry";
const QString kStartGroup = "start";
const QString kCloudIcon = ":/cloud.png";
enum Role { KindRole = Qt::UserRole, AccountRole, RepositoryRole };
class RepoModel : public QAbstractListModel {
Q_OBJECT
public:
enum Row { Clone, Open, Init };
RepoModel(QObject *parent = nullptr) : QAbstractListModel(parent) {
RecentRepositories *repos = RecentRepositories::instance();
connect(repos, &RecentRepositories::repositoryAboutToBeAdded, this,
&RepoModel::beginResetModel);
connect(repos, &RecentRepositories::repositoryAdded, this,
&RepoModel::endResetModel);
connect(repos, &RecentRepositories::repositoryAboutToBeRemoved, this,
&RepoModel::beginResetModel);
connect(repos, &RecentRepositories::repositoryRemoved, this,
&RepoModel::endResetModel);
}
void setShowFullPath(bool enabled) {
beginResetModel();
mShowFullPath = enabled;
endResetModel();
}
int rowCount(const QModelIndex &parent = QModelIndex()) const override {
RecentRepositories *repos = RecentRepositories::instance();
return (repos->count() > 0) ? repos->count() : 3;
}
QVariant data(const QModelIndex &index,
int role = Qt::DisplayRole) const override {
RecentRepositories *repos = RecentRepositories::instance();
if (repos->count() <= 0) {
switch (role) {
case Qt::DisplayRole:
switch (index.row()) {
case Clone:
return tr("Clone Repository");
case Open:
return tr("Open Existing Repository");
case Init:
return tr("Initialize New Repository");
}
case Qt::DecorationRole: {
switch (index.row()) {
case Clone:
return QIcon(":/clone.png");
case Open:
return QIcon(":/open.png");
case Init:
return QIcon(":/new.png");
}
}
}
return QVariant();
}
RecentRepository *repo = repos->repository(index.row());
switch (role) {
case Qt::DisplayRole:
return mShowFullPath ? repo->path() : repo->name();
case Qt::UserRole:
return repo->path();
}
return QVariant();
}
Qt::ItemFlags flags(const QModelIndex &index) const override {
Qt::ItemFlags flags = QAbstractItemModel::flags(index);
if (RecentRepositories::instance()->count() <= 0)
flags &= ~Qt::ItemIsSelectable;
return flags;
}
private:
bool mShowFullPath = false;
};
class HostModel : public QAbstractItemModel {
Q_OBJECT
public:
HostModel(QStyle *style, QObject *parent = nullptr)
: QAbstractItemModel(parent),
mErrorIcon(style->standardIcon(QStyle::SP_MessageBoxCritical)) {
Accounts *accounts = Accounts::instance();
connect(accounts, &Accounts::accountAboutToBeAdded, this,
&HostModel::beginResetModel);
connect(accounts, &Accounts::accountAdded, this, &HostModel::endResetModel);
connect(accounts, &Accounts::accountAboutToBeRemoved, this,
&HostModel::beginResetModel);
connect(accounts, &Accounts::accountRemoved, this,
&HostModel::endResetModel);
connect(accounts, &Accounts::progress, this, [this](int accountIndex) {
QModelIndex idx = index(0, 0, index(accountIndex, 0));
emit dataChanged(idx, idx, {Qt::DisplayRole});
});
connect(accounts, &Accounts::started, this, [this](int accountIndex) {
beginResetModel();
endResetModel();
});
connect(accounts, &Accounts::finished, this, [this](int accountIndex) {
beginResetModel();
endResetModel();
});
connect(accounts, &Accounts::repositoryAboutToBeAdded, this,
&HostModel::beginResetModel);
connect(accounts, &Accounts::repositoryAdded, this,
&HostModel::endResetModel);
connect(accounts, &Accounts::repositoryPathChanged, this,
[this](int accountIndex, int repoIndex) {
QModelIndex idx = index(repoIndex, 0, index(accountIndex, 0));
emit dataChanged(idx, idx, {Qt::DisplayRole});
});
}
void setShowFullName(bool enabled) {
beginResetModel();
mShowFullName = enabled;
endResetModel();
}
QModelIndex index(int row, int column,
const QModelIndex &parent = QModelIndex()) const override {
bool id = (!parent.isValid() || parent.internalId());
return createIndex(row, column, !id ? parent.row() + 1 : 0);
}
QModelIndex parent(const QModelIndex &index) const override {
quintptr id = index.internalId();
return !id ? QModelIndex() : createIndex(id - 1, 0);
}
int rowCount(const QModelIndex &parent = QModelIndex()) const override {
// no accounts
Accounts *accounts = Accounts::instance();
if (accounts->count() <= 0)
return !parent.isValid() ? 4 : 0;
// account
if (!parent.isValid())
return accounts->count();
if (parent.internalId())
return 0;
// repos
Account *account = accounts->account(parent.row());
int count = account->repositoryCount();
if (count > 0)
return count;
AccountError *error = account->error();
AccountProgress *progress = account->progress();
return (error->isValid() || progress->isValid()) ? 1 : 0;
}
int columnCount(const QModelIndex &parent = QModelIndex()) const override {
return 1;
}
QVariant data(const QModelIndex &index,
int role = Qt::DisplayRole) const override {
// no accounts
Accounts *accounts = Accounts::instance();
if (accounts->count() <= 0) {
Account::Kind kind = static_cast<Account::Kind>(index.row());
switch (role) {
case Qt::DisplayRole:
return Account::name(kind);
case Qt::DecorationRole:
return Account::icon(kind);
case KindRole:
return kind;
}
return QVariant();
}
// account
quintptr id = index.internalId();
if (!id) {
Account *account = accounts->account(index.row());
switch (role) {
case Qt::DisplayRole:
return account->username();
case Qt::DecorationRole:
return Account::icon(account->kind());
case KindRole:
return account->kind();
case AccountRole:
return QVariant::fromValue(account);
}
return QVariant();
}
// error
Account *account = accounts->account(id - 1);
AccountError *error = account->error();
if (error->isValid()) {
switch (role) {
case Qt::DisplayRole:
return error->text();
case Qt::DecorationRole:
return mErrorIcon;
case Qt::ToolTipRole:
return error->detailedText();
}
return QVariant();
}
// progress
if (account->repositoryCount() <= 0) {
switch (role) {
case Qt::DisplayRole:
return tr("Connecting");
case Qt::DecorationRole:
return account->progress()->value();
case Qt::FontRole: {
QFont font = static_cast<QWidget *>(QObject::parent())->font();
font.setItalic(true);
return font;
}
default:
return QVariant();
}
}
// repo
int row = index.row();
Repository *repo = account->repository(row);
switch (role) {
case Qt::DisplayRole:
return mShowFullName ? repo->fullName() : repo->name();
case Qt::DecorationRole: {
QString path = account->repositoryPath(row);
return path.isEmpty() ? QIcon(kCloudIcon) : QIcon();
}
case KindRole:
return account->kind();
case RepositoryRole:
return QVariant::fromValue(repo);
}
return QVariant();
}
Qt::ItemFlags flags(const QModelIndex &index) const override {
Qt::ItemFlags flags = QAbstractItemModel::flags(index);
if (Accounts::instance()->count() <= 0)
flags &= ~Qt::ItemIsSelectable;
return flags;
}
private:
bool mShowFullName = false;
QIcon mErrorIcon;
};
class ProgressDelegate : public QStyledItemDelegate {
public:
ProgressDelegate(QObject *parent = nullptr) : QStyledItemDelegate(parent) {}
void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const override {
QStyleOptionViewItem opt = option;
initStyleOption(&opt, index);
// Draw background.
QStyledItemDelegate::paint(painter, opt, index);
// Draw busy indicator.
QVariant progress = index.data(Qt::DecorationRole);
if (!progress.canConvert<int>())
return;
QStyle *style = opt.widget ? opt.widget->style() : QApplication::style();
QStyle::SubElement se = QStyle::SE_ItemViewItemDecoration;
QRect rect = style->subElementRect(se, &opt, opt.widget);
ProgressIndicator::paint(painter, rect, "#808080", progress.toInt());
}
protected:
void initStyleOption(QStyleOptionViewItem *option,
const QModelIndex &index) const override {
QStyledItemDelegate::initStyleOption(option, index);
if (index.data(Qt::DecorationRole).canConvert<int>()) {
option->decorationSize = ProgressIndicator::size();
} else if (index.data(RepositoryRole).isValid()) {
option->features |= QStyleOptionViewItem::HasDecoration;
option->decorationSize = QSize(20, 20);
}
}
};
} // namespace
StartDialog::StartDialog(QWidget *parent) : QDialog(parent) {
setAttribute(Qt::WA_DeleteOnClose);
setWindowTitle(tr("Choose Repository"));
QIcon icon(":/Gittyup.iconset/icon_128x128.png");
IconLabel *iconLabel = new IconLabel(icon, 128, 128, this);
QIcon title(":/logo-type_light@2x.png");
IconLabel *titleLabel = new IconLabel(title, 163, 38, this);
QString subtitleText = kSubtitleFmt.arg(tr("Understand your history!"));
QLabel *subtitle = new QLabel(subtitleText, this);
subtitle->setAlignment(Qt::AlignHCenter);
QVBoxLayout *left = new QVBoxLayout;
left->addWidget(iconLabel);
left->addWidget(titleLabel);
left->addWidget(subtitle);
left->addStretch();
mRepoList = new QListView(this);
mRepoList->setIconSize(QSize(32, 32));
mRepoList->setSelectionMode(QAbstractItemView::ExtendedSelection);
connect(mRepoList, &QListView::clicked, this,
[this](const QModelIndex &index) {
if (!index.data(Qt::UserRole).isValid()) {
switch (index.row()) {
case RepoModel::Clone:
mClone->trigger();
break;
case RepoModel::Open:
mOpen->trigger();
break;
case RepoModel::Init:
mInit->trigger();
break;
}
}
});
connect(mRepoList, &QListView::doubleClicked, this, &QDialog::accept);
RepoModel *repoModel = new RepoModel(mRepoList);
mRepoList->setModel(repoModel);
connect(repoModel, &RepoModel::modelReset, this, [this] {
mRepoList->setCurrentIndex(mRepoList->model()->index(0, 0));
});
mRepoFooter = new Footer(mRepoList);
connect(mRepoFooter, &Footer::minusClicked, this, [this] {
// Sort selection in reverse order.
QModelIndexList indexes = mRepoList->selectionModel()->selectedIndexes();
std::sort(indexes.begin(), indexes.end(),
[](const QModelIndex &lhs, const QModelIndex &rhs) {
return rhs.row() < lhs.row();
});
// Remove selected indexes from settings.
foreach (const QModelIndex &index, indexes)
RecentRepositories::instance()->remove(index.row());
});
QMenu *repoPlusMenu = new QMenu(this);
mRepoFooter->setPlusMenu(repoPlusMenu);
mClone = repoPlusMenu->addAction(tr("Clone Repository"));
connect(mClone, &QAction::triggered, this, [this] {
CloneDialog *dialog = new CloneDialog(CloneDialog::Clone, this);
connect(dialog, &CloneDialog::accepted, this, [this, dialog] {
if (MainWindow *window = openWindow(dialog->path()))
window->currentView()->addLogEntry(dialog->message(),
dialog->messageTitle());
});
dialog->open();
});
mOpen = repoPlusMenu->addAction(tr("Open Existing Repository"));
connect(mOpen, &QAction::triggered, this, [this] {
// FIXME: Filter out non-git dirs.
QFileDialog *dialog =
new QFileDialog(this, tr("Open Repository"), QDir::homePath());
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->setFileMode(QFileDialog::Directory);
dialog->setOption(QFileDialog::ShowDirsOnly);
connect(dialog, &QFileDialog::fileSelected, this, &StartDialog::openWindow);
dialog->open();
});
mInit = repoPlusMenu->addAction(tr("Initialize New Repository"));
connect(mInit, &QAction::triggered, this, [this] {
CloneDialog *dialog = new CloneDialog(CloneDialog::Init, this);
connect(dialog, &CloneDialog::accepted, this, [this, dialog] {
if (MainWindow *window = openWindow(dialog->path()))
window->currentView()->addLogEntry(dialog->message(),
dialog->messageTitle());
});
dialog->open();
});
QMenu *repoContextMenu = new QMenu(this);
mRepoFooter->setContextMenu(repoContextMenu);
QAction *clear = repoContextMenu->addAction(tr("Clear All"));
connect(clear, &QAction::triggered,
[] { RecentRepositories::instance()->clear(); });
QSettings settings;
QAction *showFullPath = repoContextMenu->addAction(tr("Show Full Path"));
bool recentChecked = settings.value("start/recent/fullpath").toBool();
showFullPath->setCheckable(true);
showFullPath->setChecked(recentChecked);
repoModel->setShowFullPath(recentChecked);
connect(showFullPath, &QAction::triggered, this, [repoModel](bool checked) {
QSettings().setValue("start/recent/fullpath", checked);
repoModel->setShowFullPath(checked);
});
QAction *filter = repoContextMenu->addAction(tr("Filter Non-existent Paths"));
filter->setCheckable(true);
filter->setChecked(settings.value("recent/filter", true).toBool());
connect(filter, &QAction::triggered,
[](bool checked) { QSettings().setValue("recent/filter", checked); });
QVBoxLayout *middle = new QVBoxLayout;
middle->setSpacing(0);
middle->addWidget(new QLabel(tr("Repositories:"), this));
middle->addSpacing(8); // FIXME: Query style?
middle->addWidget(mRepoList);
middle->addWidget(mRepoFooter);
mHostTree = new QTreeView(this);
mHostTree->setHeaderHidden(true);
mHostTree->setExpandsOnDoubleClick(false);
mHostTree->setIconSize(QSize(32, 32));
mHostTree->setSelectionMode(QAbstractItemView::ExtendedSelection);
connect(mHostTree, &QTreeView::clicked, this,
[this](const QModelIndex &index) {
int rows = mHostTree->model()->rowCount(index);
if (!rows && !index.data(RepositoryRole).isValid())
edit(index);
});
connect(mHostTree, &QTreeView::doubleClicked, this,
[this](const QModelIndex &index) {
QModelIndex parent = index.parent();
if (parent.isValid()) {
Account *account = parent.data(AccountRole).value<Account *>();
if (!account->repositoryPath(index.row()).isEmpty()) {
accept();
return;
}
}
edit(index);
});
HostModel *hostModel = new HostModel(style(), mHostTree);
mHostTree->setModel(hostModel);
connect(hostModel, &QAbstractItemModel::modelReset, this, [this] {
QModelIndex index = mHostTree->model()->index(0, 0);
mHostTree->setRootIsDecorated(index.data(AccountRole).isValid());
mHostTree->expandAll();
});
mHostTree->setItemDelegate(new ProgressDelegate(this));
mHostFooter = new Footer(mHostTree);
connect(mHostFooter, &Footer::plusClicked, this, [this] { edit(); });
connect(mHostFooter, &Footer::minusClicked, this, &StartDialog::remove);
QMenu *hostContextMenu = new QMenu(this);
mHostFooter->setContextMenu(hostContextMenu);
QAction *refresh = hostContextMenu->addAction(tr("Refresh"));
connect(refresh, &QAction::triggered, this, [] {
Accounts *accounts = Accounts::instance();
for (int i = 0; i < accounts->count(); ++i)
accounts->account(i)->connect();
});
QAction *showFullName = hostContextMenu->addAction(tr("Show Full Name"));
bool remoteChecked = QSettings().value("start/remote/fullname").toBool();
showFullName->setCheckable(true);
showFullName->setChecked(remoteChecked);
hostModel->setShowFullName(remoteChecked);
connect(showFullName, &QAction::triggered, this, [hostModel](bool checked) {
QSettings().setValue("start/remote/fullname", checked);
hostModel->setShowFullName(checked);
});
// Clear the other list when this selection changes.
QItemSelectionModel *repoSelModel = mRepoList->selectionModel();
connect(repoSelModel, &QItemSelectionModel::selectionChanged, this, [this] {
if (!mRepoList->selectionModel()->selectedIndexes().isEmpty())
mHostTree->clearSelection();
updateButtons();
});
// Clear the other list when this selection changes.
QItemSelectionModel *hostSelModel = mHostTree->selectionModel();
connect(hostSelModel, &QItemSelectionModel::selectionChanged, this, [this] {
if (!mHostTree->selectionModel()->selectedIndexes().isEmpty())
mRepoList->clearSelection();
updateButtons();
});
QVBoxLayout *right = new QVBoxLayout;
right->setSpacing(0);
right->addWidget(new QLabel(tr("Remote:"), this));
right->addSpacing(8); // FIXME: Query style?
right->addWidget(mHostTree);
right->addWidget(mHostFooter);
QHBoxLayout *top = new QHBoxLayout;
top->addLayout(left);
top->addSpacing(12);
top->addLayout(middle);
top->addSpacing(12);
top->addLayout(right);
QDialogButtonBox::StandardButtons buttons =
QDialogButtonBox::Open | QDialogButtonBox::Cancel;
mButtonBox = new QDialogButtonBox(buttons, this);
connect(mButtonBox, &QDialogButtonBox::accepted, this, &StartDialog::accept);
connect(mButtonBox, &QDialogButtonBox::rejected, this, &StartDialog::reject);
QString text = tr("View Getting Started Video");
QPushButton *help = mButtonBox->addButton(text, QDialogButtonBox::ResetRole);
connect(help, &QPushButton::clicked, [] {
QDesktopServices::openUrl(QUrl("https://gitahead.com/#tutorials"));
});
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addLayout(top);
layout->addWidget(mButtonBox);
}
void StartDialog::accept() {
QModelIndexList repoIndexes = mRepoList->selectionModel()->selectedIndexes();
QModelIndexList hostIndexes = mHostTree->selectionModel()->selectedIndexes();
QStringList paths;
foreach (const QModelIndex &index, repoIndexes)
paths.append(index.data(Qt::UserRole).toString());
QModelIndexList uncloned;
foreach (const QModelIndex &index, hostIndexes) {
QModelIndex parent = index.parent();
if (parent.isValid()) {
Account *account = parent.data(AccountRole).value<Account *>();
QString path = account->repositoryPath(index.row());
if (path.isEmpty()) {
uncloned.append(index);
} else {
paths.append(path);
}
}
}
// Clone the first repo.
if (!uncloned.isEmpty()) {
edit(uncloned.first());
return;
}
// FIXME: Fail if none of the windows were able to be opened?
QDialog::accept();
if (paths.isEmpty())
return;
// Open a new window for the first valid repo.
MainWindow *window = MainWindow::open(paths.takeFirst());
while (!window && !paths.isEmpty())
window = MainWindow::open(paths.takeFirst());
if (!window)
return;
// Add the remainder as tabs.
foreach (const QString &path, paths)
window->addTab(path);
}
StartDialog *StartDialog::openSharedInstance() {
static QPointer<StartDialog> dialog;
if (dialog) {
dialog->show();
dialog->raise();
dialog->activateWindow();
return dialog;
}
dialog = new StartDialog;
dialog->show();
return dialog;
}
void StartDialog::showEvent(QShowEvent *event) {
// Restore geometry.
QSettings settings;
settings.beginGroup(kStartGroup);
if (settings.contains(kGeometryKey))
restoreGeometry(settings.value(kGeometryKey).toByteArray());
settings.endGroup();
QDialog::showEvent(event);
}
void StartDialog::hideEvent(QHideEvent *event) {
QSettings settings;
settings.beginGroup(kStartGroup);
settings.setValue(kGeometryKey, saveGeometry());
settings.endGroup();
QDialog::hideEvent(event);
}
void StartDialog::updateButtons() {
QModelIndexList repoIndexes = mRepoList->selectionModel()->selectedIndexes();
QModelIndexList hostIndexes = mHostTree->selectionModel()->selectedIndexes();
// Update dialog Open button.
bool clone = false;
QPushButton *open = mButtonBox->button(QDialogButtonBox::Open);
open->setEnabled(!repoIndexes.isEmpty() || !hostIndexes.isEmpty());
foreach (const QModelIndex &index, hostIndexes) {
QModelIndex parent = index.parent();
if (!parent.isValid()) {
open->setEnabled(false);
} else {
Account *account = parent.data(AccountRole).value<Account *>();
if (Repository *repo = index.data(RepositoryRole).value<Repository *>()) {
if (account->repositoryPath(index.row()).isEmpty())
clone = true;
} else {
open->setEnabled(false);
}
}
}
open->setText((clone && open->isEnabled()) ? tr("Clone") : tr("Open"));
// Update repo list footer buttons.
mRepoFooter->setMinusEnabled(!repoIndexes.isEmpty());
// Update host list footer buttons.
mHostFooter->setMinusEnabled(false);
if (!hostIndexes.isEmpty()) {
QModelIndex index = hostIndexes.first();
Account *account = index.data(AccountRole).value<Account *>();
QString repoPath;
QModelIndex parent = index.parent();
if (parent.isValid()) {
Account *account = parent.data(AccountRole).value<Account *>();
repoPath = account->repositoryPath(index.row());
}
mHostFooter->setMinusEnabled(account || !repoPath.isEmpty());
}
}
void StartDialog::edit(const QModelIndex &index) {
// account
if (!index.isValid() || !index.parent().isValid()) {
Account *account = nullptr;
if (index.isValid())
account = index.data(AccountRole).value<Account *>();
AccountDialog *dialog = new AccountDialog(account, this);
if (!account && index.isValid())
dialog->setKind(index.data(KindRole).value<Account::Kind>());
dialog->open();
return;
}
// repo
Repository *repo = index.data(RepositoryRole).value<Repository *>();
if (!repo)
return;
CloneDialog *dialog = new CloneDialog(CloneDialog::Clone, this, repo);
connect(dialog, &CloneDialog::accepted, this, [this, index, dialog] {
// Set local path.
Account *account = Accounts::instance()->account(index.parent().row());
account->setRepositoryPath(index.row(), dialog->path());
// Open the repo.
QCoreApplication::processEvents();
accept();
});
dialog->open();
}
void StartDialog::remove() {
QModelIndexList indexes = mHostTree->selectionModel()->selectedIndexes();
Q_ASSERT(!indexes.isEmpty());
// account
QModelIndex index = indexes.first();
if (!index.parent().isValid()) {
Account::Kind kind = index.data(KindRole).value<Account::Kind>();
QString name = index.data(Qt::DisplayRole).toString();
QString fmt =
tr("<p>Are you sure you want to remove the %1 account for '%2'?</p>"
"<p>Only the account association will be removed. Remote "
"configurations and local clones will not be affected.</p>");
QMessageBox mb(QMessageBox::Warning, tr("Remove Account?"),
fmt.arg(Account::name(kind), name), QMessageBox::Cancel,
this);
QPushButton *remove = mb.addButton(tr("Remove"), QMessageBox::AcceptRole);
remove->setFocus();
mb.exec();
if (mb.clickedButton() == remove) {
mHostTree->clearSelection();
Accounts::instance()->removeAccount(index.row());
}
return;
}
// repo
Repository *repo = index.data(RepositoryRole).value<Repository *>();
QString fmt =
tr("<p>Are you sure you want to remove the remote repository association "
"for %1?</p><p>The local clone itself will not be affected.</p>");
QMessageBox mb(QMessageBox::Warning, tr("Remove Repository Association?"),
fmt.arg(repo->fullName()), QMessageBox::Cancel, this);
QPushButton *remove = mb.addButton(tr("Remove"), QMessageBox::AcceptRole);
remove->setFocus();
mb.exec();
if (mb.clickedButton() == remove)
repo->account()->setRepositoryPath(index.row(), QString());
// Update minus and OK buttons.
updateButtons();
}
MainWindow *StartDialog::openWindow(const QString &repo) {
// This dialog has to be hidden before opening another window so that it
// doesn't automatically move to a position that still shows the dialog.
hide();
if (MainWindow *window = MainWindow::open(repo)) {
// Dismiss this dialog without trying to open the selection.
reject();
return window;
} else {
show();
}
return nullptr;
}
#include "StartDialog.moc"
| 26,447 | 8,098 |
/*
1 3 2 6 1 4 5 5 9 2 3 79 3 -5
*/
#include <iostream>
using namespace std;
void leggo(int n[], int& dim);
void seqCrescente(int [], int, int&, int&);
int main() {
int n[100];
int dim = 0;
int lunghezzaSeq;
int lmax, imax;
leggo(n, dim);
if (dim > 0) {
seqCrescente(n, dim, imax, lmax);
// cout << "lmax: " << lmax << " imax: " << imax;
for (int i = imax; i < lmax + imax; i++) {
cout << n[i];
}
cout << endl << lmax;
} else {
cout << "Empty";
}
return 0;
}
void leggo(int n[], int& dim) {
int num;
cin >> num;
for (int i = 0; num >= 0; i++) {
n[i] = num;
cin >> num;
dim++;
}
}
void seqCrescente(int seq[], int dim, int& indiceMax, int& lmax) {
int tab[100][2] = {1}; // array x * 2 con gli indici e le lunghezze delle sequenze crescenti
int index = 0, lung = 0, j = 0;
// trovo tutte le sequenza crescenti
for (int i = 1; i < dim; i++) {
if (seq[i] >= seq[i-1]) {
tab[j][0]++;
} else {
tab[++j][1] = i;
tab[j][0] = 1;
}
}
// tra le sequenze crescenti trovo la sequenza più lunga
lmax = tab[0][0];
indiceMax = 0;
for(int i = 1; i <= j; i++) {
// cout << "indice: " << tab[i][1] << " lunghezze: " << tab[i][0] << endl;
if (tab[i][0] > lmax) {
indiceMax = tab[i][1];
lmax = tab[i][0];
}
}
}
| 1,414 | 617 |
// kv_dictionary_test_harness.cpp
/*======
This file is part of Percona Server for MongoDB.
Copyright (c) 2006, 2015, Percona and/or its affiliates. All rights reserved.
Percona Server for MongoDB is free software: you can redistribute
it and/or modify it under the terms of the GNU Affero General
Public License, version 3, as published by the Free Software
Foundation.
Percona Server for MongoDB 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public
License along with Percona Server for MongoDB. If not, see
<http://www.gnu.org/licenses/>.
======= */
#include <algorithm>
#include <vector>
#include <boost/scoped_ptr.hpp>
#include "mongo/db/storage/kv/dictionary/kv_dictionary.h"
#include "mongo/db/storage/kv/dictionary/kv_dictionary_test_harness.h"
#include "mongo/db/storage/kv/slice.h"
#include "mongo/unittest/unittest.h"
namespace mongo {
using boost::scoped_ptr;
TEST( KVDictionary, Simple1 ) {
scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() );
scoped_ptr<KVDictionary> db( harnessHelper->newKVDictionary() );
{
const Slice hi = Slice::of("hi");
const Slice there = Slice::of("there");
scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
{
Slice value;
WriteUnitOfWork uow( opCtx.get() );
Status status = db->insert( opCtx.get(), hi, there, false );
ASSERT( status.isOK() );
status = db->get( opCtx.get(), hi, value );
ASSERT( status.isOK() );
status = db->remove( opCtx.get(), hi );
ASSERT( status.isOK() );
status = db->get( opCtx.get(), hi, value );
ASSERT( status.code() == ErrorCodes::NoSuchKey );
uow.commit();
}
}
}
TEST( KVDictionary, Simple2 ) {
scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() );
scoped_ptr<KVDictionary> db( harnessHelper->newKVDictionary() );
const Slice hi = Slice::of("hi");
const Slice there = Slice::of("there");
const Slice apple = Slice::of("apple");
const Slice bears = Slice::of("bears");
{
scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
{
WriteUnitOfWork uow( opCtx.get() );
Status status = db->insert( opCtx.get(), hi, there, false );
ASSERT( status.isOK() );
uow.commit();
}
}
{
scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
{
WriteUnitOfWork uow( opCtx.get() );
Status status = db->insert( opCtx.get(), apple, bears, false );
ASSERT( status.isOK() );
uow.commit();
}
}
{
scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
{
Slice value;
Status status = db->get( opCtx.get(), hi, value );
ASSERT( status.isOK() );
ASSERT( value.size() == 6 );
ASSERT( std::string( "there" ) == std::string( value.data() ) );
}
{
Slice value;
Status status = db->get( opCtx.get(), apple, value );
ASSERT( status.isOK() );
ASSERT( value.size() == 6 );
ASSERT( std::string( "bears" ) == std::string( value.data() ) );
}
}
{
scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
{
WriteUnitOfWork uow( opCtx.get() );
Status status = db->remove( opCtx.get(), hi );
ASSERT( status.isOK() );
uow.commit();
}
}
{
scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
{
Slice value;
Status status = db->get( opCtx.get(), hi, value );
ASSERT( status.code() == ErrorCodes::NoSuchKey );
}
{
Slice value;
Status status = db->get( opCtx.get(), apple, value );
ASSERT( status.isOK() );
ASSERT( value.size() == 6 );
ASSERT( std::string( "bears" ) == std::string( value.data() ) );
}
{
WriteUnitOfWork uow( opCtx.get() );
Status status = db->remove( opCtx.get(), apple );
ASSERT( status.isOK() );
uow.commit();
}
{
Slice value;
Status status = db->get( opCtx.get(), apple, value );
ASSERT( status.code() == ErrorCodes::NoSuchKey );
}
}
}
TEST( KVDictionary, InsertSerialGetSerial ) {
scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() );
scoped_ptr<KVDictionary> db( harnessHelper->newKVDictionary() );
const unsigned char nKeys = 100;
{
scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
{
Slice value;
WriteUnitOfWork uow( opCtx.get() );
for (unsigned char i = 0; i < nKeys; i++) {
const Slice slice = Slice::of(i);
Status status = db->insert( opCtx.get(), slice, slice, false );
ASSERT( status.isOK() );
}
uow.commit();
}
}
{
scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
{
for (unsigned char i = 0; i < nKeys; i++) {
Slice value;
Status status = db->get( opCtx.get(), Slice::of(i), value );
ASSERT( status.isOK() );
ASSERT( value.as<unsigned char>() == i );
}
}
}
}
static int _rng(int i) { return std::rand() % i; }
TEST( KVDictionary, InsertRandomGetSerial ) {
scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() );
scoped_ptr<KVDictionary> db( harnessHelper->newKVDictionary() );
const unsigned char nKeys = 100;
{
std::vector<unsigned char> keys;
for (unsigned char i = 0; i < nKeys; i++) {
keys.push_back(i);
}
std::srand(unsigned(time(0)));
std::random_shuffle(keys.begin(), keys.end(), _rng);
scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
{
Slice value;
WriteUnitOfWork uow( opCtx.get() );
for (unsigned char i = 0; i < nKeys; i++) {
const Slice slice = Slice::of(keys[i]);
Status status = db->insert( opCtx.get(), slice, slice, false );
ASSERT( status.isOK() );
}
uow.commit();
}
}
{
scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
{
Slice value;
for (unsigned char i = 0; i < nKeys; i++) {
Status status = db->get( opCtx.get(), Slice::of(i), value );
ASSERT( status.isOK() );
ASSERT( value.as<unsigned char>() == i );
}
}
}
}
TEST( KVDictionary, InsertRandomCursor ) {
scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() );
scoped_ptr<KVDictionary> db( harnessHelper->newKVDictionary() );
const unsigned char nKeys = 100;
{
std::vector<unsigned char> keys;
for (unsigned char i = 0; i < nKeys; i++) {
keys.push_back(i);
}
std::srand(unsigned(time(0)));
std::random_shuffle(keys.begin(), keys.end(), _rng);
scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
{
Slice value;
WriteUnitOfWork uow( opCtx.get() );
for (unsigned char i = 0; i < nKeys; i++) {
const Slice slice = Slice::of(keys[i]);
Status status = db->insert( opCtx.get(), slice, slice, false );
ASSERT( status.isOK() );
}
uow.commit();
}
}
{
scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
{
Slice value;
const int direction = 1;
unsigned char i = 0;
for (scoped_ptr<KVDictionary::Cursor> c(db->getCursor(opCtx.get(), direction));
c->ok(); c->advance(opCtx.get()), i++) {
ASSERT( c->currKey().as<unsigned char>() == i );
ASSERT( c->currVal().as<unsigned char>() == i );
}
}
}
{
scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
{
Slice value;
const int direction = -1;
unsigned char i = nKeys - 1;
for (scoped_ptr<KVDictionary::Cursor> c(db->getCursor(opCtx.get(), direction));
c->ok(); c->advance(opCtx.get()), i--) {
ASSERT( c->currKey().as<unsigned char>() == i );
ASSERT( c->currVal().as<unsigned char>() == i );
}
}
}
}
TEST( KVDictionary, InsertDeleteCursor ) {
scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() );
scoped_ptr<KVDictionary> db( harnessHelper->newKVDictionary() );
const unsigned char nKeys = 100;
std::vector<unsigned char> keys;
for (unsigned char i = 0; i < nKeys; i++) {
keys.push_back(i);
}
{
scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
{
Slice value;
WriteUnitOfWork uow( opCtx.get() );
for (unsigned char i = 0; i < nKeys; i++) {
const Slice slice = Slice::of(keys[i]);
Status status = db->insert( opCtx.get(), slice, slice, false );
ASSERT( status.isOK() );
}
uow.commit();
}
}
std::srand(unsigned(time(0)));
std::random_shuffle(keys.begin(), keys.end(), _rng);
std::set<unsigned char> remainingKeys;
std::set<unsigned char> deletedKeys;
{
scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
{
WriteUnitOfWork uow( opCtx.get() );
for (unsigned char i = 0; i < nKeys; i++) {
unsigned char k = keys[i];
if (i < (nKeys / 2)) {
Status status = db->remove( opCtx.get(), Slice::of(k) );
ASSERT( status.isOK() );
deletedKeys.insert(k);
} else {
remainingKeys.insert(k);
}
}
uow.commit();
}
}
{
scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
{
const int direction = 1;
unsigned char i = 0;
for (scoped_ptr<KVDictionary::Cursor> c(db->getCursor(opCtx.get(), direction));
c->ok(); c->advance(opCtx.get()), i++) {
unsigned char k = c->currKey().as<unsigned char>();
ASSERT( remainingKeys.count(k) == 1 );
ASSERT( deletedKeys.count(k) == 0 );
ASSERT( k == c->currVal().as<unsigned char>() );
remainingKeys.erase(k);
}
ASSERT( remainingKeys.empty() );
}
}
{
scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
{
for (std::set<unsigned char>::const_iterator it = deletedKeys.begin();
it != deletedKeys.end(); it++) {
unsigned char k = *it;
Slice value;
Status status = db->get( opCtx.get(), Slice::of(k), value );
ASSERT( status.code() == ErrorCodes::NoSuchKey );
ASSERT( value.size() == 0 );
}
}
}
}
TEST( KVDictionary, CursorSeekForward ) {
scoped_ptr<HarnessHelper> harnessHelper( newHarnessHelper() );
scoped_ptr<KVDictionary> db( harnessHelper->newKVDictionary() );
const unsigned char nKeys = 101; // even number makes the test magic more complicated
std::vector<unsigned char> keys;
for (unsigned char i = 0; i < nKeys; i++) {
keys.push_back(i);
}
{
scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
{
Slice value;
WriteUnitOfWork uow( opCtx.get() );
for (unsigned char i = 0; i < nKeys; i += 2) {
const Slice slice = Slice::of(keys[i]);
Status status = db->insert( opCtx.get(), slice, slice, false );
ASSERT( status.isOK() );
}
uow.commit();
}
}
{
scoped_ptr<OperationContext> opCtx( harnessHelper->newOperationContext() );
{
scoped_ptr<KVDictionary::Cursor> cursor( db->getCursor( opCtx.get(), 1 ) );
for (unsigned char i = 0; i < nKeys; i++) {
cursor->seek( opCtx.get(), Slice::of(keys[i]) );
if ( i % 2 == 0 ) {
ASSERT( cursor->currKey().as<unsigned char>() == i );
} else if ( i + 1 < nKeys ) {
ASSERT( cursor->currKey().as<unsigned char>() == i + 1);
}
}
}
{
scoped_ptr<KVDictionary::Cursor> cursor( db->getCursor( opCtx.get(), -1 ) );
for (unsigned char i = 1; i < nKeys; i++) {
cursor->seek(opCtx.get(), Slice::of(keys[i]));
if ( i % 2 == 0 ) {
ASSERT( cursor->currKey().as<unsigned char>() == i );
} else {
ASSERT( cursor->currKey().as<unsigned char>() == i - 1 );
}
}
}
}
}
}
| 15,227 | 4,367 |
// 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 "src/connectivity/overnet/lib/testing/flags.h"
DEFINE_bool(verbose, false, "Enable debug output in tests");
| 283 | 92 |
/*
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array nums = [1,1,1,2,2,3],
Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.
*/
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size() < 3) return nums.size();
int triple = 1;
int res = 1;
for(auto it = nums.begin()+1; it != nums.end();) {
if(*it == *(it-1)) triple++;
else triple = 1;
if(triple >= 3) {
nums.erase(it);
triple = 2;
continue;
}
res++;
it++;
}
return res;
}
};
| 818 | 266 |
#include <opencv2/objdetect/objdetect.hpp>
#include "highgui.h"
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <unistd.h>
#include <iostream>
#include <stdio.h>
#include <cstdlib>
using namespace std;
using namespace cv;
// Captures images from each camera. Facetime and other camera software
// must NOT be running or this program can't get to the cameras.
int main( int argc, const char** argv )
{
// CvCapture* capture = 0;
Mat frame, frameCopy, image, altframe;
char i_str[5];
char fname[300];
cout << "starting" << endl;
int j=0; // AV foundation offset also try 500
// Must keep facetime closed!!
for (int i = 0; i < 6; ++i) {
sprintf(i_str, "%d", (i+j));
strcpy(fname,"../currentState/camera");
strcat(fname,i_str);
strcat(fname,".jpg");
cout<< "fname: "<<fname <<endl;
// Capture the Image from the webcam
CvCapture *pCapturedImage = cvCreateCameraCapture(i+j);
cout << "sleeping a minute" << endl;
unsigned int sleep(50);
// Get the frame
IplImage *pSaveImg = cvQueryFrame(pCapturedImage);
// Save the frame into a file
cvSaveImage(fname ,pSaveImg);
cvReleaseCapture(&pCapturedImage);
}
/*
if(!capture) cout << "No camera detected" << endl;
cvNamedWindow( "result", 1 );
if( capture )
{
cout << "In capture ..." << endl;
for(;;)
{
cout << "before query frame" << endl;
IplImage* iplImg = cvQueryFrame( capture );
cout << "before ipImg" << endl;
frame = iplImg;
if( frame.empty() )
break;
if( iplImg->origin == IPL_ORIGIN_TL )
frame.copyTo( frameCopy );
else
flip( frame, frameCopy, 0 );
cout << "before waitkey" << endl;
if( waitKey( 10 ) >= 0 )
cvReleaseCapture( &capture );
}
waitKey(0);
cvDestroyWindow("result");
return 0;
}
*/
}
| 2,145 | 697 |
// LlilumWin32.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
extern int LlosWin32_Main(void);
int main()
{
return LlosWin32_Main();
}
| 179 | 73 |
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
//
// CCC AAA V V EEEEE OOO UU UU TTTTTT LL II NN NN EEEEE RRRRR
// CC CC AA AA V V EE OO OO UU UU TT LL II NNN NN EE RR RR
// CC AA AA V V EEE OO OO UU UU TT LL II NN N NN EEE RRRRR
// CC CC AAAAAA V V EE OO OO UU UU TT LL II NN NNN EE RR R
// CCc AA AA V EEEEE OOO UUUUU TT LLLLL II NN NN EEEEE RR R
//
// CAVE OUTLINER -- Cave 3D model processing software
//
// Copyright (C) 2021 by Jari Arkko -- See LICENSE.txt for license information.
//
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
#ifndef INDEXEDMESH_HH
#define INDEXEDMESH_HH
///////////////////////////////////////////////////////////////////////////////////////////////
// Includes ///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include "outlinertypes.hh"
#include "outlinerconstants.hh"
#include "outlinerdirection.hh"
///////////////////////////////////////////////////////////////////////////////////////////////
// Internal data types ////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
struct IndexedMeshOneMeshOneTileFaces {
unsigned int nFaces;
unsigned int maxNFaces;
const aiFace** faces;
};
struct IndexedMeshOneMesh {
const aiMesh* mesh;
unsigned int nOutsideModelBoundingBox;
struct IndexedMeshOneMeshOneTileFaces** tileMatrix;
};
///////////////////////////////////////////////////////////////////////////////////////////////
// Class interface ////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
///
/// This object represents an optimized index to the mesh faces
/// contained in an imported 3D model. The imported model has a large
/// datastructure of 'faces' -- typically millions or even tens of
/// millions of faces. There is no efficient way to search for faces
/// at a given location in the 3D or 2D space, however. The indexed
/// mesh object sorts the faces into a 2D matrix of 'tiles'. For
/// instance, a large model could be split into 20x20 or 400 tiles, so
/// that when we are looking for a face within given (x,y)
/// coordinates, we only need to look at the tile where (x,y) falls
/// into. The indexing is performed only once, and all searches after
/// the indexing operation can use the more efficient search.
///
class IndexedMesh {
public:
/// Create an IndexedMesh object.
IndexedMesh(unsigned int maxMeshesIn,
unsigned int subdivisionsIn,
const OutlinerBox3D& modelBoundingBox,
const OutlinerBox2D& viewBoundingBox,
enum outlinerdirection directionIn);
/// Add a 3D scene to the optimized index.
void addScene(const aiScene* scene);
/// Add a 3D node to the optimized index.
void addNode(const aiScene* scene,
const aiNode* node);
/// Add a 3D mesh to the optimized index.
void addMesh(const aiScene* scene,
const aiMesh* mesh);
/// Quickly get faces associated with a given (x,y) point in the plan view.
void getFaces(const aiMesh* mesh,
outlinerreal x,
outlinerreal y,
unsigned int* p_nFaces,
const aiFace*** p_faces);
/// Print information about the contents of the mesh
void describe(std::ostream& stream);
/// Release all resources associated with the index.
~IndexedMesh();
private:
unsigned int nMeshes;
unsigned int maxMeshes;
unsigned int subdivisions;
OutlinerBox3D modelBoundingBox;
OutlinerBox2D viewBoundingBox;
enum outlinerdirection direction;
outlinerreal tileSizeX;
outlinerreal tileSizeY;
struct IndexedMeshOneMesh* meshes;
void addFaces(struct IndexedMeshOneMesh& shadow,
const aiScene* scene,
const aiMesh* mesh);
void addFace(struct IndexedMeshOneMesh& shadow,
const aiScene* scene,
const aiMesh* mesh,
const aiFace* face);
void addToTile(struct IndexedMeshOneMesh& shadow,
const aiScene* scene,
const aiMesh* mesh,
const aiFace* face,
unsigned int tileX,
unsigned int tileY);
void getFacesTile(struct IndexedMeshOneMesh& shadow,
const aiMesh* mesh,
unsigned int tileX,
unsigned int tileY,
unsigned int* p_nFaces,
const aiFace*** p_faces);
void coordsToTile(outlinerreal x,
outlinerreal y,
unsigned int& tileX,
unsigned int& tileY);
void getShadow(const aiMesh* mesh,
struct IndexedMeshOneMesh** shadow);
unsigned int minFacesPerTile(struct IndexedMeshOneMesh& shadow,
unsigned int& n);
unsigned int maxFacesPerTile(struct IndexedMeshOneMesh& shadow,
unsigned int& n);
float avgFacesPerTile(struct IndexedMeshOneMesh& shadow);
unsigned int countTilesWithFaces(struct IndexedMeshOneMesh& shadow);
void countFaces(struct IndexedMeshOneMesh& shadow,
unsigned int& nUniqueFaces,
unsigned int& nFacesInTiles);
};
#endif // INDEXEDMESH_HH
| 6,219 | 1,662 |
#include "PrettyPrinter.h"
#include <iostream>
#include <sstream>
void PrettyPrinter::print(ASTProgram *p, std::ostream &os, char c, int n) {
PrettyPrinter visitor(os, c, n);
p->accept(&visitor);
}
void PrettyPrinter::endVisit(ASTProgram * element) {
std::string programString = "";
bool skip = true;
for (auto &fn : element->getFunctions()) {
if (skip) {
programString = visitResults.back() + programString;
visitResults.pop_back();
skip = false;
continue;
}
programString = visitResults.back() + "\n" + programString;
visitResults.pop_back();
}
os << programString;
os.flush();
}
/*
* General approach taken by visit methods.
* - visit() is used to increase indentation (decrease should happen in endVisit).
* - endVisit() should expect a string for all of its AST nodes in reverse order in visitResults.
* Communicate the single string for the visited node by pushing to the back of visitedResults.
*/
/*
* Before visiting function, record string for signature and setup indentation for body.
* This visit method pushes a string result, that the endVisit method should extend.
*/
bool PrettyPrinter::visit(ASTFunction * element) {
indentLevel++;
return true;
}
/*
* After visiting function, collect the string representations for the:
* statements, declarations, formals, and then function name
* they are on the visit stack in that order.
*/
void PrettyPrinter::endVisit(ASTFunction * element) {
std::string bodyString = "";
for (auto &stmt : element->getStmts()) {
bodyString = visitResults.back() + "\n" + bodyString;
visitResults.pop_back();
}
for (auto &decl : element->getDeclarations()) {
bodyString = visitResults.back() + "\n" + bodyString;
visitResults.pop_back();
}
std::string formalsString = "";
bool skip = true;
for(auto &formal : element->getFormals()) {
if (skip) {
formalsString = visitResults.back() + formalsString;
visitResults.pop_back();
skip = false;
continue;
}
formalsString = visitResults.back() + ", " + formalsString;
visitResults.pop_back();
}
// function name is last element on stack
std::string functionString = visitResults.back();
visitResults.pop_back();
functionString += "(" + formalsString + ") \n{\n" + bodyString + "}\n";
indentLevel--;
visitResults.push_back(functionString);
}
void PrettyPrinter::endVisit(ASTNumberExpr * element) {
visitResults.push_back(std::to_string(element->getValue()));
}
void PrettyPrinter::endVisit(ASTVariableExpr * element) {
visitResults.push_back(element->getName());
}
void PrettyPrinter::endVisit(ASTBinaryExpr * element) {
std::string rightString = visitResults.back();
visitResults.pop_back();
std::string leftString = visitResults.back();
visitResults.pop_back();
visitResults.push_back("(" + leftString + " " + element->getOp() + " " + rightString + ")");
}
void PrettyPrinter::endVisit(ASTInputExpr * element) {
visitResults.push_back("input");
}
void PrettyPrinter::endVisit(ASTFunAppExpr * element) {
std::string funAppString;
/*
* Skip printing of comma separator for last arg.
*/
std::string actualsString = "";
bool skip = true;
for (auto &arg : element->getActuals()) {
if (skip) {
actualsString = visitResults.back() + actualsString;
visitResults.pop_back();
skip = false;
continue;
}
actualsString = visitResults.back() + ", " + actualsString;
visitResults.pop_back();
}
funAppString = visitResults.back() + "(" + actualsString + ")";
visitResults.pop_back();
visitResults.push_back(funAppString);
}
void PrettyPrinter::endVisit(ASTAllocExpr * element) {
std::string init = visitResults.back();
visitResults.pop_back();
visitResults.push_back("alloc " + init);
}
void PrettyPrinter::endVisit(ASTRefExpr * element) {
std::string var = visitResults.back();
visitResults.pop_back();
visitResults.push_back("&" + var);
}
void PrettyPrinter::endVisit(ASTDeRefExpr * element) {
std::string base = visitResults.back();
visitResults.pop_back();
visitResults.push_back("*" + base);
}
void PrettyPrinter::endVisit(ASTNullExpr * element) {
visitResults.push_back("null");
}
void PrettyPrinter::endVisit(ASTFieldExpr * element) {
std::string init = visitResults.back();
visitResults.pop_back();
visitResults.push_back(element->getField() + ":" + init);
}
void PrettyPrinter::endVisit(ASTRecordExpr * element) {
/*
* Skip printing of comma separator for last record element.
*/
std::string fieldsString = "";
bool skip = true;
for (auto &f : element->getFields()) {
if (skip) {
fieldsString = visitResults.back() + fieldsString;
visitResults.pop_back();
skip = false;
continue;
}
fieldsString = visitResults.back() + ", " + fieldsString;
visitResults.pop_back();
}
std::string recordString = "{" + fieldsString + "}";
visitResults.push_back(recordString);
}
void PrettyPrinter::endVisit(ASTAccessExpr * element) {
std::string accessString = visitResults.back();
visitResults.pop_back();
visitResults.push_back(accessString + '.' + element->getField());
}
void PrettyPrinter::endVisit(ASTDeclNode * element) {
visitResults.push_back(element->getName());
}
void PrettyPrinter::endVisit(ASTDeclStmt * element) {
std::string declString = "";
bool skip = true;
for (auto &id : element->getVars()) {
if (skip) {
declString = visitResults.back() + declString;
visitResults.pop_back();
skip = false;
continue;
}
declString = visitResults.back() + ", " + declString;
visitResults.pop_back();
}
declString = indent() + "var " + declString + ";";
visitResults.push_back(declString);
}
void PrettyPrinter::endVisit(ASTAssignStmt * element) {
std::string rhsString = visitResults.back();
visitResults.pop_back();
std::string lhsString = visitResults.back();
visitResults.pop_back();
visitResults.push_back(indent() + lhsString + " = " + rhsString + ";");
}
bool PrettyPrinter::visit(ASTBlockStmt * element) {
indentLevel++;
return true;
}
void PrettyPrinter::endVisit(ASTBlockStmt * element) {
std::string stmtsString = "";
for (auto &s : element->getStmts()) {
stmtsString = visitResults.back() + "\n" + stmtsString;
visitResults.pop_back();
}
indentLevel--;
std::string blockString = indent() + "{\n" + stmtsString + indent() + "}";
visitResults.push_back(blockString);
}
/*
* For a while the body should be indented, but not the condition.
* Since conditions are expressions and their visit methods never indent
* incrementing here works.
*/
bool PrettyPrinter::visit(ASTWhileStmt * element) {
indentLevel++;
return true;
}
void PrettyPrinter::endVisit(ASTWhileStmt * element) {
std::string bodyString = visitResults.back();
visitResults.pop_back();
std::string condString = visitResults.back();
visitResults.pop_back();
indentLevel--;
std::string whileString = indent() + "while (" + condString + ") \n" + bodyString;
visitResults.push_back(whileString);
}
bool PrettyPrinter::visit(ASTIfStmt * element) {
indentLevel++;
return true;
}
void PrettyPrinter::endVisit(ASTIfStmt * element) {
std::string elseString;
if (element->getElse() != nullptr) {
elseString = visitResults.back();
visitResults.pop_back();
}
std::string thenString = visitResults.back();
visitResults.pop_back();
std::string condString = visitResults.back();
visitResults.pop_back();
indentLevel--;
std::string ifString = indent() + "if (" + condString + ") \n" + thenString;
if (element->getElse() != nullptr) {
ifString += "\n" + indent() + "else\n" + elseString;
}
visitResults.push_back(ifString);
}
void PrettyPrinter::endVisit(ASTOutputStmt * element) {
std::string argString = visitResults.back();
visitResults.pop_back();
visitResults.push_back(indent() + "output " + argString + ";");
}
void PrettyPrinter::endVisit(ASTErrorStmt * element) {
std::string argString = visitResults.back();
visitResults.pop_back();
visitResults.push_back(indent() + "error " + argString + ";");
}
void PrettyPrinter::endVisit(ASTReturnStmt * element) {
std::string argString = visitResults.back();
visitResults.pop_back();
visitResults.push_back(indent() + "return " + argString + ";");
}
void PrettyPrinter::endVisit(ASTArrayExpr * element) {
/*
* Skip printing of comma separator for last array element.
*/
std::string entriesString = "";
bool skip = true;
for (auto &f : element->getEntries()) {
if (skip) {
entriesString = visitResults.back() + entriesString;
visitResults.pop_back();
skip = false;
continue;
}
entriesString = visitResults.back() + ", " + entriesString;
visitResults.pop_back();
}
std::string arrayString = "[" + entriesString + "]";
visitResults.push_back(arrayString);
}
void PrettyPrinter::endVisit(ASTTernaryExpr * element) {
std::string elseString = visitResults.back();
visitResults.pop_back();
std::string thenString = visitResults.back();
visitResults.pop_back();
std::string condString = visitResults.back();
visitResults.pop_back();
visitResults.push_back("(" + condString + " ? " + thenString + " : " + elseString + ")");
}
void PrettyPrinter::endVisit(ASTElementRefrenceOperatorExpr * element) {
std::string index = visitResults.back();
visitResults.pop_back();
std::string array = visitResults.back();
visitResults.pop_back();
visitResults.push_back("(" + array + "[" + index + "])");
}
void PrettyPrinter::endVisit(ASTArrayLengthExpr * element) {
std::string array = visitResults.back();
visitResults.pop_back();
visitResults.push_back("(#" + array + ")");
}
void PrettyPrinter::endVisit(ASTTrueExpr * element) {
visitResults.push_back("true");
}
void PrettyPrinter::endVisit(ASTFalseExpr * element) {
visitResults.push_back("false");
}
std::string PrettyPrinter::indent() const {
return std::string(indentLevel*indentSize, indentChar);
}
void PrettyPrinter::endVisit(ASTAndExpr * element) {
std::string rightString = visitResults.back();
visitResults.pop_back();
std::string leftString = visitResults.back();
visitResults.pop_back();
visitResults.push_back("(" + leftString + " and " + rightString + ")");
}
void PrettyPrinter::endVisit(ASTDecrementStmt * element) {
std::string e = visitResults.back();
visitResults.pop_back();
visitResults.push_back(indent() + e + "--;");
}
bool PrettyPrinter::visit(ASTForIterStmt * element) {
indentLevel++;
return true;
}
void PrettyPrinter::endVisit(ASTForIterStmt * element) {
std::string bodyString = visitResults.back();
visitResults.pop_back();
std::string right = visitResults.back();
visitResults.pop_back();
std::string left = visitResults.back();
visitResults.pop_back();
indentLevel--;
std::string forString = indent() + "for (" + left + " : " + right + ") \n" + bodyString;
visitResults.push_back(forString);
}
bool PrettyPrinter::visit(ASTForRangeStmt * element) {
indentLevel++;
return true;
}
void PrettyPrinter::endVisit(ASTForRangeStmt * element) {
std::string bodyString = visitResults.back();
visitResults.pop_back();
std::string fourString = "";
if (element->getFour() != nullptr)
{
fourString = visitResults.back();
visitResults.pop_back();
}
std::string three = visitResults.back();
visitResults.pop_back();
std::string two = visitResults.back();
visitResults.pop_back();
std::string one = visitResults.back();
visitResults.pop_back();
indentLevel--;
std::string forString = indent() + "for (" + one + " : " + two + " .. " + three;
if (element->getFour() != nullptr)
{
forString += " by " + fourString;
}
forString += ") \n" + bodyString;
visitResults.push_back(forString);
}
void PrettyPrinter::endVisit(ASTIncrementStmt * element) {
std::string e = visitResults.back();
visitResults.pop_back();
visitResults.push_back(indent() + e + "++;");
}
void PrettyPrinter::endVisit(ASTNegationExpr * element) {
std::string e = visitResults.back();
visitResults.pop_back();
visitResults.push_back("-(" + e + ")");
}
void PrettyPrinter::endVisit(ASTNotExpr * element) {
std::string e = visitResults.back();
visitResults.pop_back();
visitResults.push_back("(not " + e + ")");
}
void PrettyPrinter::endVisit(ASTOfArrayExpr * element) {
std::string rightString = visitResults.back();
visitResults.pop_back();
std::string leftString = visitResults.back();
visitResults.pop_back();
visitResults.push_back("[" + leftString + " of " + rightString + "]");
}
void PrettyPrinter::endVisit(ASTOrExpr * element) {
std::string rightString = visitResults.back();
visitResults.pop_back();
std::string leftString = visitResults.back();
visitResults.pop_back();
visitResults.push_back("(" + leftString + " or " + rightString + ")");
}
| 12,963 | 4,211 |
#pragma once
#include "./AlertDialog.hpp"
namespace android::content
{
class Context;
}
namespace android::os
{
class Bundle;
}
namespace android::widget
{
class TimePicker;
}
namespace android::app
{
class TimePickerDialog : public android::app::AlertDialog
{
public:
// Fields
// QJniObject forward
template<typename ...Ts> explicit TimePickerDialog(const char *className, const char *sig, Ts...agv) : android::app::AlertDialog(className, sig, std::forward<Ts>(agv)...) {}
TimePickerDialog(QJniObject obj);
// Constructors
TimePickerDialog(android::content::Context arg0, JObject arg1, jint arg2, jint arg3, jboolean arg4);
TimePickerDialog(android::content::Context arg0, jint arg1, JObject arg2, jint arg3, jint arg4, jboolean arg5);
// Methods
void onClick(JObject arg0, jint arg1) const;
void onRestoreInstanceState(android::os::Bundle arg0) const;
android::os::Bundle onSaveInstanceState() const;
void onTimeChanged(android::widget::TimePicker arg0, jint arg1, jint arg2) const;
void show() const;
void updateTime(jint arg0, jint arg1) const;
};
} // namespace android::app
| 1,129 | 387 |
#include <cstdio>
#include <vector>
#include <cassert>
#include <algorithm>
const int MAXN = 100001;
const int MAXM = 200001;
const int MAXQ = 100001;
const int MAXT = 600001;
const int MAXI = 3000001;
const int Maxlog = 30;
struct Edge{
int node, next;
}e[MAXM];
struct Query{
int op, x, y, answer;
}q[MAXQ];
struct Trie{
int size, c[MAXI][2], s[MAXI];
int alloc() {
size++;
c[size][0] = c[size][1] = 0;
s[size] = 0;
return size;
}
void clear() {
size = 0;
alloc();
}
void modify(int x, int d) {
for (int i = Maxlog, p = 1; i >= 0; i--) {
int bit = x >> i & 1;
if (!c[p][bit]) c[p][bit] = alloc();
p = c[p][bit];
s[p] += d;
assert(s[p] >= 0);
}
}
int query(int x) {
int ret = 0;
for (int i = Maxlog, p = 1; i >= 0; i--) {
int bit = x >> i & 1 ^ 1;
if (c[p][bit] && s[c[p][bit]]) {
ret |= 1 << i;
p = c[p][bit];
}
else p = c[p][bit ^ 1];
}
return ret;
}
}trie;
struct Tuple{
int first, second, third;
Tuple() {}
Tuple(int first, int second, int third) : first(first), second(second), third(third) {}
};
int T, n, m, t, tot, h[MAXN], oL[MAXN], oR[MAXN], a[MAXN], b[MAXN];
std::vector<Tuple> tree[MAXT];
void update(int &x, int y) {
if (x < y) x = y;
}
void addedge(int x, int y) {
t++; e[t] = (Edge){y, h[x]}; h[x] = t;
}
void dfs(int x) {
oL[x] = ++tot;
for (int i = h[x]; i; i = e[i].next) {
dfs(e[i].node);
}
oR[x] = tot;
}
void cover(int n, int l, int r, int x, int y, const Tuple &p) {
if (r < x || l > y) return;
if (x <= l && r <= y) {
tree[n].push_back(p);
return;
}
cover(n << 1, l, l + r >> 1, x, y, p);
cover(n << 1 ^ 1, (l + r >> 1) + 1, r, x, y, p);
}
void cover(int n, int l, int r, int x, const Tuple &p) {
tree[n].push_back(p);
if (l == r) return;
if (x <= (l + r >> 1)) cover(n << 1, l, l + r >> 1, x, p);
else cover(n << 1 ^ 1, (l + r >> 1) + 1, r, x, p);
}
void travel(int n, int l, int r) {
trie.clear();
for (std::vector<Tuple>::iterator it = tree[n].begin(); it != tree[n].end(); it++) {
if (it -> third) trie.modify(it -> second, it -> third);
else update(q[it -> first].answer, trie.query(it -> second));
}
tree[n].clear();
if (l == r) return;
travel(n << 1, l, l + r >> 1);
travel(n << 1 ^ 1, (l + r >> 1) + 1, r);
}
int main() {
freopen("K.in", "r", stdin);
scanf("%d", &T);
while (T--) {
scanf("%d%d", &n, &m);
t = tot = 0;
std::fill(h + 1, h + n + 1, 0);
for (int i = 2; i <= n; i++) {
int fa; scanf("%d", &fa);
addedge(fa, i);
}
dfs(1);
for (int i = 1; i <= n; i++) {
scanf("%d", a + i);
b[i] = a[i];
cover(1, 1, n, oL[i], oR[i], Tuple(i, a[i], 1));
}
for (int i = 1; i <= m; i++) {
scanf("%d%d", &q[i].op, &q[i].x);
if (q[i].op == 0) {
scanf("%d", &q[i].y);
cover(1, 1, n, oL[q[i].x], oR[q[i].x], Tuple(i, a[q[i].x], -1));
cover(1, 1, n, oL[q[i].x], oR[q[i].x], Tuple(i, a[q[i].x] = q[i].y, 1));
}
else{
cover(1, 1, n, oL[q[i].x], Tuple(i, a[q[i].x], 0));
q[i].answer = 0;
}
}
travel(1, 1, n);
for (int i = 1; i <= m; i++) {
if (q[i].op == 1) {
printf("%d\n", q[i].answer);
}
}
}
return 0;
}
| 3,131 | 1,727 |
#include "lppch.h"
#include "Terrain.h"
#include "Lamp/Core/Application.h"
#include "Lamp/Rendering/Buffers/VertexBuffer.h"
#include "Lamp/Rendering/Shader/ShaderLibrary.h"
#include "Lamp/Rendering/RenderPipeline.h"
#include "Lamp/Rendering/Textures/Texture2D.h"
#include "Lamp/Rendering/Swapchain.h"
#include "Lamp/Rendering/RenderCommand.h"
#include "Lamp/Rendering/Renderer.h"
#include "Lamp/Mesh/Materials/MaterialLibrary.h"
#include "Lamp/Mesh/Mesh.h"
#include "Platform/Vulkan/VulkanDevice.h"
namespace Lamp
{
Terrain::Terrain(const std::filesystem::path& aHeightMap)
{
if (!std::filesystem::exists(aHeightMap))
{
LP_CORE_ERROR("[Terrain]: Unable to load file {0}!", aHeightMap.string());
m_isValid = false;
return;
}
m_heightMap = Texture2D::Create(aHeightMap);
GenerateMeshFromHeightMap();
}
Terrain::Terrain(Ref<Texture2D> heightMap)
{
m_heightMap = heightMap;
GenerateMeshFromHeightMap();
}
Terrain::~Terrain()
{
}
void Terrain::Draw(Ref<RenderPipeline> pipeline)
{
SetupDescriptors(pipeline);
RenderCommand::SubmitMesh(m_mesh, nullptr, m_descriptorSet.descriptorSets, (void*)glm::value_ptr(m_transform));
}
Ref<Terrain> Terrain::Create(const std::filesystem::path& heightMap)
{
return CreateRef<Terrain>(heightMap);
}
Ref<Terrain> Terrain::Create(Ref<Texture2D> heightMap)
{
return CreateRef<Terrain>(heightMap);
}
void Terrain::SetupDescriptors(Ref<RenderPipeline> pipeline)
{
auto vulkanShader = pipeline->GetSpecification().shader;
auto device = VulkanContext::GetCurrentDevice();
const uint32_t currentFrame = Application::Get().GetWindow().GetSwapchain()->GetCurrentFrame();
auto descriptorSet = vulkanShader->CreateDescriptorSets();
std::vector<VkWriteDescriptorSet> writeDescriptors;
auto vulkanUniformBuffer = pipeline->GetSpecification().uniformBufferSets->Get(0, 0, currentFrame);
auto vulkanTerrainBuffer = Renderer::Get().GetStorage().terrainDataBuffer;
writeDescriptors.emplace_back(*vulkanShader->GetDescriptorSet("CameraDataBuffer"));
writeDescriptors[0].dstSet = descriptorSet.descriptorSets[0];
writeDescriptors[0].pBufferInfo = &vulkanUniformBuffer->GetDescriptorInfo();
writeDescriptors.emplace_back(*vulkanShader->GetDescriptorSet("DirectionalLightBuffer"));
writeDescriptors[1].dstSet = descriptorSet.descriptorSets[0];
writeDescriptors[1].pBufferInfo = &vulkanTerrainBuffer->GetDescriptorInfo();
if (m_heightMap)
{
writeDescriptors.emplace_back(*vulkanShader->GetDescriptorSet("u_HeightMap"));
writeDescriptors[2].dstSet = descriptorSet.descriptorSets[0];
writeDescriptors[2].pImageInfo = &m_heightMap->GetDescriptorInfo();
}
auto vulkanScreenUB = pipeline->GetSpecification().uniformBufferSets->Get(3, 0, currentFrame);
writeDescriptors.emplace_back(*vulkanShader->GetDescriptorSet("ScreenDataBuffer"));
writeDescriptors[3].dstSet = descriptorSet.descriptorSets[0];
writeDescriptors[3].pBufferInfo = &vulkanScreenUB->GetDescriptorInfo();
vkUpdateDescriptorSets(device->GetHandle(), (uint32_t)writeDescriptors.size(), writeDescriptors.data(), 0, nullptr);
m_descriptorSet = descriptorSet;
}
void Terrain::GenerateMeshFromHeightMap()
{
std::vector<Vertex> vertices;
std::vector<uint32_t> indices;
const uint32_t patchSize = 64;
const float uvScale = 1.f;
m_scale = m_heightMap->GetHeight() / patchSize;
const uint32_t vertexCount = patchSize * patchSize;
vertices.resize(vertexCount);
const float wx = 2.f;
const float wy = 2.f;
for (uint32_t x = 0; x < patchSize; x++)
{
for (uint32_t y = 0; y < patchSize; y++)
{
uint32_t index = (x + y * patchSize);
vertices[index].position = { x * wx + wx / 2.f - (float)patchSize * wx / 2.f, 0.f, y * wy + wy / 2.f - patchSize * wy / 2.f };
vertices[index].textureCoords = glm::vec2{ (float)x / patchSize, (float)y / patchSize } *uvScale;
}
}
const uint32_t w = patchSize - 1;
const uint32_t indexCount = w * w * 4;
indices.resize(indexCount);
for (uint32_t x = 0; x < w; x++)
{
for (uint32_t y = 0; y < w; y++)
{
uint32_t index = (x + y * w) * 4;
indices[index] = (x + y * patchSize);
indices[index + 1] = (indices[index] + patchSize);
indices[index + 2] = (indices[index + 1] + 1);
indices[index + 3] = (indices[index] + 1);
}
}
for (uint32_t x = 0; x < patchSize; x++)
{
for (uint32_t y = 0; y < patchSize; y++)
{
float heights[3][3];
for (int32_t hx = -1; hx <= 1; hx++)
{
for (int32_t hy = -1; hy <= 1; hy++)
{
heights[hx + 1][hy + 1] = GetHeight(x + hx, y + hy);
}
}
glm::vec3 normal;
normal.x = heights[0][0] - heights[2][0] + 2.f * heights[0][1] - 2.f * heights[2][1] + heights[0][2] - heights[2][2];
normal.y = heights[0][0] + 2.f * heights[1][0] + heights[2][0] - heights[0][2] - 2.f * heights[1][2] - heights[2][2];
normal.y = 0.25f * sqrtf(1.f - normal.x * normal.x - normal.y * normal.y);
vertices[x + y * patchSize].normal = glm::normalize(normal * glm::vec3(2.f, 1.f, 2.f));
}
}
m_mesh = CreateRef<SubMesh>(vertices, indices, 0, "");
m_transform = glm::scale(glm::mat4(1.f), glm::vec3{ 2.f, 1.f, 2.f });
}
float Terrain::GetHeight(uint32_t x, uint32_t y)
{
glm::ivec2 pos = glm::ivec2{ x, y } * glm::ivec2{ m_scale, m_scale };
pos.x = std::max(0, std::min(pos.x, (int)m_heightMap->GetWidth() - 1));
pos.y = std::max(0, std::min(pos.y, (int)m_heightMap->GetWidth() - 1));
pos /= glm::ivec2(m_scale);
auto buffer = m_heightMap->GetData();
return buffer.Read<uint16_t>((pos.x + pos.y * m_heightMap->GetHeight()) * m_scale) / 65535.f;
}
} | 5,648 | 2,461 |
#ifndef COURSE_HPP
#define COURSE_HPP
#include "xstring.hpp"
struct Course
{
lab::xstring code;
lab::xstring name;
bool four_year;
Course(const lab::xstring& code, const lab::xstring& name,
const bool four_year)
:code(code), name(name), four_year(four_year) {}
};
#endif /* COURSE_HPP */
| 351 | 125 |
#include <iostream>
#include <chrono>
using namespace std;
#include "LayerConvolution2D.h"
//////////////////////////////////////////////////////////////////////////////
void compare_im2col()
{
cout << "Comparing im2col() and im2col_LUT():" << endl;
Index iNbSamples=7, inRows = 31, inCols = 23, inChannels = 13, outChannels = 17; // all primes numbers
MatrixFloat mIn, mCol, mColLUT, mIm, mImLUT;
//fill with random data
mIn.resize(iNbSamples, inRows * inCols*inChannels);
mIn.setRandom();
//compare legacy and optimized forward computation
LayerConvolution2D conv2d(inRows, inCols, inChannels, 5, 3, outChannels);
conv2d.im2col(mIn, mCol);
conv2d.im2col_LUT(mIn, mColLUT);
float fMaxDiff = (mCol - mColLUT).cwiseAbs().maxCoeff();
//mIn.resize(iNbSamples*inRows*inChannels, inCols);
//cout << "Image:" << endl << toString(mIn) << endl << endl;
//cout << "Im2Col:" << endl << toString(mCol) << endl << endl;
//cout << "Im2ColLUT:" << endl << toString(mColLUT) << endl << endl;
//testu function
if (fMaxDiff > 1.e-10)
{
cout << "Test failed! MaxDifference = " << fMaxDiff << endl;
exit(-1);
}
else
cout << "Test Succeded. MaxDifference = " << fMaxDiff << endl;
}
//////////////////////////////////////////////////////////////////////////////
void compare_fastlut_slow_computation()
{
cout << "Comparing fastlut and slow computation mode:" << endl;
Index iNbSamples = 7, inRows = 31, inCols = 23, inChannels = 13, outChannels = 17; // all primes numbers
MatrixFloat mIn, mOut, mOutFast, mIm, mImFast;
//fill with random data
mIn.resize(iNbSamples, inRows * inCols*inChannels);
mIn.setRandom();
LayerConvolution2D conv2d(inRows, inCols, inChannels, 5, 3, outChannels);
conv2d.fastLUT = false;
conv2d.forward(mIn, mOut);
conv2d.fastLUT = true;
conv2d.forward(mIn, mOutFast);
conv2d.fastLUT = false;
conv2d.backpropagation(mIn, mOut, mIm);
conv2d.fastLUT = true;
conv2d.backpropagation(mIn, mOutFast, mImFast);
float fMaxDiffOut = (mOut - mOutFast).cwiseAbs().maxCoeff();
float fMaxDiffIm = (mIm - mImFast).cwiseAbs().maxCoeff();
//testu function
if (fMaxDiffOut > 1.e-10)
{
cout << "Test failed! MaxDifferenceOut = " << fMaxDiffOut << endl;
exit(-1);
}
else
cout << "Test Succeded. MaxDifferenceOut = " << fMaxDiffOut << endl;
//testu function
if (fMaxDiffIm > 1.e-6)
{
cout << "Test failed! MaxDifferenceIm = " << fMaxDiffIm << endl;
exit(-1);
}
else
cout << "Test Succeded. MaxDifferenceIm = " << fMaxDiffIm << endl;
}
//////////////////////////////////////////////////////////////////////////////
void simple_image_conv2d()
{
cout << "Simple convolution test:" << endl;
MatrixFloat mIn, mOut, mKernel;
mIn.setZero(5, 5);
mIn(2, 2) = 1;
mIn.resize(1, 5 * 5);
mKernel.setZero(3, 3);
mKernel(1, 0) = 1;
mKernel(1, 1) = 2;
mKernel(1, 2) = 1;
mKernel.resize(1, 3 * 3);
LayerConvolution2D conv2d(5,5,1,3,3,1);
conv2d.weights() = mKernel;
conv2d.forward(mIn, mOut);
mOut.resize(3, 3);
cout << "Image convoluted:" << endl;
cout << toString(mOut) << endl<< endl;
}
//////////////////////////////////////////////////////////////////////////////
void batch_conv2d()
{
cout << "Batch convolution test:" << endl;
MatrixFloat mIn, mOut, mKernel;
mIn.setZero(10, 5);
mIn(2, 2) = 1;
mIn(2+5, 2) = 3;
mIn.resize(2, 5 * 5);
mKernel.setZero(3, 3);
mKernel(1, 0) = 1;
mKernel(1, 1) = 2;
mKernel(1, 2) = 1;
mKernel.resize(1, 3 * 3);
LayerConvolution2D conv2d(5, 5, 1, 3, 3, 1);
conv2d.weights() = mKernel;
conv2d.forward(mIn, mOut);
mOut.resize(6, 3);
cout << "Batch convoluted, 2 samples:" << endl;
cout << toString(mOut) << endl << endl;
}
/////////////////////////////////////////////////////////////////
void image_2_input_channels_conv2d()
{
cout << "Image 2 input channels convolution test:" << endl;
MatrixFloat mIn, mOut, mKernel;
mIn.setZero(10, 5);
mIn(2, 2) = 1;
mIn(2 + 5, 2) = 3;
mIn.resize(1, 2 * 5 * 5);
mKernel.setZero(6, 3);
mKernel(1, 0) = 1;
mKernel(1, 1) = 2;
mKernel(1, 2) = 1;
mKernel(3, 1) = 1;
mKernel(4, 1) = 2;
mKernel(5, 1) = 1;
mKernel.resize(1, 2 * 3 * 3);
LayerConvolution2D conv2d(5, 5, 2, 3, 3, 1);
conv2d.weights() = mKernel;
conv2d.forward(mIn, mOut);
mOut.resize(3, 3);
cout << "Image 2 input channels convoluted:" << endl;
cout << toString(mOut) << endl << endl;
}
/////////////////////////////////////////////////////////////////
void image_2_output_channels_conv2d()
{
cout << "Image 2 ouput channels convolution test:" << endl;
MatrixFloat mIn, mOut, mKernel;
mIn.setZero(5, 5);
mIn(2, 2) = 1;
mIn.resize(1, 5 * 5);
mKernel.setZero(6, 3);
mKernel(1, 0) = 1;
mKernel(1, 1) = 2;
mKernel(1, 2) = 1;
mKernel(3, 1) = 3;
mKernel(4, 1) = 5;
mKernel(5, 1) = 3;
mKernel.resize(2, 3 * 3);
LayerConvolution2D conv2d(5, 5, 1, 3, 3, 2);
conv2d.weights() = mKernel;
conv2d.forward(mIn, mOut);
mOut.resize(6, 3);
cout << "Image 2 output channels convoluted:" << endl;
cout << toString(mOut) << endl << endl;
}
//////////////////////////////////////////////////////////////////////////////
void forward_backward()
{
cout << "Forward then backward test:" << endl;
Index iNbSamples = 5, inRows = 7, inCols = 11, inChannels = 13, outChannels = 17; // all primes numbers
MatrixFloat mIn, mCol, mColLUT, mIm, mImLUT;
//fill with incremented data
mIn.resize(iNbSamples, inRows * inCols * inChannels);
for (Index i = 0; i < mIn.size(); i++)
mIn.data()[i] = (float)i;
//forward and backward
LayerConvolution2D conv2d(inRows, inCols, inChannels, 2, 3, outChannels);
conv2d.forward(mIn, mCol);
conv2d.backpropagation(mIn, mCol, mIm);
cout << "mIm:" << endl << toString(mIm) << endl << endl;
}
//////////////////////////////////////////////////////////////////////////////
void simple_image_conv2d_stride2()
{
cout << "Simple convolution test stride2:" << endl;
MatrixFloat mIn, mOut, mKernel;
mIn.setZero(5, 5);
mIn(0, 0) = 100;
mIn(2, 2) = 122;
mIn(3, 4) = 134;
mIn.resize(1, 5 * 5);
mKernel.setZero(3, 3);
mKernel(0, 0) = 1;
mKernel(0, 1) = 2;
mKernel(0, 2) = 1;
mKernel(1, 0) = 2;
mKernel(1, 1) = 4;
mKernel(1, 2) = 2;
mKernel(2, 0) = 1;
mKernel(2, 1) = 2;
mKernel(2, 2) = 1;
mKernel.resize(1, 3 * 3);
LayerConvolution2D conv2d(5, 5, 1, 3, 3, 1,2,2);
conv2d.weights() = mKernel;
conv2d.forward(mIn, mOut);
mOut.resize(2, 2);
cout << "Image convoluted stride2:" << endl;
cout << toString(mOut) << endl << endl;
}
//////////////////////////////////////////////////////////////////////////////
void forward_conv2d_backprop_sgd()
{
cout << "Forward Conv2D and Backpropagation test:" << endl << endl;
MatrixFloat mIn, mOut, mKernel, mGradientOut, mGradientIn;
mIn.setZero(5, 5);
mIn(2, 2) = 1;
mIn.resize(1, 5 * 5);
mKernel.setZero(3, 3);
mKernel(1, 0) = 1;
mKernel(1, 1) = 2;
mKernel(1, 2) = 1;
mKernel.resize(1, 3 * 3);
LayerConvolution2D conv2d(5, 5, 1, 3, 3, 1);
//forward
conv2d.weights() = mKernel;
conv2d.forward(mIn, mOut);
//backpropagation
mGradientOut = mOut* 0.1f;
mGradientOut(3+1) = -1.f;
conv2d.backpropagation(mIn, mGradientOut, mGradientIn);
//disp forward
mOut.resize(3, 3);
cout << "Forward :" << endl;
cout << toString(mOut) << endl << endl;
//disp backpropagation
conv2d.gradient_weights().resize(3, 3);
cout << "Backprop Weight gradient :" << endl;
cout << toString(conv2d.gradient_weights()) << endl << endl;
mGradientIn.resize(5, 5);
cout << "Backprop Input gradient :" << endl;
cout << toString(mGradientIn) << endl << endl;
}
/////////////////////////////////////////////////////////////////
void forward_stride2_backward()
{
cout << "Forward Conv2D and Backpropagation test:" << endl << endl;
MatrixFloat mIn, mOut, mKernel, mGradientOut, mGradientIn;
mIn.setZero(5, 5);
mIn(2, 2) = 1;
mIn.resize(1, 5 * 5);
mKernel.setZero(3, 3);
mKernel(1, 0) = 1;
mKernel(1, 1) = 2;
mKernel(1, 2) = 1;
mKernel.resize(1, 3 * 3);
LayerConvolution2D conv2d(5, 5, 1, 3, 3, 1, 2, 2);
//forward
conv2d.weights() = mKernel;
conv2d.forward(mIn, mOut);
//backpropagation
mGradientOut = mOut * 0.1f;
mGradientOut(2 + 1) = -1.f;
conv2d.backpropagation(mIn, mGradientOut, mGradientIn);
//disp forward
mOut.resize(2, 2);
cout << "Forward :" << endl;
cout << toString(mOut) << endl << endl;
//disp backpropagation
conv2d.gradient_weights().resize(3, 3);
cout << "Backprop Weight gradient :" << endl;
cout << toString(conv2d.gradient_weights()) << endl << endl;
mGradientIn.resize(5, 5);
cout << "Backprop Input gradient :" << endl;
cout << toString(mGradientIn) << endl << endl;
}
/////////////////////////////////////////////////////////////////
void forward_time()
{
cout << "Forward conv2d time estimation:" << endl;
int iNbSamples = 32;
int iInRows = 64;
int iInCols = 64;
int iInChannels = 16;
int iKernelRows = 3;
int iKernelCols = 3;
int iOutChannels = 32;
int iNbConv = 10;
MatrixFloat mIn;
mIn.setRandom(iNbSamples, iInRows*iInCols*iInChannels);
MatrixFloat mOut;
LayerConvolution2D conv2d(iInRows, iInCols, iInChannels, iKernelRows, iKernelCols, iOutChannels);
//measure forward time slow
conv2d.fastLUT = false;
auto start = chrono::steady_clock::now();
for(int i=0;i< iNbConv;i++)
conv2d.forward(mIn, mOut);
auto end = chrono::steady_clock::now();
auto delta = chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
cout << "Time elapsed slow: " << delta << " ms" << endl;
//measure forward time fastlut
conv2d.fastLUT = true;
start = chrono::steady_clock::now();
for (int i = 0; i < iNbConv; i++)
conv2d.forward(mIn, mOut);
end = chrono::steady_clock::now();
delta = chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
cout << "Time elapsed fastlut: " << delta << " ms" << endl << endl;
}
/////////////////////////////////////////////////////////////////
void backward_time()
{
cout << "Backward conv2d time estimation:" << endl;
int iNbSamples = 32;
int iInRows = 64;
int iInCols = 64;
int iInChannels = 16;
int iKernelRows = 3;
int iKernelCols = 3;
int iOutChannels = 32;
int iNbConv = 10;
MatrixFloat mIn,mOut, mOutGradient, mInGradient;
mIn.setRandom(iNbSamples, iInRows*iInCols*iInChannels);
LayerConvolution2D conv2d(iInRows, iInCols, iInChannels, iKernelRows, iKernelCols, iOutChannels);
conv2d.forward(mIn, mOut); // init backward internal state
//create random gradient
mOutGradient = mOut;
mOutGradient.setRandom();
//measure backward time slow
conv2d.fastLUT = false;
auto start = chrono::steady_clock::now();
for (int i = 0; i < iNbConv; i++)
conv2d.backpropagation(mIn, mOutGradient, mInGradient);
auto end = chrono::steady_clock::now();
auto delta = chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
cout << "Time elapsed slow: " << delta << " ms" << endl;
conv2d.fastLUT = true;
start = chrono::steady_clock::now();
for (int i = 0; i < iNbConv; i++)
conv2d.backpropagation(mIn, mOutGradient, mInGradient);
end = chrono::steady_clock::now();
delta = chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
cout << "Time elapsed fast: " << delta << " ms" << endl << endl;
}
/////////////////////////////////////////////////////////////////
int main()
{
compare_im2col();
compare_fastlut_slow_computation();
simple_image_conv2d();
batch_conv2d();
image_2_input_channels_conv2d();
image_2_output_channels_conv2d();
simple_image_conv2d_stride2();
forward_conv2d_backprop_sgd();
simple_image_conv2d_stride2();
forward_backward();
forward_stride2_backward();
forward_time();
backward_time();
}
/////////////////////////////////////////////////////////////////
| 11,641 | 5,070 |
#ifndef OPENJIJ_UTILITY_CREATE_GEOMETRIC_PROGRESSION_HPP__
#define OPENJIJ_UTILITY_CREATE_GEOMETRIC_PROGRESSION_HPP__
namespace openjij {
namespace utility {
template<typename ForwardIterator, typename T>
void make_geometric_progression(ForwardIterator first, ForwardIterator last, T value, T ratio) {
for(;first != last; ++first) {
*first = value;
value *= ratio;
}
}
} // namespace utility
} // namespace openjij
#endif
| 513 | 165 |
#include <bitsery/bitsery.h>
#include <bitsery/adapter/buffer.h>
//include flexible header, to use flexible syntax
#include <bitsery/flexible.h>
//we also need additional traits to work with container types,
//instead of including <bitsery/traits/vector.h> for vector traits, now we also need traits to work with flexible types.
//so include everything from <bitsery/flexible/...> instead of <bitsery/traits/...>
//otherwise we'll get static assert error, saying to define serialize function.
#include <bitsery/flexible/vector.h>
enum class MyEnum : uint16_t {
V1, V2, V3
};
struct MyStruct {
uint32_t i;
MyEnum e;
std::vector<float> fs;
//define serialize function as usual
template<typename S>
void serialize(S &s)
{
//now we can use flexible syntax with
s.archive(i, e, fs);
}
};
using namespace bitsery;
//some helper types
using Buffer = std::vector<uint8_t>;
using OutputAdapter = OutputBufferAdapter<Buffer>;
using InputAdapter = InputBufferAdapter<Buffer>;
int main()
{
//set some random data
MyStruct data{8941, MyEnum::V2, {15.0f, -8.5f, 0.045f}};
MyStruct res{};
//serialization, deserialization flow is unchanged as in basic usage
Buffer buffer;
auto writtenSize = quickSerialization<OutputAdapter>(buffer, data);
auto state = quickDeserialization<InputAdapter>({buffer.begin(), writtenSize}, res);
assert(state.first == ReaderError::NoError && state.second);
assert(data.fs == res.fs && data.i == res.i && data.e == res.e);
}
| 1,562 | 502 |
#include "Southpole.hpp"
struct Pulse : Module {
enum ParamIds {
TRIG_PARAM,
REPEAT_PARAM,
RESET_PARAM,
RANGE_PARAM,
DELAY_PARAM,
TIME_PARAM,
AMP_PARAM,
// OFFSET_PARAM,
SLEW_PARAM,
NUM_PARAMS
};
enum InputIds {
TRIG_INPUT,
CLOCK_INPUT,
// REPEAT_INPUT,
// RESET_INPUT,
DELAY_INPUT,
TIME_INPUT,
AMP_INPUT,
// OFFSET_INPUT,
SLEW_INPUT,
NUM_INPUTS
};
enum OutputIds {
CLOCK_OUTPUT,
GATE_OUTPUT,
EOC_OUTPUT,
NUM_OUTPUTS
};
enum LightIds {
EOC_LIGHT,
GATE_LIGHT,
NUM_LIGHTS
};
dsp::SchmittTrigger clock;
dsp::SchmittTrigger trigger;
dsp::SchmittTrigger triggerBtn;
dsp::PulseGenerator clkPulse;
dsp::PulseGenerator eocPulse;
unsigned long delayt = 0;
unsigned long gatet = 0;
unsigned long clockt = 0;
unsigned long clockp = 0;
unsigned long delayTarget = 0;
unsigned long gateTarget = 0;
float level = 0;
bool reset = true;
bool repeat = false;
bool range = false;
bool gateOn = false;
bool delayOn = false;
float amp;
float slew;
static const int ndurations = 12;
const float durations[ndurations] = {
1 / 256., 1 / 128., 1 / 64., 1 / 32., 1 / 16., 1 / 8., 3. / 16., 1 / 4., 1 / 3., 1 / 2., 3. / 4., .99
//,2.,3.,4. //,5.,6.,7.,8.,12.,16.
};
Pulse() {
config(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS);
configParam(Pulse::TRIG_PARAM, 0.0, 1.0, 0., "");
configParam(Pulse::RESET_PARAM, 0.0, 1.0, 0.0, "");
configParam(Pulse::REPEAT_PARAM, 0.0, 1.0, 0.0, "");
configParam(Pulse::RANGE_PARAM, 0.0, 1.0, 0.0, "");
configParam(Pulse::TIME_PARAM, 0.0, 1.0, 0.0, "");
configParam(Pulse::DELAY_PARAM, 0.0, 1.0, 0.0, "");
configParam(Pulse::AMP_PARAM, 0.0, 1.0, 1.0, "");
configParam(Pulse::SLEW_PARAM, 0.0, 1.0, 0., "");
}
void process(const ProcessArgs &args) override;
};
void Pulse::process(const ProcessArgs &args) {
bool triggered = false;
reset = params[RESET_PARAM].getValue();
repeat = params[REPEAT_PARAM].getValue();
range = params[RANGE_PARAM].getValue();
if (triggerBtn.process(params[TRIG_PARAM].getValue())) {
triggered = true;
}
if (trigger.process(inputs[TRIG_INPUT].getNormalVoltage(0.))) {
triggered = true;
//printf("%lu\n", gateTarget);
}
if (clock.process(inputs[CLOCK_INPUT].getNormalVoltage(0.))) {
triggered = true;
clkPulse.trigger(1e-3);
clockp = clockt;
clockt = 0;
}
float dt = 1e-3 * args.sampleRate;
float sr = args.sampleRate;
amp = clamp(params[AMP_PARAM].getValue() + inputs[AMP_INPUT].getNormalVoltage(0.) / 10.0f, 0.0f, 1.0f);
slew = clamp(params[SLEW_PARAM].getValue() + inputs[SLEW_INPUT].getNormalVoltage(0.) / 10.0f, 0.0f, 1.0f);
slew = pow(2., (1. - slew) * log2(sr)) / sr;
if (range)
slew *= .1;
float delayTarget_ = clamp(params[DELAY_PARAM].getValue() + inputs[DELAY_INPUT].getNormalVoltage(0.) / 10.0f, 0.0f, 1.0f);
float gateTarget_ = clamp(params[TIME_PARAM].getValue() + inputs[TIME_INPUT].getNormalVoltage(0.) / 10.0f, 0.0f, 1.0f);
if (inputs[CLOCK_INPUT].isConnected()) {
clockt++;
delayTarget = clockp * durations[int((ndurations - 1) * delayTarget_)];
gateTarget = clockp * durations[int((ndurations - 1) * gateTarget_)];
if (gateTarget < dt)
gateTarget = dt;
} else {
unsigned int r = range ? 10 : 1;
delayTarget = r * delayTarget_ * sr;
gateTarget = r * gateTarget_ * sr + dt;
}
if (triggered && (reset || !gateOn || !delayOn)) {
delayt = 0;
delayOn = true;
gateOn = false;
}
if (delayOn) {
if (delayt < delayTarget) {
delayt++;
} else {
delayOn = false;
gateOn = true;
gatet = 0;
}
}
if (gateOn) {
if (gatet < gateTarget) {
gatet++;
} else {
eocPulse.trigger(1e-3);
gateOn = false;
if (repeat) {
delayt = 0;
delayOn = true;
}
}
if (level < 1.)
level += slew;
if (level > 1.)
level = 1.;
} else {
if (level > 0.)
level -= slew;
if (level < 0.)
level = 0.;
}
outputs[CLOCK_OUTPUT].setVoltage(10. * clkPulse.process(1.0 / args.sampleRate));
outputs[EOC_OUTPUT].value = 10. * eocPulse.process(1.0 / args.sampleRate);
outputs[GATE_OUTPUT].value = clamp(10.f * level * amp, -10.f, 10.f);
lights[EOC_LIGHT].setSmoothBrightness(outputs[EOC_OUTPUT].value, args.sampleTime);
lights[GATE_LIGHT].setSmoothBrightness(outputs[GATE_OUTPUT].value, args.sampleTime);
}
struct PulseWidget : ModuleWidget {
PulseWidget(Module *module) {
setModule(module);
box.size = Vec(15 * 4, 380);
setPanel(APP->window->loadSvg(asset::plugin(pluginInstance, "res/Pulse.svg")));
const float x1 = 5.;
const float x2 = 35.;
const float y1 = 40.;
const float yh = 35.;
addInput(createInput<sp_Port>(Vec(x1, y1 + 0 * yh), module, Pulse::CLOCK_INPUT));
addOutput(createOutput<sp_Port>(Vec(x2, y1 + 0 * yh), module, Pulse::CLOCK_OUTPUT));
addInput(createInput<sp_Port>(Vec(x1, y1 + 1 * yh), module, Pulse::TRIG_INPUT));
addParam(createParam<TL1105>(Vec(x2, y1 + 1 * yh), module, Pulse::TRIG_PARAM));
addParam(createParam<sp_Switch>(Vec(x1, y1 + 1.75 * yh), module, Pulse::RESET_PARAM));
addParam(createParam<sp_Switch>(Vec(x1, y1 + 2.25 * yh), module, Pulse::REPEAT_PARAM));
addParam(createParam<sp_Switch>(Vec(x1, y1 + 2.75 * yh), module, Pulse::RANGE_PARAM));
addInput(createInput<sp_Port>(Vec(x1, y1 + 4 * yh), module, Pulse::TIME_INPUT));
addParam(createParam<sp_SmallBlackKnob>(Vec(x2, y1 + 4 * yh), module, Pulse::TIME_PARAM));
addInput(createInput<sp_Port>(Vec(x1, y1 + 5 * yh), module, Pulse::DELAY_INPUT));
addParam(createParam<sp_SmallBlackKnob>(Vec(x2, y1 + 5 * yh), module, Pulse::DELAY_PARAM));
addInput(createInput<sp_Port>(Vec(x1, y1 + 6 * yh), module, Pulse::AMP_INPUT));
addParam(createParam<sp_SmallBlackKnob>(Vec(x2, y1 + 6 * yh), module, Pulse::AMP_PARAM));
//addInput(createInput<sp_Port> (Vec(x1, y1+7*yh), module, Pulse::OFFSET_INPUT));
//addParam(createParam<sp_SmallBlackKnob>(Vec(x2, y1+7*yh), module, Pulse::OFFSET_PARAM));
addInput(createInput<sp_Port>(Vec(x1, y1 + 7 * yh), module, Pulse::SLEW_INPUT));
addParam(createParam<sp_SmallBlackKnob>(Vec(x2, y1 + 7 * yh), module, Pulse::SLEW_PARAM));
addOutput(createOutput<sp_Port>(Vec(x1, y1 + 8.25 * yh), module, Pulse::EOC_OUTPUT));
addOutput(createOutput<sp_Port>(Vec(x2, y1 + 8.25 * yh), module, Pulse::GATE_OUTPUT));
addChild(createLight<SmallLight<RedLight>>(Vec(x1 + 7, y1 + 7.65 * yh), module, Pulse::EOC_LIGHT));
addChild(createLight<SmallLight<RedLight>>(Vec(x2 + 7, y1 + 7.65 * yh), module, Pulse::GATE_LIGHT));
}
};
Model *modelPulse = createModel<Pulse, PulseWidget>("Pulse");
| 6,846 | 2,988 |
/*/
* Project: Wireless Proximity Analyzer
*
* Repository: https://github.com/ForensicTools/WirelessProximityMonitor_474-2135_Pittner-Sirianni-Swerling
*
* Authors:
* Joe Sirianni
* Cal Pittner
* Ross Swerling
*
* License: Apache v2
/*/
#include "filter.h"
//Static lists of user input strings
static const std::string days[7] =
{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
static const std::string weekEnds[2] = {"Sat", "Sun"};
static const std::string weekDays[5] =
{"Mon", "Tue", "Wed", "Thu", "Fri"};
static const std::string months[12] =
{"Jan", "Feb", "Mar", "Apr", "May","Jun",
"Jul","Aug","Sep", "Oct", "Nov", "Dec"};
static const std::string filterCommands[6] =
{"time", "date", "days", "months", "dbm", "uniqMac"};
FILTER::FILTER() {
clearFilter();
}
FILTER::~FILTER() {
}
bool FILTER::filterPacket(packet_structure packet,
std::list<packet_structure> packetList) {
//Default answer is don't filter packet
bool answer = false;
//Structures for date and time
time_t epoch_time = packet.epoch_time;
struct tm *ptm = gmtime (&epoch_time);
if(filterTime == true) {
std::stringstream timeSs;
timeSs << std::setfill('0');
//Time in readable format
timeSs << std::setw(2) << static_cast<unsigned>(ptm->tm_hour);
timeSs << ":";
timeSs << std::setw(2) << static_cast<unsigned>(ptm->tm_min);
timeSs << ":";
timeSs << std::setw(2) << static_cast<unsigned>(ptm->tm_sec);
//Checks if packet time within specified filter range
if(startTime.compare(endTime) < 0)
if((timeSs.str()).compare(startTime) < 0 ||
(timeSs.str()).compare(endTime) > 0)
answer = true;
//If start time is greater than end
//It must extend into next day
else if(startTime.compare(endTime) > 0)
if((timeSs.str()).compare(startTime) > 0 ||
(timeSs.str()).compare(endTime) < 0)
answer = true;
else {
if((timeSs.str()).compare(startTime) != 0)
answer = true;
}
}
if(filterDate == true && answer == false) {
std::stringstream dateSs;
dateSs << std::setfill('0');
//Date in readable format
dateSs << std::setw(4) << static_cast<unsigned>(ptm->tm_year+1900);
dateSs << "/";
dateSs << std::setw(2) << static_cast<unsigned>(ptm->tm_mon+1);
dateSs << "/";
dateSs << std::setw(2) << static_cast<unsigned>(ptm->tm_mday);
//Checks if it is with in the allowable filter date
if(startDate.compare(endDate) < 0)
if((dateSs.str()).compare(startDate) < 0 ||
(dateSs.str()).compare(endDate) > 0)
answer = true;
else if(startDate.compare(endDate) > 0)
if((dateSs.str()).compare(startDate) > 0 ||
(dateSs.str()).compare(endDate) < 0)
answer = true;
else
if((dateSs.str()).compare(startDate) != 0)
answer = true;
}
if(filterDay == true && answer == false) {
//Sets fiter to true
answer = true;
for(int i = 0; i <= (matchDays.size() - 1); i++) {
//If packet day matches an allowed day
//Filter is set back to false
if(matchDays[i] == days[ptm->tm_wday]) {
answer = false;
break;
}
}
}
if(filterMonth == true && answer == false) {
//Sets filter to true
answer = true;
for(int i = 0; i <= (matchMonths.size()-1); i++) {
//If packet month matches an allowed month
//Filter is set back to true
if(matchMonths[i] == months[ptm->tm_mon]) {
answer = false;
break;
}
}
}
if(filterDbm == true && answer == false) {
//Checks if dBm is within allowable filter rnage
if(minDbm < packet.dbm || maxDbm > packet.dbm)
answer=true;
}
if(uniqMac == true && answer == false) {
//Checks packet MAC against all packets in the display filter list
for(std::list<packet_structure>::iterator it = packetList.begin();
it != packetList.end(); it++) {
if((it->mac).compare(packet.mac) == 0) {
answer = true;
break;
}
}
}
if( (blackList == true || whiteList == true) && answer == false) {
if(whiteList == true)
answer = true;
//Checks packet MAC against all packets in the MAC list
for(std::list<packet_structure>::iterator it = macList.begin();
it != macList.end(); it++) {
if((it->mac).compare(packet.mac) == 0) {
answer = !answer; //Tricky thinking
break;
}
}
}
if( macMono == true && answer == false) {
if((macAddr).compare(packet.mac) != 0)
answer = true;
}
return answer;
}
bool FILTER::setFilter(std::string filter) {
//Clears variables before setting them
clearFilter();
//Initializes Syntax as good
bool syntaxCheck = true;
std::stringstream ss(filter); //Separates commands by spaces
std::istringstream intConv; //Used for converting string numbers to type int
std::string buff; //General string buffer
std::string args; //Holds arguments for commands
std::vector<std::string> commands; //Holds all commands
//Separates commands by spaces and inputs them into list
while(ss >> buff) {
commands.push_back(buff);
}
//Parse each command
if(commands.size() != 0)
for(int i = 0; i <= (commands.size() - 1); i++) {
buff.clear();
args.clear();
//Initial syntax check for '='; All commands should have this
if((commands[i]).find_first_of("=") == std::string::npos) {
syntaxCheck = false;
break;
}
else //Split command into filter type and value
for(size_t q = 0; q <= commands[i].find_first_of("=") - 1; q++)
buff += commands[i].at(q);
for(int q = commands[i].find_first_of("=") + 1;
q <= ((commands[i]).size()-1); q++)
args += commands[i].at(q);
//Input values into variables
if(buff.compare("time" ) == 0) {
//Synatx check
if(args.find_first_of("-")==std::string::npos) {
syntaxCheck = false;
break;
}
else { //Split start and end time
filterTime = true;
for(int q = 0; q <= args.find_first_of("-") - 1; q++)
startTime += args.at(q);
for(int q = args.find_first_of("-") + 1;
q <= (args.size()-1); q++)
endTime += args.at(q);
}
}
else if(buff.compare("date") == 0) {
//Syntax check
if(args.find_first_of("-")==std::string::npos) {
syntaxCheck = false;
break;
}
else { //Split start and end date
filterDate = true;
for(int q = 0; q <= args.find_first_of("-"); q++)
startDate += args.at(q);
for(int q = args.find_first_of("-") + 1;
q <= (args.size()-1); q++)
endDate += args.at(q);
}
}
else if(buff.compare("days") == 0) {
filterDay = true;
//Relplaces commas with spaces
for(size_t q = args.find_first_of(",");
q != std::string::npos; q = args.find_first_of(",", ++q)) {
args[q] = ' ';
}
buff.clear();
ss.clear();
ss.str(args);
//Puts days into vector based on spaces
while(ss >> buff)
matchDays.push_back(buff);
}
else if(buff.compare("months") == 0) {
filterMonth = true;
//Replaces commas with spaces
for(size_t q = args.find_first_of(",");
q != std::string::npos; q = args.find_first_of(",", ++q)) {
args[q] = ' ';
}
buff.clear();
ss.clear();
ss.str(args);
//Puts days into vector based on spaces
while(ss >> buff)
matchMonths.push_back(buff);
}
else if(buff.compare("dbm") == 0) {
//Inital syntax check
if(args.find_first_of("-") == std::string::npos) {
syntaxCheck = false;
break;
}
else {
buff.clear();
//Gets Min dBm value
for(int q = 0; q <= args.find_first_of("-") - 1; q++)
buff += args.at(q);
intConv.clear();
intConv.str(buff);
intConv >> minDbm; //Convert to int
buff.clear();
//Gets Max dBm value
for(int q = args.find_first_of("-") + 1;
q <= (args.size()-1); q++)
buff += args.at(q);
intConv.clear();
intConv.str(buff);
intConv >> maxDbm; //Convert to int
}
//Syntax check for Min lt Max
if(minDbm > maxDbm)
syntaxCheck = false;
else { //Converts numbers to negative
minDbm *= - 1;
maxDbm *= - 1;
filterDbm = true;
}
}
else if(buff.compare("uniqMac") == 0) {
//Syntax checks
if(args.compare("true") == 0)
uniqMac = true;
else if(args.compare("false") != 0) {
syntaxCheck = false;
break;
}
}
else if(buff.compare("blackList") == 0 || buff.compare("whiteList") == 0) {
ReadWrite open;
open.readFromFile(args.c_str(), &macList);
if( buff.compare("blackList") == 0 )
blackList=true;
else
whiteList=true;
if( blackList == true && whiteList == true) {
syntaxCheck = false;
break;
}
}
else if(buff.compare("mac") == 0) {
macMono = true;
macAddr = args.c_str();
}
else {
syntaxCheck = false;
break;
}
}
return syntaxCheck;
}
void FILTER::clearFilter() {
//Clear variables & sets filter checks to false
filterTime = false;
startTime.clear();
endTime.clear();
filterDate = false;
startDate.clear();
endDate.clear();
filterDay = false;
matchDays.clear();
filterMonth = false;
matchMonths.clear();
filterDbm = false;
maxDbm = 0;
minDbm = 0;
uniqMac = false;
macMono = false;
macAddr.clear();
blackList = false;
whiteList = false;
macList.clear();
} | 9,012 | 3,921 |
#include <sstream>
#include <stdio.h>
#include <string>
#include <cstring>
#include <iostream>
#include <vector>
#include <map>
#include <stack>
#include <queue>
#include <cmath>
#include <algorithm>
#include <cfloat>
#include <climits>
//#include <unordered_map>
using namespace std;
/*
Time Complexity : O(n)
Space Complexity : O(n)
Trick:
since it requires max gap between sorted elements, so we need to sort it anyway.
Trick is to use Bucket Sort!
Since they are all int, maxElem - minElem should be more than 1, avg gap is bucketSize=(maxElem - minElem)/size
what we need is the max one, no need to calculate every gap, just those above avg.
Special Cases :
Summary:
memset() : Value to be set. The value is passed as an int,
but the function fills the block of memory using the unsigned char conversion of this value.
*/
class Solution {
public:
int maximumGap(vector<int> &num) {
int result = 0;
if(num.size() == 0){
return result;
}
//get the min and max of the array
int minElem = num[0];
int maxElem = num[0];
for(int i=1; i<num.size(); i++){
if(num[i] > maxElem){
maxElem = num[i];
}else if(num[i] < minElem){
minElem = num[i];
}
}
//init bucket sort
int bucketSize = max(1, (maxElem - minElem)/(int)num.size());
int bucketNum = (maxElem - minElem)/bucketSize + 1;
int bucketMin[bucketNum];
int bucketMax[bucketNum];
for(int i=0; i<bucketNum; i++){
bucketMin[i] = maxElem+1;
bucketMax[i] = minElem-1;
}
for(int i=0; i<num.size(); i++){
int pos = (num[i] - minElem)/bucketSize;
// cout<<"before :"<<bucketMin[pos]<<", "<<bucketMax[pos]<<endl;
if(bucketMin[pos] > num[i]){
bucketMin[pos] = num[i];
}
if(bucketMax[pos] < num[i]){
bucketMax[pos] = num[i];
}
// cout<<bucketMin[pos]<<", "<<bucketMax[pos]<<endl;
}
//caculate max gap
int lastMax = bucketMax[0];
for(int i=0; i<bucketNum; i++){
// cout<<bucketMin[i]<<", "<<bucketMax[i]<<endl;
if(bucketMin[i] != maxElem+1){
result = max(result, bucketMin[i]-lastMax);
lastMax = bucketMax[i];
}
}
return result;
}
};
int main(){
vector<int> input;
input.push_back(1);
input.push_back(10000000);
Solution test;
cout<<test.maximumGap(input)<<endl;
return 0;
} | 2,642 | 898 |
void AESState::expand_generic(const uint8_t* key, std::size_t len) {
uint32_t nk = (len / 4);
uint32_t n = num_rounds * 4;
for (uint32_t i = 0; i < nk; ++i) {
enc.u32[i] = RBE32(key, i);
}
for (uint32_t i = nk; i < n; ++i) {
uint32_t temp = enc.u32[i - 1];
uint32_t p = (i / nk);
uint32_t q = (i % nk);
if (q == 0) {
temp = S0(ROL32(temp, 8)) ^ (uint32_t(POW_X[p - 1]) << 24);
} else if (nk == 8 && q == 4) {
temp = S0(temp);
}
enc.u32[i] = enc.u32[i - nk] ^ temp;
}
for (uint32_t i = 0; i < n; i += 4) {
uint32_t ei = n - (i + 4);
for (uint32_t j = 0; j < 4; ++j) {
uint32_t x = enc.u32[ei + j];
if (i > 0 && (i + 4) < n) {
x = TD(S0(x));
}
dec.u32[i + j] = x;
}
}
}
void AESState::encrypt_generic(uint8_t* dst, const uint8_t* src,
std::size_t len) const {
uint32_t s0, s1, s2, s3;
uint32_t t0, t1, t2, t3;
uint32_t index;
while (len >= 16) {
// Round 1: just XOR
s0 = enc.u32[0] ^ RBE32(src, 0);
s1 = enc.u32[1] ^ RBE32(src, 1);
s2 = enc.u32[2] ^ RBE32(src, 2);
s3 = enc.u32[3] ^ RBE32(src, 3);
// Rounds 2 .. N - 1: shuffle and XOR
index = 4;
for (uint32_t i = 2; i < num_rounds; ++i) {
t0 = s0;
t1 = s1;
t2 = s2;
t3 = s3;
s0 = enc.u32[index + 0] ^ TE(t0, t1, t2, t3);
s1 = enc.u32[index + 1] ^ TE(t1, t2, t3, t0);
s2 = enc.u32[index + 2] ^ TE(t2, t3, t0, t1);
s3 = enc.u32[index + 3] ^ TE(t3, t0, t1, t2);
index += 4;
}
// Round N: S-box and XOR
t0 = s0;
t1 = s1;
t2 = s2;
t3 = s3;
s0 = enc.u32[index + 0] ^ S0(t0, t1, t2, t3);
s1 = enc.u32[index + 1] ^ S0(t1, t2, t3, t0);
s2 = enc.u32[index + 2] ^ S0(t2, t3, t0, t1);
s3 = enc.u32[index + 3] ^ S0(t3, t0, t1, t2);
WBE32(dst, 0, s0);
WBE32(dst, 1, s1);
WBE32(dst, 2, s2);
WBE32(dst, 3, s3);
src += 16;
dst += 16;
len -= 16;
}
DCHECK_EQ(len, 0U);
}
void AESState::decrypt_generic(uint8_t* dst, const uint8_t* src,
std::size_t len) const {
while (len >= 16) {
// Round 1: just XOR
uint32_t s0 = dec.u32[0] ^ RBE32(src, 0);
uint32_t s1 = dec.u32[1] ^ RBE32(src, 1);
uint32_t s2 = dec.u32[2] ^ RBE32(src, 2);
uint32_t s3 = dec.u32[3] ^ RBE32(src, 3);
uint32_t t0, t1, t2, t3;
// Rounds 2 .. N - 1: shuffle and XOR
uint32_t i = 4;
for (uint32_t round = 2; round < num_rounds; ++round) {
t0 = s0;
t1 = s1;
t2 = s2;
t3 = s3;
s0 = dec.u32[i + 0] ^ TD(t0, t3, t2, t1);
s1 = dec.u32[i + 1] ^ TD(t1, t0, t3, t2);
s2 = dec.u32[i + 2] ^ TD(t2, t1, t0, t3);
s3 = dec.u32[i + 3] ^ TD(t3, t2, t1, t0);
i += 4;
}
// Round N: S-box and XOR
t0 = s0;
t1 = s1;
t2 = s2;
t3 = s3;
s0 = dec.u32[i + 0] ^ S1(t0, t3, t2, t1);
s1 = dec.u32[i + 1] ^ S1(t1, t0, t3, t2);
s2 = dec.u32[i + 2] ^ S1(t2, t1, t0, t3);
s3 = dec.u32[i + 3] ^ S1(t3, t2, t1, t0);
WBE32(dst, 0, s0);
WBE32(dst, 1, s1);
WBE32(dst, 2, s2);
WBE32(dst, 3, s3);
src += 16;
dst += 16;
len -= 16;
}
DCHECK_EQ(len, 0U);
}
| 3,223 | 1,827 |
// This file is part of RAVL, Recognition And Vision Library
// Copyright (C) 2002, University of Surrey
// This code may be redistributed under the terms of the GNU Lesser
// General Public License (LGPL). See the lgpl.licence file for details or
// see http://www.gnu.org/copyleft/lesser.html
// file-header-ends-here
#ifndef RAVL_ARC2D_HEADER
#define RAVL_ARC2D_HEADER 1
////////////////////////////////////////////////////////////
//! userlevel=Normal
//! author="Charles Galambos"
//! date="10/3/1997"
//! docentry="Ravl.API.Math.Geometry.2D"
//! rcsid="$Id: Arc2d.hh 5240 2005-12-06 17:16:50Z plugger $"
//! lib=RavlMath
//! file="Ravl/Math/Geometry/Euclidean/2D/Arc2d.hh"
#include "Ravl/Circle2d.hh"
namespace RavlN {
//: This class implements 2d circular arcs.
class Arc2dC : public Circle2dC {
public:
inline Arc2dC() {
ends[0] = 0;
ends[1] = 0;
}
//: Default constructor.
bool FitLSQ(const Array1dC<Point2dC> &points,RealT &residual);
//: Fit points to a circle.
// 'residual' is from the least squares fit and can be used to assess the quality of the
// fit. Assumes the points are ordered around the arc.
// Returns false if fit failed.
inline RealT &StartAngle()
{ return ends[0]; }
//: Start angle of arc, which proccedes clockwise.
inline RealT StartAngle() const
{ return ends[0]; }
//: Start angle of arc, which proccedes clockwise.
inline RealT &EndAngle()
{ return ends[1]; }
//: End angle of arc, which proccedes clockwise.
inline RealT EndAngle() const
{ return ends[1]; }
//: End angle of arc, which proccedes clockwise.
bool Fit(const Point2dC &p1,const Point2dC &p2,const Point2dC &p3);
//: Fit a circle through 3 points.
// Returns false if the points are collinear.
private:
RealT ends[2];
};
}
#endif
| 1,891 | 691 |
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#pragma once
namespace JPH {
Mat44 Body::GetWorldTransform() const
{
JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sPositionAccess, BodyAccess::EAccess::Read));
return Mat44::sRotationTranslation(mRotation, GetPosition());
}
Mat44 Body::GetCenterOfMassTransform() const
{
JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sPositionAccess, BodyAccess::EAccess::Read));
return Mat44::sRotationTranslation(mRotation, mPosition);
}
Mat44 Body::GetInverseCenterOfMassTransform() const
{
JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sPositionAccess, BodyAccess::EAccess::Read));
return Mat44::sInverseRotationTranslation(mRotation, mPosition);
}
inline bool Body::sFindCollidingPairsCanCollide(const Body &inBody1, const Body &inBody2)
{
// One of these conditions must be true
// - One of the bodies must be dynamic to collide
// - A kinematic object can collide with a sensor
if ((!inBody1.IsDynamic() && !inBody2.IsDynamic())
&& !(inBody1.IsKinematic() && inBody2.IsSensor()))
return false;
// Check that body 1 is active
uint32 body1_index_in_active_bodies = inBody1.GetIndexInActiveBodiesInternal();
JPH_ASSERT(!inBody1.IsStatic() && body1_index_in_active_bodies != Body::cInactiveIndex, "This function assumes that Body 1 is active");
// If the pair A, B collides we need to ensure that the pair B, A does not collide or else we will handle the collision twice.
// If A is the same body as B we don't want to collide (1)
// If A is dynamic and B is static we should collide (2)
// If A is dynamic / kinematic and B is dynamic / kinematic we should only collide if (kinematic vs kinematic is ruled out by the if above)
// - A is active and B is not yet active (3)
// - A is active and B will become active during this simulation step (4)
// - A is active and B is active, we require a condition that makes A, B collide and B, A not (5)
//
// In order to implement this we use the index in the active body list and make use of the fact that
// a body not in the active list has Body.Index = 0xffffffff which is the highest possible value for an uint32.
//
// Because we know that A is active we know that A.Index != 0xffffffff:
// (1) Because A.Index != 0xffffffff, if A.Index = B.Index then A = B, so to collide A.Index != B.Index
// (2) A.Index != 0xffffffff, B.Index = 0xffffffff (because it's static and cannot be in the active list), so to collide A.Index != B.Index
// (3) A.Index != 0xffffffff, B.Index = 0xffffffff (because it's not yet active), so to collide A.Index != B.Index
// (4) A.Index != 0xffffffff, B.Index = 0xffffffff currently. But it can activate during the Broad/NarrowPhase step at which point it
// will be added to the end of the active list which will make B.Index > A.Index (this holds only true when we don't deactivate
// bodies during the Broad/NarrowPhase step), so to collide A.Index < B.Index.
// (5) As tie breaker we can use the same condition A.Index < B.Index to collide, this means that if A, B collides then B, A won't
static_assert(Body::cInactiveIndex == 0xffffffff, "The algorithm below uses this value");
if (body1_index_in_active_bodies >= inBody2.GetIndexInActiveBodiesInternal())
return false;
JPH_ASSERT(inBody1.GetID() != inBody2.GetID(), "Read the comment above, A and B are the same body which should not be possible!");
// Bodies in the same group don't collide
if (!inBody1.GetCollisionGroup().CanCollide(inBody2.GetCollisionGroup()))
return false;
return true;
}
void Body::AddRotationStep(Vec3Arg inAngularVelocityTimesDeltaTime)
{
JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sPositionAccess, BodyAccess::EAccess::ReadWrite));
// This used to use the equation: d/dt R(t) = 1/2 * w(t) * R(t) so that R(t + dt) = R(t) + 1/2 * w(t) * R(t) * dt
// See: Appendix B of An Introduction to Physically Based Modeling: Rigid Body Simulation II-Nonpenetration Constraints
// URL: https://www.cs.cmu.edu/~baraff/sigcourse/notesd2.pdf
// But this is a first order approximation and does not work well for kinematic ragdolls that are driven to a new
// pose if the poses differ enough. So now we split w(t) * dt into an axis and angle part and create a quaternion with it.
// Note that the resulting quaternion is normalized since otherwise numerical drift will eventually make the rotation non-normalized.
float len = inAngularVelocityTimesDeltaTime.Length();
if (len > 1.0e-6f)
{
mRotation = (Quat::sRotation(inAngularVelocityTimesDeltaTime / len, len) * mRotation).Normalized();
JPH_ASSERT(!mRotation.IsNaN());
}
}
void Body::SubRotationStep(Vec3Arg inAngularVelocityTimesDeltaTime)
{
JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sPositionAccess, BodyAccess::EAccess::ReadWrite));
// See comment at Body::AddRotationStep
float len = inAngularVelocityTimesDeltaTime.Length();
if (len > 1.0e-6f)
{
mRotation = (Quat::sRotation(inAngularVelocityTimesDeltaTime / len, -len) * mRotation).Normalized();
JPH_ASSERT(!mRotation.IsNaN());
}
}
Vec3 Body::GetWorldSpaceSurfaceNormal(const SubShapeID &inSubShapeID, Vec3Arg inPosition) const
{
Mat44 inv_com = GetInverseCenterOfMassTransform();
return inv_com.Multiply3x3Transposed(mShape->GetSurfaceNormal(inSubShapeID, inv_com * inPosition)).Normalized();
}
Mat44 Body::GetInverseInertia() const
{
JPH_ASSERT(IsDynamic());
return GetMotionProperties()->GetInverseInertiaForRotation(Mat44::sRotation(mRotation));
}
void Body::AddForce(Vec3Arg inForce, Vec3Arg inPosition)
{
AddForce(inForce);
AddTorque((inPosition - mPosition).Cross(inForce));
}
void Body::AddImpulse(Vec3Arg inImpulse)
{
JPH_ASSERT(IsDynamic());
SetLinearVelocityClamped(mMotionProperties->GetLinearVelocity() + inImpulse * mMotionProperties->GetInverseMass());
}
void Body::AddImpulse(Vec3Arg inImpulse, Vec3Arg inPosition)
{
JPH_ASSERT(IsDynamic());
SetLinearVelocityClamped(mMotionProperties->GetLinearVelocity() + inImpulse * mMotionProperties->GetInverseMass());
SetAngularVelocityClamped(mMotionProperties->GetAngularVelocity() + GetInverseInertia() * (inPosition - mPosition).Cross(inImpulse));
}
void Body::AddAngularImpulse(Vec3Arg inAngularImpulse)
{
JPH_ASSERT(IsDynamic());
SetAngularVelocityClamped(mMotionProperties->GetAngularVelocity() + GetInverseInertia() * inAngularImpulse);
}
void Body::GetSleepTestPoints(Vec3 *outPoints) const
{
JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sPositionAccess, BodyAccess::EAccess::Read));
// Center of mass is the first position
outPoints[0] = mPosition;
// The second and third position are on the largest axis of the bounding box
Vec3 extent = mShape->GetLocalBounds().GetExtent();
int lowest_component = extent.GetLowestComponentIndex();
Mat44 rotation = Mat44::sRotation(mRotation);
switch (lowest_component)
{
case 0:
outPoints[1] = mPosition + extent.GetY() * rotation.GetColumn3(1);
outPoints[2] = mPosition + extent.GetZ() * rotation.GetColumn3(2);
break;
case 1:
outPoints[1] = mPosition + extent.GetX() * rotation.GetColumn3(0);
outPoints[2] = mPosition + extent.GetZ() * rotation.GetColumn3(2);
break;
case 2:
outPoints[1] = mPosition + extent.GetX() * rotation.GetColumn3(0);
outPoints[2] = mPosition + extent.GetY() * rotation.GetColumn3(1);
break;
default:
JPH_ASSERT(false);
break;
}
}
void Body::ResetSleepTestSpheres()
{
Vec3 points[3];
GetSleepTestPoints(points);
mMotionProperties->ResetSleepTestSpheres(points);
}
} // JPH | 7,522 | 2,641 |
// Copyright (c) 2005 - 2015 Marc de Kamps
// 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 copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
// USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
///*
#include "CSRAdapter.hpp"
#include "Euler.hpp"
namespace {
const MPILib::Time TOLERANCE = 1e-6;
}
using namespace TwoDLib;
CSRAdapter::CSRAdapter
(
Ode2DSystemGroup& group,
const std::vector<TwoDLib::CSRMatrix>& vecmat,
MPILib::Rate euler_timestep
):
_group(group),
_vec_csr_matrices(vecmat),
_dydt(std::vector<MPILib::Mass>(group.Mass().size())),
_euler_timestep(euler_timestep),
_nr_iterations(this->NumberIterations())
{
}
void CSRAdapter::ClearDerivative()
{
TwoDLib::ClearDerivative(_dydt);
}
void CSRAdapter::CalculateDerivative
(
const std::vector<MPILib::Rate>& vecrates
)
{
TwoDLib::CalculateDerivative
(
_group,
_dydt,
_vec_csr_matrices,
vecrates
);
}
MPILib::Number CSRAdapter::NumberIterations() const
{
MPILib::Time tstep = _group.MeshObjects()[0].TimeStep();
for ( const auto& mesh: _group.MeshObjects() )
if (std::abs((tstep - mesh.TimeStep())/mesh.TimeStep()) > TOLERANCE){
std::cerr << "Not all meshes in this group have the same time step. " << tstep << " " << mesh.TimeStep() << " " << tstep - mesh.TimeStep() << std::endl;
exit(0);
}
MPILib::Number n_steps = static_cast<MPILib::Number>(std::round(tstep/_euler_timestep));
return n_steps;
}
void CSRAdapter::AddDerivative()
{
TwoDLib::AddDerivative
(
_group.Mass(),
_dydt,
_euler_timestep
);
}
| 2,981 | 1,080 |
#include "mvc_env.h"
#include "graph.h"
#include <cassert>
#include <random>
#include <algorithm>
#include <set>
#include <queue>
#include <stack>
MvcEnv::MvcEnv(double _norm)
{
norm = _norm;
graph = nullptr;
numCoveredEdges = 0;
CcNum = 1.0;
state_seq.clear();
act_seq.clear();
action_list.clear();
reward_seq.clear();
sum_rewards.clear();
covered_set.clear();
avail_list.clear();
}
MvcEnv::~MvcEnv()
{
norm = 0;
graph = nullptr;
numCoveredEdges = 0;
state_seq.clear();
act_seq.clear();
action_list.clear();
reward_seq.clear();
sum_rewards.clear();
covered_set.clear();
avail_list.clear();
}
void MvcEnv::s0(std::shared_ptr<Graph> _g)
{
graph = _g;
covered_set.clear();
action_list.clear();
numCoveredEdges = 0;
CcNum = 1.0;
state_seq.clear();
act_seq.clear();
reward_seq.clear();
sum_rewards.clear();
}
double MvcEnv::step(int a)
{
assert(graph);
assert(covered_set.count(a) == 0);
state_seq.push_back(action_list);
act_seq.push_back(a);
covered_set.insert(a);
action_list.push_back(a);
// double oldCcNum = CcNum;
// CcNum = getNumofConnectedComponents();
for (auto neigh : graph->adj_list[a])
if (covered_set.count(neigh) == 0)
numCoveredEdges++;
// double r_t = getReward(oldCcNum);
double r_t = getReward();
reward_seq.push_back(r_t);
sum_rewards.push_back(r_t);
return r_t;
}
void MvcEnv::stepWithoutReward(int a)
{
assert(graph);
assert(covered_set.count(a) == 0);
covered_set.insert(a);
action_list.push_back(a);
for (auto neigh : graph->adj_list[a])
if (covered_set.count(neigh) == 0)
numCoveredEdges++;
}
// random
int MvcEnv::randomAction()
{
assert(graph);
avail_list.clear();
for (int i = 0; i < graph->num_nodes; ++i)
if (covered_set.count(i) == 0)
{
bool useful = false;
for (auto neigh : graph->adj_list[i])
if (covered_set.count(neigh) == 0)
{
useful = true;
break;
}
if (useful)
avail_list.push_back(i);
}
assert(avail_list.size());
int idx = rand() % avail_list.size();
return avail_list[idx];
}
int MvcEnv::betweenAction()
{
assert(graph);
std::map<int,int> id2node;
std::map<int,int> node2id;
std::map <int,std::vector<int>> adj_dic_origin;
std::vector<std::vector<int>> adj_list_reID;
for (int i = 0; i < graph->num_nodes; ++i)
{
if (covered_set.count(i) == 0)
{
for (auto neigh : graph->adj_list[i])
{
if (covered_set.count(neigh) == 0)
{
if(adj_dic_origin.find(i) != adj_dic_origin.end())
{
adj_dic_origin[i].push_back(neigh);
}
else{
std::vector<int> neigh_list;
neigh_list.push_back(neigh);
adj_dic_origin.insert(std::make_pair(i,neigh_list));
}
}
}
}
}
std::map<int, std::vector<int>>::iterator iter;
iter = adj_dic_origin.begin();
int numrealnodes = 0;
while(iter != adj_dic_origin.end())
{
id2node[numrealnodes] = iter->first;
node2id[iter->first] = numrealnodes;
numrealnodes += 1;
iter++;
}
adj_list_reID.resize(adj_dic_origin.size());
iter = adj_dic_origin.begin();
while(iter != adj_dic_origin.end())
{
for(int i=0;i<(int)iter->second.size();++i){
adj_list_reID[node2id[iter->first]].push_back(node2id[iter->second[i]]);
}
iter++;
}
std::vector<double> BC = Betweenness(adj_list_reID);
std::vector<double>::iterator biggest_BC = std::max_element(std::begin(BC), std::end(BC));
int maxID = std::distance(std::begin(BC), biggest_BC);
int idx = id2node[maxID];
// printGraph();
// printf("\n maxBetID:%d, value:%.6f\n",idx,BC[maxID]);
return idx;
}
bool MvcEnv::isTerminal()
{
assert(graph);
// printf ("num edgeds:%d\n", graph->num_edges);
// printf ("numCoveredEdges:%d\n", numCoveredEdges);
return graph->num_edges == numCoveredEdges;
}
double MvcEnv::getReward()
{
double orig_node_num = (double) graph->num_nodes;
return -(double)getRemainingCNDScore()/(orig_node_num*orig_node_num*(orig_node_num-1)/2);
}
//double MvcEnv::getReward(double oldCcNum)
//{
// return (CcNum - oldCcNum) / CcNum*graph->num_nodes ;
//
//}
void MvcEnv::printGraph()
{
printf("edge_list:\n");
printf("[");
for (int i = 0; i < (int)graph->edge_list.size();i++)
{
printf("[%d,%d],",graph->edge_list[i].first,graph->edge_list[i].second);
}
printf("]\n");
printf("covered_set:\n");
std::set<int>::iterator it;
printf("[");
for (it=covered_set.begin();it!=covered_set.end();it++)
{
printf("%d,",*it);
}
printf("]\n");
}
double MvcEnv::getRemainingCNDScore()
{
assert(graph);
Disjoint_Set disjoint_Set = Disjoint_Set(graph->num_nodes);
for (int i = 0; i < graph->num_nodes; i++)
{
if (covered_set.count(i) == 0)
{
for (auto neigh : graph->adj_list[i])
{
if (covered_set.count(neigh) == 0)
{
disjoint_Set.merge(i, neigh);
}
}
}
}
std::set<int> lccIDs;
for(int i =0;i< graph->num_nodes; i++){
lccIDs.insert(disjoint_Set.unionSet[i]);
}
double CCDScore = 0.0;
for(std::set<int>::iterator it=lccIDs.begin(); it!=lccIDs.end(); it++)
{
double num_nodes = (double) disjoint_Set.getRank(*it);
CCDScore += (double) num_nodes * (num_nodes-1) / 2;
}
return CCDScore;
}
double MvcEnv::getMaxConnectedNodesNum()
{
assert(graph);
Disjoint_Set disjoint_Set = Disjoint_Set(graph->num_nodes);
for (int i = 0; i < graph->num_nodes; i++)
{
if (covered_set.count(i) == 0)
{
for (auto neigh : graph->adj_list[i])
{
if (covered_set.count(neigh) == 0)
{
disjoint_Set.merge(i, neigh);
}
}
}
}
return (double)disjoint_Set.maxRankCount;
}
std::vector<double> MvcEnv::Betweenness(std::vector< std::vector <int> > adj_list) {
int i, j, u, v;
int Long_max = 4294967295;
int nvertices = adj_list.size(); // The number of vertices in the network
std::vector<double> CB;
double norm=(double)(nvertices-1)*(double)(nvertices-2);
CB.resize(nvertices);
std::vector<int> d; // A vector storing shortest distance estimates
std::vector<int> sigma; // sigma is the number of shortest paths
std::vector<double> delta; // A vector storing dependency of the source vertex on all other vertices
std::vector< std::vector <int> > PredList; // A list of predecessors of all vertices
std::queue <int> Q; // A priority queue soring vertices
std::stack <int> S; // A stack containing vertices in the order found by Dijkstra's Algorithm
// Set the start time of Brandes' Algorithm
// Compute Betweenness Centrality for every vertex i
for (i=0; i < nvertices; i++) {
/* Initialize */
PredList.assign(nvertices, std::vector <int> (0, 0));
d.assign(nvertices, Long_max);
d[i] = 0;
sigma.assign(nvertices, 0);
sigma[i] = 1;
delta.assign(nvertices, 0);
Q.push(i);
// Use Breadth First Search algorithm
while (!Q.empty()) {
// Get the next element in the queue
u = Q.front();
Q.pop();
// Push u onto the stack S. Needed later for betweenness computation
S.push(u);
// Iterate over all the neighbors of u
for (j=0; j < (int) adj_list[u].size(); j++) {
// Get the neighbor v of vertex u
// v = (ui64) network->vertex[u].edge[j].target;
v = (int) adj_list[u][j];
/* Relax and Count */
if (d[v] == Long_max) {
d[v] = d[u] + 1;
Q.push(v);
}
if (d[v] == d[u] + 1) {
sigma[v] += sigma[u];
PredList[v].push_back(u);
}
} // End For
} // End While
/* Accumulation */
while (!S.empty()) {
u = S.top();
S.pop();
for (j=0; j < (int)PredList[u].size(); j++) {
delta[PredList[u][j]] += ((double) sigma[PredList[u][j]]/sigma[u]) * (1+delta[u]);
}
if (u != i)
CB[u] += delta[u];
}
// Clear data for the next run
PredList.clear();
d.clear();
sigma.clear();
delta.clear();
} // End For
// End time after Brandes' algorithm and the time difference
for(int i =0; i<nvertices;++i){
if (norm == 0)
{
CB[i] = 0;
}
else
{
CB[i]=CB[i]/norm;
}
}
return CB;
} // End of BrandesAlgorithm_Unweighted | 8,968 | 3,465 |
#if 0
#include "opencv2/opencv.hpp"
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
// Read source image.
Mat im_src = imread("book2.jpg");
// Four corners of the book in source image
vector<Point2f> pts_src;
pts_src.push_back(Point2f(141, 131));
pts_src.push_back(Point2f(480, 159));
pts_src.push_back(Point2f(493, 630));
pts_src.push_back(Point2f(64, 601));
// Read destination image.
Mat im_dst = imread("book1.jpg");
// Four corners of the book in destination image.
vector<Point2f> pts_dst;
pts_dst.push_back(Point2f(318, 256));
pts_dst.push_back(Point2f(534, 372));
pts_dst.push_back(Point2f(316, 670));
pts_dst.push_back(Point2f(73, 473));
// Calculate Homography
Mat h = findHomography(pts_src, pts_dst);
// Output image
Mat im_out;
// Warp source image to destination based on homography
warpPerspective(im_src, im_out, h, im_dst.size());
// Display images
imshow("Source Image", im_src);
imshow("Destination Image", im_dst);
imshow("Warped Source Image", im_out);
waitKey(0);
}
#endif
| 1,058 | 458 |
// Copyright 2020 Tier IV, 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 "dummy_perception_publisher/node.hpp"
#include "dummy_perception_publisher/signed_distance_function.hpp"
#include <pcl/impl/point_types.hpp>
#include <pcl/filters/voxel_grid_occlusion_estimation.h>
#include <tf2/LinearMath/Transform.h>
#include <tf2/LinearMath/Vector3.h>
#include <functional>
#include <limits>
#include <memory>
namespace
{
static constexpr double epsilon = 0.001;
static constexpr double step = 0.05;
static constexpr double vertical_theta_step = (1.0 / 180.0) * M_PI;
static constexpr double vertical_min_theta = (-15.0 / 180.0) * M_PI;
static constexpr double vertical_max_theta = (15.0 / 180.0) * M_PI;
static constexpr double horizontal_theta_step = (0.1 / 180.0) * M_PI;
static constexpr double horizontal_min_theta = (-180.0 / 180.0) * M_PI;
static constexpr double horizontal_max_theta = (180.0 / 180.0) * M_PI;
pcl::PointXYZ getPointWrtBaseLink(
const tf2::Transform & tf_base_link2moved_object, double x, double y, double z)
{
const auto p_wrt_base = tf_base_link2moved_object(tf2::Vector3(x, y, z));
return pcl::PointXYZ(p_wrt_base.x(), p_wrt_base.y(), p_wrt_base.z());
}
} // namespace
void ObjectCentricPointCloudCreator::create_object_pointcloud(
const ObjectInfo & obj_info, const tf2::Transform & tf_base_link2map,
std::mt19937 & random_generator, pcl::PointCloud<pcl::PointXYZ>::Ptr pointcloud) const
{
std::normal_distribution<> x_random(0.0, obj_info.std_dev_x);
std::normal_distribution<> y_random(0.0, obj_info.std_dev_y);
std::normal_distribution<> z_random(0.0, obj_info.std_dev_z);
const auto tf_base_link2moved_object = tf_base_link2map * obj_info.tf_map2moved_object;
const double min_z = -1.0 * (obj_info.height / 2.0) + tf_base_link2moved_object.getOrigin().z();
const double max_z = 1.0 * (obj_info.height / 2.0) + tf_base_link2moved_object.getOrigin().z();
pcl::PointCloud<pcl::PointXYZ> horizontal_candidate_pointcloud;
pcl::PointCloud<pcl::PointXYZ> horizontal_pointcloud;
{
const double y = -1.0 * (obj_info.width / 2.0);
for (double x = -1.0 * (obj_info.length / 2.0); x <= ((obj_info.length / 2.0) + epsilon);
x += step) {
horizontal_candidate_pointcloud.push_back(
getPointWrtBaseLink(tf_base_link2moved_object, x, y, 0.0));
}
}
{
const double y = 1.0 * (obj_info.width / 2.0);
for (double x = -1.0 * (obj_info.length / 2.0); x <= ((obj_info.length / 2.0) + epsilon);
x += step) {
horizontal_candidate_pointcloud.push_back(
getPointWrtBaseLink(tf_base_link2moved_object, x, y, 0.0));
}
}
{
const double x = -1.0 * (obj_info.length / 2.0);
for (double y = -1.0 * (obj_info.width / 2.0); y <= ((obj_info.width / 2.0) + epsilon);
y += step) {
horizontal_candidate_pointcloud.push_back(
getPointWrtBaseLink(tf_base_link2moved_object, x, y, 0.0));
}
}
{
const double x = 1.0 * (obj_info.length / 2.0);
for (double y = -1.0 * (obj_info.width / 2.0); y <= ((obj_info.width / 2.0) + epsilon);
y += step) {
horizontal_candidate_pointcloud.push_back(
getPointWrtBaseLink(tf_base_link2moved_object, x, y, 0.0));
}
}
// 2D ray tracing
size_t ranges_size =
std::ceil((horizontal_max_theta - horizontal_min_theta) / horizontal_theta_step);
std::vector<double> horizontal_ray_traced_2d_pointcloud;
horizontal_ray_traced_2d_pointcloud.assign(ranges_size, std::numeric_limits<double>::infinity());
const int no_data = -1;
std::vector<int> horizontal_ray_traced_pointcloud_indices;
horizontal_ray_traced_pointcloud_indices.assign(ranges_size, no_data);
for (size_t i = 0; i < horizontal_candidate_pointcloud.points.size(); ++i) {
double angle =
std::atan2(horizontal_candidate_pointcloud.at(i).y, horizontal_candidate_pointcloud.at(i).x);
double range =
std::hypot(horizontal_candidate_pointcloud.at(i).y, horizontal_candidate_pointcloud.at(i).x);
if (angle < horizontal_min_theta || angle > horizontal_max_theta) {
continue;
}
int index = (angle - horizontal_min_theta) / horizontal_theta_step;
if (range < horizontal_ray_traced_2d_pointcloud[index]) {
horizontal_ray_traced_2d_pointcloud[index] = range;
horizontal_ray_traced_pointcloud_indices.at(index) = i;
}
}
for (const auto & pointcloud_index : horizontal_ray_traced_pointcloud_indices) {
if (pointcloud_index != no_data) {
// generate vertical point
horizontal_pointcloud.push_back(horizontal_candidate_pointcloud.at(pointcloud_index));
const double distance = std::hypot(
horizontal_candidate_pointcloud.at(pointcloud_index).x,
horizontal_candidate_pointcloud.at(pointcloud_index).y);
for (double vertical_theta = vertical_min_theta;
vertical_theta <= vertical_max_theta + epsilon; vertical_theta += vertical_theta_step) {
const double z = distance * std::tan(vertical_theta);
if (min_z <= z && z <= max_z + epsilon) {
pcl::PointXYZ point;
point.x =
horizontal_candidate_pointcloud.at(pointcloud_index).x + x_random(random_generator);
point.y =
horizontal_candidate_pointcloud.at(pointcloud_index).y + y_random(random_generator);
point.z = z + z_random(random_generator);
pointcloud->push_back(point);
}
}
}
}
}
std::vector<pcl::PointCloud<pcl::PointXYZ>::Ptr> ObjectCentricPointCloudCreator::create_pointclouds(
const std::vector<ObjectInfo> & obj_infos, const tf2::Transform & tf_base_link2map,
std::mt19937 & random_generator, pcl::PointCloud<pcl::PointXYZ>::Ptr & merged_pointcloud) const
{
std::vector<pcl::PointCloud<pcl::PointXYZ>::Ptr> pointclouds_tmp;
pcl::PointCloud<pcl::PointXYZ>::Ptr merged_pointcloud_tmp(new pcl::PointCloud<pcl::PointXYZ>);
for (const auto & obj_info : obj_infos) {
pcl::PointCloud<pcl::PointXYZ>::Ptr pointcloud_shared_ptr(new pcl::PointCloud<pcl::PointXYZ>);
this->create_object_pointcloud(
obj_info, tf_base_link2map, random_generator, pointcloud_shared_ptr);
pointclouds_tmp.push_back(pointcloud_shared_ptr);
}
for (const auto & cloud : pointclouds_tmp) {
for (const auto & pt : *cloud) {
merged_pointcloud_tmp->push_back(pt);
}
}
if (!enable_ray_tracing_) {
merged_pointcloud = merged_pointcloud_tmp;
return pointclouds_tmp;
}
pcl::PointCloud<pcl::PointXYZ>::Ptr ray_traced_merged_pointcloud_ptr(
new pcl::PointCloud<pcl::PointXYZ>);
pcl::VoxelGridOcclusionEstimation<pcl::PointXYZ> ray_tracing_filter;
ray_tracing_filter.setInputCloud(merged_pointcloud_tmp);
ray_tracing_filter.setLeafSize(0.25, 0.25, 0.25);
ray_tracing_filter.initializeVoxelGrid();
std::vector<pcl::PointCloud<pcl::PointXYZ>::Ptr> pointclouds;
for (size_t i = 0; i < pointclouds_tmp.size(); ++i) {
pcl::PointCloud<pcl::PointXYZ>::Ptr ray_traced_pointcloud_ptr(
new pcl::PointCloud<pcl::PointXYZ>);
for (size_t j = 0; j < pointclouds_tmp.at(i)->size(); ++j) {
Eigen::Vector3i grid_coordinates = ray_tracing_filter.getGridCoordinates(
pointclouds_tmp.at(i)->at(j).x, pointclouds_tmp.at(i)->at(j).y,
pointclouds_tmp.at(i)->at(j).z);
int grid_state;
if (ray_tracing_filter.occlusionEstimation(grid_state, grid_coordinates) != 0) {
RCLCPP_ERROR(rclcpp::get_logger("dummy_perception_publisher"), "ray tracing failed");
}
if (grid_state == 1) { // occluded
continue;
} else { // not occluded
ray_traced_pointcloud_ptr->push_back(pointclouds_tmp.at(i)->at(j));
ray_traced_merged_pointcloud_ptr->push_back(pointclouds_tmp.at(i)->at(j));
}
}
pointclouds.push_back(ray_traced_pointcloud_ptr);
}
merged_pointcloud = ray_traced_merged_pointcloud_ptr;
return pointclouds;
}
std::vector<pcl::PointCloud<pcl::PointXYZ>::Ptr> EgoCentricPointCloudCreator::create_pointclouds(
const std::vector<ObjectInfo> & obj_infos, const tf2::Transform & tf_base_link2map,
std::mt19937 & random_generator, pcl::PointCloud<pcl::PointXYZ>::Ptr & merged_pointcloud) const
{
std::vector<std::shared_ptr<signed_distance_function::AbstractSignedDistanceFunction>> sdf_ptrs;
for (const auto & obj_info : obj_infos) {
const auto sdf_ptr = std::make_shared<signed_distance_function::BoxSDF>(
obj_info.length, obj_info.width, tf_base_link2map * obj_info.tf_map2moved_object);
sdf_ptrs.push_back(sdf_ptr);
}
const auto composite_sdf = signed_distance_function::CompositeSDF(sdf_ptrs);
std::vector<pcl::PointCloud<pcl::PointXYZ>::Ptr> pointclouds(obj_infos.size());
for (size_t i = 0; i < obj_infos.size(); ++i) {
pointclouds.at(i) = (pcl::PointCloud<pcl::PointXYZ>::Ptr(new pcl::PointCloud<pcl::PointXYZ>));
}
std::vector<double> min_zs(obj_infos.size());
std::vector<double> max_zs(obj_infos.size());
for (size_t idx = 0; idx < obj_infos.size(); ++idx) {
const auto & obj_info = obj_infos.at(idx);
const auto tf_base_link2moved_object = tf_base_link2map * obj_info.tf_map2moved_object;
const double min_z = -1.0 * (obj_info.height / 2.0) + tf_base_link2moved_object.getOrigin().z();
const double max_z = 1.0 * (obj_info.height / 2.0) + tf_base_link2moved_object.getOrigin().z();
min_zs.at(idx) = min_z;
max_zs.at(idx) = max_z;
}
double angle = 0.0;
const auto n_scan = static_cast<size_t>(std::floor(2 * M_PI / horizontal_theta_step));
for (size_t i = 0; i < n_scan; ++i) {
angle += horizontal_theta_step;
const auto dist = composite_sdf.getSphereTracingDist(0.0, 0.0, angle, visible_range_);
if (std::isfinite(dist)) {
const auto x_hit = dist * cos(angle);
const auto y_hit = dist * sin(angle);
const auto idx_hit = composite_sdf.nearest_sdf_index(x_hit, y_hit);
const auto obj_info_here = obj_infos.at(idx_hit);
const auto min_z_here = min_zs.at(idx_hit);
const auto max_z_here = max_zs.at(idx_hit);
std::normal_distribution<> x_random(0.0, obj_info_here.std_dev_x);
std::normal_distribution<> y_random(0.0, obj_info_here.std_dev_y);
std::normal_distribution<> z_random(0.0, obj_info_here.std_dev_z);
for (double vertical_theta = vertical_min_theta;
vertical_theta <= vertical_max_theta + epsilon; vertical_theta += vertical_theta_step) {
const double z = dist * std::tan(vertical_theta);
if (min_z_here <= z && z <= max_z_here + epsilon) {
pointclouds.at(idx_hit)->push_back(pcl::PointXYZ(
x_hit + x_random(random_generator), y_hit + y_random(random_generator),
z + z_random(random_generator)));
}
}
}
}
for (const auto & cloud : pointclouds) {
for (const auto & pt : *cloud) {
merged_pointcloud->push_back(pt);
}
}
return pointclouds;
}
| 11,402 | 4,262 |
#include <string>
#include <iostream>
#pragma once
enum log_level {DEBUG = 0, INFO, WARNING, ERROR, LogLevelMax};
class Loggeable {
public:
void mute() {m_mute = true;};
void unmute() {m_mute = false;};
void filter(log_level min_lvl) {m_min_lvl = min_lvl;};
void prefix(std::string prefix) {m_prefix = std::move(prefix);};
template<typename... T>
void log(log_level lvl, const char* fmt, T ... args) {
if(lvl >= m_min_lvl && !m_mute)
{
*out_streams[lvl] << m_prefix;
// don't store on the stack; no need to be reentrant and allows coroutines to have a tiny stack
static char buff[2048];
std::snprintf(&buff[0], 2048, fmt, args...); // No buffer overflow there, sir !
*out_streams[lvl] << &buff[0];
}
};
bool m_mute = false;
log_level m_min_lvl = INFO;
std::string m_prefix;
std::ostream* out_streams[LogLevelMax] =
{
&std::clog, // DEBUG
&std::cout, // INFO
&std::cerr, // WARNING
&std::cerr // ERROR
};
};
inline Loggeable global_logger;
template<typename... T>
void log(log_level lvl, const char* fmt, T ... args)
{
global_logger.log(lvl, fmt, args...);
}
template<typename... T>
void info(const char* fmt, T ... args)
{
global_logger.log(INFO, fmt, args...);
}
template<typename... T>
void warn(const char* fmt, T ... args)
{
global_logger.log(WARNING, fmt, args...);
}
template<typename... T>
void error(const char* fmt, T ... args)
{
global_logger.log(ERROR, fmt, args...);
}
| 1,581 | 571 |
#include <LogicalPlan.h>
#include <Lexer.h>
#include <Parser.h>
namespace pdb {
LogicalPlan::LogicalPlan(const std::string &tcap, Vector<Handle<Computation>> &computations) {
init(tcap, computations);
}
LogicalPlan::LogicalPlan(AtomicComputationList &computationsIn, pdb::Vector<pdb::Handle<pdb::Computation>> &allComputations) {
init(computationsIn, allComputations);
}
void LogicalPlan::init(AtomicComputationList &computationsIn, pdb::Vector<pdb::Handle<pdb::Computation>> &allComputations) {
computations = computationsIn;
for (int i = 0; i < allComputations.size(); i++) {
std::string compType = allComputations[i]->getComputationType();
compType += "_";
compType += std::to_string(i);
pdb::ComputationNode temp(allComputations[i]);
allConstituentComputations[compType] = temp;
}
}
void LogicalPlan::init(const std::string &tcap, Vector<Handle<Computation>> &allComputations) {
// get the string to compile
std::string myLogicalPlan = tcap;
myLogicalPlan.push_back('\0');
// where the result of the parse goes
AtomicComputationList *myResult;
// now, do the compilation
yyscan_t scanner;
LexerExtra extra{""};
yylex_init_extra(&extra, &scanner);
const YY_BUFFER_STATE buffer{yy_scan_string(myLogicalPlan.data(), scanner)};
const int parseFailed{yyparse(scanner, &myResult)};
yy_delete_buffer(buffer, scanner);
yylex_destroy(scanner);
// if it didn't parse, get outta here
if (parseFailed) {
std::cout << "Parse error when compiling TCAP: " << extra.errorMessage;
exit(1);
}
// copy all the computations
init(*myResult, allComputations);
delete myResult;
}
}
| 1,652 | 569 |
#include <CGAL/Simple_cartesian.h>
#include <CGAL/IO/read_points.h>
#include <CGAL/property_map.h>
#include <vector>
#include <deque>
#include <iostream>
#include <fstream>
typedef CGAL::Simple_cartesian<double> Kernel;
typedef Kernel::Point_3 Point_3;
typedef Kernel::Vector_3 Vector_3;
typedef std::pair<Point_3, Vector_3> PointVectorPair;
// this is going to be custom OutputIterator value_type
struct dummy_counter {
static std::size_t counter;
dummy_counter() { ++counter; }
operator std::size_t() { return counter-1; }
};
std::size_t dummy_counter::counter = 0;
bool check_points_and_vectors(
const boost::vector_property_map<Point_3>& points,
const boost::vector_property_map<Vector_3>& normals,
const std::vector<PointVectorPair>& pv_pairs,
const std::vector<std::size_t>& indices)
{
if(pv_pairs.size() != indices.size()) {
std::cerr << "Error: inconsistency between point / normal size." << std::endl;
return false;
}
for(std::size_t i = 0; i < pv_pairs.size(); ++i ) {
if(pv_pairs[i].first != points[i]) {
std::cerr << "Error: points are not equal." << std::endl;
return false;
}
if(pv_pairs[i].second != normals[i]) {
std::cerr << "Error: normals are not equal." << std::endl;
return false;
}
}
return true;
}
bool check_points(
const boost::vector_property_map<Point_3>& points_1,
const std::vector<Point_3>& points_2,
const std::vector<std::size_t>& indices)
{
if(points_2.size() != indices.size()) {
std::cerr << "Error: inconsistency between point / normal size." << std::endl;
return false;
}
for(std::size_t i = 0; i < points_2.size(); ++i ) {
if(points_2[i] != points_1[i]) {
std::cerr << "Error: points are not equal." << std::endl;
return false;
}
}
return true;
}
bool test_no_deduction_points_and_normals_xyz(const std::string file_name)
{
boost::vector_property_map<Point_3> points;
boost::vector_property_map<Vector_3> normals;
std::vector<std::size_t> indices;
std::vector<PointVectorPair> pv_pairs;
// read with custom output iterator type
dummy_counter::counter = 0;
std::ifstream input(file_name);
CGAL::IO::read_XYZ<dummy_counter>(
input, back_inserter(indices),
CGAL::parameters::point_map (points).
normal_map (normals).
geom_traits (Kernel()));
// read with ordinary pmaps
input.clear();
input.close();
input.open(file_name);
CGAL::IO::read_XYZ(
input, back_inserter(pv_pairs),
CGAL::parameters::point_map(CGAL::First_of_pair_property_map<PointVectorPair>()).
normal_map(CGAL::Second_of_pair_property_map<PointVectorPair>()).
geom_traits(Kernel()));
return check_points_and_vectors(points, normals, pv_pairs, indices);
}
bool test_no_deduction_points_and_normals_off(const std::string file_name)
{
boost::vector_property_map<Point_3> points;
boost::vector_property_map<Vector_3> normals;
std::vector<std::size_t> indices;
std::vector<PointVectorPair> pv_pairs;
// read with custom output iterator type
dummy_counter::counter = 0;
std::ifstream input(file_name);
CGAL::IO::read_OFF<dummy_counter>(
input, back_inserter(indices),
CGAL::parameters::point_map(points).
normal_map(normals).
geom_traits(Kernel()));
// read with ordinary pmaps
input.clear();
input.close();
input.open(file_name);
CGAL::IO::read_OFF(
input, back_inserter(pv_pairs),
CGAL::parameters::point_map(CGAL::First_of_pair_property_map<PointVectorPair>()).
normal_map(CGAL::Second_of_pair_property_map<PointVectorPair>()).
geom_traits(Kernel()));
return check_points_and_vectors(points, normals, pv_pairs, indices);
}
bool test_no_deduction_points_xyz(const std::string file_name)
{
boost::vector_property_map<Point_3> points_1; \
std::vector<std::size_t> indices;
std::vector<Point_3> points_2;
// read with custom output iterator type
dummy_counter::counter = 0;
std::ifstream input(file_name);
CGAL::IO::read_XYZ<dummy_counter>(
input, back_inserter(indices),
CGAL::parameters::point_map(points_1).geom_traits(Kernel()));
// read with ordinary pmaps
input.clear();
input.close();
input.open(file_name);
CGAL::IO::read_XYZ(
input, back_inserter(points_2),
CGAL::parameters::point_map(CGAL::Identity_property_map<Point_3>()).
geom_traits(Kernel()));
return check_points(points_1, points_2, indices);
}
bool test_no_deduction_points_off(const std::string file_name)
{
boost::vector_property_map<Point_3> points_1;
std::vector<std::size_t> indices;
std::vector<Point_3> points_2;
// read with custom output iterator type
dummy_counter::counter = 0;
std::ifstream input(file_name);
CGAL::IO::read_OFF<dummy_counter>(
input, back_inserter(indices),
CGAL::parameters::point_map(points_1).
geom_traits(Kernel()));
// read with ordinary pmaps
input.clear();
input.close();
input.open(file_name);
CGAL::IO::read_OFF(
input, back_inserter(points_2),
CGAL::parameters::point_map(CGAL::Identity_property_map<Point_3>()).
geom_traits(Kernel()));
return check_points(points_1, points_2, indices);
}
void compile_test() {
std::deque<Point_3> points;
std::deque<Vector_3> normals;
std::deque<PointVectorPair> pv_pairs;
std::ifstream input;
input.open("data/read_test/simple.xyz");
CGAL::IO::read_XYZ(
input,
std::front_inserter(points));
input.clear();
input.close();
input.open("data/read_test/simple.xyz");
CGAL::IO::read_XYZ(
input,
std::front_inserter(points),
CGAL::parameters::point_map(CGAL::Identity_property_map<Point_3>()));
input.clear();
input.close();
input.open("data/read_test/simple.xyz");
CGAL::IO::read_XYZ(
input,
std::front_inserter(points),
CGAL::parameters::point_map(CGAL::Identity_property_map<Point_3>()).
geom_traits(Kernel()));
input.clear();
input.close();
// this will span all OutputIteratorValueType versions
input.open("data/read_test/simple.xyz");
CGAL::IO::read_XYZ<Point_3>(
input,
std::front_inserter(points));
input.clear();
input.close();
//-----------------------------------------------------------------------
input.open("data/read_test/simple.off");
CGAL::IO::read_OFF(
input,
std::front_inserter(points));
input.clear();
input.close();
input.open("data/read_test/simple.off");
CGAL::IO::read_OFF(
input,
std::front_inserter(points),
CGAL::parameters::point_map(CGAL::Identity_property_map<Point_3>()));
input.clear();
input.close();
input.open("data/read_test/simple.off");
CGAL::IO::read_OFF(
input,
std::front_inserter(points),
CGAL::parameters::point_map(CGAL::Identity_property_map<Point_3>()).
geom_traits(Kernel()));
input.clear();
input.close();
// this will span all OutputIteratorValueType versions
input.open("data/read_test/simple.off");
CGAL::IO::read_OFF<Point_3>(
input,
std::front_inserter(points));
input.clear();
input.close();
//-----------------------------------------------------------------------
input.open("data/read_test/simple.xyz");
CGAL::IO::read_XYZ(
input,
std::front_inserter(points),
CGAL::parameters::normal_map(boost::dummy_property_map()));
input.clear();
input.close();
input.open("data/read_test/simple.xyz");
CGAL::IO::read_XYZ(
input,
std::front_inserter(pv_pairs),
CGAL::parameters::point_map(CGAL::First_of_pair_property_map<PointVectorPair>()).
normal_map(CGAL::Second_of_pair_property_map<PointVectorPair>()));
input.clear();
input.close();
input.open("data/read_test/simple.xyz");
CGAL::IO::read_XYZ(
input,
std::front_inserter(pv_pairs),
CGAL::parameters::point_map(CGAL::First_of_pair_property_map<PointVectorPair>()).
normal_map(CGAL::Second_of_pair_property_map<PointVectorPair>()).
geom_traits(Kernel()));
input.clear();
input.close();
input.open("data/read_test/simple.xyz");
CGAL::IO::read_XYZ<Point_3>(
input,
std::front_inserter(points),
CGAL::parameters::normal_map(boost::dummy_property_map()));
input.clear();
input.close();
//-----------------------------------------------------------------------
input.open("data/read_test/simple.off");
CGAL::IO::read_OFF(
input,
std::front_inserter(points),
CGAL::parameters::normal_map(boost::dummy_property_map()));
input.clear();
input.close();
input.open("data/read_test/simple.off");
CGAL::IO::read_OFF(
input,
std::front_inserter(pv_pairs),
CGAL::parameters::point_map(CGAL::First_of_pair_property_map<PointVectorPair>()).
normal_map(CGAL::Second_of_pair_property_map<PointVectorPair>()));
input.clear();
input.close();
input.open("data/read_test/simple.off");
CGAL::IO::read_OFF(
input,
std::front_inserter(pv_pairs),
CGAL::parameters::point_map(CGAL::First_of_pair_property_map<PointVectorPair>()).
normal_map(CGAL::Second_of_pair_property_map<PointVectorPair>()).
geom_traits(Kernel()));
input.clear();
input.close();
input.open("data/read_test/simple.off");
CGAL::IO::read_OFF<Point_3>(
input,
std::front_inserter(points),
CGAL::parameters::normal_map(boost::dummy_property_map()));
input.clear();
input.close();
}
int main() {
if(!test_no_deduction_points_and_normals_xyz("data/read_test/simple.xyz")) {
return EXIT_FAILURE;
}
std::cerr << "test_no_deduction_points_and_normals_xyz OK." << std::endl;
if(!test_no_deduction_points_and_normals_off("data/read_test/simple.off")) {
return EXIT_FAILURE;
}
std::cerr << "test_no_deduction_points_and_normals_off OK." << std::endl;
if(!test_no_deduction_points_xyz("data/read_test/simple.xyz")) {
return EXIT_FAILURE;
}
std::cerr << "test_no_deduction_points_xyz OK." << std::endl;
if(!test_no_deduction_points_off("data/read_test/simple.off")) {
return EXIT_FAILURE;
}
std::cerr << "test_no_deduction_points_off OK." << std::endl;
compile_test();
return EXIT_SUCCESS;
}
| 10,027 | 3,672 |
//Nguyen X. Vinh, Jeffrey Chan, Simone Romano and James Bailey, "Effective Global Approaches for Mutual Information based Feature Selection".
//To appear in Proceeedings of the 20th ACM SIGKDD Conference on Knowledge Discovery and Data Mining (KDD'14), August 24-27, New York City, 2014.
// (C) 2014 Nguyen Xuan Vinh
// Email: vinh.nguyen@unimelb.edu.au, vinh.nguyenx@gmail.com
// Mex code for computing the JMI matrix: last row of data matrix is class variable
#include "mex.h" /* Always include this */
#include <math.h>
#include <iostream>
using namespace std;
int compare_feature_config(double *data,int nPa,int* Pa,int a,int posi, int posj);
double conditional_MI(double *data,int i, int j,int nPa,int *Pa, int n_state,int n_stateC);
void Contingency(int Mem1,int Mem2,int n_state,int n_stateC);
double Mutu_Info(int **T, int n_state,int n_stateC);
void ClearT(int n_state,int n_stateC); //clear the share contingency table
double conditional_MI_fast(double *data,int a, int b,int nPa, int* Pa, int n_state,int n_stateC);
double getij(double* A, int nrows,int i,int j){return A[i + nrows*j];}
void setij(double* A, int nrows,int i,int j,double val){A[i + nrows*j]=val;}
//global variables
int** T=NULL;
int*** newT=NULL;
int n_state=0;
int n_stateC=0;
int N=0;
int dim=0;
double* data=NULL;
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
#define A_IN prhs[0]
#define B_OUT plhs[0]
double *B, *A;
N = mxGetM(A_IN); /* Get the dimensions of A */
dim = mxGetN(A_IN);
B_OUT = mxCreateDoubleMatrix(dim-1, dim-1, mxREAL); /* Create the output matrix */
data = mxGetPr(A_IN);
B = mxGetPr(B_OUT); /* Get the pointer to the data of B */
//get number of state of the data
for(int i=0;i<N;i++){
for (int j=0;j<dim-1;j++){
if (n_state<data[i+N*j]) n_state=data[i+N*j];
}
}
for(int i=0;i<N;i++){
if (n_stateC<data[i+(dim-1)*N]) n_stateC=data[i+(dim-1)*N];
}
n_state++; //Attention: buffer for state (C++ index starts from 0)
n_stateC++;
T=new int*[n_state];
for(int i=0;i<n_state;i++) T[i]=new int[n_stateC];
newT=new int**[n_state]; //for computing I(Xi;C|Xj)
for(int i=0;i<n_state;i++){
newT[i]=new int* [n_state];
for(int j=0;j<n_state;j++) newT[i][j]=new int [n_stateC];
}
cout<<"Computing CMI matrix v4 (fast) started...\n";
//compute JMI and fill in B
int* Pa=new int[1];
for (int i = 0; i < dim-1; i++){ /* Compute a matrix with normalized columns */
double MI1=conditional_MI(data, i, dim-1,0, Pa, n_state, n_stateC);
Pa[0]=i;
//setij(B,dim-1,i,i,MI1);
B[i+(dim-1)*i]=MI1;
for(int j = 0; j < dim-1; j++) /* Compute a matrix with normalized columns */
{
if(j==i) continue;
//double MI=conditional_MI(data, j, dim-1 ,1, Pa, n_state, n_stateC);
double MI=conditional_MI_fast(data, j, dim-1 ,1, Pa, n_state, n_stateC);
//printf(" MI=%f MI1= %f\n",MI,MI1);
//setij(B,dim-1,i,j,MI+MI1);
//setij(B,dim-1,j,i,MI+MI1);
//setij(B,dim-1,i,j,MI);
B[i+(dim-1)*j]=MI;
}
//mexPrintf("\n");
}
for(int i=0;i<n_state;i++) delete[] T[i];
delete T;
for(int i=0;i<n_state;i++) {
for(int j=0;j<n_state;j++) delete[] newT[i][j];
delete[] newT[i];
}
delete newT;
return;
}
// data[i][j] => data[i + nrows*j];
void Contingency(int a,int b,int n_state,int n_stateC){
for(int i=0;i<n_state;i++)
for(int j=0;j<n_stateC;j++)
T[i][j]=0;
//build table
for(int i =0;i<N;i++){
//T[data[i][a]][data[i][b]]++;
T[(int)data[i+N*a]][(int)data[i+N*b]]++;
}
}
//compare a feature set configuration of node a at two position in the data: char type
int compare_feature_config(double *data,int nPa,int* Pa,int a,int posi, int posj){
int isSame=1;
for (int i=0;i<nPa;i++){ //scan through the list of features
//if(data[posi][Pa[i]]!=data[posj][Pa[i]]){//check this feature value at posi & posj
if(data[posi+N*Pa[i]]!=data[posj+N*Pa[i]]){//check this feature value at posi & posj
return 0;
}
}
return isSame;
}
void ClearT(int n_state,int n_stateC){
for(int i=0;i<n_state;i++){
for(int j=0;j<n_stateC;j++){
T[i][j]=0;
}
}
}
//conditional MI between node a-> node b given other feature Pa
double conditional_MI(double *data,int a, int b,int nPa, int* Pa, int n_state,int n_stateC){
double MI=0;
if (nPa==0){ //no feature
Contingency(a,b,n_state, n_stateC);
return Mutu_Info(T, n_state, n_stateC);
}
else { //with some features?
int * scanned=new int[N];
for(int i=0;i<N;i++){scanned[i]=0;}
for(int i=0;i<N;i++){ //scan all rows of data
if(scanned[i]==0){ //a new combination of Pa found
scanned[i]=1;
double count=1;
ClearT(n_state, n_stateC);
T[(int)data[i+N*a]][(int)data[i+N*b]]++;
for(int j=i+1;j<N;j++){
if(scanned[j]==0 && data[i+N*Pa[0]]==data[j+N*Pa[0]]){ // compare_feature_config(data,nPa,Pa,b,i,j)){
scanned[j]=1;
T[(int)data[j+N*a]][(int)data[j+N*b]]++;
count++;
}
}
MI+=(count/N)*Mutu_Info(T,n_state, n_stateC);
}
}
delete[] scanned;
}
return MI;
}
//conditional MI between node a-> node b given other feature Pa
//fast version (required more memory)
double conditional_MI_fast(double *data,int a, int b,int nPa, int* Pa, int n_state,int n_stateC){
double MI=0;
if (nPa==0){ //no parents
Contingency(a,b,n_state, n_stateC);
return Mutu_Info(T, n_state, n_stateC);
}
else { //with some parents
for(int i=0;i<n_state;i++) for(int j=1;j<n_state;j++) for(int k=1;k<n_stateC;k++) newT[i][j][k]=0;
double* count=new double[n_state];
for (int i=0;i<n_state;i++) count[i]=0;
for(int i=0;i<N;i++){ //scan all rows of data
int cl=(int) data[i+N*Pa[0]];
newT[cl][(int)data[i+N*a]][(int)data[i+N*b]]++;
count[cl]++;
}
for(int i=1;i<n_state;i++) MI+=(count[i]/N)*Mutu_Info(newT[i],n_state, n_stateC);
delete count;
}
return MI;
}
double Mutu_Info(int **T, int n_state,int n_stateC){ //get the mutual information from a contingency table
//n_state: #rows n_stateC:#cols
double MI=0;
int *a = new int[n_state];
int *b = new int[n_stateC];
int N=0;
for(int i=1;i<n_state;i++){ //row sum
a[i]=0;
for(int j=1;j<n_stateC;j++)
{a[i]+=T[i][j];}
}
for(int i=1;i<n_stateC;i++){ //col sum
b[i]=0;
for(int j=1;j<n_state;j++)
{b[i]+=T[j][i];}
}
for(int i=1;i<n_state;i++) {N+=a[i];}
for(int i=1;i<n_state;i++){
for(int j=1;j<n_stateC;j++){
if(T[i][j]>0){
MI+= T[i][j]*log(double(T[i][j])*N/a[i]/b[j])/log(double(2));
}
}
}
delete []a;
delete []b;
if(N>0) return MI/N;
else return 0;
} | 6,680 | 3,078 |
#include "DBTableWidget.h"
#include "Exceptions.h"
#include "GUIHelper.h"
#include <QHeaderView>
#include <QAction>
#include <QApplication>
#include <QClipboard>
#include <QKeyEvent>
DBTableWidget::DBTableWidget(QWidget* parent)
: QTableWidget(parent)
{
//general settings
verticalHeader()->setVisible(false);
setSelectionMode(QAbstractItemView::ExtendedSelection);
setSelectionBehavior(QAbstractItemView::SelectRows);
setWordWrap(false);
connect(this, SIGNAL(cellDoubleClicked(int,int)), this, SLOT(processDoubleClick(int, int)));
//context menu
setContextMenuPolicy(Qt::ActionsContextMenu);
QAction* copy_action = new QAction(QIcon(":/Icons/CopyClipboard.png"), "Copy selection", this);
addAction(copy_action);
connect(copy_action, SIGNAL(triggered(bool)), this, SLOT(copySelectionToClipboard()));
copy_action = new QAction(QIcon(":/Icons/CopyClipboard.png"), "Copy all", this);
addAction(copy_action);
connect(copy_action, SIGNAL(triggered(bool)), this, SLOT(copyTableToClipboard()));
}
void DBTableWidget::setData(const DBTable& table, int max_col_width)
{
QStringList headers = table.headers();
//table
table_ = table.tableName();
//resize
clearContents();
setRowCount(table.rowCount());
setColumnCount(headers.count());
//headers
for(int c=0; c<headers.count(); ++c)
{
setHorizontalHeaderItem(c, GUIHelper::createTableItem(headers[c], Qt::AlignCenter));
}
//content
ids_.clear();
for(int r=0; r<table.rowCount(); ++r)
{
const DBRow& row = table.row(r);
ids_ <<row.id();
for(int c=0; c<headers.count(); ++c)
{
setItem(r, c, GUIHelper::createTableItem(row.value(c)));
}
}
//fomatting
GUIHelper::resizeTableCells(this, max_col_width);
}
int DBTableWidget::columnIndex(const QString& column_header) const
{
for (int c=0; c<columnCount(); ++c)
{
if (horizontalHeaderItem(c)->text()==column_header)
{
return c;
}
}
THROW(ArgumentException, "Could not find column with header '" + column_header + "'");
}
QString DBTableWidget::columnHeader(int index) const
{
if (index<0 || index>=columnCount())
{
THROW(ArgumentException, "Invalid column index " + QString::number(index) + ". The table has " + QString::number(columnCount()) + " columns!");
}
return horizontalHeaderItem(index)->text();
}
void DBTableWidget::setQualityIcons(const QString& column_header, const QStringList& quality_values)
{
//check
if (quality_values.count()!=rowCount())
{
THROW(ArgumentException, "Invalid quality value count '" + QString::number(quality_values.count()) + "' in DBTableWidget::setQualityIcons - expected '" + QString::number(rowCount()) + "'!");
}
int c = columnIndex(column_header);
for(int r=0; r<rowCount(); ++r)
{
QTableWidgetItem* table_item = item(r, c);
if (table_item==nullptr) continue;
const QString& quality = quality_values[r];
styleQuality(table_item, quality);
}
setColumnWidth(c, columnWidth(c) + 25);
}
void DBTableWidget::setColumnTooltips(const QString& column_header, const QStringList& tooltips)
{
if (tooltips.count()!=rowCount())
{
THROW(ArgumentException, "Invalid tooltip count '" + QString::number(tooltips.count()) + "' in DBTableWidget::setColumnTooltips - expected '" + QString::number(rowCount()) + "'!");
}
int c = columnIndex(column_header);
for(int r=0; r<rowCount(); ++r)
{
QTableWidgetItem* table_item = item(r, c);
if (table_item==nullptr) continue;
table_item->setToolTip(tooltips[r]);
}
}
void DBTableWidget::setColumnColors(const QString& column_header, const QList<QColor>& colors)
{
if (colors.count()!=rowCount())
{
THROW(ArgumentException, "Invalid color count '" + QString::number(colors.count()) + "' in DBTableWidget::setColumnColors - expected '" + QString::number(rowCount()) + "'!");
}
int c = columnIndex(column_header);
for (int r=0; r<rowCount(); ++r)
{
const QColor& color = colors[r];
if (!color.isValid()) continue;
QTableWidgetItem* table_item = item(r, c);
if (table_item==nullptr) continue;
table_item->setBackgroundColor(color);
}
}
void DBTableWidget::setBackgroundColorIfContains(const QString& column_header, const QColor& color, const QString& substring)
{
setBackgroundColorIf(column_header, color, [substring](const QString& str) { return str.contains(substring); });
}
void DBTableWidget::setBackgroundColorIfEqual(const QString& column_header, const QColor& color, const QString& text)
{
setBackgroundColorIf(column_header, color, [text](const QString& str) { return str==text; });
}
void DBTableWidget::setBackgroundColorIfLt(const QString& column_header, const QColor& color, double cutoff)
{
setBackgroundColorIf(column_header, color, [cutoff](const QString& str) { bool ok; double value = str.toDouble(&ok); if (!ok) return false; return value<cutoff; });
}
void DBTableWidget::setBackgroundColorIfGt(const QString& column_header, const QColor& color, double cutoff)
{
setBackgroundColorIf(column_header, color, [cutoff](const QString& str) { bool ok; double value = str.toDouble(&ok); if (!ok) return false; return value>cutoff; });
}
void DBTableWidget::showTextAsTooltip(const QString& column_header)
{
int c = columnIndex(column_header);
for (int r=0; r<rowCount(); ++r)
{
QTableWidgetItem* table_item = item(r, c);
if (table_item==nullptr) continue;
table_item->setToolTip(table_item->text());
}
}
QSet<int> DBTableWidget::selectedRows() const
{
QSet<int> output;
foreach(const QTableWidgetSelectionRange& range, selectedRanges())
{
for (int row=range.topRow(); row<=range.bottomRow(); ++row)
{
output << row;
}
}
return output;
}
QSet<int> DBTableWidget::selectedColumns() const
{
QSet<int> output;
foreach(const QTableWidgetSelectionRange& range, selectedRanges())
{
for (int col=range.leftColumn(); col<=range.rightColumn(); ++col)
{
output << col;
}
}
return output;
}
const QString& DBTableWidget::getId(int r) const
{
if (r<0 || r>=rowCount())
{
THROW(ArgumentException, "Invalid row index '" + QString::number(r) + "' in DBTableWidget::getId!");
}
return ids_[r];
}
const QString& DBTableWidget::tableName() const
{
return table_;
}
void DBTableWidget::styleQuality(QTableWidgetItem* item, const QString& quality)
{
//init
static QIcon i_good = QIcon(":/Icons/quality_good.png");
static QIcon i_medium = QIcon(":/Icons/quality_medium.png");
static QIcon i_bad = QIcon(":/Icons/quality_bad.png");
static QIcon i_na = QIcon(":/Icons/quality_unset.png");
//icon
if (quality=="good") item->setIcon(i_good);
else if (quality=="medium") item->setIcon(i_medium);
else if (quality=="bad") item->setIcon(i_bad);
else item->setIcon(i_na);
//tooltip
item->setToolTip(quality);
}
void DBTableWidget::keyPressEvent(QKeyEvent* event)
{
if(event->matches(QKeySequence::Copy))
{
copySelectionToClipboard();
event->accept();
return;
}
QTableWidget::keyPressEvent(event);
}
void DBTableWidget::copySelectionToClipboard()
{
GUIHelper::copyToClipboard(this, true);
}
void DBTableWidget::copyTableToClipboard()
{
GUIHelper::copyToClipboard(this, false);
}
void DBTableWidget::processDoubleClick(int row, int /*column*/)
{
emit rowDoubleClicked(row);
}
| 7,143 | 2,547 |
#include <xpcc/architecture/driver/accessor.hpp>
namespace bitmap
{
FLASH_STORAGE(uint8_t skull_64x64[]) =
{
64, 64,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xe0, 0x60, 0x30, 0x18, 0x08, 0x0c, 0x0c, 0x04, 0x06, 0x06, 0x02, 0x02, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x02, 0x02, 0x06, 0x06, 0x04, 0x0c, 0x0c, 0x18, 0x18, 0x30, 0x60, 0xc0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x3e, 0x07, 0x01, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x03, 0x0f, 0x7c, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7f, 0xf0, 0x80, 0x03, 0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x3f, 0x03, 0x80, 0xf0, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xc0, 0xc0, 0x40, 0xc0, 0x80, 0x00, 0x00, 0x00, 0x00, 0x01, 0x07, 0x0e, 0xfc, 0x7f, 0x00, 0x00, 0x3e, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x3c, 0x00, 0x00, 0x7f, 0xfc, 0x0e, 0x07, 0x01, 0x00, 0x00, 0x00, 0x80, 0x80, 0xc0, 0x80, 0x80, 0x00, 0x00, 0x00,
0xf0, 0xb8, 0x9e, 0x8f, 0x80, 0x80, 0x80, 0x83, 0x07, 0x0c, 0x18, 0x18, 0x30, 0x30, 0x60, 0x6f, 0xfc, 0xf0, 0xe0, 0xc0, 0xc0, 0xc1, 0xc1, 0x83, 0x03, 0x01, 0x00, 0x00, 0x00, 0xfc, 0xfe, 0xff, 0x00, 0xff, 0xfe, 0xf8, 0x00, 0x00, 0x00, 0x01, 0x03, 0x83, 0x81, 0xc1, 0xc0, 0xe0, 0xe0, 0xf0, 0xfc, 0xcf, 0x40, 0x60, 0x30, 0x10, 0x1c, 0x0e, 0x03, 0x01, 0x00, 0x01, 0x1f, 0x30, 0x60, 0xc0,
0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x03, 0x02, 0x06, 0x04, 0x0c, 0x0c, 0x18, 0x18, 0x30, 0x30, 0x63, 0xff, 0x31, 0x0d, 0xe3, 0x0f, 0x5c, 0xf0, 0x90, 0xf0, 0x11, 0xe1, 0x20, 0xe0, 0x10, 0xf1, 0x11, 0xf0, 0x90, 0x90, 0xdc, 0x0f, 0xf1, 0x0f, 0xf9, 0xff, 0xc7, 0x61, 0x61, 0x30, 0x30, 0x18, 0x18, 0x0c, 0x04, 0x06, 0x02, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x01,
0x00, 0x00, 0x00, 0x00, 0xe0, 0xb0, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x10, 0x18, 0x08, 0x0c, 0x0c, 0x86, 0xc2, 0xc3, 0x6f, 0x7e, 0x70, 0xc1, 0x83, 0x82, 0x07, 0x04, 0x07, 0x08, 0x0f, 0x09, 0x0f, 0x09, 0x0f, 0x09, 0x05, 0x04, 0x05, 0x82, 0xc3, 0xe0, 0x70, 0x7f, 0x6f, 0xc6, 0xcc, 0x8c, 0x08, 0x18, 0x10, 0x30, 0x20, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0xc0, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x07, 0x7e, 0x60, 0x40, 0x60, 0x30, 0x1c, 0x06, 0x02, 0x03, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x03, 0x03, 0x02, 0x02, 0x02, 0x06, 0x06, 0x06, 0x02, 0x02, 0x02, 0x03, 0x03, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x03, 0x02, 0x06, 0x1c, 0x30, 0x60, 0x40, 0x60, 0x3c, 0x06, 0x03, 0x01, 0x00, 0x00, 0x00,
};
}
| 3,218 | 3,081 |
/**
* \class L1RetrieveL1Extra
*
*
* Description: retrieve L1Extra collection, return validity flag and pointer to collection.
*
* Implementation:
* <TODO: enter implementation details>
*
* \author: Vasile Mihai Ghete - HEPHY Vienna
*
*
*/
// this class header
#include "L1Trigger/GlobalTriggerAnalyzer/interface/L1RetrieveL1Extra.h"
// system include files
#include <iostream>
#include <memory>
#include <string>
// user include files
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
// constructor
L1RetrieveL1Extra::L1RetrieveL1Extra(const edm::ParameterSet& paramSet, edm::ConsumesCollector&& iC)
: //
m_tagL1ExtraMuon(paramSet.getParameter<edm::InputTag>("TagL1ExtraMuon")),
m_tagL1ExtraIsoEG(paramSet.getParameter<edm::InputTag>("TagL1ExtraIsoEG")),
m_tagL1ExtraNoIsoEG(paramSet.getParameter<edm::InputTag>("TagL1ExtraNoIsoEG")),
m_tagL1ExtraCenJet(paramSet.getParameter<edm::InputTag>("TagL1ExtraCenJet")),
m_tagL1ExtraForJet(paramSet.getParameter<edm::InputTag>("TagL1ExtraForJet")),
m_tagL1ExtraTauJet(paramSet.getParameter<edm::InputTag>("TagL1ExtraTauJet")),
m_tagL1ExtraEtMissMET(paramSet.getParameter<edm::InputTag>("TagL1ExtraEtMissMET")),
m_tagL1ExtraEtMissHTM(paramSet.getParameter<edm::InputTag>("TagL1ExtraEtMissHTM")),
m_tagL1ExtraHFRings(paramSet.getParameter<edm::InputTag>("TagL1ExtraHFRings")),
//
//
m_validL1ExtraMuon(false),
m_validL1ExtraIsoEG(false),
m_validL1ExtraNoIsoEG(false),
m_validL1ExtraCenJet(false),
m_validL1ExtraForJet(false),
m_validL1ExtraTauJet(false),
m_validL1ExtraETT(false),
m_validL1ExtraETM(false),
m_validL1ExtraHTT(false),
m_validL1ExtraHTM(false),
m_validL1ExtraHfBitCounts(false),
m_validL1ExtraHfRingEtSums(false),
//
m_l1ExtraMuon(nullptr),
m_l1ExtraIsoEG(nullptr),
m_l1ExtraNoIsoEG(nullptr),
m_l1ExtraCenJet(nullptr),
m_l1ExtraForJet(nullptr),
m_l1ExtraTauJet(nullptr),
m_l1ExtraETT(nullptr),
m_l1ExtraETM(nullptr),
m_l1ExtraHTT(nullptr),
m_l1ExtraHTM(nullptr),
m_l1ExtraHfBitCounts(nullptr),
m_l1ExtraHfRingEtSums(nullptr)
//
{
m_tagL1ExtraMuonTok = iC.consumes<l1extra::L1MuonParticleCollection>(m_tagL1ExtraMuon);
m_tagL1ExtraIsoEGTok = iC.consumes<l1extra::L1EmParticleCollection>(m_tagL1ExtraIsoEG);
m_tagL1ExtraNoIsoEGTok = iC.consumes<l1extra::L1EmParticleCollection>(m_tagL1ExtraNoIsoEG);
m_tagL1ExtraCenJetTok = iC.consumes<l1extra::L1JetParticleCollection>(m_tagL1ExtraCenJet);
m_tagL1ExtraForJetTok = iC.consumes<l1extra::L1JetParticleCollection>(m_tagL1ExtraForJet);
m_tagL1ExtraTauJetTok = iC.consumes<l1extra::L1JetParticleCollection>(m_tagL1ExtraTauJet);
m_tagL1ExtraEtMissMETTok = iC.consumes<l1extra::L1EtMissParticleCollection>(m_tagL1ExtraEtMissMET);
m_tagL1ExtraEtMissHTMTok = iC.consumes<l1extra::L1EtMissParticleCollection>(m_tagL1ExtraEtMissHTM);
m_tagL1ExtraHFRingsTok = iC.consumes<l1extra::L1HFRingsCollection>(m_tagL1ExtraHFRings);
// empty
}
// destructor
L1RetrieveL1Extra::~L1RetrieveL1Extra() {
// empty
}
void L1RetrieveL1Extra::retrieveL1ExtraObjects(const edm::Event& iEvent, const edm::EventSetup& evSetup) {
//
edm::Handle<l1extra::L1MuonParticleCollection> collL1ExtraMuon;
iEvent.getByToken(m_tagL1ExtraMuonTok, collL1ExtraMuon);
if (collL1ExtraMuon.isValid()) {
m_validL1ExtraMuon = true;
m_l1ExtraMuon = collL1ExtraMuon.product();
} else {
LogDebug("L1RetrieveL1Extra") << "\n l1extra::L1MuonParticleCollection with input tag \n " << m_tagL1ExtraMuon
<< "\n not found in the event.\n"
<< "\n Return pointer 0 and false validity tag." << std::endl;
m_validL1ExtraMuon = false;
m_l1ExtraMuon = nullptr;
}
//
edm::Handle<l1extra::L1EmParticleCollection> collL1ExtraIsoEG;
iEvent.getByToken(m_tagL1ExtraIsoEGTok, collL1ExtraIsoEG);
if (collL1ExtraIsoEG.isValid()) {
m_validL1ExtraIsoEG = true;
m_l1ExtraIsoEG = collL1ExtraIsoEG.product();
} else {
LogDebug("L1RetrieveL1Extra") << "\n l1extra::L1EmParticleCollection with input tag \n " << m_tagL1ExtraIsoEG
<< "\n not found in the event.\n"
<< "\n Return pointer 0 and false validity tag." << std::endl;
m_validL1ExtraIsoEG = false;
m_l1ExtraIsoEG = nullptr;
}
edm::Handle<l1extra::L1EmParticleCollection> collL1ExtraNoIsoEG;
iEvent.getByToken(m_tagL1ExtraNoIsoEGTok, collL1ExtraNoIsoEG);
if (collL1ExtraNoIsoEG.isValid()) {
m_validL1ExtraNoIsoEG = true;
m_l1ExtraNoIsoEG = collL1ExtraNoIsoEG.product();
} else {
LogDebug("L1RetrieveL1Extra") << "\n l1extra::L1EmParticleCollection with input tag \n " << m_tagL1ExtraNoIsoEG
<< "\n not found in the event.\n"
<< "\n Return pointer 0 and false validity tag." << std::endl;
m_validL1ExtraNoIsoEG = false;
m_l1ExtraNoIsoEG = nullptr;
}
//
edm::Handle<l1extra::L1JetParticleCollection> collL1ExtraCenJet;
iEvent.getByToken(m_tagL1ExtraCenJetTok, collL1ExtraCenJet);
if (collL1ExtraCenJet.isValid()) {
m_validL1ExtraCenJet = true;
m_l1ExtraCenJet = collL1ExtraCenJet.product();
} else {
LogDebug("L1RetrieveL1Extra") << "\n l1extra::L1JetParticleCollection with input tag \n " << m_tagL1ExtraCenJet
<< "\n not found in the event.\n"
<< "\n Return pointer 0 and false validity tag." << std::endl;
m_validL1ExtraCenJet = false;
m_l1ExtraCenJet = nullptr;
}
edm::Handle<l1extra::L1JetParticleCollection> collL1ExtraForJet;
iEvent.getByToken(m_tagL1ExtraForJetTok, collL1ExtraForJet);
if (collL1ExtraForJet.isValid()) {
m_validL1ExtraForJet = true;
m_l1ExtraForJet = collL1ExtraForJet.product();
} else {
LogDebug("L1RetrieveL1Extra") << "\n l1extra::L1JetParticleCollection with input tag \n " << m_tagL1ExtraForJet
<< "\n not found in the event.\n"
<< "\n Return pointer 0 and false validity tag." << std::endl;
m_validL1ExtraForJet = false;
m_l1ExtraForJet = nullptr;
}
edm::Handle<l1extra::L1JetParticleCollection> collL1ExtraTauJet;
iEvent.getByToken(m_tagL1ExtraTauJetTok, collL1ExtraTauJet);
if (collL1ExtraTauJet.isValid()) {
m_validL1ExtraTauJet = true;
m_l1ExtraTauJet = collL1ExtraTauJet.product();
} else {
LogDebug("L1RetrieveL1Extra") << "\n l1extra::L1JetParticleCollection with input tag \n " << m_tagL1ExtraTauJet
<< "\n not found in the event.\n"
<< "\n Return pointer 0 and false validity tag." << std::endl;
m_validL1ExtraTauJet = false;
m_l1ExtraTauJet = nullptr;
}
//
edm::Handle<l1extra::L1EtMissParticleCollection> collL1ExtraEtMissMET;
iEvent.getByToken(m_tagL1ExtraEtMissMETTok, collL1ExtraEtMissMET);
if (collL1ExtraEtMissMET.isValid()) {
m_validL1ExtraETT = true;
m_validL1ExtraETM = true;
m_l1ExtraETT = collL1ExtraEtMissMET.product();
m_l1ExtraETM = collL1ExtraEtMissMET.product();
} else {
LogDebug("L1RetrieveL1Extra") << "\n l1extra::L1EtMissParticleCollection with input tag \n "
<< m_tagL1ExtraEtMissMET << "\n not found in the event.\n"
<< "\n Return pointer 0 and false validity tag." << std::endl;
m_validL1ExtraETT = false;
m_validL1ExtraETM = false;
m_l1ExtraETT = nullptr;
m_l1ExtraETM = nullptr;
}
edm::Handle<l1extra::L1EtMissParticleCollection> collL1ExtraEtMissHTM;
iEvent.getByToken(m_tagL1ExtraEtMissHTMTok, collL1ExtraEtMissHTM);
if (collL1ExtraEtMissHTM.isValid()) {
m_validL1ExtraHTT = true;
m_validL1ExtraHTM = true;
m_l1ExtraHTT = collL1ExtraEtMissHTM.product();
m_l1ExtraHTM = collL1ExtraEtMissHTM.product();
} else {
LogDebug("L1RetrieveL1Extra") << "\n l1extra::L1EtMissParticleCollection with input tag \n "
<< m_tagL1ExtraEtMissHTM << "\n not found in the event.\n"
<< "\n Return pointer 0 and false validity tag." << std::endl;
m_validL1ExtraHTT = false;
m_validL1ExtraHTM = false;
m_l1ExtraHTT = nullptr;
m_l1ExtraHTM = nullptr;
}
//
edm::Handle<l1extra::L1HFRingsCollection> collL1ExtraHFRings;
iEvent.getByToken(m_tagL1ExtraHFRingsTok, collL1ExtraHFRings);
if (collL1ExtraHFRings.isValid()) {
m_validL1ExtraHfBitCounts = true;
m_validL1ExtraHfRingEtSums = true;
m_l1ExtraHfBitCounts = collL1ExtraHFRings.product();
m_l1ExtraHfRingEtSums = collL1ExtraHFRings.product();
} else {
LogDebug("L1RetrieveL1Extra") << "\n l1extra::L1HFRingsCollection with input tag \n " << m_tagL1ExtraHFRings
<< "\n not found in the event.\n"
<< "\n Return pointer 0 and false validity tag." << std::endl;
m_validL1ExtraHfBitCounts = false;
m_validL1ExtraHfRingEtSums = false;
m_l1ExtraHfBitCounts = nullptr;
m_l1ExtraHfRingEtSums = nullptr;
}
}
/// input tag for a given collection
const edm::InputTag L1RetrieveL1Extra::inputTagL1ExtraColl(const L1GtObject& gtObject) const {
edm::InputTag emptyInputTag;
switch (gtObject) {
case Mu: {
return m_tagL1ExtraMuon;
} break;
case NoIsoEG: {
return m_tagL1ExtraNoIsoEG;
} break;
case IsoEG: {
return m_tagL1ExtraIsoEG;
} break;
case CenJet: {
return m_tagL1ExtraCenJet;
} break;
case ForJet: {
return m_tagL1ExtraForJet;
} break;
case TauJet: {
return m_tagL1ExtraTauJet;
} break;
case ETM:
case ETT: {
return m_tagL1ExtraEtMissMET;
} break;
case HTT:
case HTM: {
return m_tagL1ExtraEtMissHTM;
} break;
case JetCounts: {
// TODO update when JetCounts will be available
return emptyInputTag;
} break;
case HfBitCounts:
case HfRingEtSums: {
return m_tagL1ExtraHFRings;
} break;
case TechTrig: {
return emptyInputTag;
} break;
case Castor: {
return emptyInputTag;
} break;
case BPTX: {
return emptyInputTag;
} break;
case GtExternal: {
return emptyInputTag;
} break;
case ObjNull: {
return emptyInputTag;
} break;
default: {
edm::LogInfo("L1GtObject") << "\n '" << gtObject << "' is not a recognized L1GtObject. ";
return emptyInputTag;
} break;
}
return emptyInputTag;
}
const bool L1RetrieveL1Extra::validL1ExtraColl(const L1GtObject& gtObject) const {
switch (gtObject) {
case Mu: {
return m_validL1ExtraMuon;
} break;
case NoIsoEG: {
return m_validL1ExtraNoIsoEG;
} break;
case IsoEG: {
return m_validL1ExtraIsoEG;
} break;
case CenJet: {
return m_validL1ExtraCenJet;
} break;
case ForJet: {
return m_validL1ExtraForJet;
} break;
case TauJet: {
return m_validL1ExtraTauJet;
} break;
case ETM: {
return m_validL1ExtraETM;
} break;
case ETT: {
return m_validL1ExtraETT;
} break;
case HTT: {
return m_validL1ExtraHTT;
} break;
case HTM: {
return m_validL1ExtraHTM;
} break;
case JetCounts: {
// TODO update when JetCounts will be available
return false;
} break;
case HfBitCounts: {
return m_validL1ExtraHfBitCounts;
} break;
case HfRingEtSums: {
return m_validL1ExtraHfRingEtSums;
} break;
case TechTrig: {
return false;
} break;
case Castor: {
return false;
} break;
case BPTX: {
return false;
} break;
case GtExternal: {
return false;
} break;
case ObjNull: {
return false;
} break;
default: {
edm::LogInfo("L1GtObject") << "\n '" << gtObject << "' is not a recognized L1GtObject. ";
return false;
} break;
}
return false;
}
void L1RetrieveL1Extra::printL1Extra(std::ostream& oStr,
const L1GtObject& gtObject,
const bool checkBxInEvent,
const int bxInEvent,
const bool checkObjIndexInColl,
const int objIndexInColl) const {
if (!validL1ExtraColl(gtObject)) {
oStr << "\n L1Extra collection for L1 GT object " << l1GtObjectEnumToString(gtObject)
<< " with collection input tag " << inputTagL1ExtraColl(gtObject) << " not valid." << std::endl;
}
switch (gtObject) {
case Mu: {
oStr << "\n Mu collection\n" << std::endl;
int indexInColl = -1;
for (l1extra::L1MuonParticleCollection::const_iterator iterColl = m_l1ExtraMuon->begin();
iterColl != m_l1ExtraMuon->end();
++iterColl) {
if (checkBxInEvent) {
if (iterColl->bx() != bxInEvent) {
continue;
oStr << "\n BxInEvent " << bxInEvent << ": collection not in the event" << std::endl;
} else {
indexInColl++;
if (!checkObjIndexInColl) {
oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " indexInColl = " << indexInColl
<< " PT = " << std::right << std::setw(6) << (iterColl->pt()) << " GeV"
<< " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right
<< std::setw(8) << (iterColl->phi()) << " rad" << std::endl;
} else {
if (objIndexInColl == indexInColl) {
oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent
<< " indexInColl = " << indexInColl << " PT = " << std::right << std::setw(6) << (iterColl->pt())
<< " GeV"
<< " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right
<< std::setw(8) << (iterColl->phi()) << " rad" << std::endl;
}
}
}
} else {
oStr << " bxInEvent = " << std::right << std::setw(2) << (iterColl->bx()) << " PT = " << std::right
<< std::setw(6) << (iterColl->pt()) << " GeV"
<< " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right
<< std::setw(8) << (iterColl->phi()) << " rad" << std::endl;
}
}
} break;
case NoIsoEG: {
oStr << "\n NoIsoEG collection\n" << std::endl;
int indexInColl = -1;
for (l1extra::L1EmParticleCollection::const_iterator iterColl = m_l1ExtraNoIsoEG->begin();
iterColl != m_l1ExtraNoIsoEG->end();
++iterColl) {
if (checkBxInEvent) {
if (iterColl->bx() != bxInEvent) {
continue;
oStr << "\n BxInEvent " << bxInEvent << ": collection not in the event" << std::endl;
} else {
indexInColl++;
if (!checkObjIndexInColl) {
oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " indexInColl = " << indexInColl
<< " ET = " << std::right << std::setw(6) << (iterColl->et()) << " GeV"
<< " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right
<< std::setw(8) << (iterColl->phi()) << " rad" << std::endl;
} else {
if (objIndexInColl == indexInColl) {
oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent
<< " indexInColl = " << indexInColl << " ET = " << std::right << std::setw(6) << (iterColl->et())
<< " GeV"
<< " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right
<< std::setw(8) << (iterColl->phi()) << " rad" << std::endl;
}
}
}
} else {
oStr << " bxInEvent = " << std::right << std::setw(2) << (iterColl->bx()) << " ET = " << std::right
<< std::setw(6) << (iterColl->et()) << " GeV"
<< " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right
<< std::setw(8) << (iterColl->phi()) << " rad" << std::endl;
}
}
} break;
case IsoEG: {
oStr << "\n IsoEG collection\n" << std::endl;
int indexInColl = -1;
for (l1extra::L1EmParticleCollection::const_iterator iterColl = m_l1ExtraIsoEG->begin();
iterColl != m_l1ExtraIsoEG->end();
++iterColl) {
if (checkBxInEvent) {
if (iterColl->bx() != bxInEvent) {
continue;
oStr << "\n BxInEvent " << bxInEvent << ": collection not in the event" << std::endl;
} else {
indexInColl++;
if (!checkObjIndexInColl) {
oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " indexInColl = " << indexInColl
<< " ET = " << std::right << std::setw(6) << (iterColl->et()) << " GeV"
<< " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right
<< std::setw(8) << (iterColl->phi()) << " rad" << std::endl;
} else {
if (objIndexInColl == indexInColl) {
oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent
<< " indexInColl = " << indexInColl << " ET = " << std::right << std::setw(6) << (iterColl->et())
<< " GeV"
<< " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right
<< std::setw(8) << (iterColl->phi()) << " rad" << std::endl;
}
}
}
} else {
oStr << " bxInEvent = " << std::right << std::setw(2) << (iterColl->bx()) << " ET = " << std::right
<< std::setw(6) << (iterColl->et()) << " GeV"
<< " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right
<< std::setw(8) << (iterColl->phi()) << " rad" << std::endl;
}
}
} break;
case CenJet: {
oStr << "\n CenJet collection\n" << std::endl;
int indexInColl = -1;
for (l1extra::L1JetParticleCollection::const_iterator iterColl = m_l1ExtraCenJet->begin();
iterColl != m_l1ExtraCenJet->end();
++iterColl) {
if (checkBxInEvent) {
if (iterColl->bx() != bxInEvent) {
continue;
oStr << "\n BxInEvent " << bxInEvent << ": collection not in the event" << std::endl;
} else {
indexInColl++;
if (!checkObjIndexInColl) {
oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " indexInColl = " << indexInColl
<< " ET = " << std::right << std::setw(6) << (iterColl->et()) << " GeV"
<< " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right
<< std::setw(8) << (iterColl->phi()) << " rad" << std::endl;
} else {
if (objIndexInColl == indexInColl) {
oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent
<< " indexInColl = " << indexInColl << " ET = " << std::right << std::setw(6) << (iterColl->et())
<< " GeV"
<< " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right
<< std::setw(8) << (iterColl->phi()) << " rad" << std::endl;
}
}
}
} else {
oStr << " bxInEvent = " << std::right << std::setw(2) << (iterColl->bx()) << " ET = " << std::right
<< std::setw(6) << (iterColl->et()) << " GeV"
<< " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right
<< std::setw(8) << (iterColl->phi()) << " rad" << std::endl;
}
}
} break;
case ForJet: {
oStr << "\n ForJet collection\n" << std::endl;
int indexInColl = -1;
for (l1extra::L1JetParticleCollection::const_iterator iterColl = m_l1ExtraForJet->begin();
iterColl != m_l1ExtraForJet->end();
++iterColl) {
if (checkBxInEvent) {
if (iterColl->bx() != bxInEvent) {
continue;
oStr << "\n BxInEvent " << bxInEvent << ": collection not in the event" << std::endl;
} else {
indexInColl++;
if (!checkObjIndexInColl) {
oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " indexInColl = " << indexInColl
<< " ET = " << std::right << std::setw(6) << (iterColl->et()) << " GeV"
<< " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right
<< std::setw(8) << (iterColl->phi()) << " rad" << std::endl;
} else {
if (objIndexInColl == indexInColl) {
oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent
<< " indexInColl = " << indexInColl << " ET = " << std::right << std::setw(6) << (iterColl->et())
<< " GeV"
<< " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right
<< std::setw(8) << (iterColl->phi()) << " rad" << std::endl;
}
}
}
} else {
oStr << " bxInEvent = " << std::right << std::setw(2) << (iterColl->bx()) << " ET = " << std::right
<< std::setw(6) << (iterColl->et()) << " GeV"
<< " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right
<< std::setw(8) << (iterColl->phi()) << " rad" << std::endl;
}
}
} break;
case TauJet: {
oStr << "\n TauJet collection\n" << std::endl;
int indexInColl = -1;
for (l1extra::L1JetParticleCollection::const_iterator iterColl = m_l1ExtraTauJet->begin();
iterColl != m_l1ExtraTauJet->end();
++iterColl) {
if (checkBxInEvent) {
if (iterColl->bx() != bxInEvent) {
continue;
oStr << "\n BxInEvent " << bxInEvent << ": collection not in the event" << std::endl;
} else {
indexInColl++;
if (!checkObjIndexInColl) {
oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " indexInColl = " << indexInColl
<< " ET = " << std::right << std::setw(6) << (iterColl->et()) << " GeV"
<< " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right
<< std::setw(8) << (iterColl->phi()) << " rad" << std::endl;
} else {
if (objIndexInColl == indexInColl) {
oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent
<< " indexInColl = " << indexInColl << " ET = " << std::right << std::setw(6) << (iterColl->et())
<< " GeV"
<< " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right
<< std::setw(8) << (iterColl->phi()) << " rad" << std::endl;
}
}
}
} else {
oStr << " bxInEvent = " << std::right << std::setw(2) << (iterColl->bx()) << " ET = " << std::right
<< std::setw(6) << (iterColl->et()) << " GeV"
<< " eta = " << std::right << std::setw(8) << (iterColl->eta()) << " phi = " << std::right
<< std::setw(8) << (iterColl->phi()) << " rad" << std::endl;
}
}
} break;
case ETM: {
oStr << "\n ETM collection\n" << std::endl;
int indexInColl = -1;
for (l1extra::L1EtMissParticleCollection::const_iterator iterColl = m_l1ExtraETM->begin();
iterColl != m_l1ExtraETM->end();
++iterColl) {
if (checkBxInEvent) {
if (iterColl->bx() != bxInEvent) {
continue;
oStr << "\n BxInEvent " << bxInEvent << ": collection not in the event" << std::endl;
} else {
indexInColl++;
if (!checkObjIndexInColl) {
oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " indexInColl = " << indexInColl
<< " ET = " << std::right << std::setw(6) << (iterColl->et()) << " GeV"
<< " phi = " << std::right << std::setw(8) << (iterColl->phi()) << " rad" << std::endl;
} else {
if (objIndexInColl == indexInColl) {
oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent
<< " indexInColl = " << indexInColl << " ET = " << std::right << std::setw(6) << (iterColl->et())
<< " GeV"
<< " phi = " << std::right << std::setw(8) << (iterColl->phi()) << " rad" << std::endl;
}
}
}
} else {
oStr << " bxInEvent = " << std::right << std::setw(2) << (iterColl->bx()) << " ET = " << std::right
<< std::setw(6) << (iterColl->et()) << " GeV"
<< " phi = " << std::right << std::setw(8) << (iterColl->phi()) << " rad" << std::endl;
}
}
} break;
case ETT: {
oStr << "\n ETT collection\n" << std::endl;
int indexInColl = -1;
for (l1extra::L1EtMissParticleCollection::const_iterator iterColl = m_l1ExtraETT->begin();
iterColl != m_l1ExtraETT->end();
++iterColl) {
if (checkBxInEvent) {
if (iterColl->bx() != bxInEvent) {
continue;
oStr << "\n BxInEvent " << bxInEvent << ": collection not in the event" << std::endl;
} else {
indexInColl++;
if (!checkObjIndexInColl) {
oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " indexInColl = " << indexInColl
<< " ET = " << std::right << std::setw(6) << (iterColl->etTotal()) << " GeV" << std::endl;
} else {
if (objIndexInColl == indexInColl) {
oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent
<< " indexInColl = " << indexInColl << " ET = " << std::right << std::setw(6)
<< (iterColl->etTotal()) << " GeV" << std::endl;
}
}
}
} else {
oStr << " bxInEvent = " << std::right << std::setw(2) << (iterColl->bx()) << " ET = " << std::right
<< std::setw(6) << (iterColl->etTotal()) << " GeV" << std::endl;
}
}
} break;
case HTT: {
oStr << "\n HTT collection\n" << std::endl;
int indexInColl = -1;
for (l1extra::L1EtMissParticleCollection::const_iterator iterColl = m_l1ExtraHTT->begin();
iterColl != m_l1ExtraHTT->end();
++iterColl) {
if (checkBxInEvent) {
if (iterColl->bx() != bxInEvent) {
continue;
oStr << "\n BxInEvent " << bxInEvent << ": collection not in the event" << std::endl;
} else {
indexInColl++;
if (!checkObjIndexInColl) {
oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " indexInColl = " << indexInColl
<< " ET = " << std::right << std::setw(6) << (iterColl->etTotal()) << " GeV" << std::endl;
} else {
if (objIndexInColl == indexInColl) {
oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent
<< " indexInColl = " << indexInColl << " ET = " << std::right << std::setw(6)
<< (iterColl->etTotal()) << " GeV" << std::endl;
}
}
}
} else {
oStr << " bxInEvent = " << std::right << std::setw(2) << (iterColl->bx()) << " ET = " << std::right
<< std::setw(6) << (iterColl->etTotal()) << " GeV" << std::endl;
}
}
} break;
case HTM: {
oStr << "\n HTM collection\n" << std::endl;
int indexInColl = -1;
for (l1extra::L1EtMissParticleCollection::const_iterator iterColl = m_l1ExtraHTM->begin();
iterColl != m_l1ExtraHTM->end();
++iterColl) {
if (checkBxInEvent) {
if (iterColl->bx() != bxInEvent) {
continue;
oStr << "\n BxInEvent " << bxInEvent << ": collection not in the event" << std::endl;
} else {
indexInColl++;
if (!checkObjIndexInColl) {
oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " indexInColl = " << indexInColl
<< " ET = " << std::right << std::setw(6) << (iterColl->et()) << " GeV"
<< " phi = " << std::right << std::setw(8) << (iterColl->phi()) << " rad" << std::endl;
} else {
if (objIndexInColl == indexInColl) {
oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent
<< " indexInColl = " << indexInColl << " ET = " << std::right << std::setw(6) << (iterColl->et())
<< " GeV"
<< " phi = " << std::right << std::setw(8) << (iterColl->phi()) << " rad" << std::endl;
}
}
}
} else {
oStr << " bxInEvent = " << std::right << std::setw(2) << (iterColl->bx()) << " ET = " << std::right
<< std::setw(6) << (iterColl->et()) << " GeV"
<< " phi = " << std::right << std::setw(8) << (iterColl->phi()) << " rad" << std::endl;
}
}
} break;
case JetCounts: {
// TODO print if and when JetCounts will be available
} break;
case HfBitCounts: {
oStr << "\n HfBitCounts collection\n" << std::endl;
for (l1extra::L1HFRingsCollection::const_iterator iterColl = m_l1ExtraHfBitCounts->begin();
iterColl != m_l1ExtraHfBitCounts->end();
++iterColl) {
if (checkBxInEvent) {
if (iterColl->bx() != bxInEvent) {
continue;
oStr << "\n BxInEvent " << bxInEvent << ": collection not in the event" << std::endl;
} else {
if (!checkObjIndexInColl) {
for (int iCount = 0; iCount < l1extra::L1HFRings::kNumRings; ++iCount) {
oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " count = " << iCount
<< " HF counts = " << (iterColl->hfBitCount((l1extra::L1HFRings::HFRingLabels)iCount))
<< std::endl;
}
} else {
for (int iCount = 0; iCount < l1extra::L1HFRings::kNumRings; ++iCount) {
if (objIndexInColl == iCount) {
oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " count = " << iCount
<< " HF counts = " << (iterColl->hfBitCount((l1extra::L1HFRings::HFRingLabels)iCount))
<< std::endl;
}
}
}
}
} else {
for (int iCount = 0; iCount < l1extra::L1HFRings::kNumRings; ++iCount) {
if (objIndexInColl == iCount) {
oStr << " bxInEvent = " << std::right << std::setw(2) << (iterColl->bx()) << " count = " << iCount
<< " HF counts = " << (iterColl->hfBitCount((l1extra::L1HFRings::HFRingLabels)iCount)) << std::endl;
}
}
}
}
} break;
case HfRingEtSums: {
oStr << "\n HfRingEtSums collection\n" << std::endl;
for (l1extra::L1HFRingsCollection::const_iterator iterColl = m_l1ExtraHfRingEtSums->begin();
iterColl != m_l1ExtraHfRingEtSums->end();
++iterColl) {
if (checkBxInEvent) {
if (iterColl->bx() != bxInEvent) {
continue;
oStr << "\n BxInEvent " << bxInEvent << ": collection not in the event" << std::endl;
} else {
if (!checkObjIndexInColl) {
for (int iCount = 0; iCount < l1extra::L1HFRings::kNumRings; ++iCount) {
oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " count = " << iCount
<< " HF ET sum = " << (iterColl->hfEtSum((l1extra::L1HFRings::HFRingLabels)iCount)) << " GeV"
<< std::endl;
}
} else {
for (int iCount = 0; iCount < l1extra::L1HFRings::kNumRings; ++iCount) {
if (objIndexInColl == iCount) {
oStr << " bxInEvent = " << std::right << std::setw(2) << bxInEvent << " count = " << iCount
<< " HF ET sum = " << (iterColl->hfEtSum((l1extra::L1HFRings::HFRingLabels)iCount)) << " GeV"
<< std::endl;
}
}
}
}
} else {
for (int iCount = 0; iCount < l1extra::L1HFRings::kNumRings; ++iCount) {
if (objIndexInColl == iCount) {
oStr << " bxInEvent = " << std::right << std::setw(2) << (iterColl->bx()) << " count = " << iCount
<< " HF ET sum = " << (iterColl->hfEtSum((l1extra::L1HFRings::HFRingLabels)iCount)) << " GeV"
<< std::endl;
}
}
}
}
} break;
case TechTrig: {
// do nothing, not in L1Extra
} break;
case Castor: {
// do nothing, not in L1Extra
} break;
case BPTX: {
// do nothing, not in L1Extra
} break;
case GtExternal: {
// do nothing, not in L1Extra
} break;
case ObjNull: {
// do nothing, not in L1Extra
} break;
default: {
edm::LogInfo("L1GtObject") << "\n '" << gtObject << "' is not a recognized L1GtObject. ";
// do nothing
} break;
}
}
void L1RetrieveL1Extra::printL1Extra(std::ostream& oStr, const L1GtObject& gtObject, const int bxInEvent) const {
bool checkBxInEvent = true;
bool checkObjIndexInColl = false;
int objIndexInColl = -1;
printL1Extra(oStr, gtObject, checkBxInEvent, bxInEvent, checkObjIndexInColl, objIndexInColl);
}
void L1RetrieveL1Extra::printL1Extra(std::ostream& oStr, const L1GtObject& gtObject) const {
bool checkBxInEvent = false;
bool checkObjIndexInColl = false;
int bxInEvent = 999;
int objIndexInColl = -1;
printL1Extra(oStr, gtObject, checkBxInEvent, bxInEvent, checkObjIndexInColl, objIndexInColl);
}
void L1RetrieveL1Extra::printL1Extra(std::ostream& oStr, const int iBxInEvent) const {
printL1Extra(oStr, Mu, iBxInEvent);
printL1Extra(oStr, NoIsoEG, iBxInEvent);
printL1Extra(oStr, IsoEG, iBxInEvent);
printL1Extra(oStr, CenJet, iBxInEvent);
printL1Extra(oStr, ForJet, iBxInEvent);
printL1Extra(oStr, TauJet, iBxInEvent);
printL1Extra(oStr, ETM, iBxInEvent);
printL1Extra(oStr, ETT, iBxInEvent);
printL1Extra(oStr, HTT, iBxInEvent);
printL1Extra(oStr, HTM, iBxInEvent);
// printL1Extra(oStr, JetCounts, iBxInEvent);
printL1Extra(oStr, HfBitCounts, iBxInEvent);
printL1Extra(oStr, HfRingEtSums, iBxInEvent);
}
void L1RetrieveL1Extra::printL1Extra(std::ostream& oStr) const {
printL1Extra(oStr, Mu);
printL1Extra(oStr, NoIsoEG);
printL1Extra(oStr, IsoEG);
printL1Extra(oStr, CenJet);
printL1Extra(oStr, ForJet);
printL1Extra(oStr, TauJet);
printL1Extra(oStr, ETM);
printL1Extra(oStr, ETT);
printL1Extra(oStr, HTT);
printL1Extra(oStr, HTM);
// printL1Extra(oStr, JetCounts);
printL1Extra(oStr, HfBitCounts);
printL1Extra(oStr, HfRingEtSums);
}
| 36,384 | 13,021 |
class Solution {
public:
string convert(string s, int n) {
//OM GAN GANAPATHAYE NAMO NAMAH
//JAI SHRI RAM
//JAI BAJRANGBALI
//AMME NARAYANA, DEVI NARAYANA, LAKSHMI NARAYANA, BHADRE NARAYANA
if(n == 0 || n == 1)
return s;
string res;
for(int i = 1; i <= n; i++)
{
int j = i-1;
char dir = 'd';
while(j < s.length())
{
if(i == 1 || i == n)
{
res.push_back(s[j]);
j += (2*n - 2);
}
else
{
if(dir == 'd')
{
res.push_back(s[j]);
j += 2*(n - i);
dir = 'u';
}
else
{
res.push_back(s[j]);
j += 2*(i-1);
dir = 'd';
}
}
}
}
return res;
}
};
| 1,093 | 344 |
class Solution {
public:
vector<int> countSubTrees(int n, vector<vector<int>> &edges, string labels) {
vector<vector<int>> g(n);
for (auto &v : edges) {
g[v[0]].push_back(v[1]);
g[v[1]].push_back(v[0]);
}
vector<int> ans(n);
dfs(ans, g, labels);
return ans;
}
vector<int> dfs(vector<int> &ans, vector<vector<int>> &g, string &labels,
int i = 0, int parent = -1) {
vector<int> temp(26);
for (int j : g[i]) {
if (j == parent)
continue;
auto temp2 = dfs(ans, g, labels, j, i);
for (int i = 0; i < 26; i++)
temp[i] += temp2[i];
}
ans[i] = ++temp[labels[i] - 'a'];
return temp;
}
};
| 697 | 288 |
#include <QApplication>
#include <QFontDatabase>
#include <QWidget>
#include <QVBoxLayout>
#include "keyboard.h"
#include "display.h"
int main(int argc, char **argv)
{
QApplication a(argc, argv);
QFontDatabase::addApplicationFont(":/gemunu-libre.bold.otf");
Display* disp = new Display(12);
Keyboard* kb = new Keyboard(disp);
QVBoxLayout* mainLay = new QVBoxLayout;
mainLay->addWidget(disp);
mainLay->addWidget(kb);
QWidget wid;
wid.setLayout(mainLay);
wid.setWindowTitle("Calculator");
wid.show();
return a.exec();
}
| 552 | 218 |
/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkVersion.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
Portions of this code are covered under the VTK copyright.
See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "itkVersion.h"
namespace itk
{
Version::Version()
{
}
Version::~Version()
{
}
const char *
Version::GetITKVersion()
{
return ITK_VERSION;
}
int
Version::GetITKMajorVersion()
{
return ITK_VERSION_MAJOR;
}
int
Version::GetITKMinorVersion()
{
return ITK_VERSION_MINOR;
}
int
Version::GetITKBuildVersion()
{
return ITK_VERSION_PATCH;
}
const char *
Version::GetITKSourceVersion()
{
return ITK_SOURCE_VERSION;
}
} // end namespace itk
| 1,257 | 419 |
//Author:LanceYu
#include<iostream>
#include<string>
#include<cstring>
#include<cstdio>
#include<fstream>
#include<iosfwd>
#include<sstream>
#include<fstream>
#include<cwchar>
#include<iomanip>
#include<ostream>
#include<vector>
#include<cstdlib>
#include<queue>
#include<set>
#include<ctime>
#include<algorithm>
#include<complex>
#include<cmath>
#include<valarray>
#include<bitset>
#include<iterator>
#define ll long long
using namespace std;
const double clf=1e-8;
//const double e=2.718281828;
const double PI=3.141592653589793;
const int MMAX=2147483647;
const int mod=1e9+7;
//priority_queue<int>p;
//priority_queue<int,vector<int>,greater<int> >pq;
int main()
{
int n,book[12]={31,28,31,30,31,30,31,31,30,31,30,31};
int d,h,m,month;
while(scanf("%d",&n)!=EOF)
{
d=1;h=0;m=0;month=1;
while(n>=86400)
{
n-=86400;
d++;
}
while(n>=3600)
{
n-=3600;
h++;
}
while(n>=60)
{
n-=60;
m++;
}
while(d>book[month-1])
{
d-=book[month-1];
month++;
}
printf("2009-%02d-%02d %02d:%02d:%02d\n",month,d,h,m,n);
}
return 0;
}
| 1,071 | 592 |
// ModelView.c++ - an Abstract Base Class for a combined Model and View for OpenGL
#include <iostream>
#include "ModelView.h"
#include "Controller.h"
cryph::AffPoint ModelView::eye(0, 0, 2);
cryph::AffPoint ModelView::center(0, 0, 0);
cryph::AffVector ModelView::up(0, 1, 0);
double ModelView::mcRegionOfInterest[6] = { -1.0, 1.0, -1.0, 1.0, -1.0, 1.0 };
ProjectionType ModelView::projType = PERSPECTIVE;
cryph::AffVector ModelView::obliqueProjectionDir(0.25, 0.5, 1.0);
double ModelView::ecZmin = -2.0;
double ModelView::ecZmax = -0.01; // for perspective, must be strictly < 0
double ModelView::zpp = -1.0; // for perspective, must be strictly < 0
double ModelView::dynamic_zoomScale = 1.0; // dynamic zoom
cryph::Matrix4x4 ModelView::dynamic_view; // dynamic 3D rotation/pan
ModelView::ModelView()
{
}
ModelView::~ModelView()
{
}
#if 0
void ModelView::addToGlobalRotationDegrees(double rx, double ry, double rz)
{
// TODO: 1. UPDATE dynamic_view
// TODO: 2. Use dynamic_view in ModelView::getMatrices
}
#endif
void ModelView::addToGlobalZoom(double increment)
{
dynamic_zoomScale += increment;
// TODO: Use dynamic_zoomScale in ModelView::getMatrices
}
// compute2DScaleTrans determines the current model coordinate region of
// interest and then uses linearMap to determine how to map coordinates
// in the region of interest to their proper location in Logical Device
// Space. (Returns float[] because glUniform currently favors float[].)
void ModelView::compute2DScaleTrans(float* scaleTransF) // CLASS METHOD
{
double xmin = mcRegionOfInterest[0];
double xmax = mcRegionOfInterest[1];
double ymin = mcRegionOfInterest[2];
double ymax = mcRegionOfInterest[3];
// preserve aspect ratio. Make "region of interest" wider or taller to
// match the Controller's viewport aspect ratio.
double vAR = Controller::getCurrentController()->getViewportAspectRatio();
matchAspectRatio(xmin, xmax, ymin, ymax, vAR);
double scaleTrans[4];
linearMap(xmin, xmax, -1.0, 1.0, scaleTrans[0], scaleTrans[1]);
linearMap(ymin, ymax, -1.0, 1.0, scaleTrans[2], scaleTrans[3]);
for (int i=0 ; i<4 ; i++)
scaleTransF[i] = static_cast<float>(scaleTrans[i]);
}
#if 0
void ModelView::getMatrices(cryph::Matrix4x4& mc_ec, cryph::Matrix4x4& ec_lds)
{
// TODO:
// 1. Create the mc_ec matrix:
// Matrix M_ECu is created from the eye, center, and up. You can use the
// following utility from Matrix4x4:
//
// cryph::Matrix4x4 cryph::Matrix4x4::lookAt(
// const cryph::AffPoint& eye, const cryph::AffPoint& center,
// const cryph::AffVector& up);
//
// NOTE: eye, center, and up are specified in MODEL COORDINATES (MC)
//
// So, for example:
// cryph::Matrix4x4 M_ECu = cryph::Matrix4x4::lookAt(eye, center, up);
//
// a) For project 2: mc_ec = M_ECu
// b) For project 3: mc_ec = dynamic_view * M_ECu
//
// 2. Create the ec_lds matrix:
// Using the WIDTHS of the established mcRegionOfInterest:
// i) Adjust in the x OR y direction to match the viewport aspect ratio;
// ii) Scale both widths by dynamic_zoom;
// iii) create the matrix using the method for the desired type of projection.
//
// Any of the three Matrix4x4 methods shown below (declared in Matrix4x4.h)
// can be used to create ec_lds. On a given call to this "getMatrices" routine,
// you will use EXACTLY ONE of them, depending on what type of projection you
// currently want.
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// !!!!! All coordinate data in the parameter lists below are specified !!!!!!
// !!!!! in EYE COORDINATES (EC)! Be VERY sure you understand what that !!!!!!
// !!!!! means! (This is why I emphasized "WIDTHS" above.) !!!!!!
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
/* The three choices:
cryph::Matrix4x4 cryph::Matrix4x4::orthogonal(double ecXmin, double ecXmax,
double ecYmin, double ecYmax, double ecZmin, double ecZmax);
cryph::Matrix4x4 cryph::Matrix4x4::perspective(double zpp, double ecXmin, double ecXmax,
double ecYmin, double ecYmax, double ecZmin, double ecZmax);
cryph::Matrix4x4 cryph::Matrix4x4::oblique(double zpp, double ecXmin, double ecXmax,
double ecYmin, double ecYmax, double ecZmin, double ecZmax, const cryph::AffVector& projDir);
*/
// For example:
// ec_lds = cryph::Matrix4x4::perspective(zpp, ecXmin, ecXmax, ecYmin, ecYmax, ecZmin, ecZmax);
//
// RECALL: Use the class variables ecZmin, ecZmax, and zpp in these calls.
// THEN IN THE CALLER OF THIS METHOD:
//
// float mat[16];
// glUniformMatrix4fv(ppuLoc_mc_ec, 1, false, mc_ec.extractColMajor(mat));
// glUniformMatrix4fv(ppuLoc_ec_lds, 1, false, ec_lds.extractColMajor(mat));
//
// (The extractColMajor method copies the elements of the matrix into the given
// array which is assumed to be of length 16. It then returns the array pointer
// so it can be used as indicated in the two calls. Since the array is immediately
// copied by glUniformMatrix to the GPU, "mat" can be reused as indicated.)
}
#endif
// linearMap determines the scale and translate parameters needed in
// order to map a value, f (fromMin <= f <= fromMax) to its corresponding
// value, t (toMin <= t <= toMax). Specifically: t = scale*f + trans.
void ModelView::linearMap(double fromMin, double fromMax, double toMin, double toMax,
double& scale, double& trans) // CLASS METHOD
{
scale = (toMax - toMin) / (fromMax - fromMin);
trans = toMin - scale*fromMin;
}
void ModelView::matchAspectRatio(double& xmin, double& xmax,
double& ymin, double& ymax, double vAR)
{
double wHeight = ymax - ymin;
double wWidth = xmax - xmin;
double wAR = wHeight / wWidth;
if (wAR > vAR)
{
// make window wider
wWidth = wHeight / vAR;
double xmid = 0.5 * (xmin + xmax);
xmin = xmid - 0.5*wWidth;
xmax = xmid + 0.5*wWidth;
}
else
{
// make window taller
wHeight = wWidth * vAR;
double ymid = 0.5 * (ymin + ymax);
ymin = ymid - 0.5*wHeight;
ymax = ymid + 0.5*wHeight;
}
}
GLint ModelView::ppUniformLocation(GLuint glslProgram, const std::string& name)
{
GLint loc = glGetUniformLocation(glslProgram, name.c_str());
if (loc < 0)
std::cerr << "Could not locate per-primitive uniform: '" << name << "'\n";
return loc;
}
GLint ModelView::pvAttribLocation(GLuint glslProgram, const std::string& name)
{
GLint loc = glGetAttribLocation(glslProgram, name.c_str());
if (loc < 0)
std::cerr << "Could not locate per-vertex attribute: '" << name << "'\n";
return loc;
}
void ModelView::setECZminZmax(double zMinIn, double zMaxIn)
{
ecZmin = zMinIn;
ecZmax = zMaxIn;
}
void ModelView::setEyeCenterUp(cryph::AffPoint E, cryph::AffPoint C, cryph::AffVector Up)
{
eye = E;
center = C;
up = Up;
}
void ModelView::setMCRegionOfInterest(double xyz[6])
{
for (int i=0 ; i<6 ; i++)
mcRegionOfInterest[i] = xyz[i];
}
void ModelView::setProjection(ProjectionType pType)
{
projType = pType;
}
void ModelView::setProjectionPlaneZ(double zppIn)
{
zpp = zppIn;
}
| 7,264 | 2,776 |
/***************************************************************************
qgsdecorationlayoutextentdialog.cpp
----------------------------
begin : May 2017
copyright : (C) 2017 by Nyall Dawson
email : nyall dot dawson at gmail dot com
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgsdecorationlayoutextentdialog.h"
#include "qgsdecorationlayoutextent.h"
#include "qgslogger.h"
#include "qgshelp.h"
#include "qgsstyle.h"
#include "qgssymbol.h"
#include "qgssymbolselectordialog.h"
#include "qgisapp.h"
#include "qgsguiutils.h"
#include "qgssettings.h"
#include "qgstextformatwidget.h"
#include "qgsgui.h"
QgsDecorationLayoutExtentDialog::QgsDecorationLayoutExtentDialog( QgsDecorationLayoutExtent &deco, QWidget *parent )
: QDialog( parent )
, mDeco( deco )
{
setupUi( this );
QgsGui::enableAutoGeometryRestore( this );
connect( buttonBox, &QDialogButtonBox::accepted, this, &QgsDecorationLayoutExtentDialog::buttonBox_accepted );
connect( buttonBox, &QDialogButtonBox::rejected, this, &QgsDecorationLayoutExtentDialog::buttonBox_rejected );
mSymbolButton->setSymbolType( QgsSymbol::Fill );
updateGuiElements();
connect( buttonBox->button( QDialogButtonBox::Apply ), &QAbstractButton::clicked, this, &QgsDecorationLayoutExtentDialog::apply );
connect( buttonBox, &QDialogButtonBox::helpRequested, this, &QgsDecorationLayoutExtentDialog::showHelp );
mSymbolButton->setMapCanvas( QgisApp::instance()->mapCanvas() );
mSymbolButton->setMessageBar( QgisApp::instance()->messageBar() );
}
void QgsDecorationLayoutExtentDialog::updateGuiElements()
{
grpEnable->setChecked( mDeco.enabled() );
mSymbolButton->setSymbol( mDeco.symbol()->clone() );
mButtonFontStyle->setTextFormat( mDeco.textFormat() );
mCheckBoxLabelExtents->setChecked( mDeco.labelExtents() );
}
void QgsDecorationLayoutExtentDialog::updateDecoFromGui()
{
mDeco.setEnabled( grpEnable->isChecked() );
mDeco.setSymbol( mSymbolButton->clonedSymbol< QgsFillSymbol >() );
mDeco.setTextFormat( mButtonFontStyle->textFormat() );
mDeco.setLabelExtents( mCheckBoxLabelExtents->isChecked() );
}
void QgsDecorationLayoutExtentDialog::buttonBox_accepted()
{
apply();
accept();
}
void QgsDecorationLayoutExtentDialog::apply()
{
updateDecoFromGui();
mDeco.update();
}
void QgsDecorationLayoutExtentDialog::buttonBox_rejected()
{
reject();
}
void QgsDecorationLayoutExtentDialog::showHelp()
{
QgsHelp::openHelp( QStringLiteral( "introduction/general_tools.html#decorations" ) );
}
| 3,263 | 963 |
#define _WIN32_WINNT 0x0600
#include <algorithm>
#include <iostream>
#include <regex>
#include <string>
#include <windows.h>
#define DEBUG 1
#define HKCR HKEY_CLASSES_ROOT
#define HKCU HKEY_CURRENT_USER
#define HKLM HKEY_LOCAL_MACHINE
#define HKU HKEY_USERS
#define HKCC HKEY_CURRENT_CONFIG
HKEY CreateNewKey(HKEY root, const std::string& subDirectory);
void SetKeyValue(HKEY hRegistryKey, const std::string& valueName, const std::string& data);
void DeleteKey(HKEY root, const std::string& subDirectory);
void DeleteTree(HKEY root, const std::string& subDirectory);
int main(int argc, char* argv[])
{
DeleteKey(HKCR, "*\\shellex\\ContextMenuHandlers\\abc");
DeleteKey(HKCR, "CLSID\\{01b25495-d2f0-4568-a708-911d380db1be}");
DeleteTree(HKCR, "abcfile");
DeleteTree(HKCR, ".abc");
std::cin.get();
return 0;
}
HKEY CreateNewKey(HKEY root, const std::string& subDirectory)
{
HKEY typeLocation = {};
DWORD status = {};
RegCreateKeyExA(
root,
const_cast<char *>(subDirectory.c_str()),
NULL,
NULL,
REG_OPTION_NON_VOLATILE,
KEY_ALL_ACCESS | KEY_WOW64_64KEY,
NULL,
&typeLocation,
&status
);
#if DEBUG == 1
std::cout << std::endl;
if (status == REG_CREATED_NEW_KEY)
std::cout << "[Warn] Location \"" << subDirectory << "\" successfully created." << std::endl;
else
std::cout << "[Info] Location \"" << subDirectory << "\" successfully opened." << std::endl;
#endif
return typeLocation;
}
void SetKeyValue(HKEY hRegistryKey, const std::string& valueName , const std::string& data)
{
auto status = RegSetValueExA(
hRegistryKey,
const_cast<char *>(valueName.c_str()),
NULL,
REG_SZ,
(LPBYTE)const_cast<char *>(data.c_str()),
data.size() + 1
);
#if DEBUG == 1
if (status == ERROR_SUCCESS)
std::cout << "[Success] Value \"" << valueName << ": " << data << "\" was successfully set." << std::endl;
else
std::cout << "[Error] Error appeared while setting value." << std::endl;
#endif
}
void DeleteKey(HKEY root, const std::string& subDirectory)
{
auto status = RegDeleteKeyExA(
root,
const_cast<char *>(subDirectory.c_str()),
KEY_WOW64_64KEY,
NULL
);
#if DEBUG == 1
if (status == ERROR_SUCCESS)
std::cout << "[Success] Key \"" << subDirectory << "\" was successfully deleted." << std::endl;
else
std::cout << "[Error] Error appeared while deleting key." << std::endl;
#endif
}
void DeleteTree(HKEY root, const std::string& subDirectory)
{
auto status = RegDeleteTreeA(
root,
const_cast<char *>(subDirectory.c_str())
);
#if DEBUG == 1
if (status == ERROR_SUCCESS)
std::cout << "[Success] Key \"" << subDirectory << "\" was successfully deleted." << std::endl;
else
std::cout << "[Error] Error appeared while deleting key." << std::endl;
#endif
} | 2,754 | 1,058 |
#include <algorithm>
#include <fstream>
#include <iostream>
#include <queue>
#include <sstream>
#include <tuple>
#include <vector>
#include "utils/types.h"
#include "utils/utils.h"
#include "graph/graph.h"
Graph::Graph()
: edge_count_(0)
, vlabel_count_(0)
, elabel_count_(0)
, neighbors_{}
, elabels_{}
, updates_{}
, vlabels_{}
{}
void Graph::AddVertex(uint id, uint label)
{
if (id >= vlabels_.size())
{
vlabels_.resize(id + 1, NOT_EXIST);
vlabels_[id] = label;
neighbors_.resize(id + 1);
elabels_.resize(id + 1);
}
else if (vlabels_[id] == NOT_EXIST)
{
vlabels_[id] = label;
}
vlabel_count_ = std::max(vlabel_count_, label + 1);
// print graph
/*std::cout << "labels: ";
for (uint i = 0; i < vlabels_.size(); i++)
{
std::cout << i << ":" << vlabels_[i] << " (";
for (uint j = 0; j < neighbors_[i].size(); j++)
{
std::cout << neighbors_[i][j] << ":" << elabels_[i][j] << " ";
}
std::cout << ")" << std::endl;
}*/
}
void Graph::RemoveVertex(uint id)
{
vlabels_[id] = NOT_EXIST;
neighbors_[id].clear();
elabels_[id].clear();
}
void Graph::AddEdge(uint v1, uint v2, uint label)
{
auto lower = std::lower_bound(neighbors_[v1].begin(), neighbors_[v1].end(), v2);
if (lower != neighbors_[v1].end() && *lower == v2) return;
size_t dis = std::distance(neighbors_[v1].begin(), lower);
neighbors_[v1].insert(lower, v2);
elabels_[v1].insert(elabels_[v1].begin() + dis, label);
lower = std::lower_bound(neighbors_[v2].begin(), neighbors_[v2].end(), v1);
dis = std::distance(neighbors_[v2].begin(), lower);
neighbors_[v2].insert(lower, v1);
elabels_[v2].insert(elabels_[v2].begin() + dis, label);
edge_count_++;
elabel_count_ = std::max(elabel_count_, label + 1);
// print graph
/*std::cout << "labels: ";
for (uint i = 0; i < vlabels_.size(); i++)
{
std::cout << i << ":" << vlabels_[i] << " (";
for (uint j = 0; j < neighbors_[i].size(); j++)
{
std::cout << neighbors_[i][j] << ":" << elabels_[i][j] << " ";
}
std::cout << ")" << std::endl;
}*/
}
void Graph::RemoveEdge(uint v1, uint v2)
{
auto lower = std::lower_bound(neighbors_[v1].begin(), neighbors_[v1].end(), v2);
if (lower == neighbors_[v1].end() || *lower != v2)
{
std::cout << "deletion error" << std::endl;
exit(-1);
}
neighbors_[v1].erase(lower);
elabels_[v1].erase(elabels_[v1].begin() + std::distance(neighbors_[v1].begin(), lower));
lower = std::lower_bound(neighbors_[v2].begin(), neighbors_[v2].end(), v1);
if (lower == neighbors_[v2].end() || *lower != v1)
{
std::cout << "deletion error" << std::endl;
exit(-1);
}
neighbors_[v2].erase(lower);
elabels_[v2].erase(elabels_[v2].begin() + std::distance(neighbors_[v2].begin(), lower));
edge_count_--;
}
uint Graph::GetVertexLabel(uint u) const
{
return vlabels_[u];
}
const std::vector<uint>& Graph::GetNeighbors(uint v) const
{
return neighbors_[v];
}
const std::vector<uint>& Graph::GetNeighborLabels(uint v) const
{
return elabels_[v];
}
std::tuple<uint, uint, uint> Graph::GetEdgeLabel(uint v1, uint v2) const
{
uint v1_label, v2_label, e_label;
v1_label = GetVertexLabel(v1);
v2_label = GetVertexLabel(v2);
const std::vector<uint> *nbrs;
const std::vector<uint> *elabel;
uint other;
if (GetDegree(v1) < GetDegree(v2))
{
nbrs = &GetNeighbors(v1);
elabel = &elabels_[v1];
other = v2;
}
else
{
nbrs = &GetNeighbors(v2);
elabel = &elabels_[v2];
other = v1;
}
long start = 0, end = nbrs->size() - 1, mid;
while (start <= end)
{
mid = (start + end) / 2;
if (nbrs->at(mid) < other)
{
start = mid + 1;
}
else if (nbrs->at(mid) > other)
{
end = mid - 1;
}
else
{
e_label = elabel->at(mid);
return {v1_label, v2_label, e_label};
}
}
return {v1_label, v2_label, -1};
}
uint Graph::GetDegree(uint v) const
{
return neighbors_[v].size();
}
uint Graph::GetDiameter() const
{
uint diameter = 0;
for (uint i = 0u; i < NumVertices(); i++)
if (GetVertexLabel(i) != NOT_EXIST)
{
std::queue<uint> bfs_queue;
std::vector<bool> visited(NumVertices(), false);
uint level = UINT_MAX;
bfs_queue.push(i);
visited[i] = true;
while (!bfs_queue.empty())
{
level++;
uint size = bfs_queue.size();
for (uint j = 0u; j < size; j++)
{
uint front = bfs_queue.front();
bfs_queue.pop();
const auto& nbrs = GetNeighbors(front);
for (const uint nbr: nbrs)
{
if (!visited[nbr])
{
bfs_queue.push(nbr);
visited[nbr] = true;
}
}
}
}
if (level > diameter) diameter = level;
}
return diameter;
}
void Graph::LoadFromFile(const std::string &path)
{
if (!io::file_exists(path.c_str()))
{
std::cout << "Failed to open: " << path << std::endl;
exit(-1);
}
std::ifstream ifs(path);
char type;
while (ifs >> type)
{
if (type == 't')
{
char temp1;
uint temp2;
ifs >> temp1 >> temp2;
}
else if (type == 'v')
{
uint vertex_id, label;
ifs >> vertex_id >> label;
AddVertex(vertex_id, label);
}
else
{
uint from_id, to_id, label;
ifs >> from_id >> to_id >> label;
AddEdge(from_id, to_id, label);
}
}
ifs.close();
}
void Graph::LoadUpdateStream(const std::string &path)
{
if (!io::file_exists(path.c_str()))
{
std::cout << "Failed to open: " << path << std::endl;
exit(-1);
}
std::ifstream ifs(path);
std::string type;
while (ifs >> type)
{
if (type == "v" || type == "-v")
{
uint vertex_id, label;
ifs >> vertex_id >> label;
updates_.emplace('v', type == "v", vertex_id, 0u, label);
}
else
{
uint from_id, to_id, label;
ifs >> from_id >> to_id >> label;
updates_.emplace('e', type == "e", from_id, to_id, label);
}
}
ifs.close();
}
void Graph::PrintMetaData() const
{
std::cout << "# vertices = " << NumVertices() <<
"\n# edges = " << NumEdges() << std::endl;
} | 6,849 | 2,519 |
#include "caffe2/core/net.h"
#include <set>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include "caffe2/core/operator.h"
#include "caffe2/core/static_tracepoint.h"
#include "caffe2/core/timer.h"
#include "caffe2/proto/caffe2.pb.h"
#include "caffe2/utils/proto_utils.h"
CAFFE2_DEFINE_bool(
caffe2_disable_chaining,
false,
"Disable chaining logic (some latent multi-device issues).");
namespace caffe2 {
namespace {
bool sameDevice(const OperatorDef& lhs, const OperatorDef& rhs) {
return lhs.device_option().device_type() ==
rhs.device_option().device_type() &&
lhs.device_option().cuda_gpu_id() == rhs.device_option().cuda_gpu_id();
}
using OpIndex = int;
DAGNetBase::ExecutionChains singleChains(
const std::vector<internal::OperatorNode>& nodes) {
DAGNetBase::ExecutionChains chains;
for (auto i = 0; i < nodes.size(); ++i) {
chains[i] = {i};
}
return chains;
}
static void prune(int node_idx, std::vector<internal::OpGraphNode>& nodes) {
// Ancestor table for tracking the visited nodes
std::vector<bool> ancestors(nodes.size(), false);
// stack element is pair of <curr_node, previous_node>
std::stack<std::pair<int, int>> nodes_stack;
// initialize the prev_node to be -1
nodes_stack.push(std::make_pair(node_idx, -1));
while (!nodes_stack.empty()) {
const auto& node_pair = nodes_stack.top();
int curr = node_pair.first;
int prev = node_pair.second;
// If the node has already been visited, pop curr out of
// stack and clean up the ancestor table
CAFFE_ENFORCE(curr < ancestors.size(), "Out of bound access");
if (ancestors[curr]) {
ancestors[curr] = false;
nodes_stack.pop();
continue;
}
// Check if this has a parent that can be pruned:
// if parent is not the previous node visited and is
// an ancestor of the current traversar, it can be
// pruned.
if (prev >= 0) {
std::vector<int> new_parents;
for (auto parent : nodes[curr].parents_) {
if (parent != prev && ancestors[parent]) {
// We can prune this one
nodes[parent].children_.erase(
std::remove(
nodes[parent].children_.begin(),
nodes[parent].children_.end(),
curr),
nodes[parent].children_.end());
} else {
new_parents.push_back(parent);
}
}
nodes[curr].parents_ = new_parents;
}
ancestors[curr] = true;
// Descend -- but only once from each node
if (nodes[curr].visited_inputs == nodes[curr].num_orig_parents) {
const auto& children = nodes[curr].children_;
for (auto child : children) {
nodes[child].visited_inputs++;
nodes_stack.push(std::make_pair(child, curr));
}
}
}
}
/**
* Prune redundant dependencies to improve chaining.
* TODO: t15868555 This algorithm is fast but can miss dependencies.
*/
std::vector<internal::OpGraphNode> pruneOpNodeGraph(
const std::vector<internal::OperatorNode>& orig_nodes) {
Timer t;
std::vector<internal::OpGraphNode> pruned;
// Create a separate list of pruned operatornodes used
// for the chaining computation. Because of the unique_ptr
// in the OperatorNode, we cannot do a copy but have to
// copy just the fields we need.
for (auto& node : orig_nodes) {
internal::OpGraphNode nd;
nd.children_ = node.children_;
nd.parents_ = node.parents_;
nd.num_orig_parents = nd.parents_.size();
pruned.push_back(nd);
}
for (int i = 0; i < pruned.size(); ++i) {
if (pruned[i].parents_.size() == 0) {
prune(i, pruned);
}
}
LOG(INFO) << "Operator graph pruning prior to chain compute took: "
<< t.Seconds() << " secs";
return pruned;
}
DAGNetBase::ExecutionChains computeChains(
const std::vector<internal::OperatorNode>& orig_nodes) {
const std::vector<internal::OpGraphNode> nodes = pruneOpNodeGraph(orig_nodes);
vector<int> initial_frontier;
for (int idx = 0; idx < nodes.size(); ++idx) {
if (nodes[idx].parents_.size() == 0) {
initial_frontier.push_back(idx);
}
}
// We need to construct the node_seen_count to know how many inner edges each
// node has.
std::unordered_map<OpIndex, int> node_seen_count;
for (int root_index : initial_frontier) {
const auto& root = nodes[root_index];
std::stack<std::pair<OpIndex, std::vector<int>::const_iterator>>
depth_stack;
depth_stack.push(make_pair(root_index, root.children_.begin()));
node_seen_count[root_index]++;
CAFFE_ENFORCE(
node_seen_count[root_index] == 1,
"root node ",
root_index,
" visit count must be == 1");
while (depth_stack.size() > 0) {
auto cur = depth_stack.top();
depth_stack.pop();
if (cur.second != nodes[cur.first].children_.end()) {
OpIndex node_index = *cur.second;
node_seen_count[node_index]++;
cur.second++;
depth_stack.push(cur);
if (node_seen_count[node_index] == 1) {
// Visit each child only once.
depth_stack.push(
make_pair(node_index, nodes[node_index].children_.begin()));
}
}
}
}
// Now, we compute the set of execution chains An execution chain is
// a linear set of nodes that can be executed on a single stream
// (e.g. a chain of single input, single output operators)
DAGNetBase::ExecutionChains chains;
std::unordered_set<OpIndex> seen_nodes;
std::vector<OpIndex> chain;
std::pair<OpIndex, std::vector<int>::const_iterator> cur;
std::stack<std::pair<OpIndex, std::vector<int>::const_iterator>> depth_stack;
auto check_current_for_chaining = [&]() -> bool {
return (
node_seen_count[cur.first] == 1 &&
(chain.size() == 0 || sameDevice(
orig_nodes[cur.first].operator_->def(),
orig_nodes[chain.back()].operator_->def())));
};
auto commit_chain = [&]() {
if (chain.size() > 0) {
CAFFE_ENFORCE(
chains.insert({chain.front(), chain}).second,
"Chain ",
chain.front(),
" was already added.");
VLOG(2) << "Added chain: " << chain.front() << "with elements";
for (auto ch : chain) {
VLOG(2) << ch << ", ";
}
chain.clear();
}
};
auto depth_traverse = [&]() {
while (cur.second != nodes[cur.first].children_.end() &&
seen_nodes.find(*cur.second) != seen_nodes.end()) {
cur.second++;
}
if (cur.second != nodes[cur.first].children_.end()) {
auto next = make_pair(*cur.second, nodes[*cur.second].children_.begin());
depth_stack.push(cur);
depth_stack.push(next);
}
};
for (int root_index : initial_frontier) {
depth_stack.push(
make_pair(root_index, nodes[root_index].children_.begin()));
while (depth_stack.size() > 0) {
cur = depth_stack.top();
depth_stack.pop();
if (seen_nodes.find(cur.first) == seen_nodes.end()) {
seen_nodes.insert(cur.first);
// Has one child, can be candidate for chain or can be added to the
// previous chain.
if (nodes[cur.first].children_.size() == 1) {
if (check_current_for_chaining()) {
// Add oneself to the current chain.
VLOG(1) << "Adding to existing chain" << cur.first;
chain.push_back(cur.first);
int index = *nodes[cur.first].children_.begin();
depth_stack.push(make_pair(index, nodes[index].children_.begin()));
} else {
// Can't belong to the previous chain, commit previous chain and
// start a new one.
commit_chain();
chain.push_back(cur.first);
int index = *nodes[cur.first].children_.begin();
depth_stack.push(make_pair(index, nodes[index].children_.begin()));
}
} else if (
nodes[cur.first].children_.size() == 0 &&
check_current_for_chaining()) {
// Add current node to the current chain and commit.
chain.push_back(cur.first);
commit_chain();
} else {
// Node has more than one child.
commit_chain();
// Add current node as an independent chain since it won't be a part
// of a bigger chain.
chain.push_back(cur.first);
commit_chain();
depth_traverse();
}
} else {
// This node has been seen before, we will only traverse its children.
// Commit any pending chains and continue traversing.
commit_chain();
depth_traverse();
}
} // End while
// Check if this if is even needed.
commit_chain();
}
CAFFE_ENFORCE(
seen_nodes.size() == nodes.size(),
"Haven't seen all the nodes, expected number of nodes ",
nodes.size(),
", but seen only ",
seen_nodes.size(),
".");
return chains;
}
}
DAGNetBase::DAGNetBase(const NetDef& net_def, Workspace* ws)
: NetBase(net_def, ws), operator_nodes_(net_def.op_size()) {
// Blob creator allows us to track which operator created which blob.
VLOG(1) << "Constructing DAGNet " << net_def.name();
std::map<string, int> blob_creator;
std::map<string, std::set<int>> blob_readers;
bool net_def_has_device_option = net_def.has_device_option();
// Initialize the operators
for (int idx = 0; idx < net_def.op_size(); ++idx) {
const OperatorDef& op_def = net_def.op(idx);
VLOG(1) << "Creating operator #" << idx << ": " << op_def.name() << ":"
<< op_def.type();
if (!op_def.has_device_option() && net_def_has_device_option) {
OperatorDef temp_def(op_def);
temp_def.mutable_device_option()->CopyFrom(net_def.device_option());
operator_nodes_[idx].operator_ = CreateOperator(temp_def, ws);
} else {
operator_nodes_[idx].operator_ = CreateOperator(op_def, ws);
}
// Check the inputs, and set up parents if necessary. This addressese the
// read after write case.
auto checkInputs =
[&](const google::protobuf::RepeatedPtrField<std::string>& inputs) {
for (const string& input : inputs) {
if (blob_creator.count(input) == 0) {
VLOG(1) << "Input " << input << " not produced by this net. "
<< "Assuming it is pre-existing.";
} else {
int parent = blob_creator[input];
VLOG(1) << "op dependency (RaW " << input << "): " << parent
<< "->" << idx;
operator_nodes_[idx].parents_.push_back(parent);
operator_nodes_[parent].children_.push_back(idx);
}
// Add the current idx to the readers of this input.
blob_readers[input].insert(idx);
}
};
checkInputs(op_def.input());
checkInputs(op_def.control_input());
// Check the outputs.
for (const string& output : op_def.output()) {
if (blob_creator.count(output) != 0) {
// This addresses the write after write case - we will assume that all
// writes are inherently sequential.
int waw_parent = blob_creator[output];
VLOG(1) << "op dependency (WaW " << output << "): " << waw_parent
<< "->" << idx;
operator_nodes_[idx].parents_.push_back(waw_parent);
operator_nodes_[waw_parent].children_.push_back(idx);
}
// This addresses the write after read case - we will assume that writes
// should only occur after all previous reads are finished.
for (const int war_parent : blob_readers[output]) {
VLOG(1) << "op dependency (WaR " << output << "): " << war_parent
<< "->" << idx;
operator_nodes_[idx].parents_.push_back(war_parent);
operator_nodes_[war_parent].children_.push_back(idx);
}
// Renew the creator of the output name.
blob_creator[output] = idx;
// The write would create an implicit barrier that all earlier readers of
// this output is now parents of the current op, and future writes would
// not need to depend on these earlier readers. Thus, we can clear up the
// blob readers.
blob_readers[output].clear();
}
}
// Now, make sure that the parent list and the children list do not contain
// duplicated items.
for (int i = 0; i < operator_nodes_.size(); ++i) {
auto& node = operator_nodes_[i];
// Sort, remove duplicates, and delete self dependency.
auto& p = node.parents_;
std::sort(p.begin(), p.end());
p.erase(std::unique(p.begin(), p.end()), p.end());
p.erase(std::remove(p.begin(), p.end(), i), p.end());
// Do the same for the children vector.
auto& c = node.children_;
std::sort(c.begin(), c.end());
c.erase(std::unique(c.begin(), c.end()), c.end());
c.erase(std::remove(c.begin(), c.end(), i), c.end());
}
execution_chains_ =
(FLAGS_caffe2_disable_chaining ? singleChains(operator_nodes_)
: computeChains(operator_nodes_));
// Tag operator nodes that start chains
for (int i = 0; i < operator_nodes_.size(); ++i) {
auto& node = operator_nodes_[i];
if (execution_chains_.find(i) != execution_chains_.end()) {
node.is_chain_start_ = true;
} else {
node.is_chain_start_ = false;
}
node.runtime_parent_count_ = 0;
}
LOG(INFO) << "Number of parallel execution chains "
<< execution_chains_.size()
<< " Number of operators = " << net_def.op_size();
// TODO: do we want to make sure that there are no loops in the
// dependency graph?
// Figure out the initial frontier - this is the one we will feed into the job
// queue to start a run.
for (int idx = 0; idx < operator_nodes_.size(); ++idx) {
if (operator_nodes_[idx].parents_.size() == 0) {
initial_frontier_.push_back(idx);
}
}
// Finally, start the workers.
int num_workers = net_def.has_num_workers() ? net_def.num_workers() : 1;
CAFFE_ENFORCE(num_workers > 0, "Must have a positive number of workers.");
if (num_workers == 1) {
LOG(WARNING) << "Number of workers is 1: this means that all operators "
<< "will be executed sequentially. Did you forget to set "
<< "num_workers in the NetDef?";
}
num_workers_ = num_workers;
int num_workers_to_start = num_workers_;
// Option to start only one thread for first iteration. This hack is
// needed to prevent deadlocks happening with CUDA and concurrent allocations
// that operators do when run the first time.
ArgumentHelper arg_helper(net_def);
if (arg_helper.HasArgument("first_iter_only_one_worker")) {
if (arg_helper.GetSingleArgument<int64_t>(
"first_iter_only_one_worker", 0)) {
num_workers_to_start = 1;
}
}
for (int i = 0; i < num_workers_to_start; ++i) {
VLOG(1) << "Start worker #" << i;
workers_.push_back(std::thread(&DAGNetBase::WorkerFunction, this));
}
}
DAGNetBase::~DAGNetBase() {
// Safely join all the workers before exiting.
job_queue_.NoMoreJobs();
VLOG(1) << "Joining workers.";
for (auto& worker : workers_) {
worker.join();
}
}
bool DAGNetBase::Run() {
// Lock the run_in_progress_ lock so that we do not accidentally call Run()
// in parallel.
std::unique_lock<std::mutex> run_lock(run_in_progress_);
VLOG(1) << "Running parallel net.";
// First, set up job queue.
remaining_ops_ = operator_nodes_.size();
success_ = true;
// TODO(jiayq): Start all worker threads.
// Initialize the runtime parent count.
for (auto& node : operator_nodes_) {
node.runtime_parent_count_ = node.parents_.size();
}
// Kickstart the job queue.
for (auto& value : initial_frontier_) {
job_queue_.Push(value);
}
std::unique_lock<std::mutex> mutex_lock(remaining_ops_mutex_);
while (remaining_ops_ > 0) {
VLOG(2) << "Remaining ops to run: " << remaining_ops_;
cv_.wait(mutex_lock);
}
VLOG(2) << "All ops finished running.";
for (const auto& op : operator_nodes_) {
CAFFE_ENFORCE(
op.runtime_parent_count_ == 0,
"Operator ",
op.operator_->def().name(),
"(",
op.operator_->def().type(),
") has some runtime parents left.");
}
// Ensure the number of workers matches the defined
for (auto i = workers_.size(); i < num_workers_; ++i) {
VLOG(1) << "Start worker #" << i;
workers_.push_back(std::thread(&DAGNetBase::WorkerFunction, this));
}
// If the above while loop finished, we know that the current run finished.
return success_;
}
void DAGNetBase::WorkerFunction() {
// WorkerFunctions() is an infinite loop until there are no more jobs to run.
while (true) {
int idx = 0;
// If there is no more jobs - meaning that the DAGNetBase is destructing -
// we will exit safely.
if (!job_queue_.Pop(&idx)) {
return;
}
VLOG(1) << "Running operator #" << idx << " "
<< operator_nodes_[idx].operator_->def().name() << "("
<< operator_nodes_[idx].operator_->def().type() << ").";
CAFFE_ENFORCE(
execution_chains_.find(idx) != execution_chains_.end(),
"Can't find chain ",
idx,
".");
const auto& chain = execution_chains_[idx];
bool this_success = RunAt(execution_chains_[idx]);
if (!this_success) {
LOG(ERROR) << "Operator chain failed: "
<< ProtoDebugString(operator_nodes_[idx].operator_->def());
}
// Do book-keeping
for (const auto idx : chain) {
for (const auto child : operator_nodes_[idx].children_) {
const int count = --operator_nodes_[child].runtime_parent_count_;
CAFFE_ENFORCE(
count >= 0,
"Found runtime parent count smaller than zero for ",
"operator node ",
operator_nodes_[child].operator_->def().name(),
"(",
operator_nodes_[child].operator_->def().type(),
").");
if (count != 0) {
continue;
}
if (operator_nodes_[child].is_chain_start_) {
VLOG(2) << "Pushing chain #" << child << " to queue.";
job_queue_.Push(child);
}
}
}
// Notify that the processed op is incremented by one.
{
std::unique_lock<std::mutex> mutex_lock(remaining_ops_mutex_);
remaining_ops_ -= chain.size();
success_ &= this_success;
CAFFE_ENFORCE(
remaining_ops_ >= 0,
"All the operations should be finished by now, still have ",
remaining_ops_,
" remaining.");
}
cv_.notify_one();
VLOG(2) << "Finished executing operator #" << idx;
}
}
vector<float> DAGNetBase::TEST_Benchmark(
const int warmup_runs,
const int main_runs,
const bool run_individual) {
LOG(INFO) << "Starting benchmark.";
LOG(INFO) << "Running warmup runs.";
CAFFE_ENFORCE(
warmup_runs >= 0,
"Number of warm up runs should be non negative, provided ",
warmup_runs,
".");
for (int i = 0; i < warmup_runs; ++i) {
CAFFE_ENFORCE(Run(), "Warmup run ", i, " has failed.");
}
LOG(INFO) << "Main runs.";
CAFFE_ENFORCE(
main_runs >= 0,
"Number of main runs should be non negative, provided ",
main_runs,
".");
Timer timer;
for (int i = 0; i < main_runs; ++i) {
CAFFE_ENFORCE(Run(), "Main run ", i, " has failed.");
}
auto millis = timer.MilliSeconds();
LOG(INFO) << "Main run finished. Milliseconds per iter: "
<< millis / main_runs
<< ". Iters per second: " << 1000.0 * main_runs / millis;
if (run_individual) {
LOG(INFO) << "DAGNet does not do per-op benchmark. To do so, "
"switch to a simple net type.";
}
return vector<float>{millis / main_runs};
}
class DAGNet : public DAGNetBase {
public:
using DAGNetBase::DAGNetBase;
protected:
bool RunAt(const std::vector<int>& chain) override {
bool success = true;
const auto& net_name = name_.c_str();
for (const auto i : chain) {
const auto& op_name = operator_nodes_[i].operator_->def().name().c_str();
const auto& op_type = operator_nodes_[i].operator_->def().type().c_str();
CAFFE_SDT(operator_start, net_name, op_name, op_type);
success &= operator_nodes_[i].operator_->Run();
CAFFE_SDT(operator_done, net_name, op_name, op_type);
}
return success;
}
};
namespace {
REGISTER_NET(dag, DAGNet);
}
} // namespace caffe2
| 20,577 | 6,660 |
/// HEADER
#include <csapex/io/request.h>
using namespace csapex;
uint8_t Request::getPacketType() const
{
return PACKET_TYPE_ID;
}
Request::Request(uint8_t id) : request_id_(id)
{
}
void Request::overwriteRequestID(uint8_t id) const
{
request_id_ = id;
}
uint8_t Request::getRequestID() const
{
return request_id_;
}
| 335 | 134 |
/*
* Vulkan Example - Indirect drawing
*
* Copyright (C) 2016 by Sascha Willems - www.saschawillems.de
*
* This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
*
* Summary:
* Use a device local buffer that stores draw commands for instanced rendering of different meshes stored
* in the same buffer.
*
* Indirect drawing offloads draw command generation and offers the ability to update them on the GPU
* without the CPU having to touch the buffer again, also reducing the number of drawcalls.
*
* The example shows how to setup and fill such a buffer on the CPU side, stages it to the device and
* shows how to render it using only one draw command.
*
* See readme.md for details
*
*/
#include <vulkanExampleBase.h>
// Number of instances per object
#if defined(__ANDROID__)
#define OBJECT_INSTANCE_COUNT 1024
// Circular range of plant distribution
#define PLANT_RADIUS 20.0f
#else
#define OBJECT_INSTANCE_COUNT 2048
// Circular range of plant distribution
#define PLANT_RADIUS 25.0f
#endif
class VulkanExample : public vkx::ExampleBase {
public:
struct {
vks::texture::Texture2DArray plants;
vks::texture::Texture2D ground;
} textures;
// Vertex layout for the models
vks::model::VertexLayout vertexLayout = vks::model::VertexLayout({
vks::model::VERTEX_COMPONENT_POSITION,
vks::model::VERTEX_COMPONENT_NORMAL,
vks::model::VERTEX_COMPONENT_UV,
vks::model::VERTEX_COMPONENT_COLOR,
});
struct {
vks::model::Model plants;
vks::model::Model ground;
vks::model::Model skysphere;
} models;
// Per-instance data block
struct InstanceData {
glm::vec3 pos;
glm::vec3 rot;
float scale;
uint32_t texIndex;
};
// Contains the instanced data
vks::Buffer instanceBuffer;
// Contains the indirect drawing commands
vks::Buffer indirectCommandsBuffer;
uint32_t indirectDrawCount;
struct {
glm::mat4 projection;
glm::mat4 view;
} uboVS;
struct {
vks::Buffer scene;
} uniformData;
struct {
vk::Pipeline plants;
vk::Pipeline ground;
vk::Pipeline skysphere;
} pipelines;
vk::PipelineLayout pipelineLayout;
vk::DescriptorSet descriptorSet;
vk::DescriptorSetLayout descriptorSetLayout;
vk::Sampler samplerRepeat;
uint32_t objectCount = 0;
// Store the indirect draw commands containing index offsets and instance count per object
std::vector<vk::DrawIndexedIndirectCommand> indirectCommands;
VulkanExample() {
title = "Indirect rendering";
camera.type = Camera::CameraType::firstperson;
camera.setPerspective(60.0f, (float)width / (float)height, 0.1f, 512.0f);
camera.setRotation(glm::vec3(-12.0f, 159.0f, 0.0f));
camera.setTranslation(glm::vec3(0.4f, 1.25f, 0.0f));
camera.movementSpeed = 5.0f;
defaultClearColor = vks::util::clearColor({ 0.18f, 0.27f, 0.5f, 0.0f });
settings.overlay = true;
}
~VulkanExample() {
device.destroy(pipelines.plants);
device.destroy(pipelines.ground);
device.destroy(pipelines.skysphere);
device.destroy(pipelineLayout);
device.destroy(descriptorSetLayout);
models.plants.destroy();
models.ground.destroy();
models.skysphere.destroy();
textures.plants.destroy();
textures.ground.destroy();
instanceBuffer.destroy();
indirectCommandsBuffer.destroy();
uniformData.scene.destroy();
}
// Enable physical device features required for this example
void getEnabledFeatures() override {
// Example uses multi draw indirect if available
if (deviceFeatures.multiDrawIndirect) {
enabledFeatures.multiDrawIndirect = VK_TRUE;
}
// Enable anisotropic filtering if supported
if (deviceFeatures.samplerAnisotropy) {
enabledFeatures.samplerAnisotropy = VK_TRUE;
}
// Enable texture compression
if (deviceFeatures.textureCompressionBC) {
enabledFeatures.textureCompressionBC = VK_TRUE;
} else if (deviceFeatures.textureCompressionASTC_LDR) {
enabledFeatures.textureCompressionASTC_LDR = VK_TRUE;
} else if (deviceFeatures.textureCompressionETC2) {
enabledFeatures.textureCompressionETC2 = VK_TRUE;
}
};
void updateDrawCommandBuffer(const vk::CommandBuffer& drawCmdBuffer) {
drawCmdBuffer.setViewport(0, viewport());
drawCmdBuffer.setScissor(0, scissor());
drawCmdBuffer.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, pipelineLayout, 0, descriptorSet, nullptr);
// Plants
drawCmdBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipelines.plants);
// Binding point 0 : Mesh vertex buffer
drawCmdBuffer.bindVertexBuffers(0, models.plants.vertices.buffer, { 0 });
// Binding point 1 : Instance data buffer
drawCmdBuffer.bindVertexBuffers(1, instanceBuffer.buffer, { 0 });
drawCmdBuffer.bindIndexBuffer(models.plants.indices.buffer, 0, vk::IndexType::eUint32);
// If the multi draw feature is supported:
// One draw call for an arbitrary number of ojects
// Index offsets and instance count are taken from the indirect buffer
if (deviceFeatures.multiDrawIndirect) {
drawCmdBuffer.drawIndexedIndirect(indirectCommandsBuffer.buffer, 0, indirectDrawCount, sizeof(VkDrawIndexedIndirectCommand));
} else {
// If multi draw is not available, we must issue separate draw commands
for (auto j = 0; j < indirectCommands.size(); j++) {
drawCmdBuffer.drawIndexedIndirect(indirectCommandsBuffer.buffer, j * sizeof(VkDrawIndexedIndirectCommand), 1,
sizeof(VkDrawIndexedIndirectCommand));
}
}
// Ground
drawCmdBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipelines.ground);
drawCmdBuffer.bindVertexBuffers(0, models.ground.vertices.buffer, { 0 });
drawCmdBuffer.bindIndexBuffer(models.ground.indices.buffer, 0, vk::IndexType::eUint32);
drawCmdBuffer.drawIndexed(models.ground.indexCount, 1, 0, 0, 0);
// Skysphere
drawCmdBuffer.bindPipeline(vk::PipelineBindPoint::eGraphics, pipelines.skysphere);
drawCmdBuffer.bindVertexBuffers(0, models.skysphere.vertices.buffer, { 0 });
drawCmdBuffer.bindIndexBuffer(models.skysphere.indices.buffer, 0, vk::IndexType::eUint32);
drawCmdBuffer.drawIndexed(models.skysphere.indexCount, 1, 0, 0, 0);
}
void loadAssets() override {
models.plants.loadFromFile(context, getAssetPath() + "models/plants.dae", vertexLayout, 0.0025f);
models.ground.loadFromFile(context, getAssetPath() + "models/plane_circle.dae", vertexLayout, PLANT_RADIUS + 1.0f);
models.skysphere.loadFromFile(context, getAssetPath() + "models/skysphere.dae", vertexLayout, 512.0f / 10.0f);
// Textures
std::string texFormatSuffix;
vk::Format texFormat;
// Get supported compressed texture format
if (deviceFeatures.textureCompressionBC) {
texFormatSuffix = "_bc3_unorm";
texFormat = vk::Format::eBc3UnormBlock;
} else if (deviceFeatures.textureCompressionASTC_LDR) {
texFormatSuffix = "_astc_8x8_unorm";
texFormat = vk::Format::eAstc8x8UnormBlock;
} else if (deviceFeatures.textureCompressionETC2) {
texFormatSuffix = "_etc2_unorm";
texFormat = vk::Format::eEtc2R8G8B8A8UnormBlock;
} else {
throw std::runtime_error("Device does not support any compressed texture format!");
}
textures.plants.loadFromFile(context, getAssetPath() + "textures/texturearray_plants" + texFormatSuffix + ".ktx", texFormat);
textures.ground.loadFromFile(context, getAssetPath() + "textures/ground_dry" + texFormatSuffix + ".ktx", texFormat);
}
void setupDescriptorPool() {
// Example uses one ubo
std::vector<vk::DescriptorPoolSize> poolSizes = {
{ vk::DescriptorType::eUniformBuffer, 1 },
{ vk::DescriptorType::eCombinedImageSampler, 2 },
};
descriptorPool = device.createDescriptorPool({ {}, 2, (uint32_t)poolSizes.size(), poolSizes.data() });
}
void setupDescriptorSetLayout() {
std::vector<vk::DescriptorSetLayoutBinding> setLayoutBindings{
{ 0, vk::DescriptorType::eUniformBuffer, 1, vk::ShaderStageFlagBits::eVertex },
{ 1, vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment },
{ 2, vk::DescriptorType::eCombinedImageSampler, 1, vk::ShaderStageFlagBits::eFragment },
};
descriptorSetLayout = device.createDescriptorSetLayout({ {}, static_cast<uint32_t>(setLayoutBindings.size()), setLayoutBindings.data() });
pipelineLayout = device.createPipelineLayout(vk::PipelineLayoutCreateInfo{ {}, 1, &descriptorSetLayout });
}
void setupDescriptorSet() {
descriptorSet = device.allocateDescriptorSets({ descriptorPool, 1, &descriptorSetLayout })[0];
std::vector<vk::WriteDescriptorSet> writeDescriptorSets{
{ descriptorSet, 0, 0, 1, vk::DescriptorType::eUniformBuffer, nullptr, &uniformData.scene.descriptor },
{ descriptorSet, 1, 0, 1, vk::DescriptorType::eCombinedImageSampler, &textures.plants.descriptor },
{ descriptorSet, 2, 0, 1, vk::DescriptorType::eCombinedImageSampler, &textures.ground.descriptor },
};
device.updateDescriptorSets(writeDescriptorSets, nullptr);
}
void preparePipelines() {
vks::pipelines::GraphicsPipelineBuilder builder{ device, pipelineLayout, renderPass };
builder.rasterizationState.frontFace = vk::FrontFace::eClockwise;
builder.vertexInputState.appendVertexLayout(vertexLayout);
// Ground
builder.loadShader(getAssetPath() + "shaders/indirectdraw/ground.vert.spv", vk::ShaderStageFlagBits::eVertex);
builder.loadShader(getAssetPath() + "shaders/indirectdraw/ground.frag.spv", vk::ShaderStageFlagBits::eFragment);
pipelines.ground = builder.create(context.pipelineCache);
builder.destroyShaderModules();
// Skysphere
builder.loadShader(getAssetPath() + "shaders/indirectdraw/skysphere.vert.spv", vk::ShaderStageFlagBits::eVertex);
builder.loadShader(getAssetPath() + "shaders/indirectdraw/skysphere.frag.spv", vk::ShaderStageFlagBits::eFragment);
builder.rasterizationState.cullMode = vk::CullModeFlagBits::eFront;
pipelines.skysphere = builder.create(context.pipelineCache);
builder.destroyShaderModules();
// Indirect (and instanced) pipeline for the plants
builder.rasterizationState.cullMode = vk::CullModeFlagBits::eBack;
builder.vertexInputState.bindingDescriptions.push_back({ 1, sizeof(InstanceData), vk::VertexInputRate::eInstance });
builder.vertexInputState.attributeDescriptions.push_back({ 4, 1, vk::Format::eR32G32B32Sfloat, offsetof(InstanceData, pos) });
builder.vertexInputState.attributeDescriptions.push_back({ 5, 1, vk::Format::eR32G32B32Sfloat, offsetof(InstanceData, rot) });
builder.vertexInputState.attributeDescriptions.push_back({ 6, 1, vk::Format::eR32Sfloat, offsetof(InstanceData, scale) });
builder.vertexInputState.attributeDescriptions.push_back({ 7, 1, vk::Format::eR32Sint, offsetof(InstanceData, texIndex) });
builder.loadShader(getAssetPath() + "shaders/indirectdraw/indirectdraw.vert.spv", vk::ShaderStageFlagBits::eVertex);
builder.loadShader(getAssetPath() + "shaders/indirectdraw/indirectdraw.frag.spv", vk::ShaderStageFlagBits::eFragment);
pipelines.plants = builder.create(context.pipelineCache);
builder.destroyShaderModules();
}
// Prepare (and stage) a buffer containing the indirect draw commands
void prepareIndirectData() {
indirectCommands.clear();
// Create on indirect command for each mesh in the scene
uint32_t m = 0;
for (auto& modelPart : models.plants.parts) {
VkDrawIndexedIndirectCommand indirectCmd{};
indirectCmd.instanceCount = OBJECT_INSTANCE_COUNT;
indirectCmd.firstInstance = m * OBJECT_INSTANCE_COUNT;
indirectCmd.firstIndex = modelPart.indexBase;
indirectCmd.indexCount = modelPart.indexCount;
indirectCommands.push_back(indirectCmd);
m++;
}
objectCount = 0;
for (auto indirectCmd : indirectCommands) {
objectCount += indirectCmd.instanceCount;
}
indirectDrawCount = static_cast<uint32_t>(indirectCommands.size());
indirectCommandsBuffer = context.stageToDeviceBuffer(vk::BufferUsageFlagBits::eIndirectBuffer, indirectCommands);
}
// Prepare (and stage) a buffer containing instanced data for the mesh draws
void prepareInstanceData() {
std::vector<InstanceData> instanceData;
instanceData.resize(objectCount);
std::mt19937 rndGenerator((unsigned)time(NULL));
std::uniform_real_distribution<float> uniformDist(0.0f, 1.0f);
for (uint32_t i = 0; i < objectCount; i++) {
instanceData[i].rot = glm::vec3(0.0f, float(M_PI) * uniformDist(rndGenerator), 0.0f);
float theta = 2 * float(M_PI) * uniformDist(rndGenerator);
float phi = acos(1 - 2 * uniformDist(rndGenerator));
instanceData[i].pos = glm::vec3(sin(phi) * cos(theta), 0.0f, cos(phi)) * PLANT_RADIUS;
instanceData[i].scale = 1.0f + uniformDist(rndGenerator) * 2.0f;
instanceData[i].texIndex = i / OBJECT_INSTANCE_COUNT;
}
instanceBuffer = context.stageToDeviceBuffer(vk::BufferUsageFlagBits::eVertexBuffer, instanceData);
}
void prepareUniformBuffers() {
uniformData.scene = context.createUniformBuffer(uboVS);
updateUniformBuffer(true);
}
void updateUniformBuffer(bool viewChanged) {
if (viewChanged) {
uboVS.projection = camera.matrices.perspective;
uboVS.view = camera.matrices.view;
}
memcpy(uniformData.scene.mapped, &uboVS, sizeof(uboVS));
}
void prepare() {
ExampleBase::prepare();
prepareIndirectData();
prepareInstanceData();
prepareUniformBuffers();
setupDescriptorSetLayout();
preparePipelines();
setupDescriptorPool();
setupDescriptorSet();
buildCommandBuffers();
prepared = true;
}
void viewChanged() override { updateUniformBuffer(true); }
void OnUpdateUIOverlay() override {
if (!deviceFeatures.multiDrawIndirect) {
if (ui.header("Info")) {
ui.text("multiDrawIndirect not supported");
}
}
if (ui.header("Statistics")) {
ui.text("Objects: %d", objectCount);
}
}
};
VULKAN_EXAMPLE_MAIN()
| 15,195 | 4,728 |
#include "day4.h"
#include <iostream>
int main(void) {
static constexpr auto input = "yzbqklnj";
std::cout << "Day 4, part 1: " << day4::mineAdventCoin(input, false) << '\n';
std::cout << "Day 4, part 2: " << day4::mineAdventCoin(input, true) << '\n';
}
| 268 | 111 |
#include "controllers/SmartController.h"
using namespace wml::controllers;
bool SmartController::Exists(tAxis axis, bool value) {
try {
_axes.at(axis.id);
} catch (std::out_of_range) {
return !value;
}
return value;
}
bool SmartController::Exists(tButton button, bool value) {
try {
_buttons.at(button.id);
} catch (std::out_of_range) {
return !value;
}
return value;
}
bool SmartController::Exists(tPOV pov, bool value) {
try {
_POVs.at(pov.id);
} catch (std::out_of_range) {
return !value;
}
return value;
}
bool SmartController::Exists(std::vector<tAxis> axi, bool value) {
bool val = value;
for (auto axis : axi) val |= Exists(axis, value);
return val;
}
bool SmartController::Exists(std::vector<tButton> buttons, bool value) {
bool val = value;
for (auto button : buttons) val |= Exists(button, value);
return val;
}
bool SmartController::Exists(std::vector<tPOV> povs, bool value) {
bool val = value;
for (auto pov : povs) val |= Exists(pov, value);
return val;
}
inputs::ContAxis *SmartController::GetObj(tAxis axis) {
return Exists(axis) ? _axes.at(axis.id) : nullptr;
}
inputs::ContButton *SmartController::GetObj(tButton button) {
return Exists(button) ? _buttons.at(button.id) : nullptr;
}
inputs::ContPOV *SmartController::GetObj(tPOV pov) {
return Exists(pov) ? _POVs.at(pov.id) : nullptr;
}
void SmartController::Map(tAxis axis, inputs::ContAxis *newAxis, bool force) {
if (!force) if (Exists(axis)) return;
_axes[axis.id] = newAxis;
}
void SmartController::Map(tButton button, inputs::ContButton *newButton, bool force) {
if (!force) if (Exists(button)) return;
_buttons[button.id] = newButton;
}
void SmartController::Map(tPOV pov, inputs::ContPOV *newPOV, bool force) {
if (!force) if (Exists(pov)) return;
_POVs[pov.id] = newPOV;
}
void SmartController::Map(tAxis map_axis, tButton virt_button, double threshold, bool force) {
if (!Exists(map_axis)) return;
Map(virt_button, inputs::MakeAxisButton(GetObj(map_axis), threshold).at(0), force);
// _axes.erase(_axes.find(map_axis.id));
}
void SmartController::Map(tAxis map_axis, std::vector<tButton> virt_buttons, bool force) {
if (!Exists(map_axis)) return;
std::vector<inputs::AxisSelectorButton*> buttons = inputs::MakeAxisSelectorButtons(GetObj(map_axis), virt_buttons.size());
for (unsigned int i = 0; i < buttons.size(); i++) {
if (virt_buttons.at(i) != noButton) Map(virt_buttons.at(i), buttons.at(i), force);
}
// _axes.erase(_axes.find(map_axis.id));
}
void SmartController::PairAxis(tAxis primary_axis, tAxis secondary_axis, bool squared) {
if (!Exists(primary_axis) || !Exists(secondary_axis)) return;
std::pair<inputs::FieldAxis*, inputs::FieldAxis*> axi = inputs::MakeFieldAxi(new inputs::Field(std::make_pair<inputs::ContAxis*, inputs::ContAxis*>(GetObj(primary_axis), GetObj(secondary_axis)), squared));
Map(primary_axis, axi.first, true);
Map(secondary_axis, axi.second, true);
}
void SmartController::Map(std::pair<tButton, tButton> map_buttons, std::vector<tButton> virt_buttons, bool wrap, bool force) {
if (!Exists(std::vector<tButton>({ map_buttons.first, map_buttons.second }))) return;
std::vector<inputs::ButtonSelectorButton*> buttons = inputs::MakeButtonSelectorButtons({ GetObj(map_buttons.first), GetObj(map_buttons.second) }, virt_buttons.size(), wrap);
for (unsigned int i = 0; i < buttons.size(); i++) {
if (virt_buttons.at(i) != noButton) Map(virt_buttons.at(i), buttons.at(i), force);
}
// _buttons.erase(_buttons.find(map_buttons.first.id));
// _buttons.erase(_buttons.find(map_buttons.second.id));
}
void SmartController::Map(tPOV map_POV, std::map<Controller::POVPos, tButton> virt_buttons, bool force) {
if (!Exists(map_POV)) return;
std::map<Controller::POVPos, inputs::POVButton*> buttons = inputs::MakePOVButtons(GetObj(map_POV));
for (auto pair : virt_buttons) {
if (pair.second != noButton) Map(pair.second, buttons.at(pair.first), force);
}
// _POVs.erase(_POVs.find(map_POV.id));
}
// --------------------------------------------- INPUT GETTERS ---------------------------------------------
double SmartController::Get(tAxis axis) {
if (Exists(axis, false)) return 0;
return GetObj(axis)->Get();
}
bool SmartController::Get(tButton button, SmartController::ButtonMode mode) {
if (Exists(button, false)) return false;
switch (mode) {
case ButtonMode::RAW:
return GetObj(button)->Get();
case ButtonMode::ONRISE:
return GetObj(button)->GetOnRise();
case ButtonMode::ONFALL:
return GetObj(button)->GetOnFall();
case ButtonMode::ONCHANGE:
return GetObj(button)->GetOnChange();
}
return false;
}
wml::controllers::Controller::POVPos SmartController::Get(tPOV pov) {
if (Exists(pov, false)) return kNone;
return GetObj(pov)->Get();
}
// ------------------------------------------- FEEDBACK SETTERS --------------------------------------------
void SmartController::Set(tRumble rumble, double value) {
_cont->SetRumble(rumble.type, value);
}
// --------------------------------------------- UPDATE FUNCS ----------------------------------------------
void SmartController::UpdateButtonSelectors() {
for (auto pair : _buttons) UpdateButtonSelector(tButton(-1, pair.first));
}
| 5,328 | 1,892 |
/**
* UGENE - Integrated Bioinformatics Tools.
* Copyright (C) 2008-2012 UniPro <ugene@unipro.ru>
* http://ugene.unipro.ru
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "BlastPlusWorker.h"
#include "TaskLocalStorage.h"
#include "BlastPlusSupport.h"
#include "BlastNPlusSupportTask.h"
#include "BlastPPlusSupportTask.h"
#include "BlastXPlusSupportTask.h"
#include "TBlastNPlusSupportTask.h"
#include "TBlastXPlusSupportTask.h"
#include <U2Lang/IntegralBusModel.h>
#include <U2Lang/WorkflowEnv.h>
#include <U2Lang/ActorPrototypeRegistry.h>
#include <U2Lang/BaseTypes.h>
#include <U2Lang/BaseSlots.h>
#include <U2Lang/BasePorts.h>
#include <U2Lang/BaseActorCategories.h>
#include <U2Designer/DelegateEditors.h>
#include <U2Lang/CoreLibConstants.h>
#include <U2Core/AppContext.h>
#include <U2Core/AppSettings.h>
#include <U2Core/UserApplicationsSettings.h>
#include <U2Core/ExternalToolRegistry.h>
#include <U2Core/Log.h>
#include <U2Core/FailTask.h>
#include <U2Core/U2AlphabetUtils.h>
#include <U2Core/DNASequenceObject.h>
namespace U2 {
namespace LocalWorkflow {
/****************************
* BlastAllWorkerFactory
****************************/
const QString BlastPlusWorkerFactory::ACTOR_ID("blast-plus");
#define BLASTPLUS_PROGRAM_NAME "blast-type"
#define BLASTPLUS_DATABASE_PATH "db-path"
#define BLASTPLUS_DATABASE_NAME "db-name"
#define BLASTPLUS_EXPECT_VALUE "e-val"
#define BLASTPLUS_GROUP_NAME "result-name"
#define BLASTPLUS_EXT_TOOL_PATH "tool-path"
#define BLASTPLUS_TMP_DIR_PATH "temp-dir"
//Additional options
#define BLASTPLUS_ORIGINAL_OUT "blast-output" //path for output file
#define BLASTPLUS_OUT_TYPE "type-output" //original option -m 0-11
#define BLASTPLUS_GAPPED_ALN "gapped-aln" //Perform gapped alignment (not available with tblastx)
void BlastPlusWorkerFactory::init() {
QList<PortDescriptor*> p; QList<Attribute*> a;
Descriptor ind(BasePorts::IN_SEQ_PORT_ID(), BlastPlusWorker::tr("Input sequence"),
BlastPlusWorker::tr("Sequence for which annotations is searched."));
Descriptor oud(BasePorts::OUT_ANNOTATIONS_PORT_ID(), BlastPlusWorker::tr("Annotations"), BlastPlusWorker::tr("Found annotations."));
QMap<Descriptor, DataTypePtr> inM;
inM[BaseSlots::DNA_SEQUENCE_SLOT()] = BaseTypes::DNA_SEQUENCE_TYPE();
p << new PortDescriptor(ind, DataTypePtr(new MapDataType("blast.plus.seq", inM)), true /*input*/);
QMap<Descriptor, DataTypePtr> outM;
outM[BaseSlots::ANNOTATION_TABLE_SLOT()] = BaseTypes::ANNOTATION_TABLE_TYPE();
p << new PortDescriptor(oud, DataTypePtr(new MapDataType("blast.plus.annotations", outM)), false /*input*/, true /*multi*/);
Descriptor pn(BLASTPLUS_PROGRAM_NAME, BlastPlusWorker::tr("Search type"),
BlastPlusWorker::tr("Select type of BLAST+ searches"));
Descriptor dp(BLASTPLUS_DATABASE_PATH, BlastPlusWorker::tr("Database Path"),
BlastPlusWorker::tr("Path with database files"));
Descriptor dn(BLASTPLUS_DATABASE_NAME, BlastPlusWorker::tr("Database Name"),
BlastPlusWorker::tr("Base name for BLAST+ DB files"));
Descriptor ev(BLASTPLUS_EXPECT_VALUE, BlastPlusWorker::tr("Expected value"),
BlastPlusWorker::tr("This setting specifies the statistical significance threshold for reporting matches against database sequences."));
Descriptor gn(BLASTPLUS_GROUP_NAME, BlastPlusWorker::tr("Annotate as"),
BlastPlusWorker::tr("Name for annotations"));
Descriptor etp(BLASTPLUS_EXT_TOOL_PATH, BlastPlusWorker::tr("Tool Path"),
BlastPlusWorker::tr("External tool path"));
Descriptor tdp(BLASTPLUS_TMP_DIR_PATH, BlastPlusWorker::tr("Temporary directory"),
BlastPlusWorker::tr("Directory for temporary files"));
Descriptor output(BLASTPLUS_ORIGINAL_OUT, BlastPlusWorker::tr("BLAST output"),
BlastPlusWorker::tr("Location of BLAST output file."));
Descriptor outtype(BLASTPLUS_OUT_TYPE, BlastPlusWorker::tr("BLAST output type"),
BlastPlusWorker::tr("Type of BLAST output file."));
Descriptor ga(BLASTPLUS_GAPPED_ALN, BlastPlusWorker::tr("Gapped alignment"),
BlastPlusWorker::tr("Perform gapped alignment"));
a << new Attribute(pn, BaseTypes::STRING_TYPE(), true, QVariant("blastn"));
a << new Attribute(dp, BaseTypes::STRING_TYPE(), true, QVariant(""));
a << new Attribute(dn, BaseTypes::STRING_TYPE(), true, QVariant(""));
a << new Attribute(etp, BaseTypes::STRING_TYPE(), true, QVariant("default"));
a << new Attribute(tdp, BaseTypes::STRING_TYPE(), true, QVariant("default"));
a << new Attribute(ev, BaseTypes::NUM_TYPE(), false, QVariant(10.00));
a << new Attribute(gn, BaseTypes::STRING_TYPE(), false, QVariant(""));
Attribute* gaAttr= new Attribute(ga, BaseTypes::BOOL_TYPE(), false, QVariant(true));
gaAttr->addRelation(new VisibilityRelation(BLASTPLUS_PROGRAM_NAME,"blastn"));
gaAttr->addRelation(new VisibilityRelation(BLASTPLUS_PROGRAM_NAME,"blastp"));
gaAttr->addRelation(new VisibilityRelation(BLASTPLUS_PROGRAM_NAME,"gpu-blastp"));
gaAttr->addRelation(new VisibilityRelation(BLASTPLUS_PROGRAM_NAME,"blastx"));
gaAttr->addRelation(new VisibilityRelation(BLASTPLUS_PROGRAM_NAME,"tblastn"));
a << gaAttr;
a << new Attribute(output, BaseTypes::STRING_TYPE(), false, QVariant(""));
a << new Attribute(outtype, BaseTypes::STRING_TYPE(), false, QVariant("5"));
Descriptor desc(ACTOR_ID, BlastPlusWorker::tr("Local BLAST+ Search"),
BlastPlusWorker::tr("Finds annotations for DNA sequence in local database"));
ActorPrototype* proto = new IntegralBusActorPrototype(desc, p, a);
proto->addSlotRelation(BasePorts::IN_SEQ_PORT_ID(), BaseSlots::DNA_SEQUENCE_SLOT().getId(),
BasePorts::OUT_ANNOTATIONS_PORT_ID(), BaseSlots::ANNOTATION_TABLE_SLOT().getId());
QMap<QString, PropertyDelegate*> delegates;
{
QVariantMap m;
m["blastn"] = "blastn";
m["blastp"] = "blastp";
m["gpu-blastp"] = "gpu-blastp";
m["blastx"] = "blastx";
m["tblastn"] = "tblastn";
m["tblastx"] = "tblastx";
delegates[BLASTPLUS_PROGRAM_NAME] = new ComboBoxDelegate(m);
}
{
QVariantMap m;
m["minimum"] = 0.000001;
m["maximum"] = 100000;
m["singleStep"] = 1.0;
m["decimals"] = 6;
delegates[BLASTPLUS_EXPECT_VALUE] = new DoubleSpinBoxDelegate(m);
}
{
QVariantMap m;
m["use"] = true;
m["not use"] = false;
delegates[BLASTPLUS_GAPPED_ALN] = new ComboBoxDelegate(m);
}
{
QVariantMap m;
m["traditional pairwise (-outfmt 0)"] = 0;
// m["query-anchored showing identities"] = 1;
// m["query-anchored no identities"] = 2;
// m["flat query-anchored, show identities"] = 3;
// m["flat query-anchored, no identities"] = 4;
m["XML (-outfmt 5)"] = 5;
m["tabular (-outfmt 6)"] = 6;
// m["tabular with comment lines"] = 7;
// m["Text ASN.1"] = 8;
// m["Binary ASN.1"] = 9;
// m["Comma-separated values"] = 10;
// m["BLAST archive format (ASN.1)"] = 11;
delegates[BLASTPLUS_OUT_TYPE] = new ComboBoxDelegate(m);
}
delegates[BLASTPLUS_ORIGINAL_OUT] = new URLDelegate("", "out file", false);
delegates[BLASTPLUS_DATABASE_PATH] = new URLDelegate("", "Database Directory", false, true);
delegates[BLASTPLUS_EXT_TOOL_PATH] = new URLDelegate("", "executable", false);
delegates[BLASTPLUS_TMP_DIR_PATH] = new URLDelegate("", "TmpDir", false, true);
proto->setEditor(new DelegateEditor(delegates));
proto->setPrompter(new BlastPlusPrompter());
proto->setIconPath(":external_tool_support/images/ncbi.png");
WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_BASIC(), proto);
DomainFactory* localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID);
localDomain->registerEntry(new BlastPlusWorkerFactory());
}
/****************************
* BlastPlusPrompter
****************************/
BlastPlusPrompter::BlastPlusPrompter(Actor* p) : PrompterBase<BlastPlusPrompter>(p) {
}
QString BlastPlusPrompter::composeRichDoc() {
IntegralBusPort* input = qobject_cast<IntegralBusPort*>(target->getPort(BasePorts::IN_SEQ_PORT_ID()));
Actor* producer = input->getProducer(BaseSlots::DNA_SEQUENCE_SLOT().getId());
QString unsetStr = "<font color='red'>"+tr("unset")+"</font>";
QString producerName = tr(" from <u>%1</u>").arg(producer ? producer->getLabel() : unsetStr);
QString doc = tr("For sequence <u>%1</u> find annotations in database <u>%2</u>")
.arg(producerName).arg(getHyperlink(BLASTPLUS_DATABASE_NAME, getRequiredParam(BLASTPLUS_DATABASE_NAME)));
return doc;
}
/****************************
* BlastPlusWorker
****************************/
BlastPlusWorker::BlastPlusWorker(Actor* a) : BaseWorker(a), input(NULL), output(NULL) {
}
void BlastPlusWorker::init() {
input = ports.value(BasePorts::IN_SEQ_PORT_ID());
output = ports.value(BasePorts::OUT_ANNOTATIONS_PORT_ID());
}
Task* BlastPlusWorker::tick() {
if (input->hasMessage()) {
Message inputMessage = getMessageAndSetupScriptValues(input);
if (inputMessage.isEmpty()) {
output->transit();
return NULL;
}
cfg.programName=actor->getParameter(BLASTPLUS_PROGRAM_NAME)->getAttributeValue<QString>(context);
cfg.databaseNameAndPath=actor->getParameter(BLASTPLUS_DATABASE_PATH)->getAttributeValue<QString>(context) +"/"+
actor->getParameter(BLASTPLUS_DATABASE_NAME)->getAttributeValue<QString>(context);
cfg.isDefaultCosts=true;
cfg.isDefaultMatrix=true;
cfg.isDefautScores=true;
cfg.expectValue=actor->getParameter(BLASTPLUS_EXPECT_VALUE)->getAttributeValue<double>(context);
cfg.groupName=actor->getParameter(BLASTPLUS_GROUP_NAME)->getAttributeValue<QString>(context);
if(cfg.groupName.isEmpty()){
cfg.groupName="blast result";
}
cfg.wordSize=0;
cfg.isGappedAlignment=actor->getParameter(BLASTPLUS_GAPPED_ALN)->getAttributeValue<bool>(context);
QString path=actor->getParameter(BLASTPLUS_EXT_TOOL_PATH)->getAttributeValue<QString>(context);
if(QString::compare(path, "default", Qt::CaseInsensitive) != 0){
if(cfg.programName == "blastn"){
AppContext::getExternalToolRegistry()->getByName(BLASTN_TOOL_NAME)->setPath(path);
}else if(cfg.programName == "blastp"){
AppContext::getExternalToolRegistry()->getByName(BLASTP_TOOL_NAME)->setPath(path);
// }else if(cfg.programName == "gpu-blastp"){ // https://ugene.unipro.ru/tracker/browse/UGENE-945
// AppContext::getExternalToolRegistry()->getByName(GPU_BLASTP_TOOL_NAME)->setPath(path);
}else if(cfg.programName == "blastx"){
AppContext::getExternalToolRegistry()->getByName(BLASTX_TOOL_NAME)->setPath(path);
}else if(cfg.programName == "tblastn"){
AppContext::getExternalToolRegistry()->getByName(TBLASTN_TOOL_NAME)->setPath(path);
}else if(cfg.programName == "tblastx"){
AppContext::getExternalToolRegistry()->getByName(TBLASTX_TOOL_NAME)->setPath(path);
}
}
path=actor->getParameter(BLASTPLUS_TMP_DIR_PATH)->getAttributeValue<QString>(context);
if(QString::compare(path, "default", Qt::CaseInsensitive) != 0){
AppContext::getAppSettings()->getUserAppsSettings()->setUserTemporaryDirPath(path);
}
SharedDbiDataHandler seqId = inputMessage.getData().toMap().value(BaseSlots::DNA_SEQUENCE_SLOT().getId()).value<SharedDbiDataHandler>();
std::auto_ptr<U2SequenceObject> seqObj(StorageUtils::getSequenceObject(context->getDataStorage(), seqId));
if (NULL == seqObj.get()) {
return NULL;
}
DNASequence seq = seqObj->getWholeSequence();
if( seq.length() < 1) {
return new FailTask(tr("Empty sequence supplied to BLAST"));
}
cfg.querySequence=seq.seq;
DNAAlphabet *alp = U2AlphabetUtils::findBestAlphabet(seq.seq);
cfg.alphabet=alp;
//TO DO: Check alphabet
if(seq.alphabet->isAmino()) {
if(cfg.programName == "blastn" || cfg.programName == "blastx" || cfg.programName == "tblastx") {
return new FailTask(tr("Selected BLAST search with nucleotide input sequence"));
}
}
else {
if(cfg.programName == "blastp" || cfg.programName == "gpu-blastp" || cfg.programName == "tblastn") {
return new FailTask(tr("Selected BLAST search with amino acid input sequence"));
}
}
cfg.needCreateAnnotations=false;
cfg.outputType=actor->getParameter(BLASTPLUS_OUT_TYPE)->getAttributeValue<int>(context);
cfg.outputOriginalFile=actor->getParameter(BLASTPLUS_ORIGINAL_OUT)->getAttributeValue<QString>(context);
if(cfg.outputType != 5 && cfg.outputOriginalFile.isEmpty()){
return new FailTask(tr("Not selected BLAST output file"));
}
if(cfg.programName == "blastn"){
cfg.megablast = true;
cfg.wordSize = 28;
cfg.windowSize = 0;
}else{
cfg.megablast = false;
cfg.wordSize = 3;
cfg.windowSize = 40;
}
//set X dropoff values
if(cfg.programName == "blastn"){
cfg.xDropoffFGA = 100;
cfg.xDropoffGA = 20;
cfg.xDropoffUnGA = 10;
}else if (cfg.programName == "tblastx"){
cfg.xDropoffFGA = 0;
cfg.xDropoffGA = 0;
cfg.xDropoffUnGA = 7;
}else{
cfg.xDropoffFGA = 25;
cfg.xDropoffGA = 15;
cfg.xDropoffUnGA = 7;
}
Task * t=NULL;
if(cfg.programName == "blastn"){
t = new BlastNPlusSupportTask(cfg);
}else if(cfg.programName == "blastp" || cfg.programName == "gpu-blastp"){
t = new BlastPPlusSupportTask(cfg);
}else if(cfg.programName == "blastx"){
t = new BlastXPlusSupportTask(cfg);
}else if(cfg.programName == "tblastn"){
t = new TBlastNPlusSupportTask(cfg);
}else if(cfg.programName == "tblastx"){
t = new TBlastXPlusSupportTask(cfg);
}
connect(t, SIGNAL(si_stateChanged()), SLOT(sl_taskFinished()));
return t;
} else if (input->isEnded()) {
setDone();
output->setEnded();
}
return NULL;
}
void BlastPlusWorker::sl_taskFinished() {
BlastPlusSupportCommonTask* t = qobject_cast<BlastPlusSupportCommonTask*>(sender());
if (t->getState() != Task::State_Finished) return;
if(output) {
QList<SharedAnnotationData> res = t->getResultedAnnotations();
QString annName = actor->getParameter(BLASTPLUS_GROUP_NAME)->getAttributeValue<QString>(context);
if(!annName.isEmpty()) {
for(int i = 0; i<res.count();i++) {
res[i]->name = annName;
}
}
QVariant v = qVariantFromValue<QList<SharedAnnotationData> >(res);
output->put(Message(BaseTypes::ANNOTATION_TABLE_TYPE(), v));
}
}
void BlastPlusWorker::cleanup() {
}
} //namespace LocalWorkflow
} //namespace U2
| 16,225 | 5,449 |
/**
Sunny and Johnny together have MM dollars they want to spend on ice cream.
The parlor offers N flavors, and they want to choose two flavors so that they end up spending the whole amount.
You are given the cost of these flavors. The cost of the ith flavor is denoted by ci. You have to display the indices of the two flavors whose sum is M.
Input Format
The first line of the input contains T; T test cases follow.
Each test case follows the format detailed below:
The first line contains M.
The second line contains N.
The third line contains N space-separated integers denoting the price of each flavor. Here, the ith integer denotes ci.
Output Format
Output two integers, each of which is a valid index of a flavor. The lower index must be printed first. Indices are indexed from 1 to N.
Constraints
1 <= T <= 50
2 <= M <= 10000
2 <= N <= 10000
1 <= ci <= 10000, where i in [1,N]
The prices of any two items may be the same and each test case has a unique solution.
Sample Input
2
4
5
1 4 5 3 2
4
4
2 2 4 3
Sample Output
1 4
1 2
Explanation
The sample input has two test cases.
For the 1st, the amount M = 4 and there are 5 flavors at the store. The flavors indexed at 1 and 4 sum up to 4.
For the 2nd test case, the amount M = 4 and the flavors indexed at 1 and 2 sum up to 4.
**/
/**
NOTE:
http://stackoverflow.com/questions/4720271/find-a-pair-of-elements-from-an-array-whose-sum-equals-a-given-number
There are 3 approaches to this solution:
Let the sum be T and n be the size of array
Approach 1:
The naive way to do this would be to check all combinations (n choose 2). This exhaustive search is O(n2).
Approach 2:
A better way would be to sort the array. This takes O(n log n)
Then for each x in array A, use binary search to look for T-x. This will take O(nlogn).
So, overall search is O(n log n)
Approach 3 :
The best way would be to insert every element into a hash table (without sorting). This takes O(n) as constant time insertion.
Then for every x, we can just look up its complement, T-x, which is O(1).
Overall the run time of this approach is O(n).
**/
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;
int main() {
int t = 0;
cin >> t;
while(t--){
unsigned M = 0;
unsigned N = 0;
cin >> M >> N;
unordered_map<int,unsigned> prices;
for(unsigned i = 0; i < N; i++){
unsigned price = 0;
cin >> price;
prices.insert({price,i});
unordered_map<int,unsigned>::const_iterator got = prices.find(M-price);
if(got != prices.end() && got->second != i){
cout << got->second + 1 << " " << i+1;
}
}
cout << "\n";
}
return 0;
}
| 2,820 | 918 |
#ifndef WXSFMLCANVAS_HPP
#define WXSFMLCANVAS_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics.hpp>
#include <wx/wx.h>
////////////////////////////////////////////////////////////
/// wxSFMLCanvas allows to run SFML in a wxWidgets control
////////////////////////////////////////////////////////////
class wxSFMLCanvas : public wxControl, public sf::RenderWindow
{
public :
////////////////////////////////////////////////////////////
/// Construct the wxSFMLCanvas
///
/// \param Parent : Parent of the control (NULL by default)
/// \param Id : Identifier of the control (-1 by default)
/// \param Position : Position of the control (wxDefaultPosition by default)
/// \param Size : Size of the control (wxDefaultSize by default)
/// \param Style : Style of the control (0 by default)
///
////////////////////////////////////////////////////////////
wxSFMLCanvas(wxWindow* Parent = NULL, wxWindowID Id = -1, const wxPoint& Position = wxDefaultPosition, const wxSize& Size = wxDefaultSize, long Style = 0);
////////////////////////////////////////////////////////////
/// Destructor
///
////////////////////////////////////////////////////////////
virtual ~wxSFMLCanvas();
private :
DECLARE_EVENT_TABLE()
////////////////////////////////////////////////////////////
/// Notification for the derived class that moment is good
/// for doing its update and drawing stuff
///
////////////////////////////////////////////////////////////
virtual void OnUpdate();
////////////////////////////////////////////////////////////
/// Called when the window is idle - we can refresh our
/// SFML window
///
////////////////////////////////////////////////////////////
void OnIdle(wxIdleEvent&);
////////////////////////////////////////////////////////////
/// Called when the window is repainted - we can display our
/// SFML window
///
////////////////////////////////////////////////////////////
void OnPaint(wxPaintEvent&);
////////////////////////////////////////////////////////////
/// Called when the window needs to draw its background
///
////////////////////////////////////////////////////////////
void OnEraseBackground(wxEraseEvent&);
};
#endif // WXSFMLCANVAS_HPP
| 2,536 | 618 |
// Copyright (C) 2018-2019 Internet Systems Consortium, Inc. ("ISC")
//
// 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/.
#include <config.h>
#include <process/config_ctl_info.h>
#include <exceptions/exceptions.h>
#include <gtest/gtest.h>
#include <sstream>
#include <iostream>
using namespace isc::process;
using namespace isc::data;
using namespace isc::util;
// Verifies initializing via an access string and unparsing into elements
// We just test basic unparsing, as more rigorous testing is done in
// libkea-db testing which ConfibDBInfo uses.
TEST(ConfigDbInfo, basicOperation) {
ConfigDbInfo db;
std::string access = "type=mysql user=tom password=terrific";
std::string redacted_access = "password=***** type=mysql user=tom";
std::string access_json = "{\n"
" \"type\":\"mysql\", \n"
" \"user\":\"tom\", \n"
" \"password\":\"terrific\" \n"
"} \n";
// Convert the above configuration into Elements for comparison.
ElementPtr exp_elems;
ASSERT_NO_THROW(exp_elems = Element::fromJSON(access_json))
<< "test is broken";
// Initialize the db from an the access string
db.setAccessString(access);
EXPECT_EQ(access, db.getAccessString());
EXPECT_EQ(redacted_access, db.redactedAccessString());
// Convert the db into Elements and make sure they are as expected.
ElementPtr db_elems;
ASSERT_NO_THROW(db_elems = db.toElement());
EXPECT_TRUE(db_elems->equals(*exp_elems));
}
// Verify that db parameter values may be retrieved.
TEST(ConfigDbInfo, getParameterValue) {
ConfigDbInfo db1;
std::string access1 = "type=mysql name=keatest port=33 readonly=false";
db1.setAccessString(access1);
std::string value;
bool found = false;
// Should find "type"
ASSERT_NO_THROW(found = db1.getParameterValue("type", value));
EXPECT_TRUE(found);
EXPECT_EQ("mysql", value);
// Should find "name"
ASSERT_NO_THROW(found = db1.getParameterValue("name", value));
EXPECT_TRUE(found);
EXPECT_EQ("keatest", value);
// Should find "port"
ASSERT_NO_THROW(found = db1.getParameterValue("port", value));
EXPECT_TRUE(found);
EXPECT_EQ("33", value);
// Should find "readonly"
ASSERT_NO_THROW(found = db1.getParameterValue("readonly", value));
EXPECT_TRUE(found);
EXPECT_EQ("false", value);
// Should not find "bogus"
ASSERT_NO_THROW(found = db1.getParameterValue("bogus", value));
EXPECT_FALSE(found);
}
// Verify that db equality operators work correctly.
TEST(ConfigDbInfo, equalityOperators) {
ConfigDbInfo db1;
std::string access1 = "type=mysql user=tom password=terrific";
ASSERT_NO_THROW(db1.setAccessString(access1));
ConfigDbInfo db2;
std::string access2 = "type=postgresql user=tom password=terrific";
ASSERT_NO_THROW(db2.setAccessString(access2));
// Verify that the two unequal dbs are in fact not equal.
EXPECT_FALSE(db1.equals(db2));
EXPECT_FALSE(db1 == db2);
EXPECT_TRUE(db1 != db2);
// Verify that the two equal dbs are in fact equal.
db2.setAccessString(access1);
EXPECT_TRUE(db1.equals(db2));
EXPECT_TRUE(db1 == db2);
EXPECT_FALSE(db1 != db2);
}
// Verifies the basic operations of ConfigControlInfo
TEST(ConfigControlInfo, basicOperation) {
ConfigControlInfo ctl;
// We should have no dbs in the list.
EXPECT_EQ(0, ctl.getConfigDatabases().size());
// The default fetch time is 30 and it is unspecified.
EXPECT_TRUE(ctl.getConfigFetchWaitTime().unspecified());
EXPECT_EQ(30, ctl.getConfigFetchWaitTime().get());
// Override the default fetch time.
ctl.setConfigFetchWaitTime(Optional<uint16_t>(123));
EXPECT_EQ(123, ctl.getConfigFetchWaitTime().get());
// We should be able to add two distinct, valid dbs
std::string access_str1 = "type=mysql host=machine1.org";
ASSERT_NO_THROW(ctl.addConfigDatabase(access_str1));
std::string access_str2 = "type=postgresql host=machine2.org";
ASSERT_NO_THROW(ctl.addConfigDatabase(access_str2));
// We should fail on a duplicate db.
ASSERT_THROW(ctl.addConfigDatabase(access_str1), isc::BadValue);
// We should have two dbs in the list.
const ConfigDbInfoList& db_list = ctl.getConfigDatabases();
EXPECT_EQ(2, db_list.size());
// Verify the dbs in the list are as we expect them to be.
EXPECT_EQ (access_str1, db_list[0].getAccessString());
EXPECT_EQ (access_str2, db_list[1].getAccessString());
// Verify we can find dbs based on a property values.
const ConfigDbInfo& db_info = ctl.findConfigDb("type", "mysql");
EXPECT_FALSE(db_info == ConfigControlInfo::EMPTY_DB());
EXPECT_EQ (access_str1, db_info.getAccessString());
const ConfigDbInfo& db_info2 = ctl.findConfigDb("host", "machine2.org");
EXPECT_FALSE(db_info2 == ConfigControlInfo::EMPTY_DB());
EXPECT_EQ (access_str2, db_info2.getAccessString());
// Verify not finding a db reutrns EMPTY_DB().
const ConfigDbInfo& db_info3 = ctl.findConfigDb("type", "bogus");
EXPECT_TRUE(db_info3 == ConfigControlInfo::EMPTY_DB());
// Verify we can clear the list of dbs and the fetch time.
ctl.clear();
EXPECT_EQ(0, ctl.getConfigDatabases().size());
EXPECT_TRUE(ctl.getConfigFetchWaitTime().unspecified());
EXPECT_EQ(30, ctl.getConfigFetchWaitTime().get());
}
// Verifies the copy ctor and equality functions ConfigControlInfo
TEST(ConfigControlInfo, copyAndEquality) {
// Make an instance with two dbs.
ConfigControlInfo ctl1;
ASSERT_NO_THROW(ctl1.addConfigDatabase("type=mysql host=mach1.org"));
ASSERT_NO_THROW(ctl1.addConfigDatabase("type=postgresql host=mach2.org"));
ctl1.setConfigFetchWaitTime(Optional<uint16_t>(123));
// Clone that instance.
ConfigControlInfo ctl2(ctl1);
// They should be equal.
EXPECT_TRUE(ctl1.equals(ctl2));
// Make a third instance with a different db.
ConfigControlInfo ctl3;
ASSERT_NO_THROW(ctl1.addConfigDatabase("type=cql host=other.org"));
// They should not equal.
EXPECT_FALSE(ctl3.equals(ctl1));
}
| 6,257 | 2,171 |
#include "test_load_ntdll.h"
#include "peconv.h"
#include <iostream>
#include "shellcodes.h"
int (_cdecl *ntdll_tolower) (int) = NULL;
NTSTATUS (NTAPI *ntdll_ZwAllocateVirtualMemory)(
_In_ HANDLE ProcessHandle,
_Inout_ PVOID *BaseAddress,
_In_ ULONG_PTR ZeroBits,
_Inout_ PSIZE_T RegionSize,
_In_ ULONG AllocationType,
_In_ ULONG Protect
) = NULL;
//For now this is for manual tests only:
int tests::test_ntdll(char *path)
{
CHAR ntdllPath[MAX_PATH];
ExpandEnvironmentStrings("%SystemRoot%\\system32\\ntdll.dll", ntdllPath, MAX_PATH);
size_t v_size = 0;
BYTE *ntdll_module = peconv::load_pe_module(ntdllPath, v_size, true, true);
if (!ntdll_module) {
return -1;
}
bool is64 = peconv::is64bit(ntdll_module);
std::cout << "NTDLL loaded" << is64 << std::endl;
FARPROC n_offset = peconv::get_exported_func(ntdll_module, "tolower");
if (n_offset == NULL) {
return -1;
}
std::cout << "Got tolower: " << n_offset << std::endl;
ntdll_tolower = (int (_cdecl *) (int)) n_offset;
int out = ntdll_tolower('C');
std::cout << "To lower char: " << (char) out << std::endl;
n_offset = peconv::get_exported_func(ntdll_module, "ZwAllocateVirtualMemory");
if (n_offset == NULL) {
return -1;
}
PVOID base_addr = 0;
SIZE_T buffer_size = 0x200;
ntdll_ZwAllocateVirtualMemory = (NTSTATUS (NTAPI *)(HANDLE, PVOID *, ULONG_PTR, PSIZE_T, ULONG, ULONG)) n_offset;
NTSTATUS status = ntdll_ZwAllocateVirtualMemory(
GetCurrentProcess(), &base_addr, 0, &buffer_size, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE
);
if (status != S_OK) {
return -1;
}
printf("allocated: %p\n", base_addr);
#ifndef _WIN64
memcpy(base_addr, messageBox32bit_sc, sizeof(messageBox32bit_sc));
#else
memcpy(base_addr, messageBox64bit_sc, sizeof(messageBox64bit_sc));
#endif
void (*shellc)(void) = (void (*)(void))base_addr;
shellc();
return 0;
}
| 2,009 | 808 |
// Copyright 2022 Google LLC
//
// 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
//
// https://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.
// Generated by the Codegen C++ plugin.
// If you make any local changes, they will be lost.
// source: google/cloud/bigquery/v2/model.proto
#include "google/cloud/bigquery/internal/model_logging_decorator.h"
#include "google/cloud/internal/log_wrapper.h"
#include "google/cloud/status_or.h"
#include <google/cloud/bigquery/v2/model.grpc.pb.h>
#include <memory>
namespace google {
namespace cloud {
namespace bigquery_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
ModelServiceLogging::ModelServiceLogging(
std::shared_ptr<ModelServiceStub> child, TracingOptions tracing_options,
std::set<std::string> components)
: child_(std::move(child)),
tracing_options_(std::move(tracing_options)),
components_(std::move(components)) {}
StatusOr<google::cloud::bigquery::v2::Model> ModelServiceLogging::GetModel(
grpc::ClientContext& context,
google::cloud::bigquery::v2::GetModelRequest const& request) {
return google::cloud::internal::LogWrapper(
[this](grpc::ClientContext& context,
google::cloud::bigquery::v2::GetModelRequest const& request) {
return child_->GetModel(context, request);
},
context, request, __func__, tracing_options_);
}
StatusOr<google::cloud::bigquery::v2::ListModelsResponse>
ModelServiceLogging::ListModels(
grpc::ClientContext& context,
google::cloud::bigquery::v2::ListModelsRequest const& request) {
return google::cloud::internal::LogWrapper(
[this](grpc::ClientContext& context,
google::cloud::bigquery::v2::ListModelsRequest const& request) {
return child_->ListModels(context, request);
},
context, request, __func__, tracing_options_);
}
StatusOr<google::cloud::bigquery::v2::Model> ModelServiceLogging::PatchModel(
grpc::ClientContext& context,
google::cloud::bigquery::v2::PatchModelRequest const& request) {
return google::cloud::internal::LogWrapper(
[this](grpc::ClientContext& context,
google::cloud::bigquery::v2::PatchModelRequest const& request) {
return child_->PatchModel(context, request);
},
context, request, __func__, tracing_options_);
}
Status ModelServiceLogging::DeleteModel(
grpc::ClientContext& context,
google::cloud::bigquery::v2::DeleteModelRequest const& request) {
return google::cloud::internal::LogWrapper(
[this](grpc::ClientContext& context,
google::cloud::bigquery::v2::DeleteModelRequest const& request) {
return child_->DeleteModel(context, request);
},
context, request, __func__, tracing_options_);
}
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace bigquery_internal
} // namespace cloud
} // namespace google
| 3,300 | 991 |
/*
* Copyright 2009, Google Inc.
* 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 Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// This file implements class ClassManager.
#include "core/cross/bitmap.h"
#include "core/cross/bounding_box.h"
#include "core/cross/buffer.h"
#include "core/cross/canvas.h"
#include "core/cross/canvas_paint.h"
#include "core/cross/canvas_shader.h"
#include "core/cross/class_manager.h"
#include "core/cross/clear_buffer.h"
#include "core/cross/counter.h"
#include "core/cross/curve.h"
#include "core/cross/draw_context.h"
#include "core/cross/draw_pass.h"
#include "core/cross/effect.h"
#include "core/cross/function.h"
#include "core/cross/material.h"
#include "core/cross/matrix4_axis_rotation.h"
#include "core/cross/matrix4_composition.h"
#include "core/cross/matrix4_scale.h"
#include "core/cross/matrix4_translation.h"
#include "core/cross/param_array.h"
#include "core/cross/param_operation.h"
#include "core/cross/primitive.h"
#include "core/cross/render_surface_set.h"
#include "core/cross/sampler.h"
#include "core/cross/shape.h"
#include "core/cross/skin.h"
#include "core/cross/standard_param.h"
#include "core/cross/state_set.h"
#include "core/cross/stream.h"
#include "core/cross/stream_bank.h"
#include "core/cross/transform.h"
#include "core/cross/tree_traversal.h"
#include "core/cross/viewport.h"
namespace o3d {
ClassManager::ClassManager(ServiceLocator* service_locator)
: service_locator_(service_locator),
service_(service_locator_, this) {
// Params
AddTypedClass<ParamBoolean>();
AddTypedClass<ParamBoundingBox>();
AddTypedClass<ParamDrawContext>();
AddTypedClass<ParamDrawList>();
AddTypedClass<ParamEffect>();
AddTypedClass<ParamFloat>();
AddTypedClass<ParamFloat2>();
AddTypedClass<ParamFloat3>();
AddTypedClass<ParamFloat4>();
AddTypedClass<ParamFunction>();
AddTypedClass<ParamInteger>();
AddTypedClass<ParamMaterial>();
AddTypedClass<ParamMatrix4>();
AddTypedClass<ParamParamArray>();
AddTypedClass<ParamRenderSurface>();
AddTypedClass<ParamRenderDepthStencilSurface>();
AddTypedClass<ParamSampler>();
AddTypedClass<ParamSkin>();
AddTypedClass<ParamState>();
AddTypedClass<ParamStreamBank>();
AddTypedClass<ParamString>();
AddTypedClass<ParamTexture>();
AddTypedClass<ParamTransform>();
// Param operations.
AddTypedClass<Matrix4AxisRotation>();
AddTypedClass<Matrix4Composition>();
AddTypedClass<Matrix4Scale>();
AddTypedClass<Matrix4Translation>();
AddTypedClass<ParamOp2FloatsToFloat2>();
AddTypedClass<ParamOp3FloatsToFloat3>();
AddTypedClass<ParamOp4FloatsToFloat4>();
AddTypedClass<ParamOp16FloatsToMatrix4>();
AddTypedClass<TRSToMatrix4>();
// SAS Params
AddTypedClass<WorldParamMatrix4>();
AddTypedClass<WorldInverseParamMatrix4>();
AddTypedClass<WorldTransposeParamMatrix4>();
AddTypedClass<WorldInverseTransposeParamMatrix4>();
AddTypedClass<ViewParamMatrix4>();
AddTypedClass<ViewInverseParamMatrix4>();
AddTypedClass<ViewTransposeParamMatrix4>();
AddTypedClass<ViewInverseTransposeParamMatrix4>();
AddTypedClass<ProjectionParamMatrix4>();
AddTypedClass<ProjectionInverseParamMatrix4>();
AddTypedClass<ProjectionTransposeParamMatrix4>();
AddTypedClass<ProjectionInverseTransposeParamMatrix4>();
AddTypedClass<WorldViewParamMatrix4>();
AddTypedClass<WorldViewInverseParamMatrix4>();
AddTypedClass<WorldViewTransposeParamMatrix4>();
AddTypedClass<WorldViewInverseTransposeParamMatrix4>();
AddTypedClass<ViewProjectionParamMatrix4>();
AddTypedClass<ViewProjectionInverseParamMatrix4>();
AddTypedClass<ViewProjectionTransposeParamMatrix4>();
AddTypedClass<ViewProjectionInverseTransposeParamMatrix4>();
AddTypedClass<WorldViewProjectionParamMatrix4>();
AddTypedClass<WorldViewProjectionInverseParamMatrix4>();
AddTypedClass<WorldViewProjectionTransposeParamMatrix4>();
AddTypedClass<WorldViewProjectionInverseTransposeParamMatrix4>();
// Other Objects.
AddTypedClass<Bitmap>();
AddTypedClass<Canvas>();
AddTypedClass<CanvasLinearGradient>();
AddTypedClass<CanvasPaint>();
AddTypedClass<ClearBuffer>();
AddTypedClass<Counter>();
AddTypedClass<Curve>();
AddTypedClass<DrawContext>();
AddTypedClass<DrawElement>();
AddTypedClass<DrawList>();
AddTypedClass<DrawPass>();
AddTypedClass<Effect>();
AddTypedClass<FunctionEval>();
AddTypedClass<IndexBuffer>();
AddTypedClass<Material>();
AddTypedClass<ParamArray>();
AddTypedClass<ParamObject>();
AddTypedClass<Primitive>();
AddTypedClass<RenderFrameCounter>();
AddTypedClass<RenderNode>();
AddTypedClass<RenderSurfaceSet>();
AddTypedClass<Sampler>();
AddTypedClass<SecondCounter>();
AddTypedClass<Shape>();
AddTypedClass<Skin>();
AddTypedClass<SkinEval>();
AddTypedClass<SourceBuffer>();
AddTypedClass<State>();
AddTypedClass<StateSet>();
AddTypedClass<StreamBank>();
AddTypedClass<Texture2D>();
AddTypedClass<TextureCUBE>();
AddTypedClass<TickCounter>();
AddTypedClass<Transform>();
AddTypedClass<TreeTraversal>();
AddTypedClass<VertexBuffer>();
AddTypedClass<Viewport>();
}
void ClassManager::AddClass(const ObjectBase::Class* object_class,
ObjectCreateFunc function) {
DLOG_ASSERT(object_class_info_name_map_.find(object_class->name()) ==
object_class_info_name_map_.end())
<< "attempt to register duplicate class name";
object_class_info_name_map_.insert(
std::make_pair(object_class->name(),
ObjectClassInfo(object_class, function)));
DLOG_ASSERT(object_creator_class_map_.find(object_class) ==
object_creator_class_map_.end())
<< "attempt to register duplicate class";
object_creator_class_map_.insert(std::make_pair(object_class,
function));
}
void ClassManager::RemoveClass(const ObjectBase::Class* object_class) {
ObjectClassInfoNameMap::size_type ii = object_class_info_name_map_.erase(
object_class->name());
DLOG_ASSERT(ii == 1) << "attempt to unregister non-existant class name";
ObjectCreatorClassMap::size_type jj = object_creator_class_map_.erase(
object_class);
DLOG_ASSERT(jj == 1) << "attempt to unregister non-existant class";
}
const ObjectBase::Class* ClassManager::GetClassByClassName(
const String& class_name) const {
ObjectClassInfoNameMap::const_iterator iter =
object_class_info_name_map_.find(class_name);
if (iter == object_class_info_name_map_.end()) {
// Try adding the o3d namespace prefix
String prefixed_class_name(O3D_STRING_CONSTANT("") + class_name);
iter = object_class_info_name_map_.find(prefixed_class_name);
}
return (iter != object_class_info_name_map_.end()) ?
iter->second.class_type() : NULL;
}
bool ClassManager::ClassNameIsAClass(
const String& derived_class_name,
const ObjectBase::Class* base_class) const {
const ObjectBase::Class* derived_class = GetClassByClassName(
derived_class_name);
return derived_class && ObjectBase::ClassIsA(derived_class, base_class);
}
// Factory method to create a new object by class name.
ObjectBase::Ref ClassManager::CreateObject(const String& type_name) {
ObjectClassInfoNameMap::const_iterator iter =
object_class_info_name_map_.find(type_name);
if (iter == object_class_info_name_map_.end()) {
// Try adding the o3d namespace prefix
String prefixed_type_name(O3D_STRING_CONSTANT("") + type_name);
iter = object_class_info_name_map_.find(prefixed_type_name);
}
if (iter != object_class_info_name_map_.end()) {
return ObjectBase::Ref(iter->second.creation_func()(service_locator_));
}
return ObjectBase::Ref();
}
// Factory method to create a new object by class.
ObjectBase::Ref ClassManager::CreateObjectByClass(
const ObjectBase::Class* object_class) {
ObjectCreatorClassMap::const_iterator iter =
object_creator_class_map_.find(object_class);
if (iter != object_creator_class_map_.end()) {
return ObjectBase::Ref(iter->second(service_locator_));
}
return ObjectBase::Ref();
}
std::vector<const ObjectBase::Class*> ClassManager::GetAllClasses() const {
std::vector<const ObjectBase::Class*> classes;
for (ObjectClassInfoNameMap::const_iterator it =
object_class_info_name_map_.begin();
it != object_class_info_name_map_.end(); ++it) {
classes.push_back(it->second.class_type());
}
return classes;
}
} // namespace o3d
| 9,898 | 3,256 |
// -----------------------------------------------------------------------------
// File IO_TTY.CPP
//
// (c) by Elijah Koziev all rights reserved
//
// SOLARIX Intellectronix Project http://www.solarix.ru
// https://github.com/Koziev/GrammarEngine
//
// Content:
// Реализация TtyStream - потока для вывода символов на терминал (или в окно
// эмуляции терминала для графических сред).
//
// 27.04.2007 - TtyUcs4Stream and TtyUtf8Stream are implemented for Windows and
// Linux UNICODE console.
//
// 25.05.2007 - Utf8 tty stream bug fixed under linux UTF-8 console
// -----------------------------------------------------------------------------
//
// CD->20.06.1998
// LC->01.04.2018
// --------------
#include <lem/config.h>
#include <stdio.h>
#if defined LEM_DOS
#include <conio.h>
#elif defined LEM_UNIX
#if LEM_USES_NCURSES==1
#include <curses.h>
#endif
#endif
#include <lem/unicode.h>
#include <lem/console_application.h>
#include <lem/streams.h>
#if defined LEM_WINDOWS
#define WIN_CUI
#include <windows.h>
static HANDLE hOut = 0;
#endif
using namespace lem;
#if defined LEM_UNIX
// Make NCURSES initialization once.
static volatile int inited_ncurses = 0;
#endif
TtyStreamStd::TtyStreamStd(void)
:Stream(false, true)
{
SetMode(false, true, false);
binary = false;
return;
}
TtyStreamStd::~TtyStreamStd(void)
{}
void TtyStreamStd::close(void)
{
return;
}
void TtyStreamStd::write(const void *src, pos_type size)
{
for (pos_type i = 0; i < size; i++)
put(((const char*)src)[i]);
return;
}
void TtyStreamStd::put(char ch)
{
putchar(0x00ff & ch);
return;
}
void TtyStreamStd::puts(const char *s)
{
::puts(s);
return;
}
int TtyStreamStd::get(void)
{
return 0;
}
bool TtyStreamStd::eof(void) const
{
return false;
}
lem::Stream::pos_type TtyStreamStd::seekp(off_type /*pos*/, int /*whereto*/)
{
return 0;
}
lem::Stream::pos_type TtyStreamStd::tellp(void) const
{
LEM_STOPIT;
#if !defined LEM_BORLAND
return pos_type();
#endif
}
bool TtyStreamStd::move(lem::Stream::off_type /*offset*/)
{
return false;
}
lem::Stream::pos_type TtyStreamStd::fsize(void) const
{
return 0;
}
void TtyStreamStd::flush(void)
{
fflush(stdout);
return;
}
void TtyStreamStd::SetForeGroundColor(int iColor)
{}
void TtyStreamStd::SetBackGroundColor(int iColor)
{}
void TtyStreamStd::SetBlinkMode(bool blinks)
{}
void TtyStreamStd::SetHighLightMode(void)
{}
void TtyStreamStd::SetLowLightMode(void)
{}
void TtyStreamStd::SetNormalMode(void)
{}
lem::Stream::pos_type TtyStreamStd::read(void * /*dest*/, size_t /*size*/)
{
LEM_STOPIT;
#if !defined LEM_BORLAND
return pos_type();
#endif
}
// ##############################################################
/***************************************************************************
Работа с терминалом стандартными UNIX-подобными средствами не составляет
труда и интереса. Обращаю внимание лишь на способ, которым мы манипулируем
цветовыми характеристиками выводимых символов (с помощью стандартной
библиотеки NCURSES). Для управления цветом консоли Windows используются
также стандартные функции WinAPI).
****************************************************************************/
TtyStream::TtyStream(void)
:Stream(false, true)
{
SetMode(false, true, false);
binary = false;
#if defined LEM_UNIX && LEM_USES_NCURSES==1
// ************************************************
// Инициализация библиотеки NCURSES для LINUX
// ************************************************
if (!inited_ncurses)
{
initscr();
start_color();
cbreak();
// nonl();
// intrflush(stdscr,FALSE);
noecho();
scrollok(stdscr, TRUE);
init_pair(1, COLOR_BLACK, COLOR_WHITE);
init_pair(2, COLOR_BLUE, COLOR_BLACK);
init_pair(3, COLOR_GREEN, COLOR_BLACK);
init_pair(4, COLOR_CYAN, COLOR_BLACK);
init_pair(5, COLOR_RED, COLOR_BLACK);
init_pair(6, COLOR_MAGENTA, COLOR_BLACK);
init_pair(7, COLOR_YELLOW, COLOR_BLACK);
init_pair(8, COLOR_WHITE, COLOR_BLACK);
refresh();
}
inited_ncurses++;
#endif
#if defined WIN_CUI
if (!hOut)
hOut = GetStdHandle(STD_OUTPUT_HANDLE);
fg = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
bg = 0;
#endif
return;
}
int TtyStream::get(void)
{
return 0;
}
bool TtyStream::eof(void) const
{
return false;
}
Stream::pos_type TtyStream::tellp(void) const
{
LEM_STOPIT;
#if !defined LEM_BORLAND
return pos_type();
#endif
}
Stream::pos_type TtyStream::seekp(lem::Stream::off_type /*pos*/, int /*whereto*/)
{
return 0;
}
bool TtyStream::move(Stream::off_type /*offset*/)
{
return false;
}
Stream::pos_type TtyStream::fsize(void) const
{
return 0;
}
Stream::pos_type TtyStream::read(void * /*dest*/, size_t /*size*/)
{
LEM_STOPIT;
#if !defined LEM_BORLAND
return pos_type();
#endif
}
TtyStream::~TtyStream(void)
{
#if defined LEM_UNIX && LEM_USES_NCURSES==1
if (!--inited_ncurses)
{
// NCURSES should be closed
endwin();
}
#endif
/* ... nothing to do ... */
return;
}
void TtyStream::close(void)
{
return;
}
void TtyStream::write(const void *src, pos_type size)
{
for (pos_type i = 0; i < size; i++)
put(((const char*)src)[i]);
return;
}
void TtyStream::put(char ch)
{
#if defined WIN_CUI
char buf[1] = { ch };
DWORD dummy;
SetConsoleTextAttribute(hOut, fg | bg); // set the current colors
WriteConsoleA(hOut, buf, 1, &dummy, NULL); // put the char
#elif defined LEM_WIN32 && defined LEM_CONSOLE
printf("%c", ch);
#elif defined LEM_UNIX && LEM_USES_NCURSES==1
// UNIX (including LINUX) does not require 0x0d character in eol's.
// putchar(ch);
addch(0x00ffU & lem::uint16_t(ch));
if (ch == '\n')
{
refresh();
}
#else
printf("%c", ch);
if (ch == '\n')
printf("\r");
#endif
return;
}
void TtyStream::puts(const char *s)
{
#if defined WIN_CUI
DWORD dummy;
SetConsoleTextAttribute(hOut, fg | bg);
WriteConsoleA(hOut, s, lem_strlen(s), &dummy, NULL);
#elif defined LEM_WIN32 && defined LEM_CONSOLE
int i = 0;
while (s[i])
put(s[i++]);
#else
int i = 0;
while (s[i])
put(s[i++]);
#endif
return;
}
// *********************************************************
// Все символы, застрявшие в буфере вывода, принудительно
// отрисовываются на экране.
// *********************************************************
void TtyStream::flush(void)
{
#if defined WIN_CUI
// nothing to do
#elif defined LEM_WIN32 && defined LEM_CONSOLE
// nothing to do
#elif defined LEM_UNIX && defined LEM_CONSOLE && LEM_USES_NCURSES==1
refresh();
#else
fflush(stdout);
#endif
return;
}
/********************************************************
Индексом задается цвет символов для последующего вывода.
*********************************************************/
void TtyStream::SetForeGroundColor(int iColor)
{
#if defined WIN_CUI
switch (iColor)
{
case 0: fg = 0; break;
case 1: fg = FOREGROUND_BLUE; break;
case 2: fg = FOREGROUND_GREEN; break;
case 3: fg = FOREGROUND_BLUE | FOREGROUND_GREEN; break; // CYAN
case 4: fg = FOREGROUND_RED; break;
case 5: fg = FOREGROUND_RED | FOREGROUND_BLUE; break; // MAGENTA
case 6: fg = FOREGROUND_RED | FOREGROUND_GREEN; break; // BROWN
case 7:
fg = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE |
FOREGROUND_INTENSITY; // LIGHTGRAY
break;
case 8:
fg = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE; // DARKWHITE
break;
case 9:
fg = FOREGROUND_BLUE | FOREGROUND_INTENSITY;
break;
case 10:
fg = FOREGROUND_GREEN | FOREGROUND_INTENSITY;
break;
case 11:
fg = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY;
break;
case 12:
fg = FOREGROUND_RED | FOREGROUND_INTENSITY;
break;
case 13:
fg = FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY;
break;
case 14:
fg = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY;
break;
case 15:
fg = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE |
FOREGROUND_INTENSITY; // WHITE
break;
}
#elif defined(LEM_BORLAND_3_1) && defined(LEM_DOS)
textcolor(iColor);
#elif defined LEM_UNIX && LEM_USES_NCURSES==1
switch (iColor)
{
case 0: attrset(COLOR_PAIR(1)); break;
case 1: attrset(COLOR_PAIR(2)); break;
case 2: attrset(COLOR_PAIR(3)); break;
case 3: attrset(COLOR_PAIR(4)); break;
case 4: attrset(COLOR_PAIR(5)); break;
case 5: attrset(COLOR_PAIR(6)); break;
case 6: attrset(COLOR_PAIR(7)); break;
case 7: attrset(COLOR_PAIR(8)); break;
case 8: attrset(0); break;
case 9: attrset(COLOR_PAIR(2) | A_BOLD); break;
case 10: attrset(COLOR_PAIR(3) | A_BOLD); break;
case 11: attrset(COLOR_PAIR(4) | A_BOLD); break;
case 12: attrset(COLOR_PAIR(5) | A_BOLD); break;
case 13: attrset(COLOR_PAIR(6) | A_BOLD); break;
case 14: attrset(COLOR_PAIR(7) | A_BOLD); break;
case 15: attrset(COLOR_PAIR(8) | A_BOLD); break;
}
#endif
return;
}
/****************************************************************
При выводе на терминал - установка текущего цвета фона символов.
Цвет задается индексом.
*****************************************************************/
void TtyStream::SetBackGroundColor(int iColor)
{
#if defined(LEM_BORLAND_3_1) && defined(LEM_DOS)
textbackground(iColor);
#endif
return;
}
// ***********************************************************************
// Режим мерцания символов - был доступен для MSDOS. Особой пользы от него
// нет, но оставил метод для поддержки совместимости старых программ.
// ***********************************************************************
void TtyStream::SetBlinkMode(bool blinks)
{
#if defined(LEM_BORLAND_3_1) && defined(LEM_DOS)
text_info ti;
gettextinfo(&ti);
int atr = ti.attribute;
atr ^= BLINK;
textattr(atr);
#endif
return;
}
// ***********************************************************************
// Установка режима вывода символов с повышенной яркостью (белые).
// ***********************************************************************
void TtyStream::SetHighLightMode(void)
{
#if defined WIN_CUI
fg = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
bg = 0;
#elif defined(LEM_BORLAND_3_1) && defined(LEM_DOS)
highvideo();
#endif
return;
}
// ***********************************************************************
// Установка режима вывода символов с пониженной яркостью (темно-серые).
// ***********************************************************************
void TtyStream::SetLowLightMode(void)
{
#if defined WIN_CUI
fg = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
bg = 0;
#elif defined(LEM_BORLAND_3_1) && defined(LEM_DOS)
lowvideo();
#endif
return;
}
// *********************************************************************
// Установка режима вывода символов обычного цвета (серебристо-серые).
// *********************************************************************
void TtyStream::SetNormalMode(void)
{
#if defined WIN_CUI
fg = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
bg = 0;
// –ўҐв д® Ё бЁ¬ў®«®ў Ї® 㬮«з Ёо.
#elif defined(LEM_BORLAND_3_1) && defined(LEM_DOS)
// normvideo();
lowvideo();
#elif defined LEM_UNIX && LEM_USES_NCURSES==1
attrset(0);
#endif
return;
}
#if defined LEM_UNICODE_CONSOLE
#if defined LEM_WINDOWS
TtyUcs2Stream::TtyUcs2Stream(void) : TtyStream()
{}
int TtyUcs2Stream::Bits_Per_Char(void) const
{
return 16;
}
void TtyUcs2Stream::wput(wchar_t ch)
{
#if defined WIN_CUI
wchar_t buf[1] = { ch };
DWORD dummy;
BOOL res = SetConsoleTextAttribute(hOut, fg | bg); // set the current colors
LEM_CHECKIT_Z(res != 0);
res = WriteConsoleW(hOut, buf, 1, &dummy, NULL); // put the char
LEM_CHECKIT_Z(res != 0);
#else
LEM_STOPIT;
#endif
}
#endif
#if defined LEM_LINUX || defined LEM_DARWIN
TtyUtf8Stream::TtyUtf8Stream(void) : TtyStreamStd()
{}
void TtyUtf8Stream::put(char ch)
{
putchar(ch);
if (ch == '\n')
{
putchar('\r');
}
return;
}
void TtyUtf8Stream::wput(wchar_t ch)
{
if (!(0xffffff00 & ch))
putchar(ch);
else
{
uint8_t utf8[8];
const int n8 = lem::UCS4_to_UTF8(ch, utf8);
for (int i = 0; i < n8; i++)
putchar(utf8[i + 1]);
}
if (ch == L'\n')
{
putchar('\r');
// refresh();
}
}
#endif
#endif
StdTtyStream::StdTtyStream(void)
{
stream = NULL;
}
StdTtyStream::StdTtyStream(ostream *s)
:Stream(false, true)
{
stream = s;
}
void StdTtyStream::write(const void *src, pos_type size)
{
stream->write((const char*)src, size);
}
void StdTtyStream::put(char Ch)
{
stream->put(Ch);
#if LEM_DEBUGGING==1
Assert();
#endif
}
lem::Stream::pos_type StdTtyStream::read(void * /*dest*/, pos_type /*size*/)
{
return 0;
}
int StdTtyStream::get(void)
{
return -1;
}
void StdTtyStream::Check(void) const
{
#if LEM_DEBUGGING==1
Assert();
#endif
}
void StdTtyStream::flush(void)
{
#if LEM_DEBUGGING==1
Assert();
#endif
stream->flush();
}
void StdTtyStream::close(void)
{
#if LEM_DEBUGGING==1
Assert();
#endif
}
bool StdTtyStream::eof(void) const
{
#if LEM_DEBUGGING==1
Assert();
#endif
return false;
}
lem::Stream::pos_type StdTtyStream::tellp(void) const
{
#if LEM_DEBUGGING==1
Assert();
#endif
return 0;
}
StdTtyStream::pos_type StdTtyStream::seekp(lem::Stream::off_type /*to*/, int /*whereto*/)
{
#if LEM_DEBUGGING==1
Assert();
#endif
return (size_t)-1;
}
bool StdTtyStream::move(off_type /*offset*/)
{
#if LEM_DEBUGGING==1
Assert();
#endif
return false;
}
lem::Stream::pos_type StdTtyStream::fsize(void) const
{
#if LEM_DEBUGGING==1
Assert();
#endif
return 0;
}
| 15,072 | 5,992 |
/*** Copyright (c), The Regents of the University of California ***
*** For more information please refer to files in the COPYRIGHT directory ***/
/*
This is an interface to the Ticket management system.
*/
#include "irods_client_api_table.hpp"
#include "irods_pack_table.hpp"
#include "rods.h"
#include "rodsClient.h"
#include "irods_random.hpp"
#define MAX_SQL 300
#define BIG_STR 3000
extern int get64RandomBytes( char *buf );
char cwd[BIG_STR];
int debug = 0;
int longMode = 0; /* more detailed listing */
char zoneArgument[MAX_NAME_LEN + 2] = "";
rcComm_t *Conn;
rodsEnv myEnv;
int lastCommandStatus = 0;
int printCount = 0;
int printedRows = 0;
int usage( char *subOpt );
void showRestrictions( char *inColumn );
/*
print the results of a general query.
*/
void
printResultsAndSubQuery( rcComm_t *Conn, int status, genQueryOut_t *genQueryOut,
char *descriptions[], int subColumn, int dashOpt ) {
int i, j;
lastCommandStatus = status;
if ( status == CAT_NO_ROWS_FOUND ) {
lastCommandStatus = 0;
}
if ( status != 0 && status != CAT_NO_ROWS_FOUND ) {
printError( Conn, status, "rcGenQuery" );
}
else {
if ( status == CAT_NO_ROWS_FOUND ) {
if ( printCount == 0 ) {
printf( "No rows found\n" );
}
}
else {
for ( i = 0; i < genQueryOut->rowCnt; i++ ) {
printedRows++;
char *subCol = "";
if ( i > 0 && dashOpt > 0 ) {
printf( "----\n" );
}
for ( j = 0; j < genQueryOut->attriCnt; j++ ) {
char *tResult;
tResult = genQueryOut->sqlResult[j].value;
tResult += i * genQueryOut->sqlResult[j].len;
if ( subColumn == j ) {
subCol = tResult;
}
if ( *descriptions[j] != '\0' ) {
if ( strstr( descriptions[j], "time" ) != 0 ) {
char localTime[TIME_LEN];
getLocalTimeFromRodsTime( tResult, localTime );
if ( strcmp( tResult, "0" ) == 0 || *tResult == '\0' ) {
strcpy( localTime, "none" );
}
printf( "%s: %s\n", descriptions[j],
localTime );
}
else {
printf( "%s: %s\n", descriptions[j], tResult );
printCount++;
}
}
}
if ( subColumn >= 0 ) {
showRestrictions( subCol );
}
}
}
}
}
void
showRestrictionsByHost( char *inColumn ) {
genQueryInp_t genQueryInp;
genQueryOut_t *genQueryOut;
int i1a[10];
int i1b[10];
int i2a[10];
int i;
char v1[MAX_NAME_LEN];
char *condVal[10];
int status;
char *columnNames[] = {"restricted-to host"};
memset( &genQueryInp, 0, sizeof( genQueryInp_t ) );
printCount = 0;
i = 0;
i1a[i] = COL_TICKET_ALLOWED_HOST;
i1b[i++] = 0;
genQueryInp.selectInp.inx = i1a;
genQueryInp.selectInp.value = i1b;
genQueryInp.selectInp.len = i;
i2a[0] = COL_TICKET_ALLOWED_HOST_TICKET_ID;
snprintf( v1, sizeof( v1 ), "='%s'", inColumn );
condVal[0] = v1;
genQueryInp.sqlCondInp.inx = i2a;
genQueryInp.sqlCondInp.value = condVal;
genQueryInp.sqlCondInp.len = 1;
genQueryInp.maxRows = 10;
genQueryInp.continueInx = 0;
genQueryInp.condInput.len = 0;
status = rcGenQuery( Conn, &genQueryInp, &genQueryOut );
if ( status == CAT_NO_ROWS_FOUND ) {
i1a[0] = COL_USER_COMMENT;
genQueryInp.selectInp.len = 1;
status = rcGenQuery( Conn, &genQueryInp, &genQueryOut );
if ( status == 0 ) {
printf( "No host restrictions (1)\n" );
return;
}
if ( status == CAT_NO_ROWS_FOUND ) {
printf( "No host restrictions\n" );
return;
}
}
printResultsAndSubQuery( Conn, status, genQueryOut, columnNames, -1, 0 );
while ( status == 0 && genQueryOut->continueInx > 0 ) {
genQueryInp.continueInx = genQueryOut->continueInx;
status = rcGenQuery( Conn, &genQueryInp, &genQueryOut );
printResultsAndSubQuery( Conn, status, genQueryOut,
columnNames, 0, 0 );
}
return;
}
void
showRestrictionsByUser( char *inColumn ) {
genQueryInp_t genQueryInp;
genQueryOut_t *genQueryOut;
int i1a[10];
int i1b[10];
int i2a[10];
int i;
char v1[MAX_NAME_LEN];
char *condVal[10];
int status;
char *columnNames[] = {"restricted-to user"};
memset( &genQueryInp, 0, sizeof( genQueryInp_t ) );
printCount = 0;
i = 0;
i1a[i] = COL_TICKET_ALLOWED_USER_NAME;
i1b[i++] = 0;
genQueryInp.selectInp.inx = i1a;
genQueryInp.selectInp.value = i1b;
genQueryInp.selectInp.len = i;
i2a[0] = COL_TICKET_ALLOWED_USER_TICKET_ID;
snprintf( v1, sizeof( v1 ), "='%s'", inColumn );
condVal[0] = v1;
genQueryInp.sqlCondInp.inx = i2a;
genQueryInp.sqlCondInp.value = condVal;
genQueryInp.sqlCondInp.len = 1;
genQueryInp.maxRows = 10;
genQueryInp.continueInx = 0;
genQueryInp.condInput.len = 0;
status = rcGenQuery( Conn, &genQueryInp, &genQueryOut );
if ( status == CAT_NO_ROWS_FOUND ) {
i1a[0] = COL_USER_COMMENT;
genQueryInp.selectInp.len = 1;
status = rcGenQuery( Conn, &genQueryInp, &genQueryOut );
if ( status == 0 ) {
printf( "No user restrictions (1)\n" );
return;
}
if ( status == CAT_NO_ROWS_FOUND ) {
printf( "No user restrictions\n" );
return;
}
}
printResultsAndSubQuery( Conn, status, genQueryOut, columnNames, -1, 0 );
while ( status == 0 && genQueryOut->continueInx > 0 ) {
genQueryInp.continueInx = genQueryOut->continueInx;
status = rcGenQuery( Conn, &genQueryInp, &genQueryOut );
printResultsAndSubQuery( Conn, status, genQueryOut,
columnNames, 0, 0 );
}
return;
}
void
showRestrictionsByGroup( char *inColumn ) {
genQueryInp_t genQueryInp;
genQueryOut_t *genQueryOut;
int i1a[10];
int i1b[10];
int i2a[10];
int i;
char v1[MAX_NAME_LEN];
char *condVal[10];
int status;
char *columnNames[] = {"restricted-to group"};
memset( &genQueryInp, 0, sizeof( genQueryInp_t ) );
printCount = 0;
i = 0;
i1a[i] = COL_TICKET_ALLOWED_GROUP_NAME;
i1b[i++] = 0;
genQueryInp.selectInp.inx = i1a;
genQueryInp.selectInp.value = i1b;
genQueryInp.selectInp.len = i;
i2a[0] = COL_TICKET_ALLOWED_GROUP_TICKET_ID;
snprintf( v1, sizeof( v1 ), "='%s'", inColumn );
condVal[0] = v1;
genQueryInp.sqlCondInp.inx = i2a;
genQueryInp.sqlCondInp.value = condVal;
genQueryInp.sqlCondInp.len = 1;
genQueryInp.maxRows = 10;
genQueryInp.continueInx = 0;
genQueryInp.condInput.len = 0;
status = rcGenQuery( Conn, &genQueryInp, &genQueryOut );
if ( status == CAT_NO_ROWS_FOUND ) {
i1a[0] = COL_USER_COMMENT;
genQueryInp.selectInp.len = 1;
status = rcGenQuery( Conn, &genQueryInp, &genQueryOut );
if ( status == 0 ) {
printf( "No group restrictions (1)\n" );
return;
}
if ( status == CAT_NO_ROWS_FOUND ) {
printf( "No group restrictions\n" );
return;
}
}
printResultsAndSubQuery( Conn, status, genQueryOut, columnNames, -1, 0 );
while ( status == 0 && genQueryOut->continueInx > 0 ) {
genQueryInp.continueInx = genQueryOut->continueInx;
status = rcGenQuery( Conn, &genQueryInp, &genQueryOut );
printResultsAndSubQuery( Conn, status, genQueryOut,
columnNames, 0, 0 );
}
return;
}
void
showRestrictions( char *inColumn ) {
showRestrictionsByHost( inColumn );
showRestrictionsByUser( inColumn );
showRestrictionsByGroup( inColumn );
return;
}
/*
Via a general query, show the Tickets for this user
*/
int
showTickets1( char *inOption, char *inName ) {
genQueryInp_t genQueryInp;
genQueryOut_t *genQueryOut;
int i1a[20];
int i1b[20];
int i2a[20];
int i;
char v1[MAX_NAME_LEN];
char *condVal[20];
int status;
char *columnNames[] = {"id", "string", "ticket type", "obj type", "owner name", "owner zone", "uses count", "uses limit", "write file count", "write file limit", "write byte count", "write byte limit", "expire time", "collection name", "data collection"};
memset( &genQueryInp, 0, sizeof( genQueryInp_t ) );
printCount = 0;
i = 0;
i1a[i] = COL_TICKET_ID;
i1b[i++] = 0;
i1a[i] = COL_TICKET_STRING;
i1b[i++] = 0;
i1a[i] = COL_TICKET_TYPE;
i1b[i++] = 0;
i1a[i] = COL_TICKET_OBJECT_TYPE;
i1b[i++] = 0;
i1a[i] = COL_TICKET_OWNER_NAME;
i1b[i++] = 0;
i1a[i] = COL_TICKET_OWNER_ZONE;
i1b[i++] = 0;
i1a[i] = COL_TICKET_USES_COUNT;
i1b[i++] = 0;
i1a[i] = COL_TICKET_USES_LIMIT;
i1b[i++] = 0;
i1a[i] = COL_TICKET_WRITE_FILE_COUNT;
i1b[i++] = 0;
i1a[i] = COL_TICKET_WRITE_FILE_LIMIT;
i1b[i++] = 0;
i1a[i] = COL_TICKET_WRITE_BYTE_COUNT;
i1b[i++] = 0;
i1a[i] = COL_TICKET_WRITE_BYTE_LIMIT;
i1b[i++] = 0;
i1a[i] = COL_TICKET_EXPIRY_TS;
i1b[i++] = 0;
i1a[i] = COL_TICKET_COLL_NAME;
i1b[i++] = 0;
if ( strstr( inOption, "data" ) != 0 ) {
i--;
i1a[i] = COL_TICKET_DATA_NAME;
columnNames[i] = "data-object name";
i1b[i++] = 0;
i1a[i] = COL_TICKET_DATA_COLL_NAME;
i1b[i++] = 0;
}
if ( strstr( inOption, "basic" ) != 0 ) {
/* skip the COLL or DATA_NAME so it's just a query on the ticket tables */
i--;
}
genQueryInp.selectInp.inx = i1a;
genQueryInp.selectInp.value = i1b;
genQueryInp.selectInp.len = i;
genQueryInp.condInput.len = 0;
if ( inName != NULL && *inName != '\0' ) {
if ( isInteger( inName ) == 1 ) {
/* Could have an all-integer ticket but in most cases this is a good
guess */
i2a[0] = COL_TICKET_ID;
}
else {
i2a[0] = COL_TICKET_STRING;
}
snprintf( v1, sizeof( v1 ), "='%s'", inName );
condVal[0] = v1;
genQueryInp.sqlCondInp.inx = i2a;
genQueryInp.sqlCondInp.value = condVal;
genQueryInp.sqlCondInp.len = 1;
}
genQueryInp.maxRows = 10;
genQueryInp.continueInx = 0;
if ( zoneArgument[0] != '\0' ) {
addKeyVal( &genQueryInp.condInput, ZONE_KW, zoneArgument );
}
status = rcGenQuery( Conn, &genQueryInp, &genQueryOut );
if ( status == CAT_NO_ROWS_FOUND ) {
i1a[0] = COL_USER_COMMENT;
genQueryInp.selectInp.len = 1;
status = rcGenQuery( Conn, &genQueryInp, &genQueryOut );
if ( status == 0 ) {
return 0;
}
if ( status == CAT_NO_ROWS_FOUND ) {
return 0;
}
}
printResultsAndSubQuery( Conn, status, genQueryOut, columnNames, 0, 1 );
while ( status == 0 && genQueryOut->continueInx > 0 ) {
genQueryInp.continueInx = genQueryOut->continueInx;
status = rcGenQuery( Conn, &genQueryInp, &genQueryOut );
if ( genQueryOut->rowCnt > 0 ) {
printf( "----\n" );
}
printResultsAndSubQuery( Conn, status, genQueryOut,
columnNames, 0, 1 );
}
return 0;
}
void
showTickets( char *inName ) {
printedRows = 0;
showTickets1( "data", inName );
if ( printedRows > 0 ) {
printf( "----\n" );
}
showTickets1( "collection", inName );
if ( printedRows == 0 ) {
/* try a more basic query in case the data obj or collection is gone */
showTickets1( "basic", inName );
if ( printedRows > 0 &&
inName != NULL && *inName != '\0' ) {
printf( "Warning: the data-object or collection for this ticket no longer exists\n" );
}
}
}
std::string
makeFullPath( const char *inName ) {
std::stringstream fullPathStream;
if ( strlen( inName ) == 0 ) {
return std::string();
}
if ( *inName != '/' ) {
fullPathStream << cwd << "/";
}
fullPathStream << inName;
return fullPathStream.str();
}
/*
Create, modify, or delete a ticket
*/
int
doTicketOp( const char *arg1, const char *arg2, const char *arg3,
const char *arg4, const char *arg5 ) {
ticketAdminInp_t ticketAdminInp;
int status;
ticketAdminInp.arg1 = strdup( arg1 );
ticketAdminInp.arg2 = strdup( arg2 );
ticketAdminInp.arg3 = strdup( arg3 );
ticketAdminInp.arg4 = strdup( arg4 );
ticketAdminInp.arg5 = strdup( arg5 );
ticketAdminInp.arg6 = "";
status = rcTicketAdmin( Conn, &ticketAdminInp );
lastCommandStatus = status;
free( ticketAdminInp.arg1 );
free( ticketAdminInp.arg2 );
free( ticketAdminInp.arg3 );
free( ticketAdminInp.arg4 );
free( ticketAdminInp.arg5 );
if ( status < 0 ) {
if ( Conn->rError ) {
rError_t *Err;
rErrMsg_t *ErrMsg;
int i, len;
Err = Conn->rError;
len = Err->len;
for ( i = 0; i < len; i++ ) {
ErrMsg = Err->errMsg[i];
rodsLog( LOG_ERROR, "Level %d: %s", i, ErrMsg->msg );
}
}
char *mySubName = NULL;
const char *myName = rodsErrorName( status, &mySubName );
rodsLog( LOG_ERROR, "rcTicketAdmin failed with error %d %s %s",
status, myName, mySubName );
free( mySubName );
}
return status;
}
void
makeTicket( char *newTicket ) {
const int ticket_len = 15;
// random_bytes must be (unsigned char[]) to guarantee that following
// modulo result is positive (i.e. in [0, 61])
unsigned char random_bytes[ticket_len];
irods::getRandomBytes( random_bytes, ticket_len );
const char characterSet[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G',
'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9'};
for ( int i = 0; i < ticket_len; ++i ) {
const int ix = random_bytes[i] % sizeof(characterSet);
newTicket[i] = characterSet[ix];
}
newTicket[ticket_len] = '\0';
printf( "ticket:%s\n", newTicket );
}
/*
Prompt for input and parse into tokens
*/
void
getInput( char *cmdToken[], int maxTokens ) {
int lenstr, i;
static char ttybuf[BIG_STR];
int nTokens;
int tokenFlag; /* 1: start reg, 2: start ", 3: start ' */
char *cpTokenStart;
char *stat;
memset( ttybuf, 0, BIG_STR );
fputs( "iticket>", stdout );
stat = fgets( ttybuf, BIG_STR, stdin );
if ( stat == 0 ) {
printf( "\n" );
rcDisconnect( Conn );
if ( lastCommandStatus != 0 ) {
exit( 4 );
}
exit( 0 );
}
lenstr = strlen( ttybuf );
for ( i = 0; i < maxTokens; i++ ) {
cmdToken[i] = "";
}
cpTokenStart = ttybuf;
nTokens = 0;
tokenFlag = 0;
for ( i = 0; i < lenstr; i++ ) {
if ( ttybuf[i] == '\n' ) {
ttybuf[i] = '\0';
cmdToken[nTokens++] = cpTokenStart;
return;
}
if ( tokenFlag == 0 ) {
if ( ttybuf[i] == '\'' ) {
tokenFlag = 3;
cpTokenStart++;
}
else if ( ttybuf[i] == '"' ) {
tokenFlag = 2;
cpTokenStart++;
}
else if ( ttybuf[i] == ' ' ) {
cpTokenStart++;
}
else {
tokenFlag = 1;
}
}
else if ( tokenFlag == 1 ) {
if ( ttybuf[i] == ' ' ) {
ttybuf[i] = '\0';
cmdToken[nTokens++] = cpTokenStart;
cpTokenStart = &ttybuf[i + 1];
tokenFlag = 0;
}
}
else if ( tokenFlag == 2 ) {
if ( ttybuf[i] == '"' ) {
ttybuf[i] = '\0';
cmdToken[nTokens++] = cpTokenStart;
cpTokenStart = &ttybuf[i + 1];
tokenFlag = 0;
}
}
else if ( tokenFlag == 3 ) {
if ( ttybuf[i] == '\'' ) {
ttybuf[i] = '\0';
cmdToken[nTokens++] = cpTokenStart;
cpTokenStart = &ttybuf[i + 1];
tokenFlag = 0;
}
}
}
}
/* handle a command,
return code is 0 if the command was (at least partially) valid,
-1 for quitting,
-2 for if invalid
-3 if empty.
*/
int
doCommand( char *cmdToken[] ) {
if ( strcmp( cmdToken[0], "help" ) == 0 ||
strcmp( cmdToken[0], "h" ) == 0 ) {
usage( cmdToken[1] );
return 0;
}
if ( strcmp( cmdToken[0], "quit" ) == 0 ||
strcmp( cmdToken[0], "q" ) == 0 ) {
return -1;
}
if ( strcmp( cmdToken[0], "create" ) == 0
|| strcmp( cmdToken[0], "make" ) == 0
|| strcmp( cmdToken[0], "mk" ) == 0
) {
char myTicket[30];
if ( strlen( cmdToken[3] ) > 0 ) {
snprintf( myTicket, sizeof( myTicket ), "%s", cmdToken[3] );
}
else {
makeTicket( myTicket );
}
std::string fullPath = makeFullPath( cmdToken[2] );
doTicketOp( "create", myTicket, cmdToken[1], fullPath.c_str(),
cmdToken[3] );
return 0;
}
if ( strcmp( cmdToken[0], "delete" ) == 0 ) {
doTicketOp( "delete", cmdToken[1], cmdToken[2],
cmdToken[3], cmdToken[4] );
return 0;
}
if ( strcmp( cmdToken[0], "mod" ) == 0 ) {
doTicketOp( "mod", cmdToken[1], cmdToken[2],
cmdToken[3], cmdToken[4] );
return 0;
}
if ( strcmp( cmdToken[0], "ls" ) == 0 ) {
showTickets( cmdToken[1] );
return 0;
}
if ( strcmp( cmdToken[0], "ls-all" ) == 0 ) {
printf( "Listing all of your tickets, even those for which the target collection\nor data-object no longer exists:\n" );
showTickets1( "basic", "" );
return 0;
}
if ( *cmdToken[0] != '\0' ) {
printf( "unrecognized command, try 'help'\n" );
return -2;
}
return -3;
}
int
main( int argc, char **argv ) {
signal( SIGPIPE, SIG_IGN );
int status, i, j;
rErrMsg_t errMsg;
rodsArguments_t myRodsArgs;
char *mySubName;
int argOffset;
int maxCmdTokens = 20;
char *cmdToken[20];
int keepGoing;
int firstTime;
rodsLogLevel( LOG_ERROR );
status = parseCmdLineOpt( argc, argv, "vVhgrcGRCdulz:", 0, &myRodsArgs );
if ( status ) {
printf( "Use -h for help.\n" );
exit( 1 );
}
if ( myRodsArgs.help == True ) {
usage( "" );
exit( 0 );
}
if ( myRodsArgs.zone == True ) {
strncpy( zoneArgument, myRodsArgs.zoneName, MAX_NAME_LEN );
}
if ( myRodsArgs.longOption ) {
longMode = 1;
}
argOffset = myRodsArgs.optind;
if ( argOffset > 1 ) {
if ( argOffset > 2 ) {
if ( *argv[1] == '-' && *( argv[1] + 1 ) == 'z' ) {
if ( *( argv[1] + 2 ) == '\0' ) {
argOffset = 3; /* skip -z zone */
}
else {
argOffset = 2; /* skip -zzone */
}
}
else {
argOffset = 1; /* Ignore the parseCmdLineOpt parsing
as -d etc handled below*/
}
}
else {
argOffset = 1; /* Ignore the parseCmdLineOpt parsing
as -d etc handled below*/
}
}
status = getRodsEnv( &myEnv );
if ( status < 0 ) {
rodsLog( LOG_ERROR, "main: getRodsEnv error. status = %d",
status );
exit( 1 );
}
strncpy( cwd, myEnv.rodsCwd, BIG_STR );
if ( strlen( cwd ) == 0 ) {
strcpy( cwd, "/" );
}
for ( i = 0; i < maxCmdTokens; i++ ) {
cmdToken[i] = "";
}
j = 0;
for ( i = argOffset; i < argc; i++ ) {
cmdToken[j++] = argv[i];
}
#if defined(linux_platform)
/*
imeta cp -d TestFile1 -d TestFile3
comes in as: -d -d cp TestFile1 TestFile3
so switch it to: cp -d -d TestFile1 TestFile3
*/
if ( cmdToken[0] != NULL && *cmdToken[0] == '-' ) {
/* args were toggled, switch them back */
if ( cmdToken[1] != NULL && *cmdToken[1] == '-' ) {
cmdToken[0] = argv[argOffset + 2];
cmdToken[1] = argv[argOffset];
cmdToken[2] = argv[argOffset + 1];
}
else {
cmdToken[0] = argv[argOffset + 1];
cmdToken[1] = argv[argOffset];
}
}
#else
/* tested on Solaris, not sure other than Linux/Solaris */
/*
imeta cp -d TestFile1 -d TestFile3
comes in as: cp -d TestFile1 -d TestFile3
so switch it to: cp -d -d TestFile1 TestFile3
*/
if ( cmdToken[0] != NULL && cmdToken[1] != NULL && *cmdToken[1] == '-' &&
cmdToken[2] != NULL && cmdToken[3] != NULL && *cmdToken[3] == '-' ) {
/* two args */
cmdToken[2] = argv[argOffset + 3];
cmdToken[3] = argv[argOffset + 2];
}
#endif
if ( strcmp( cmdToken[0], "help" ) == 0 ||
strcmp( cmdToken[0], "h" ) == 0 ) {
usage( cmdToken[1] );
exit( 0 );
}
if ( strcmp( cmdToken[0], "spass" ) == 0 ) {
char scrambled[MAX_PASSWORD_LEN + 100];
if ( strlen( cmdToken[1] ) > MAX_PASSWORD_LEN - 2 ) {
printf( "Password exceeds maximum length\n" );
}
else {
obfEncodeByKey( cmdToken[1], cmdToken[2], scrambled );
printf( "Scrambled form is:%s\n", scrambled );
}
exit( 0 );
}
// =-=-=-=-=-=-=-
// initialize pluggable api table
irods::api_entry_table& api_tbl = irods::get_client_api_table();
irods::pack_entry_table& pk_tbl = irods::get_pack_table();
init_api_table( api_tbl, pk_tbl );
Conn = rcConnect( myEnv.rodsHost, myEnv.rodsPort, myEnv.rodsUserName,
myEnv.rodsZone, 0, &errMsg );
if ( Conn == NULL ) {
const char *myName = rodsErrorName( errMsg.status, &mySubName );
rodsLog( LOG_ERROR, "rcConnect failure %s (%s) (%d) %s",
myName,
mySubName,
errMsg.status,
errMsg.msg );
exit( 2 );
}
status = clientLogin( Conn );
if ( status != 0 ) {
if ( !debug ) {
exit( 3 );
}
}
keepGoing = 1;
firstTime = 1;
while ( keepGoing ) {
int status;
status = doCommand( cmdToken );
if ( status == -1 ) {
keepGoing = 0;
}
if ( firstTime ) {
if ( status == 0 ) {
keepGoing = 0;
}
if ( status == -2 ) {
keepGoing = 0;
lastCommandStatus = -1;
}
firstTime = 0;
}
if ( keepGoing ) {
getInput( cmdToken, maxCmdTokens );
}
}
printErrorStack( Conn->rError );
rcDisconnect( Conn );
if ( lastCommandStatus != 0 ) {
exit( 4 );
}
exit( 0 );
}
/*
Print the main usage/help information.
*/
void usageMain() {
char *msgs[] = {
"Usage: iticket [-h] [command]",
" -h This help",
"Commands are:",
" create read/write Object-Name [string] (create a new ticket)",
" mod Ticket_string-or-id uses/expire string-or-none (modify restrictions)",
" mod Ticket_string-or-id write-bytes-or-file number-or-0 (modify restrictions)",
" mod Ticket_string-or-id add/remove host/user/group string (modify restrictions)",
" ls [Ticket_string-or-id] (non-admins will see just your own)",
" ls-all (list all your tickets, even with missing targets)",
" delete ticket_string-or-id",
" quit",
" ",
"Tickets are another way to provide access to iRODS data-objects (files) or",
"collections (directories or folders). The 'iticket' command allows you",
"to create, modify, list, and delete tickets. When you create a ticket",
"its 15 character string is given to you which you can share with others.",
"This is less secure than normal iRODS login-based access control, but",
"is useful in some situations. See the 'ticket-based access' page on",
"irods.org for more information.",
" ",
"A blank execute line invokes the interactive mode, where iticket",
"prompts and executes commands until 'quit' or 'q' is entered.",
"Like other unix utilities, a series of commands can be piped into it:",
"'cat file1 | iticket' (maintaining one connection for all commands).",
" ",
"Use 'help command' for more help on a specific command.",
""
};
int i;
for ( i = 0;; i++ ) {
if ( strlen( msgs[i] ) == 0 ) {
break;
}
printf( "%s\n", msgs[i] );
}
printReleaseInfo( "iticket" );
}
/*
Print either main usage/help information, or some more specific
information on particular commands.
*/
int
usage( char *subOpt ) {
int i;
if ( *subOpt == '\0' ) {
usageMain();
}
else {
if ( strcmp( subOpt, "create" ) == 0 ) {
char *msgs[] = {
" create read/write Object-Name [string] (create a new ticket)",
"Create a new ticket for Object-Name, which is either a data-object (file)",
"or a collection (directory). ",
"Example: create read myFile",
"The ticket string, which can be used for access, will be displayed.",
"If 'string' is provided on the command line, it is the ticket-string to use",
"as the ticket instead of a randomly generated string of characters.",
""
};
for ( i = 0;; i++ ) {
if ( strlen( msgs[i] ) == 0 ) {
return 0;
}
printf( "%s\n", msgs[i] );
}
}
if ( strcmp( subOpt, "mod" ) == 0 ) {
char *msgs[] = {
" mod Ticket-id uses/expire string-or-none",
"or mod Ticket-id add/remove host/user/group string (modify restrictions)",
"Modify a ticket to use one of the specialized options. By default a",
"ticket can be used by anyone (and 'anonymous'), from any host, and any",
"number of times, and for all time (until deleted). You can modify it to",
"add (or remove) these types of restrictions.",
" ",
" 'mod Ticket-id uses integer-or-0' will make the ticket only valid",
"the specified number of times. Use 0 to remove this restriction.",
" ",
" 'mod Ticket-id write-file integer-or-0' will make the write-ticket only",
"valid for writing the specified number of times. Use 0 to remove this",
"restriction.",
" ",
" 'mod Ticket-id write-byte integer-or-0' will make the write-ticket only",
"valid for writing the specified number of bytes. Use 0 to remove this",
"restriction.",
" ",
" 'mod Ticket-id add/remove user Username' will make the ticket only valid",
"when used by that particular iRODS user. You can use multiple mod commands",
"to add more users to the allowed list.",
" ",
" 'mod Ticket-id add/remove group Groupname' will make the ticket only valid",
"when used by iRODS users in that particular iRODS group. You can use",
"multiple mod commands to add more groups to the allowed list.",
" ",
" 'mod Ticket-id add/remove host Host/IP' will make the ticket only valid",
"when used from that particular host computer. Host (full DNS name) will be",
"converted to the IP address for use in the internal checks or you can enter",
"the IP address itself. 'iticket ls' will display the IP addresses.",
"You can use multiple mod commands to add more hosts to the list.",
" ",
" 'mod Ticket-id expire date.time-or-0' will make the ticket only valid",
"before the specified date-time. You can cancel this expiration by using",
"'0'. The time is year-mo-da.hr:min:sec, for example: 2012-05-07.23:00:00",
" ",
" The Ticket-id is either the ticket object number or the ticket-string",
""
};
for ( i = 0;; i++ ) {
if ( strlen( msgs[i] ) == 0 ) {
return 0;
}
printf( "%s\n", msgs[i] );
}
}
if ( strcmp( subOpt, "delete" ) == 0 ) {
char *msgs[] = {
" delete Ticket-string",
"Remove a ticket from the system. Access will no longer be allowed",
"via the ticket-string.",
""
};
for ( i = 0;; i++ ) {
if ( strlen( msgs[i] ) == 0 ) {
return 0;
}
printf( "%s\n", msgs[i] );
}
}
if ( strcmp( subOpt, "ls" ) == 0 ) {
char *msgs[] = {
" ls [Ticket_string-or-id]",
"List the tickets owned by you or, for admin users, all tickets.",
"Include a ticket-string or the ticket-id (object number) to list only one",
"(in this case, a numeric string is assumed to be an id).",
""
};
for ( i = 0;; i++ ) {
if ( strlen( msgs[i] ) == 0 ) {
return 0;
}
printf( "%s\n", msgs[i] );
}
}
if ( strcmp( subOpt, "ls-all" ) == 0 ) {
char *msgs[] = {
" ls-all",
"Similar to 'ls' (with no ticket string-or-id) but will list all of your",
"tickets even if the target collection or data-object no longer exists.",
""
};
for ( i = 0;; i++ ) {
if ( strlen( msgs[i] ) == 0 ) {
return 0;
}
printf( "%s\n", msgs[i] );
}
}
if ( strcmp( subOpt, "quit" ) == 0 ) {
char *msgs[] = {
" Exits the interactive mode",
""
};
for ( i = 0;; i++ ) {
if ( strlen( msgs[i] ) == 0 ) {
return 0;
}
printf( "%s\n", msgs[i] );
}
}
printf( "Sorry, either %s is an invalid command or the help has not been written yet\n",
subOpt );
}
return 0;
}
| 31,899 | 11,036 |
/*
******************************************************************************
* Copyright (C) 2015, International Business Machines Corporation and
* others. All Rights Reserved.
******************************************************************************
*
* File UNIFIEDCACHE.CPP
******************************************************************************
*/
#include "uhash.h"
#include "unifiedcache.h"
#include "umutex.h"
#include "mutex.h"
#include "uassert.h"
#include "ucln_cmn.h"
static icu::UnifiedCache *gCache = NULL;
static icu::SharedObject *gNoValue = NULL;
static UMutex gCacheMutex = U_MUTEX_INITIALIZER;
static UConditionVar gInProgressValueAddedCond = U_CONDITION_INITIALIZER;
static icu::UInitOnce gCacheInitOnce = U_INITONCE_INITIALIZER;
static const int32_t MAX_EVICT_ITERATIONS = 10;
static int32_t DEFAULT_MAX_UNUSED = 1000;
static int32_t DEFAULT_PERCENTAGE_OF_IN_USE = 100;
U_CDECL_BEGIN
static UBool U_CALLCONV unifiedcache_cleanup() {
gCacheInitOnce.reset();
if (gCache) {
delete gCache;
gCache = NULL;
}
if (gNoValue) {
delete gNoValue;
gNoValue = NULL;
}
return TRUE;
}
U_CDECL_END
U_NAMESPACE_BEGIN
U_CAPI int32_t U_EXPORT2
ucache_hashKeys(const UHashTok key) {
const CacheKeyBase *ckey = (const CacheKeyBase *) key.pointer;
return ckey->hashCode();
}
U_CAPI UBool U_EXPORT2
ucache_compareKeys(const UHashTok key1, const UHashTok key2) {
const CacheKeyBase *p1 = (const CacheKeyBase *) key1.pointer;
const CacheKeyBase *p2 = (const CacheKeyBase *) key2.pointer;
return *p1 == *p2;
}
U_CAPI void U_EXPORT2
ucache_deleteKey(void *obj) {
CacheKeyBase *p = (CacheKeyBase *) obj;
delete p;
}
CacheKeyBase::~CacheKeyBase() {
}
static void U_CALLCONV cacheInit(UErrorCode &status) {
U_ASSERT(gCache == NULL);
ucln_common_registerCleanup(
UCLN_COMMON_UNIFIED_CACHE, unifiedcache_cleanup);
// gNoValue must be created first to avoid assertion error in
// cache constructor.
gNoValue = new SharedObject();
gCache = new UnifiedCache(status);
if (gCache == NULL) {
status = U_MEMORY_ALLOCATION_ERROR;
}
if (U_FAILURE(status)) {
delete gCache;
delete gNoValue;
gCache = NULL;
gNoValue = NULL;
return;
}
// We add a softref because we want hash elements with gNoValue to be
// elligible for purging but we don't ever want gNoValue to be deleted.
gNoValue->addSoftRef();
}
UnifiedCache *UnifiedCache::getInstance(UErrorCode &status) {
umtx_initOnce(gCacheInitOnce, &cacheInit, status);
if (U_FAILURE(status)) {
return NULL;
}
U_ASSERT(gCache != NULL);
return gCache;
}
UnifiedCache::UnifiedCache(UErrorCode &status) :
fHashtable(NULL),
fEvictPos(UHASH_FIRST),
fItemsInUseCount(0),
fMaxUnused(DEFAULT_MAX_UNUSED),
fMaxPercentageOfInUse(DEFAULT_PERCENTAGE_OF_IN_USE),
fAutoEvictedCount(0) {
if (U_FAILURE(status)) {
return;
}
U_ASSERT(gNoValue != NULL);
fHashtable = uhash_open(
&ucache_hashKeys,
&ucache_compareKeys,
NULL,
&status);
if (U_FAILURE(status)) {
return;
}
uhash_setKeyDeleter(fHashtable, &ucache_deleteKey);
}
void UnifiedCache::setEvictionPolicy(
int32_t count, int32_t percentageOfInUseItems, UErrorCode &status) {
if (U_FAILURE(status)) {
return;
}
if (count < 0 || percentageOfInUseItems < 0) {
status = U_ILLEGAL_ARGUMENT_ERROR;
return;
}
Mutex lock(&gCacheMutex);
fMaxUnused = count;
fMaxPercentageOfInUse = percentageOfInUseItems;
}
int32_t UnifiedCache::unusedCount() const {
Mutex lock(&gCacheMutex);
return uhash_count(fHashtable) - fItemsInUseCount;
}
int64_t UnifiedCache::autoEvictedCount() const {
Mutex lock(&gCacheMutex);
return fAutoEvictedCount;
}
int32_t UnifiedCache::keyCount() const {
Mutex lock(&gCacheMutex);
return uhash_count(fHashtable);
}
void UnifiedCache::flush() const {
Mutex lock(&gCacheMutex);
// Use a loop in case cache items that are flushed held hard references to
// other cache items making those additional cache items eligible for
// flushing.
while (_flush(FALSE));
}
#ifdef UNIFIED_CACHE_DEBUG
#include <stdio.h>
void UnifiedCache::dump() {
UErrorCode status = U_ZERO_ERROR;
const UnifiedCache *cache = getInstance(status);
if (U_FAILURE(status)) {
fprintf(stderr, "Unified Cache: Error fetching cache.\n");
return;
}
cache->dumpContents();
}
void UnifiedCache::dumpContents() const {
Mutex lock(&gCacheMutex);
_dumpContents();
}
// Dumps content of cache.
// On entry, gCacheMutex must be held.
// On exit, cache contents dumped to stderr.
void UnifiedCache::_dumpContents() const {
int32_t pos = UHASH_FIRST;
const UHashElement *element = uhash_nextElement(fHashtable, &pos);
char buffer[256];
int32_t cnt = 0;
for (; element != NULL; element = uhash_nextElement(fHashtable, &pos)) {
const SharedObject *sharedObject =
(const SharedObject *) element->value.pointer;
const CacheKeyBase *key =
(const CacheKeyBase *) element->key.pointer;
if (sharedObject->hasHardReferences()) {
++cnt;
fprintf(
stderr,
"Unified Cache: Key '%s', error %d, value %p, total refcount %d, soft refcount %d\n",
key->writeDescription(buffer, 256),
key->creationStatus,
sharedObject == gNoValue ? NULL :sharedObject,
sharedObject->getRefCount(),
sharedObject->getSoftRefCount());
}
}
fprintf(stderr, "Unified Cache: %d out of a total of %d still have hard references\n", cnt, uhash_count(fHashtable));
}
#endif
UnifiedCache::~UnifiedCache() {
// Try our best to clean up first.
flush();
{
// Now all that should be left in the cache are entries that refer to
// each other and entries with hard references from outside the cache.
// Nothing we can do about these so proceed to wipe out the cache.
Mutex lock(&gCacheMutex);
_flush(TRUE);
}
uhash_close(fHashtable);
}
// Returns the next element in the cache round robin style.
// On entry, gCacheMutex must be held.
const UHashElement *
UnifiedCache::_nextElement() const {
const UHashElement *element = uhash_nextElement(fHashtable, &fEvictPos);
if (element == NULL) {
fEvictPos = UHASH_FIRST;
return uhash_nextElement(fHashtable, &fEvictPos);
}
return element;
}
// Flushes the contents of the cache. If cache values hold references to other
// cache values then _flush should be called in a loop until it returns FALSE.
// On entry, gCacheMutex must be held.
// On exit, those values with are evictable are flushed. If all is true
// then every value is flushed even if it is not evictable.
// Returns TRUE if any value in cache was flushed or FALSE otherwise.
UBool UnifiedCache::_flush(UBool all) const {
UBool result = FALSE;
int32_t origSize = uhash_count(fHashtable);
for (int32_t i = 0; i < origSize; ++i) {
const UHashElement *element = _nextElement();
if (all || _isEvictable(element)) {
const SharedObject *sharedObject =
(const SharedObject *) element->value.pointer;
uhash_removeElement(fHashtable, element);
sharedObject->removeSoftRef();
result = TRUE;
}
}
return result;
}
// Computes how many items should be evicted.
// On entry, gCacheMutex must be held.
// Returns number of items that should be evicted or a value <= 0 if no
// items need to be evicted.
int32_t UnifiedCache::_computeCountOfItemsToEvict() const {
int32_t maxPercentageOfInUseCount =
fItemsInUseCount * fMaxPercentageOfInUse / 100;
int32_t maxUnusedCount = fMaxUnused;
if (maxUnusedCount < maxPercentageOfInUseCount) {
maxUnusedCount = maxPercentageOfInUseCount;
}
return uhash_count(fHashtable) - fItemsInUseCount - maxUnusedCount;
}
// Run an eviction slice.
// On entry, gCacheMutex must be held.
// _runEvictionSlice runs a slice of the evict pipeline by examining the next
// 10 entries in the cache round robin style evicting them if they are eligible.
void UnifiedCache::_runEvictionSlice() const {
int32_t maxItemsToEvict = _computeCountOfItemsToEvict();
if (maxItemsToEvict <= 0) {
return;
}
for (int32_t i = 0; i < MAX_EVICT_ITERATIONS; ++i) {
const UHashElement *element = _nextElement();
if (_isEvictable(element)) {
const SharedObject *sharedObject =
(const SharedObject *) element->value.pointer;
uhash_removeElement(fHashtable, element);
sharedObject->removeSoftRef();
++fAutoEvictedCount;
if (--maxItemsToEvict == 0) {
break;
}
}
}
}
// Places a new value and creationStatus in the cache for the given key.
// On entry, gCacheMutex must be held. key must not exist in the cache.
// On exit, value and creation status placed under key. Soft reference added
// to value on successful add. On error sets status.
void UnifiedCache::_putNew(
const CacheKeyBase &key,
const SharedObject *value,
const UErrorCode creationStatus,
UErrorCode &status) const {
if (U_FAILURE(status)) {
return;
}
CacheKeyBase *keyToAdopt = key.clone();
if (keyToAdopt == NULL) {
status = U_MEMORY_ALLOCATION_ERROR;
return;
}
keyToAdopt->fCreationStatus = creationStatus;
if (value->noSoftReferences()) {
_registerMaster(keyToAdopt, value);
}
uhash_put(fHashtable, keyToAdopt, (void *) value, &status);
if (U_SUCCESS(status)) {
value->addSoftRef();
}
}
// Places value and status at key if there is no value at key or if cache
// entry for key is in progress. Otherwise, it leaves the current value and
// status there.
// On entry. gCacheMutex must not be held. value must be
// included in the reference count of the object to which it points.
// On exit, value and status are changed to what was already in the cache if
// something was there and not in progress. Otherwise, value and status are left
// unchanged in which case they are placed in the cache on a best-effort basis.
// Caller must call removeRef() on value.
void UnifiedCache::_putIfAbsentAndGet(
const CacheKeyBase &key,
const SharedObject *&value,
UErrorCode &status) const {
Mutex lock(&gCacheMutex);
const UHashElement *element = uhash_find(fHashtable, &key);
if (element != NULL && !_inProgress(element)) {
_fetch(element, value, status);
return;
}
if (element == NULL) {
UErrorCode putError = U_ZERO_ERROR;
// best-effort basis only.
_putNew(key, value, status, putError);
} else {
_put(element, value, status);
}
// Run an eviction slice. This will run even if we added a master entry
// which doesn't increase the unused count, but that is still o.k
_runEvictionSlice();
}
// Attempts to fetch value and status for key from cache.
// On entry, gCacheMutex must not be held value must be NULL and status must
// be U_ZERO_ERROR.
// On exit, either returns FALSE (In this
// case caller should try to create the object) or returns TRUE with value
// pointing to the fetched value and status set to fetched status. When
// FALSE is returned status may be set to failure if an in progress hash
// entry could not be made but value will remain unchanged. When TRUE is
// returned, caler must call removeRef() on value.
UBool UnifiedCache::_poll(
const CacheKeyBase &key,
const SharedObject *&value,
UErrorCode &status) const {
U_ASSERT(value == NULL);
U_ASSERT(status == U_ZERO_ERROR);
Mutex lock(&gCacheMutex);
const UHashElement *element = uhash_find(fHashtable, &key);
while (element != NULL && _inProgress(element)) {
umtx_condWait(&gInProgressValueAddedCond, &gCacheMutex);
element = uhash_find(fHashtable, &key);
}
if (element != NULL) {
_fetch(element, value, status);
return TRUE;
}
_putNew(key, gNoValue, U_ZERO_ERROR, status);
return FALSE;
}
// Gets value out of cache.
// On entry. gCacheMutex must not be held. value must be NULL. status
// must be U_ZERO_ERROR.
// On exit. value and status set to what is in cache at key or on cache
// miss the key's createObject() is called and value and status are set to
// the result of that. In this latter case, best effort is made to add the
// value and status to the cache. If createObject() fails to create a value,
// gNoValue is stored in cache, and value is set to NULL. Caller must call
// removeRef on value if non NULL.
void UnifiedCache::_get(
const CacheKeyBase &key,
const SharedObject *&value,
const void *creationContext,
UErrorCode &status) const {
U_ASSERT(value == NULL);
U_ASSERT(status == U_ZERO_ERROR);
if (_poll(key, value, status)) {
if (value == gNoValue) {
SharedObject::clearPtr(value);
}
return;
}
if (U_FAILURE(status)) {
return;
}
value = key.createObject(creationContext, status);
U_ASSERT(value == NULL || value->hasHardReferences());
U_ASSERT(value != NULL || status != U_ZERO_ERROR);
if (value == NULL) {
SharedObject::copyPtr(gNoValue, value);
}
_putIfAbsentAndGet(key, value, status);
if (value == gNoValue) {
SharedObject::clearPtr(value);
}
}
void UnifiedCache::decrementItemsInUseWithLockingAndEviction() const {
Mutex mutex(&gCacheMutex);
decrementItemsInUse();
_runEvictionSlice();
}
void UnifiedCache::incrementItemsInUse() const {
++fItemsInUseCount;
}
void UnifiedCache::decrementItemsInUse() const {
--fItemsInUseCount;
}
// Register a master cache entry.
// On entry, gCacheMutex must be held.
// On exit, items in use count incremented, entry is marked as a master
// entry, and value registered with cache so that subsequent calls to
// addRef() and removeRef() on it correctly updates items in use count
void UnifiedCache::_registerMaster(
const CacheKeyBase *theKey, const SharedObject *value) const {
theKey->fIsMaster = TRUE;
++fItemsInUseCount;
value->registerWithCache(this);
}
// Store a value and error in given hash entry.
// On entry, gCacheMutex must be held. Hash entry element must be in progress.
// value must be non NULL.
// On Exit, soft reference added to value. value and status stored in hash
// entry. Soft reference removed from previous stored value. Waiting
// threads notified.
void UnifiedCache::_put(
const UHashElement *element,
const SharedObject *value,
const UErrorCode status) const {
U_ASSERT(_inProgress(element));
const CacheKeyBase *theKey = (const CacheKeyBase *) element->key.pointer;
const SharedObject *oldValue = (const SharedObject *) element->value.pointer;
theKey->fCreationStatus = status;
if (value->noSoftReferences()) {
_registerMaster(theKey, value);
}
value->addSoftRef();
UHashElement *ptr = const_cast<UHashElement *>(element);
ptr->value.pointer = (void *) value;
oldValue->removeSoftRef();
// Tell waiting threads that we replace in-progress status with
// an error.
umtx_condBroadcast(&gInProgressValueAddedCond);
}
void
UnifiedCache::copyPtr(const SharedObject *src, const SharedObject *&dest) {
if(src != dest) {
if(dest != NULL) {
dest->removeRefWhileHoldingCacheLock();
}
dest = src;
if(src != NULL) {
src->addRefWhileHoldingCacheLock();
}
}
}
void
UnifiedCache::clearPtr(const SharedObject *&ptr) {
if (ptr != NULL) {
ptr->removeRefWhileHoldingCacheLock();
ptr = NULL;
}
}
// Fetch value and error code from a particular hash entry.
// On entry, gCacheMutex must be held. value must be either NULL or must be
// included in the ref count of the object to which it points.
// On exit, value and status set to what is in the hash entry. Caller must
// eventually call removeRef on value.
// If hash entry is in progress, value will be set to gNoValue and status will
// be set to U_ZERO_ERROR.
void UnifiedCache::_fetch(
const UHashElement *element,
const SharedObject *&value,
UErrorCode &status) {
const CacheKeyBase *theKey = (const CacheKeyBase *) element->key.pointer;
status = theKey->fCreationStatus;
// Since we have the cache lock, calling regular SharedObject methods
// could cause us to deadlock on ourselves since they may need to lock
// the cache mutex.
UnifiedCache::copyPtr((const SharedObject *) element->value.pointer, value);
}
// Determine if given hash entry is in progress.
// On entry, gCacheMutex must be held.
UBool UnifiedCache::_inProgress(const UHashElement *element) {
const SharedObject *value = NULL;
UErrorCode status = U_ZERO_ERROR;
_fetch(element, value, status);
UBool result = _inProgress(value, status);
// Since we have the cache lock, calling regular SharedObject methods
// could cause us to deadlock on ourselves since they may need to lock
// the cache mutex.
UnifiedCache::clearPtr(value);
return result;
}
// Determine if given hash entry is in progress.
// On entry, gCacheMutex must be held.
UBool UnifiedCache::_inProgress(
const SharedObject *theValue, UErrorCode creationStatus) {
return (theValue == gNoValue && creationStatus == U_ZERO_ERROR);
}
// Determine if given hash entry is eligible for eviction.
// On entry, gCacheMutex must be held.
UBool UnifiedCache::_isEvictable(const UHashElement *element) {
const CacheKeyBase *theKey = (const CacheKeyBase *) element->key.pointer;
const SharedObject *theValue =
(const SharedObject *) element->value.pointer;
// Entries that are under construction are never evictable
if (_inProgress(theValue, theKey->fCreationStatus)) {
return FALSE;
}
// We can evict entries that are either not a master or have just
// one reference (The one reference being from the cache itself).
return (!theKey->fIsMaster || (theValue->getSoftRefCount() == 1 && theValue->noHardReferences()));
}
U_NAMESPACE_END
| 18,666 | 5,830 |
//=========================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
//
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//=========================================================================
#include "smtk/plugin/Registry.h"
#include "smtk/common/testing/cxx/helpers.h"
#include <set>
namespace
{
class Manager_1
{
public:
std::set<std::string> managed;
};
class Manager_2
{
public:
std::set<std::string> managed;
};
class Manager_3
{
public:
std::set<std::string> managed;
};
class Registrar_1
{
public:
static constexpr const char* const type_name = "Registrar 1";
bool registerTo(const std::shared_ptr<Manager_1>& /*m*/) const;
bool unregisterFrom(const std::shared_ptr<Manager_1>& /*m*/) const;
bool registerTo(const std::shared_ptr<Manager_2>& /*m*/) const;
void unregisterFrom(const std::shared_ptr<Manager_2>& /*m*/) const;
void registerTo(const std::shared_ptr<Manager_3>& /*m*/) const;
void unregisterFrom(const std::shared_ptr<Manager_3>& /*m*/) const;
};
bool Registrar_1::registerTo(const std::shared_ptr<Manager_1>& m) const
{
auto inserted = m->managed.insert(type_name);
test(inserted.second, "Double registering a registrar with a manager");
return true;
}
bool Registrar_1::unregisterFrom(const std::shared_ptr<Manager_1>& m) const
{
auto it = m->managed.find(type_name);
test(it != m->managed.end(), "unregistering an unkown registrar from a manager");
m->managed.erase(it);
return true;
}
bool Registrar_1::registerTo(const std::shared_ptr<Manager_2>& m) const
{
auto inserted = m->managed.insert(type_name);
test(inserted.second, "Double registering a registrar with a manager");
return true;
}
void Registrar_1::unregisterFrom(const std::shared_ptr<Manager_2>& m) const
{
auto it = m->managed.find(type_name);
test(it != m->managed.end(), "unregistering an unkown registrar from a manager");
m->managed.erase(it);
}
void Registrar_1::registerTo(const std::shared_ptr<Manager_3>& m) const
{
auto inserted = m->managed.insert(type_name);
test(inserted.second, "Double registering a registrar with a manager");
}
void Registrar_1::unregisterFrom(const std::shared_ptr<Manager_3>& m) const
{
auto it = m->managed.find(type_name);
test(it != m->managed.end(), "unregistering an unkown registrar from a manager");
m->managed.erase(it);
}
class Registrar_2
{
public:
static constexpr const char* const type_name = "Registrar 2";
static int registerTo(const std::shared_ptr<Manager_1>& /*m*/);
static bool unregisterFrom(const std::shared_ptr<Manager_1>& /*m*/);
static bool registerTo(const std::shared_ptr<Manager_2>& /*m*/);
static void unregisterFrom(const std::shared_ptr<Manager_2>& /*m*/);
};
int Registrar_2::registerTo(const std::shared_ptr<Manager_1>& m)
{
auto inserted = m->managed.insert(type_name);
test(inserted.second, "Double registering a registrar with a manager");
return 4;
}
bool Registrar_2::unregisterFrom(const std::shared_ptr<Manager_1>& m)
{
auto it = m->managed.find(type_name);
test(it != m->managed.end(), "unregistering an unkown registrar from a manager");
m->managed.erase(it);
return true;
}
bool Registrar_2::registerTo(const std::shared_ptr<Manager_2>& m)
{
auto inserted = m->managed.insert(type_name);
test(inserted.second, "Double registering a registrar with a manager");
return true;
}
void Registrar_2::unregisterFrom(const std::shared_ptr<Manager_2>& m)
{
auto it = m->managed.find(type_name);
test(it != m->managed.end(), "unregistering an unkown registrar from a manager");
m->managed.erase(it);
}
} // namespace
int UnitTestRegistry(int /*unused*/, char** const /*unused*/)
{
auto manager_1 = std::make_shared<Manager_1>();
auto manager_2 = std::make_shared<Manager_2>();
auto manager_3 = std::make_shared<Manager_3>();
test(
manager_1->managed.empty() && manager_2->managed.empty() && manager_3->managed.empty(),
"New managers should not be managing anything");
{
smtk::plugin::Registry<Registrar_1, Manager_1, Manager_2, Manager_3> registry_1(
manager_1, manager_2, manager_3);
test(
manager_1->managed.size() == 1 && manager_2->managed.size() == 1 &&
manager_3->managed.size() == 1,
"Managers should be managing one thing");
}
test(
manager_1->managed.empty() && manager_2->managed.empty() && manager_3->managed.empty(),
"Cleared managers should not be managing anything");
smtk::plugin::Registry<Registrar_1, Manager_1, Manager_2, Manager_3> registry_2(
manager_1, manager_2, manager_3);
test(
manager_1->managed.size() == 1 && manager_2->managed.size() == 1 &&
manager_3->managed.size() == 1,
"Managers should be managing one thing again");
auto manager_22 = std::make_shared<Manager_2>();
auto manager_33 = std::make_shared<Manager_3>();
{
smtk::plugin::Registry<Registrar_2, Manager_1, Manager_2, Manager_3> registry_3(
manager_1, manager_22, manager_33);
test(manager_1->managed.size() == 2, "Manager_1 should be managing two things");
test(manager_2->managed.size() == 1, "Manager_2 should be managing one thing");
test(manager_22->managed.size() == 1, "Manager_22 should be managing one thing");
test(manager_3->managed.size() == 1, "Manager_3 should be managing one thing");
test(manager_33->managed.empty(), "Manager_3 should not be managing anything");
}
return 0;
}
| 5,642 | 1,924 |
/*
* This file is part of ACADO Toolkit.
*
* ACADO Toolkit -- A Toolkit for Automatic Control and Dynamic Optimization.
* Copyright (C) 2008-2014 by Boris Houska, Hans Joachim Ferreau,
* Milan Vukov, Rien Quirynen, KU Leuven.
* Developed within the Optimization in Engineering Center (OPTEC)
* under supervision of Moritz Diehl. All rights reserved.
*
* ACADO Toolkit 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 3 of the License, or (at your option) any later version.
*
* ACADO Toolkit 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 ACADO Toolkit; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file include/acado/estimator/estimator.hpp
* \author Hans Joachim Ferreau, Boris Houska
*/
#ifndef ACADO_TOOLKIT_ESTIMATOR_HPP
#define ACADO_TOOLKIT_ESTIMATOR_HPP
#include <acado/utils/acado_utils.hpp>
#include <acado/simulation_environment/simulation_block.hpp>
#include <acado/function/function.hpp>
BEGIN_NAMESPACE_ACADO
/**
* \brief Base class for interfacing online state/parameter estimators.
*
* \ingroup UserInterfaces
*
* The class Estimator serves as a base class for interfacing online
* state/parameter estimators.
*
* \author Hans Joachim Ferreau, Boris Houska
*/
class Estimator : public SimulationBlock
{
//
// PUBLIC MEMBER FUNCTIONS:
//
public:
/** Default constructor. */
Estimator( );
/** Constructor taking minimal sub-block configuration. */
Estimator( double _samplingTime
);
/** Copy constructor (deep copy). */
Estimator( const Estimator& rhs );
/** Destructor. */
virtual ~Estimator( );
/** Assignment operator (deep copy). */
Estimator& operator=( const Estimator& rhs );
virtual Estimator* clone( ) const = 0;
/** Initialization. */
virtual returnValue init( double startTime = 0.0,
const DVector &x0_ = emptyConstVector,
const DVector &p_ = emptyConstVector
);
/** Executes next single step. */
virtual returnValue step( double currentTime,
const DVector& _y
) = 0;
/** Returns all estimator outputs. */
inline returnValue getOutputs( DVector& _x, /**< Estimated differential states. */
DVector& _xa, /**< Estimated algebraic states. */
DVector& _u, /**< Estimated previous controls. */
DVector& _p, /**< Estimated parameters. */
DVector& _w /**< Estimated disturbances. */
) const;
/** Returns estimated differential states. */
inline returnValue getX( DVector& _x /**< OUTPUT: estimated differential states. */
) const;
/** Returns estimated algebraic states. */
inline returnValue getXA( DVector& _xa /**< OUTPUT: estimated algebraic states. */
) const;
/** Returns estimated previous controls. */
inline returnValue getU( DVector& _u /**< OUTPUT: estimated previous controls. */
) const;
/** Returns estimated parameters. */
inline returnValue getP( DVector& _p /**< OUTPUT: estimated parameters. */
) const;
/** Returns estimated disturbances. */
inline returnValue getW( DVector& _w /**< OUTPUT: estimated disturbances. */
) const;
/** Returns number of estimated differential states.
* \return Number of estimated differential states */
inline uint getNX( ) const;
/** Returns number of estimated algebraic states.
* \return Number of estimated algebraic states */
inline uint getNXA( ) const;
/** Returns number of estimated previous controls.
* \return Number of estimated previous controls */
inline uint getNU( ) const;
/** Returns number of estimated parameters.
* \return Number of estimated parameters */
inline uint getNP( ) const;
/** Returns number of estimated disturbances.
* \return Number of estimated disturbances */
inline uint getNW( ) const;
/** Returns number of process outputs.
* \return Number of process outputs */
inline uint getNY( ) const;
//
// PROTECTED MEMBER FUNCTIONS:
//
protected:
//
// DATA MEMBERS:
//
protected:
DVector x; /**< Estimated differential state. */
DVector xa; /**< Estimated algebraic state. */
DVector u; /**< Estimated previous controls. */
DVector p; /**< Estimated parameters. */
DVector w; /**< Estimated disturbances. */
};
CLOSE_NAMESPACE_ACADO
#include <acado/estimator/estimator.ipp>
#endif // ACADO_TOOLKIT_ESTIMATOR_HPP
/*
* end of file
*/
| 5,111 | 1,754 |
/*===========================================================================*\
* *
* OpenMesh *
* Copyright (C) 2001-2012 by Computer Graphics Group, RWTH Aachen *
* www.openmesh.org *
* *
*---------------------------------------------------------------------------*
* This file is part of OpenMesh. *
* *
* OpenMesh 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 3 of *
* the License, or (at your option) any later version with the *
* following exceptions: *
* *
* If other files instantiate templates or use macros *
* or inline functions from this file, or you compile this file and *
* link it with other files to produce an executable, this file does *
* not by itself cause the resulting executable to be covered by the *
* GNU Lesser General Public License. This exception does not however *
* invalidate any other reasons why the executable file might be *
* covered by the GNU Lesser General Public License. *
* *
* OpenMesh 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 LesserGeneral Public *
* License along with OpenMesh. If not, *
* see <http://www.gnu.org/licenses/>. *
* *
\*===========================================================================*/
/*===========================================================================*\
* *
* $Revision: 808 $ *
* $Date: 2013-02-20 13:25:03 +0100 (Wed, 20 Feb 2013) $ *
* *
\*===========================================================================*/
/** \file SmootherT.cc
*/
//=============================================================================
//
// CLASS SmootherT - IMPLEMENTATION
//
//=============================================================================
#define OPENMESH_SMOOTHERT_C
//== INCLUDES =================================================================
#include <OpenMesh/Core/Utils/vector_cast.hh>
#include <OpenMesh/Tools/Smoother/SmootherT.hh>
//== NAMESPACES ===============================================================
namespace OpenMesh {
namespace Smoother {
//== IMPLEMENTATION ==========================================================
template <class Mesh>
SmootherT<Mesh>::
SmootherT(Mesh& _mesh)
: mesh_(_mesh),
skip_features_(false)
{
// request properties
mesh_.request_vertex_status();
mesh_.request_face_normals();
mesh_.request_vertex_normals();
// custom properties
mesh_.add_property(original_positions_);
mesh_.add_property(original_normals_);
mesh_.add_property(new_positions_);
mesh_.add_property(is_active_);
// default settings
component_ = Tangential_and_Normal;
continuity_ = C0;
tolerance_ = -1.0;
}
//-----------------------------------------------------------------------------
template <class Mesh>
SmootherT<Mesh>::
~SmootherT()
{
// free properties
mesh_.release_vertex_status();
mesh_.release_face_normals();
mesh_.release_vertex_normals();
// free custom properties
mesh_.remove_property(original_positions_);
mesh_.remove_property(original_normals_);
mesh_.remove_property(new_positions_);
mesh_.remove_property(is_active_);
}
//-----------------------------------------------------------------------------
template <class Mesh>
void
SmootherT<Mesh>::
initialize(Component _comp, Continuity _cont)
{
typename Mesh::VertexIter v_it, v_end(mesh_.vertices_end());
// store smoothing settings
component_ = _comp;
continuity_ = _cont;
// update normals
mesh_.update_face_normals();
mesh_.update_vertex_normals();
// store original points & normals
for (v_it=mesh_.vertices_begin(); v_it!=v_end; ++v_it)
{
mesh_.property(original_positions_, v_it) = mesh_.point(v_it);
mesh_.property(original_normals_, v_it) = mesh_.normal(v_it);
}
}
//-----------------------------------------------------------------------------
template <class Mesh>
void
SmootherT<Mesh>::
set_active_vertices()
{
typename Mesh::VertexIter v_it, v_end(mesh_.vertices_end());
// is something selected?
bool nothing_selected(true);
for (v_it=mesh_.vertices_begin(); v_it!=v_end; ++v_it)
if (mesh_.status(v_it).selected())
{ nothing_selected = false; break; }
// tagg all active vertices
bool active;
for (v_it=mesh_.vertices_begin(); v_it!=v_end; ++v_it)
{
active = ((nothing_selected || mesh_.status(v_it).selected())
&& !mesh_.is_boundary(v_it)
&& !mesh_.status(v_it).locked());
if ( skip_features_ ) {
active = active && !mesh_.status(v_it).feature();
typename Mesh::VertexOHalfedgeIter voh_it(mesh_,v_it);
for ( ; voh_it ; ++voh_it ) {
// If the edge is a feature edge, skip the current vertex while smoothing
if ( mesh_.status(mesh_.edge_handle(voh_it.handle())).feature() )
active = false;
typename Mesh::FaceHandle fh1 = mesh_.face_handle(voh_it.handle() );
typename Mesh::FaceHandle fh2 = mesh_.face_handle(mesh_.opposite_halfedge_handle(voh_it.handle() ) );
// If one of the faces is a feature, lock current vertex
if ( fh1.is_valid() && mesh_.status( fh1 ).feature() )
active = false;
if ( fh2.is_valid() && mesh_.status( fh2 ).feature() )
active = false;
}
}
mesh_.property(is_active_, v_it) = active;
}
// C1: remove one ring of boundary vertices
if (continuity_ == C1)
{
typename Mesh::VVIter vv_it;
for (v_it=mesh_.vertices_begin(); v_it!=v_end; ++v_it)
if (mesh_.is_boundary(v_it))
for (vv_it=mesh_.vv_iter(v_it); vv_it; ++vv_it)
mesh_.property(is_active_, vv_it) = false;
}
// C2: remove two rings of boundary vertices
if (continuity_ == C2)
{
typename Mesh::VVIter vv_it;
for (v_it=mesh_.vertices_begin(); v_it!=v_end; ++v_it)
{
mesh_.status(v_it).set_tagged(false);
mesh_.status(v_it).set_tagged2(false);
}
for (v_it=mesh_.vertices_begin(); v_it!=v_end; ++v_it)
if (mesh_.is_boundary(v_it))
for (vv_it=mesh_.vv_iter(v_it); vv_it; ++vv_it)
mesh_.status(v_it).set_tagged(true);
for (v_it=mesh_.vertices_begin(); v_it!=v_end; ++v_it)
if (mesh_.status(v_it).tagged())
for (vv_it=mesh_.vv_iter(v_it); vv_it; ++vv_it)
mesh_.status(v_it).set_tagged2(true);
for (v_it=mesh_.vertices_begin(); v_it!=v_end; ++v_it)
{
if (mesh_.status(v_it).tagged2())
mesh_.property(is_active_, vv_it) = false;
mesh_.status(v_it).set_tagged(false);
mesh_.status(v_it).set_tagged2(false);
}
}
}
//-----------------------------------------------------------------------------
template <class Mesh>
void
SmootherT<Mesh>::
set_relative_local_error(Scalar _err)
{
if (!mesh_.vertices_empty())
{
typename Mesh::VertexIter v_it(mesh_.vertices_begin()),
v_end(mesh_.vertices_end());
// compute bounding box
Point bb_min, bb_max;
bb_min = bb_max = mesh_.point(v_it);
for (++v_it; v_it!=v_end; ++v_it)
{
bb_min.minimize(mesh_.point(v_it));
bb_max.minimize(mesh_.point(v_it));
}
// abs. error = rel. error * bounding-diagonal
set_absolute_error(_err * (bb_max-bb_min).norm());
}
}
//-----------------------------------------------------------------------------
template <class Mesh>
void
SmootherT<Mesh>::
set_absolute_local_error(Scalar _err)
{
tolerance_ = _err;
}
//-----------------------------------------------------------------------------
template <class Mesh>
void
SmootherT<Mesh>::
disable_local_error_check()
{
tolerance_ = -1.0;
}
//-----------------------------------------------------------------------------
template <class Mesh>
void
SmootherT<Mesh>::
smooth(unsigned int _n)
{
// mark active vertices
set_active_vertices();
// smooth _n iterations
while (_n--)
{
compute_new_positions();
if (component_ == Tangential)
project_to_tangent_plane();
else if (tolerance_ >= 0.0)
local_error_check();
move_points();
}
}
//-----------------------------------------------------------------------------
template <class Mesh>
void
SmootherT<Mesh>::
compute_new_positions()
{
switch (continuity_)
{
case C0:
compute_new_positions_C0();
break;
case C1:
compute_new_positions_C1();
break;
case C2:
break;
}
}
//-----------------------------------------------------------------------------
template <class Mesh>
void
SmootherT<Mesh>::
project_to_tangent_plane()
{
typename Mesh::VertexIter v_it(mesh_.vertices_begin()),
v_end(mesh_.vertices_end());
// Normal should be a vector type. In some environment a vector type
// is different from point type, e.g. OpenSG!
typename Mesh::Normal translation, normal;
for (; v_it != v_end; ++v_it)
{
if (is_active(v_it))
{
translation = new_position(v_it)-orig_position(v_it);
normal = orig_normal(v_it);
normal *= dot(translation, normal);
translation -= normal;
translation += vector_cast<typename Mesh::Normal>(orig_position(v_it));
set_new_position(v_it, translation);
}
}
}
//-----------------------------------------------------------------------------
template <class Mesh>
void
SmootherT<Mesh>::
local_error_check()
{
typename Mesh::VertexIter v_it(mesh_.vertices_begin()),
v_end(mesh_.vertices_end());
typename Mesh::Normal translation;
typename Mesh::Scalar s;
for (; v_it != v_end; ++v_it)
{
if (is_active(v_it))
{
translation = new_position(v_it) - orig_position(v_it);
s = fabs(dot(translation, orig_normal(v_it)));
if (s > tolerance_)
{
translation *= (tolerance_ / s);
translation += vector_cast<NormalType>(orig_position(v_it));
set_new_position(v_it, translation);
}
}
}
}
//-----------------------------------------------------------------------------
template <class Mesh>
void
SmootherT<Mesh>::
move_points()
{
typename Mesh::VertexIter v_it(mesh_.vertices_begin()),
v_end(mesh_.vertices_end());
for (; v_it != v_end; ++v_it)
if (is_active(v_it))
mesh_.set_point(v_it, mesh_.property(new_positions_, v_it));
}
//=============================================================================
} // namespace Smoother
} // namespace OpenMesh
//=============================================================================
| 12,073 | 3,743 |
class Solution {
public:
int longestStrChain(vector<string>& words) {
set<pair<int, string>> lengthWordSet;
unordered_map<string, int> dp;
for(const string& WORD: words){
lengthWordSet.emplace(WORD.length(), WORD);
dp[WORD] = 1;
}
int answer = 0;
for(set<pair<int, string>>::const_reverse_iterator crit = lengthWordSet.crbegin(); crit != lengthWordSet.crend(); ++crit){
const string& WORD = crit->second;
answer = max(dp[WORD], answer);
for(int i = 0; i < (int)WORD.length(); ++i){
string nextWord = WORD.substr(0, i) + WORD.substr(i + 1);
if(dp.count(nextWord)){
dp[nextWord] = max(1 + dp[WORD], dp[nextWord]);
}
}
}
return answer;
}
}; | 891 | 277 |
#include <bits/stdc++.h>
#define _ ios::sync_with_stdio(0);cin.tie(0);
using namespace std;
int main(){
long long int N,M;
while(~scanf("%lld %lld",&N,&M)&&N){
int cnt[1024][128]={0};
int RUN=N*M-1;
char str[1024];
getchar();
while(RUN--){
fgets(str,1024,stdin);
for(int i=0;str[i]!='\n';i++){
cnt[i][str[i]]++;
}
}
for(int i=0;i<1024;i++){
for(int j=0;j<128;j++){
if(cnt[i][j]%M){
printf("%c",j);
j=128;
}
}
}
printf("\n");
}
return 0;
} | 497 | 304 |
/*
Table.cpp
By Jim Davies
Jacobus Systems, Brighton & Hove, UK
http://www.jacobus.co.uk
Provided under the MIT license: https://github.com/jacobussystems/ArdJack/blob/master/LICENSE
Copyright (c) 2019 James Davies, Jacobus Systems, Brighton & Hove, UK
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
#include "pch.h"
#ifdef ARDUINO
#define _strlwr strlwr
#else
#include "stdafx.h"
#include <typeinfo>
#endif
#include "Globals.h"
#include "Log.h"
#include "Table.h"
#include "Utils.h"
Table::Table()
{
ColumnCount = 0;
HorzLineChar = '_';
LeftMargin = 3;
TotalWidth = 0;
VertLineChar = '|';
for (int i = 0; i < ARDJACK_MAX_TABLE_COLUMNS; i++)
ColumnDefs[i] = NULL;
}
Table::~Table()
{
for (int i = 0; i < ARDJACK_MAX_TABLE_COLUMNS; i++)
{
if (NULL != ColumnDefs[i])
{
delete ColumnDefs[i];
ColumnDefs[i] = NULL;
}
}
ColumnCount = 0;
}
bool Table::AddColumn(const char* caption, int width, int align, int padding)
{
TableColumnDef* colDef = new TableColumnDef();
ColumnDefs[ColumnCount++] = colDef;
colDef->Alignment = align;
strcpy(colDef->Caption, caption);
colDef->Padding = padding;
colDef->Width = width;
TotalWidth += width;
return true;
}
char* Table::AddLeftMargin(char* text)
{
Utils::RepeatChar(text, ' ', LeftMargin);
return text;
}
char* Table::Cell(char* text, const char* colText, int col)
{
text[0] = NULL;
if (col >= ColumnCount)
return text;
TableColumnDef* colDef = ColumnDefs[col];
if (Utils::StringIsNullOrEmpty(colText))
{
// There's no text.
return Utils::RepeatChar(text, ' ', colDef->Width);
}
char format[22];
char padding[82];
char temp[102];
// Left-side padding.
Utils::RepeatChar(padding, ' ', colDef->Padding);
strcat(text, padding);
// Align the column text.
int textWidth = colDef->Width - 2 * colDef->Padding;
switch (colDef->Alignment)
{
case ARDJACK_HORZ_ALIGN_CENTRE:
{
int remainder = textWidth - (NULL != colText) ? Utils::StringLen(colText) : 0;
if (remainder <= 0)
strcat(text, colText);
else
{
int spaces = remainder / 2;
Utils::RepeatChar(padding, ' ', spaces);
strcat(text, padding);
strcat(text, colText);
Utils::RepeatChar(padding, ' ', remainder - spaces);
strcat(text, padding);
}
}
break;
case ARDJACK_HORZ_ALIGN_LEFT:
sprintf(format, "%%-%ds", textWidth);
sprintf(temp, format, (NULL != colText) ? colText : "");
strcat(text, temp);
break;
case ARDJACK_HORZ_ALIGN_RIGHT:
sprintf(format, "%%%ds", textWidth);
sprintf(temp, format, (NULL != colText) ? colText : "");
strcat(text, temp);
break;
}
if (col < ColumnCount - 1)
{
// Right-side padding.
Utils::RepeatChar(padding, ' ', colDef->Padding);
strcat(text, padding);
}
return text;
}
char* Table::Header(char* text)
{
text[0] = NULL;
AddLeftMargin(text);
char temp[82];
for (int col = 0; col < ColumnCount; col++)
{
TableColumnDef* colDef = ColumnDefs[col];
Cell(temp, colDef->Caption, col);
strcat(text, temp);
}
return text;
}
char* Table::HorizontalLine(char* text)
{
text[0] = NULL;
AddLeftMargin(text);
// A horizontal line.
char temp[202];
Utils::RepeatChar(temp, HorzLineChar, TotalWidth);
strcat(text, temp);
return text;
}
char* Table::Row(char* text, const char* col0, const char* col1, const char* col2,
const char* col3, const char* col4, const char* col5, const char* col6, const char* col7,
const char* col8, const char* col9, const char* col10, const char* col11)
{
text[0] = NULL;
AddLeftMargin(text);
if (strlen(col0) == 0) return text;
char work[102];
int col = 0;
strcat(text, Cell(work, col0, col++));
strcat(text, Cell(work, col1, col++));
strcat(text, Cell(work, col2, col++));
strcat(text, Cell(work, col3, col++));
strcat(text, Cell(work, col4, col++));
strcat(text, Cell(work, col5, col++));
strcat(text, Cell(work, col6, col++));
strcat(text, Cell(work, col7, col++));
strcat(text, Cell(work, col8, col++));
strcat(text, Cell(work, col9, col++));
strcat(text, Cell(work, col10, col++));
strcat(text, Cell(work, col11, col++));
return text;
}
| 5,096 | 2,065 |
/*
A zero-indexed array A consisting of N different integers is given. The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing.
Your goal is to find that missing element.
Write a function:
int solution(int A[], int N);
that, given a zero-indexed array A, returns the value of the missing element.
*/
// you can write to stdout for debugging purposes, e.g.
// printf("this is a debug message\n");
int solution(int A[], int N) {
// write your code in C99
int Sum=(N+1)*(N+2)/2;
for(int i=0;i<N;i++)
Sum=Sum-A[i];
return Sum;
}
| 598 | 192 |
//
// Created by Spud on 7/16/21.
//
#include "npf/layout/ask.hpp"
void Ask::populateBlocks(const JSON_ARRAY &array) { // TODO Comments
blocks = std::vector<int>(array.Size());
for (JSON_ARRAY_ENTRY &entry : array) {
if (entry.IsInt()) {
blocks.push_back(entry.GetInt());
}
}
}
void Ask::populateNPF(JSON_OBJECT entry) { // TODO Comments
POPULATE_ARRAY(entry, "blocks", populateBlocks(entry["blocks"].GetArray());)
POPULATE_OBJECT(entry, "attribution", Attribution attr;
attr.populateNPF(entry["attribution"].GetObj());
attribution = attr;)
}
| 567 | 231 |
/**
* \file dnn/src/rocm/pooling/opr_impl.cpp
* MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
*
* Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#include "hcc_detail/hcc_defs_prologue.h"
#include "src/rocm/pooling/opr_impl.h"
#include "src/rocm/utils.h"
namespace megdnn {
namespace rocm {
void PoolingForwardImpl::setup_descs(const TensorLayout &src,
const TensorLayout &dst)
{
src_desc.set(src, param().format);
dst_desc.set(dst, param().format);
pooling_desc.set(this->param());
}
void PoolingForwardImpl::exec(_megdnn_tensor_in src,
_megdnn_tensor_out dst,
_megdnn_workspace workspace)
{
check_exec(src.layout, dst.layout, workspace.size);
auto handle = miopen_handle(this->handle());
setup_descs(src.layout, dst.layout);
dt_float32 alpha = 1.0f, beta = 0.0f;
miopen_check(miopenPoolingForward(handle, pooling_desc.desc, &alpha,
src_desc.desc, src.raw_ptr, &beta,
dst_desc.desc, dst.raw_ptr, false,
nullptr, 0_z));
}
void PoolingBackwardImpl::setup_descs(const TensorLayout& src,
const TensorLayout& dst,
const TensorLayout& diff,
const TensorLayout& grad) {
src_desc.set(src);
dst_desc.set(dst);
diff_desc.set(diff);
grad_desc.set(grad);
pooling_desc.set(this->param());
}
void PoolingBackwardImpl::exec(_megdnn_tensor_in src,
_megdnn_tensor_in dst,
_megdnn_tensor_in diff,
_megdnn_tensor_out grad,
_megdnn_workspace workspace)
{
check_exec(src.layout, dst.layout, diff.layout, grad.layout, workspace.size);
auto handle = miopen_handle(this->handle());
setup_descs(src.layout, dst.layout, diff.layout, grad.layout);
float alpha = 1.0f, beta = 0.0f;
if (param().mode == param::Pooling::Mode::MAX) {
//! FIXME: when using max pooling opr, the backward opr need the indices
//! of the forward opr which stored in workspace. We have to recompute
//! the indices by calling miopenPoolingForward again.
miopen_check(miopenPoolingForward(handle, pooling_desc.desc, &alpha,
src_desc.desc, src.raw_ptr, &beta,
dst_desc.desc, dst.raw_ptr, true,
workspace.raw_ptr, workspace.size));
}
miopen_check(miopenPoolingBackward(
handle, pooling_desc.desc, &alpha, dst_desc.desc, dst.raw_ptr,
diff_desc.desc, diff.raw_ptr, src_desc.desc, src.raw_ptr, &beta,
grad_desc.desc, grad.raw_ptr, workspace.raw_ptr));
}
size_t PoolingBackwardImpl::get_workspace_in_bytes(const TensorLayout& src,
const TensorLayout& dst,
const TensorLayout& diff,
const TensorLayout& grad) {
setup_descs(src, dst, diff, grad);
size_t ws_size = 0_z;
miopenPoolingGetWorkSpaceSize(dst_desc.desc, &ws_size);
return ws_size;
};
} // namespace rocm
} // namespace megdnn
// vim: syntax=cpp.doxygen
| 3,450 | 1,139 |
#include "Shape.h"
Shape::Shape() { log("Shape::Shape()"); }
Shape::Shape(const Shape& shp) { log("Shape::Shape(const Shape&)"); }
Shape::~Shape() { log("Shape::~Shape()\n"); }
bool Shape::operator==(const Shape& rhs) {
return numberOfSides() == rhs.numberOfSides();
}
bool Shape::operator!=(const Shape& rhs) {
return numberOfSides() != rhs.numberOfSides();
}
bool Shape::operator<(const Shape& rhs) {
return numberOfSides() < rhs.numberOfSides();
}
bool Shape::operator>(const Shape& rhs) {
return numberOfSides() > rhs.numberOfSides();
}
bool Shape::operator<=(const Shape& rhs) {
return numberOfSides() <= rhs.numberOfSides();
}
bool Shape::operator>=(const Shape& rhs) {
return numberOfSides() >= rhs.numberOfSides();
} | 740 | 267 |
// Problem Link:
// https://practice.geeksforgeeks.org/problems/top-view-of-binary-tree/1
// Recursive and Iterative
// TC: O(n)
// SC: O(n)
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define deb(x) cout << #x << ": " << x << "\n"
class TreeNode
{
public:
TreeNode *left;
int val;
TreeNode *right;
TreeNode() { TreeNode(-1); }
TreeNode(int _val) : left(NULL), val(_val), right(NULL) {}
};
// Recusive
void helper(TreeNode *root, map<int, pair<int, int>> &hash, int distance, int level)
{
if (root)
{
if (hash.find(distance) == hash.end() or level <= hash[distance].first)
hash[distance] = {level, root->val};
helper(root->left, hash, distance - 1, level + 1);
helper(root->right, hash, distance + 1, level + 1);
}
}
vector<int> topView1(TreeNode *root)
{
vector<int> res{};
map<int, pair<int, int>> hash{};
helper(root, hash, 0, 0);
for (auto i : hash)
res.push_back(i.second.second);
return res;
}
// Iterative
vector<int> topView2(TreeNode *root)
{
vector<int> res{};
map<int, int> hash{};
queue<pair<TreeNode *, int>> qu;
qu.push({root, 0});
while (!qu.empty())
{
pair<TreeNode *, int> curr = qu.front();
qu.pop();
if (hash.find(curr.second) == hash.end())
hash[curr.second] = curr.first->val;
if (curr.first->left)
qu.push({curr.first->left, curr.second - 1});
if (curr.first->right)
qu.push({curr.first->right, curr.second + 1});
}
for (auto i : hash)
res.push_back(i.second);
return res;
}
void solve()
{
TreeNode *root = new TreeNode(10);
root->left = new TreeNode(20);
root->right = new TreeNode(30);
root->left->left = new TreeNode(40);
root->left->right = new TreeNode(60);
vector<int> res;
res = topView1(root);
for (auto i : res)
cout << i << " ";
cout << endl;
res = topView2(root);
for (auto i : res)
cout << i << " ";
cout << endl;
}
int main()
{
ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int t{1};
// cin >> t;
while (t--)
solve();
return 0;
} | 2,223 | 834 |
#include "bits/stdc++.h"
using namespace std;
#define X first
#define Y second
class Board {
public:
static map<Board*, vector<Board*>> adj;
static map<Board, Board*> all;
Board* par;
char data[6][6];
Board();
Board(Board*);
~Board();
void Fill(char);
void draw();
string rot90(char[3][3], int);
void rotPlate(int, int);
};
bool operator<(Board &a, Board &b) {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
if (a.data[i][j] == b.data[i][j])
continue;
return a.data[i][j] < b.data[i][j];
}
}
}
Board::Board() {
par = nullptr;
Fill('_');
}
Board::Board(Board* oth) {
par = oth;
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
this->data[i][j] = oth->data[i][j];
}
}
}
Board::~Board() {
cout << "board dead" << endl;
}
void Board::Fill(char c) {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
this->data[i][j] = c;
}
}
}
void Board::draw() {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++)
cout << this->data[i][j] << " ";
cout << endl;
}
cout << endl;
}
string Board::rot90(char in[3][3] ,int k) {
char tmp[3][3];
string ans = "";
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (k == 1)
tmp[i][j] = in[2-j][i];
else
tmp[i][j] = in[j][2-i];
ans += string(1 , tmp[i][j]);
}
}
return ans;
}
void Board::rotPlate(int plate , int k) {
/* 0 2
1 3 */
int x = plate % 2 * 3 , y = plate / 2 * 3;
char tmp[3][3];
for(int i = x ; i < x + 3 ; i++)
for(int j = y ; j < y + 3 ; j++)
tmp[i - x][j - y] = this->data[i][j];
string s = rot90(tmp , k);
for(int i = x ; i < x + 3 ; i++)
for(int j = y ; j < y + 3 ; j++)
this->data[i][j] = s[(i - x) * 3 + j - y];
}
int main()
{
Board* a = new Board();
Board* b = new Board(a);
b->data[0][0] = 'X';
a->draw();
b->draw();
b->rotPlate(0, 1);
b->draw();
delete a;
delete b;
return 0;
}
| 2,250 | 947 |
// 06-point3.cpp : Point type with global operator+ defined
import std.core;
using namespace std;
struct Point{
int x{}, y{};
};
Point operator+ (const Point& lhs, const Point& rhs) {
Point result;
result.x = lhs.x + rhs.x;
result.y = lhs.y + rhs.y;
return result;
}
int main() {
Point p1{ 100, 200 }, p2{ 200, -50 }, p3;
p3 = p1 + p2;
cout << "p3 = (" << p3.x << ',' << p3.y << ")\n";
}
| 400 | 184 |
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include <stdio.h>
#include <TClonesArray.h>
#include "AliAlgSens.h"
#include "AliAlgAux.h"
#include "AliLog.h"
#include "AliGeomManager.h"
#include "AliExternalTrackParam.h"
#include "AliAlgPoint.h"
#include "AliAlgDet.h"
#include "AliAlgDOFStat.h"
ClassImp(AliAlgSens)
using namespace AliAlgAux;
using namespace TMath;
//_________________________________________________________
AliAlgSens::AliAlgSens(const char* name,Int_t vid, Int_t iid)
: AliAlgVol(name,iid)
,fSID(0)
,fDet(0)
,fMatClAlg()
,fMatClAlgReco()
{
// def c-tor
SetVolID(vid);
fAddError[0] = fAddError[1] = 0;
fConstrChild = 0; // sensors don't have children
}
//_________________________________________________________
AliAlgSens::~AliAlgSens()
{
// d-tor
}
//_________________________________________________________
void AliAlgSens::DPosTraDParGeomLOC(const AliAlgPoint* pnt, double* deriv) const
{
// Jacobian of position in sensor tracking frame (tra) vs sensor LOCAL frame
// parameters in TGeoHMatrix convention.
// Result is stored in array deriv as linearized matrix 6x3
const double kDelta[kNDOFGeom]={0.1,0.1,0.1,0.5,0.5,0.5};
double delta[kNDOFGeom],pos0[3],pos1[3],pos2[3],pos3[3];
TGeoHMatrix matMod;
//
memset(delta,0,kNDOFGeom*sizeof(double));
memset(deriv,0,kNDOFGeom*3*sizeof(double));
const double *tra = pnt->GetXYZTracking();
//
for (int ip=kNDOFGeom;ip--;) {
//
if (!IsFreeDOF(ip)) continue;
//
double var = kDelta[ip];
delta[ip] -= var;
// variation matrix in tracking frame for variation in sensor LOCAL frame
GetDeltaT2LmodLOC(matMod, delta);
matMod.LocalToMaster(tra,pos0); // varied position in tracking frame
//
delta[ip] += 0.5*var;
GetDeltaT2LmodLOC(matMod, delta);
matMod.LocalToMaster(tra,pos1); // varied position in tracking frame
//
delta[ip] += var;
GetDeltaT2LmodLOC(matMod, delta);
matMod.LocalToMaster(tra,pos2); // varied position in tracking frame
//
delta[ip] += 0.5*var;
GetDeltaT2LmodLOC(matMod, delta);
matMod.LocalToMaster(tra,pos3); // varied position in tracking frame
//
delta[ip] = 0;
double *curd = deriv + ip*3;
for (int i=3;i--;) curd[i] = (8.*(pos2[i]-pos1[i]) - (pos3[i]-pos0[i]))/6./var;
}
//
}
//_________________________________________________________
void AliAlgSens::DPosTraDParGeomLOC(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent) const
{
// Jacobian of position in sensor tracking frame (tra) vs parent volume LOCAL frame parameters.
// NO check of parentship is done!
// Result is stored in array deriv as linearized matrix 6x3
const double kDelta[kNDOFGeom]={0.1,0.1,0.1,0.5,0.5,0.5};
double delta[kNDOFGeom],pos0[3],pos1[3],pos2[3],pos3[3];
TGeoHMatrix matMod;
// this is the matrix for transition from sensor to parent volume local frames: LOC=matRel*loc
TGeoHMatrix matRel = parent->GetMatrixL2GIdeal().Inverse();
matRel *= GetMatrixL2GIdeal();
//
memset(delta,0,kNDOFGeom*sizeof(double));
memset(deriv,0,kNDOFGeom*3*sizeof(double));
const double *tra = pnt->GetXYZTracking();
//
for (int ip=kNDOFGeom;ip--;) {
//
if (!IsFreeDOF(ip)) continue;
//
double var = kDelta[ip];
delta[ip] -= var;
GetDeltaT2LmodLOC(matMod, delta, matRel);
matMod.LocalToMaster(tra,pos0); // varied position in tracking frame
//
delta[ip] += 0.5*var;
GetDeltaT2LmodLOC(matMod, delta, matRel);
matMod.LocalToMaster(tra,pos1); // varied position in tracking frame
//
delta[ip] += var;
GetDeltaT2LmodLOC(matMod, delta, matRel);
matMod.LocalToMaster(tra,pos2); // varied position in tracking frame
//
delta[ip] += 0.5*var;
GetDeltaT2LmodLOC(matMod, delta, matRel);
matMod.LocalToMaster(tra,pos3); // varied position in tracking frame
//
delta[ip] = 0;
double *curd = deriv + ip*3;
for (int i=3;i--;) curd[i] = (8.*(pos2[i]-pos1[i]) - (pos3[i]-pos0[i]))/6./var;
}
//
}
//_________________________________________________________
void AliAlgSens::DPosTraDParGeomTRA(const AliAlgPoint* pnt, double* deriv) const
{
// Jacobian of position in sensor tracking frame (tra) vs sensor TRACKING
// frame parameters in TGeoHMatrix convention, i.e. the modified parameter is
// tra' = tau*tra
//
// Result is stored in array deriv as linearized matrix 6x3
const double kDelta[kNDOFGeom]={0.1,0.1,0.1,0.5,0.5,0.5};
double delta[kNDOFGeom],pos0[3],pos1[3],pos2[3],pos3[3];
TGeoHMatrix matMod;
//
memset(delta,0,kNDOFGeom*sizeof(double));
memset(deriv,0,kNDOFGeom*3*sizeof(double));
const double *tra = pnt->GetXYZTracking();
//
for (int ip=kNDOFGeom;ip--;) {
//
if (!IsFreeDOF(ip)) continue;
//
double var = kDelta[ip];
delta[ip] -= var;
GetDeltaT2LmodTRA(matMod,delta);
matMod.LocalToMaster(tra,pos0); // varied position in tracking frame
//
delta[ip] += 0.5*var;
GetDeltaT2LmodTRA(matMod,delta);
matMod.LocalToMaster(tra,pos1); // varied position in tracking frame
//
delta[ip] += var;
GetDeltaT2LmodTRA(matMod,delta);
matMod.LocalToMaster(tra,pos2); // varied position in tracking frame
//
delta[ip] += 0.5*var;
GetDeltaT2LmodTRA(matMod,delta);
matMod.LocalToMaster(tra,pos3); // varied position in tracking frame
//
delta[ip] = 0;
double *curd = deriv + ip*3;
for (int i=3;i--;) curd[i] = (8.*(pos2[i]-pos1[i]) - (pos3[i]-pos0[i]))/6./var;
}
//
}
//_________________________________________________________
void AliAlgSens::DPosTraDParGeomTRA(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent) const
{
// Jacobian of position in sensor tracking frame (tra) vs sensor TRACKING
// frame parameters in TGeoHMatrix convention, i.e. the modified parameter is
// tra' = tau*tra
//
// Result is stored in array deriv as linearized matrix 6x3
const double kDelta[kNDOFGeom]={0.1,0.1,0.1,0.5,0.5,0.5};
double delta[kNDOFGeom],pos0[3],pos1[3],pos2[3],pos3[3];
TGeoHMatrix matMod;
//
// 1st we need a matrix for transition between child and parent TRACKING frames
// Let TRA,LOC are positions in tracking and local frame of parent, linked as LOC=T2L*TRA
// and tra,loc are positions in tracking and local frame of child, linked as loc=t2l*tra
// The loc and LOC are linked as LOC=R*loc, where R = L2G^-1*l2g, with L2G and l2g
// local2global matrices for parent and child
//
// Then, TRA = T2L^-1*LOC = T2L^-1*R*loc = T2L^-1*R*t2l*tra
// -> TRA = matRel*tra, with matRel = T2L^-1*L2G^-1 * l2g*t2l
// Note that l2g*t2l are tracking to global matrices
TGeoHMatrix matRel,t2gP;
GetMatrixT2G(matRel); // t2g matrix of child
parent->GetMatrixT2G(t2gP); // t2g matrix of parent
matRel.MultiplyLeft(&t2gP.Inverse());
//
memset(delta,0,kNDOFGeom*sizeof(double));
memset(deriv,0,kNDOFGeom*3*sizeof(double));
const double *tra = pnt->GetXYZTracking();
//
for (int ip=kNDOFGeom;ip--;) {
//
if (!IsFreeDOF(ip)) continue;
//
double var = kDelta[ip];
delta[ip] -= var;
GetDeltaT2LmodTRA(matMod,delta,matRel);
matMod.LocalToMaster(tra,pos0); // varied position in tracking frame
//
delta[ip] += 0.5*var;
GetDeltaT2LmodTRA(matMod,delta,matRel);
matMod.LocalToMaster(tra,pos1); // varied position in tracking frame
//
delta[ip] += var;
GetDeltaT2LmodTRA(matMod,delta,matRel);
matMod.LocalToMaster(tra,pos2); // varied position in tracking frame
//
delta[ip] += 0.5*var;
GetDeltaT2LmodTRA(matMod,delta,matRel);
matMod.LocalToMaster(tra,pos3); // varied position in tracking frame
//
delta[ip] = 0;
double *curd = deriv + ip*3;
for (int i=3;i--;) curd[i] = (8.*(pos2[i]-pos1[i]) - (pos3[i]-pos0[i]))/6./var;
}
//
}
//_________________________________________________________
void AliAlgSens::DPosTraDParGeom(const AliAlgPoint* pnt, double* deriv, const AliAlgVol* parent) const
{
// calculate point position derivatives in tracking frame of sensor
// vs standard geometrical DOFs of its parent volume (if parent!=0) or sensor itself
Frame_t frame = parent ? parent->GetVarFrame() : GetVarFrame();
switch(frame) {
case kLOC : parent ? DPosTraDParGeomLOC(pnt,deriv,parent) : DPosTraDParGeomLOC(pnt,deriv);
break;
case kTRA : parent ? DPosTraDParGeomTRA(pnt,deriv,parent) : DPosTraDParGeomTRA(pnt,deriv);
break;
default : AliErrorF("Alignment frame %d is not implemented",parent->GetVarFrame());
break;
}
}
//__________________________________________________________________
void AliAlgSens::GetModifiedMatrixT2LmodLOC(TGeoHMatrix& matMod, const Double_t *delta) const
{
// prepare the sensitive module tracking2local matrix from its current T2L matrix
// by applying local delta of modification of LOCAL frame:
// loc' = delta*loc = T2L'*tra = T2L'*T2L^-1*loc -> T2L' = delta*T2L
Delta2Matrix(matMod, delta);
matMod.Multiply(&GetMatrixT2L());
}
//__________________________________________________________________
void AliAlgSens::GetModifiedMatrixT2LmodTRA(TGeoHMatrix& matMod, const Double_t *delta) const
{
// prepare the sensitive module tracking2local matrix from its current T2L matrix
// by applying local delta of modification of TRACKING frame:
// loc' = T2L'*tra = T2L*delta*tra -> T2L' = T2L*delta
Delta2Matrix(matMod, delta);
matMod.MultiplyLeft(&GetMatrixT2L());
}
//__________________________________________________________________
void AliAlgSens::AddChild(AliAlgVol*)
{
AliFatalF("Sensor volume cannot have childs: id=%d %s",GetVolID(),GetName());
}
//__________________________________________________________________
Int_t AliAlgSens::Compare(const TObject* b) const
{
// compare VolIDs
return GetUniqueID()<b->GetUniqueID() ? -1 : 1;
}
//__________________________________________________________________
void AliAlgSens::SetTrackingFrame()
{
// define tracking frame of the sensor
// AliWarningF("Generic method called for %s",GetSymName());
double tra[3]={0},glo[3];
TGeoHMatrix t2g;
GetMatrixT2G(t2g);
t2g.LocalToMaster(tra,glo);
fX = Sqrt(glo[0]*glo[0]+glo[1]*glo[1]);
fAlp = ATan2(glo[1],glo[0]);
AliAlgAux::BringToPiPM(fAlp);
//
}
//____________________________________________
void AliAlgSens::Print(const Option_t *opt) const
{
// print info
TString opts = opt;
opts.ToLower();
printf("Lev:%2d IntID:%7d %s VId:%6d X:%8.4f Alp:%+.4f | Err: %.4e %.4e | Used Points: %d\n",
CountParents(), GetInternalID(), GetSymName(), GetVolID(), fX, fAlp,
fAddError[0],fAddError[1],fNProcPoints);
printf(" DOFs: Tot: %d (offs: %5d) Free: %d Geom: %d {",fNDOFs,fFirstParGloID,fNDOFFree,fNDOFGeomFree);
for (int i=0;i<kNDOFGeom;i++) printf("%d",IsFreeDOF(i) ? 1:0);
printf("} in %s frame\n",fgkFrameName[fVarFrame]);
//
//
//
if (opts.Contains("par") && fParVals) {
printf(" Lb: "); for (int i=0;i<fNDOFs;i++) printf("%10d ",GetParLab(i)); printf("\n");
printf(" Vl: "); for (int i=0;i<fNDOFs;i++) printf("%+9.3e ",GetParVal(i)); printf("\n");
printf(" Er: "); for (int i=0;i<fNDOFs;i++) printf("%+9.3e ",GetParErr(i)); printf("\n");
}
//
if (opts.Contains("mat")) { // print matrices
printf("L2G ideal : ");
GetMatrixL2GIdeal().Print();
printf("L2G misalign: ");
GetMatrixL2G().Print();
printf("L2G RecoTime: ");
GetMatrixL2GReco().Print();
printf("T2L : ");
GetMatrixT2L().Print();
printf("ClAlg : ");
GetMatrixClAlg().Print();
printf("ClAlgReco: ");
GetMatrixClAlgReco().Print();
}
//
}
//____________________________________________
void AliAlgSens::PrepareMatrixT2L()
{
// extract from geometry T2L matrix
const TGeoHMatrix* t2l = AliGeomManager::GetTracking2LocalMatrix(GetVolID());
if (!t2l) {
Print("long");
AliFatalF("Failed to find T2L matrix for VID:%d %s",GetVolID(),GetSymName());
}
SetMatrixT2L(*t2l);
//
}
//____________________________________________
void AliAlgSens::PrepareMatrixClAlg()
{
// prepare alignment matrix in the LOCAL frame: delta = Gideal^-1 * G
TGeoHMatrix ma = GetMatrixL2GIdeal().Inverse();
ma *= GetMatrixL2G();
SetMatrixClAlg(ma);
//
}
//____________________________________________
void AliAlgSens::PrepareMatrixClAlgReco()
{
// prepare alignment matrix used at reco time
TGeoHMatrix ma = GetMatrixL2GIdeal().Inverse();
ma *= GetMatrixL2GReco();
SetMatrixClAlgReco(ma);
//
}
//____________________________________________
void AliAlgSens::UpdatePointByTrackInfo(AliAlgPoint* pnt, const AliExternalTrackParam* t) const
{
// update
fDet->UpdatePointByTrackInfo(pnt,t);
}
//____________________________________________
void AliAlgSens::DPosTraDParCalib(const AliAlgPoint* pnt,double* deriv,int calibID,const AliAlgVol* parent) const
{
// calculate point position X,Y,Z derivatives wrt calibration parameter calibID of given parent
// parent=0 means top detector object calibration
//
deriv[0]=deriv[1]=deriv[2]=0;
}
//______________________________________________________
Int_t AliAlgSens::FinalizeStat(AliAlgDOFStat* st)
{
// finalize statistics on processed points
if (st) FillDOFStat(st);
return fNProcPoints;
}
//_________________________________________________________________
void AliAlgSens::UpdateL2GRecoMatrices(const TClonesArray* algArr, const TGeoHMatrix *cumulDelta)
{
// recreate fMatL2GReco matrices from ideal L2G matrix and alignment objects
// used during data reconstruction.
// On top of what each volume does, also update misalignment matrix inverse
//
AliAlgVol::UpdateL2GRecoMatrices(algArr,cumulDelta);
PrepareMatrixClAlgReco();
//
}
/*
//_________________________________________________________________
AliAlgPoint* AliAlgSens::TrackPoint2AlgPoint(int, const AliTrackPointArray*, const AliESDtrack*)
{
// dummy converter
AliError("Generic method, must be implemented in specific sensor");
return 0;
}
*/
//_________________________________________________________________
void AliAlgSens::ApplyAlignmentFromMPSol()
{
// apply to the tracking coordinates in the sensor frame the full chain
// of alignments found by MP for this sensor and its parents
//
const AliAlgVol* vol = this;
TGeoHMatrix deltaG;
// create global combined delta:
// DeltaG = deltaG_0*...*deltaG_j, where delta_i is global delta of each member of hierarchy
while(vol) {
TGeoHMatrix deltaGJ;
vol->CreateAlignmenMatrix(deltaGJ);
deltaG.MultiplyLeft(&deltaGJ);
vol = vol->GetParent();
}
//
// update misaligned L2G matrix
deltaG *= GetMatrixL2GIdeal();
SetMatrixL2G(deltaG);
//
// update local misalignment matrix
PrepareMatrixClAlg();
//
}
/*
//_________________________________________________________________
void AliAlgSens::ApplyAlignmentFromMPSol()
{
// apply to the tracking coordinates in the sensor frame the full chain
// of alignments found by MP for this sensor and its parents
double delta[kNDOFGeom]={0};
//
TGeoHMatrix matMod;
//
// sensor proper variation
GetParValGeom(delta);
IsFrameTRA() ? GetDeltaT2LmodTRA(matMod,delta) : GetDeltaT2LmodLOC(matMod,delta);
fMatClAlg.MultiplyLeft(&matMod);
//
AliAlgVol* parent = this;
while ((parent==parent->GetParent())) {
// this is the matrix for transition from sensor to parent volume frame
parent->GetParValGeom(delta);
TGeoHMatrix matRel,t2gP;
if (parent->IsFrameTRA()) {
GetMatrixT2G(matRel); // t2g matrix of child
parent->GetMatrixT2G(t2gP); // t2g matrix of parent
matRel.MultiplyLeft(&t2gP.Inverse());
GetDeltaT2LmodTRA(matMod, delta, matRel);
}
else {
matRel = parent->GetMatrixL2GIdeal().Inverse();
matRel *= GetMatrixL2GIdeal();
GetDeltaT2LmodLOC(matMod, delta, matRel);
}
fMatClAlg.MultiplyLeft(&matMod);
}
//
}
*/
| 17,039 | 6,048 |
/****************************************************************************
* Copyright (c) 2015 - 2016, CEA
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder 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.
*
*****************************************************************************/
//////////////////////////////////////////////////////////////////////////////
//
// File: Integrer_champ_med.cpp
// Directory: $TRUST_ROOT/src/Kernel/MEDimpl
// Version: /main/9
//
//////////////////////////////////////////////////////////////////////////////
#include <Integrer_champ_med.h>
#include <Param.h>
#include <Champ_Fonc_MED.h>
#include <SFichier.h>
Implemente_instanciable(Integrer_champ_med,"Integrer_champ_med",Interprete);
// Description:
// Simple appel a: Interprete::printOn(Sortie&)
// Precondition:
// Parametre: Sortie& os
// Signification: un flot de sortie
// Valeurs par defaut:
// Contraintes:
// Acces: entree/sortie
// Retour: Sortie&
// Signification: le flot de sortie modifie
// Contraintes:
// Exception:
// Effets de bord:
// Postcondition: la methode ne modifie pas l'objet
Sortie& Integrer_champ_med::printOn(Sortie& os) const
{
return Interprete::printOn(os);
}
// Description:
// Simple appel a: Interprete::readOn(Entree&)
// Precondition:
// Parametre: Entree& is
// Signification: un flot d'entree
// Valeurs par defaut:
// Contraintes:
// Acces: entree/sortie
// Retour: Entree&
// Signification: le flot d'entree modifie
// Contraintes:
// Exception:
// Effets de bord:
// Postcondition:
Entree& Integrer_champ_med::readOn(Entree& is)
{
return Interprete::readOn(is);
}
void calcul_normal_norme(const ArrOfDouble& org,const ArrOfDouble& point1, const ArrOfDouble& point2,ArrOfDouble& normal);
double calcul_surface_triangle(const ArrOfDouble& origine,const ArrOfDouble& point1, const ArrOfDouble& point2)
{
double normal0=(point1(1)-origine(1))*(point2(2)-origine(2))-((point2(1)-origine(1))*(point1(2)-origine(2)));
double normal1=(point1(2)-origine(2))*(point2(0)-origine(0))-((point2(2)-origine(2))*(point1(0)-origine(0)));
double normal2=(point1(0)-origine(0))*(point2(1)-origine(1))-((point2(0)-origine(0))*(point1(1)-origine(1)));
double res=normal0*normal0+ normal1*normal1 + normal2*normal2 ;
return sqrt(res)/2.;
}
double portion_surface_elem(const ArrOfDouble& pointA,const ArrOfDouble& pointB, const ArrOfDouble& pointC,const double& z)
{
if (z<=pointA(2)) return 0;
if (z>pointC(2)) return calcul_surface_triangle(pointA,pointB,pointC);
ArrOfDouble pointD(3);
// le point D est sur AC a hauteur de B.
pointD(2)=pointB(2);
double lambda=(pointB(2)-pointA(2))/(pointC(2)-pointA(2));
for (int i=0; i<2; i++)
pointD(i)=pointA(i)+lambda*(pointC(i)-pointA(i));
if (z<=pointB(2))
{
// on calcul la surface du triangle inferieur
// et on prend la proportion...
double surf_inf=calcul_surface_triangle(pointA,pointB,pointD);
double rap=1;
if (pointB(2)!=pointA(2))
rap=(z-pointA(2))/(pointB(2)-pointA(2));
return surf_inf*rap*rap;
}
else
{
// on calcul la surface du triangle inferieur
// et on prend la proportion...
// et on retire a la surface totale
double surf_sup=calcul_surface_triangle(pointB,pointD,pointC);
double rap=(z-pointC(2))/(pointB(2)-pointC(2));
double surf_tot=calcul_surface_triangle(pointA,pointB,pointC);
return surf_tot-surf_sup*rap*rap;
}
}
double portion_surface(const ArrOfDouble& point0,const ArrOfDouble& point1, const ArrOfDouble& point2,const double& zmin,const double& zmax)
{
return portion_surface_elem(point0,point1,point2,zmax)- portion_surface_elem(point0,point1,point2,zmin);
}
static True_int fonction_tri_data(const void *ptr1,
const void *ptr2)
{
const double * tab1 = (const double *) ptr1;
const double * tab2 = (const double *) ptr2;
double delta=(tab1[0] - tab2[0]);
if (delta>0)
return 1;
else if (delta<0)
return -1;
return 0;
}
// Description:
// Fonction principale de l'interprete.
// Precondition:
// Parametre: Entree& is
// Signification: un flot d'entree
// Valeurs par defaut:
// Contraintes:
// Acces: entree/sortie
// Retour: Entree&
// Signification: le flot d'entree
// Contraintes:
// Exception:
// Effets de bord:
// Postcondition:
Entree& Integrer_champ_med::interpreter(Entree& is)
{
Motcle nom_methode;
Nom nom_fichier("integrale");
Nom nom_champ_fonc_med;
double zmin=0,zmax=0;
int nb_tranche=1;
Param param(que_suis_je());
param.ajouter("champ_med",&nom_champ_fonc_med,Param::REQUIRED);
param.ajouter("methode",&nom_methode,Param::REQUIRED);
param.ajouter("zmin",&zmin);
param.ajouter("zmax",&zmax);
param.ajouter("nb_tranche",&nb_tranche);
param.ajouter("fichier_sortie",&nom_fichier);
param.lire_avec_accolades_depuis(is);
if ((nom_methode!="integrale_en_z")&&(nom_methode!="debit_total"))
{
Cerr<<"method "<<nom_methode <<" not coded yet "<<finl;
}
// on recupere le domaine
if(! sub_type(Champ_Fonc_MED, objet(nom_champ_fonc_med)))
{
Cerr << nom_champ_fonc_med << " type is " << objet(nom_champ_fonc_med).que_suis_je() << finl;
Cerr << "only the objects of type Champ_Fonc_MED can be meshed" << finl;
exit();
}
Champ_Fonc_MED& champ=ref_cast(Champ_Fonc_MED, objet(nom_champ_fonc_med));
const Zone& zone=champ.zone_dis_base().zone();
const DoubleTab& coord=zone.domaine().les_sommets();
// on fait une coie pour les modifier
IntTab les_elems_mod=zone.les_elems();
const IntTab& les_elems=zone.les_elems();
ArrOfDouble normal(3);
const DoubleTab& valeurs= champ.valeurs();
assert(valeurs.dimension(0)==zone.nb_elem());
assert(valeurs.dimension(1)==3);
double dz=(zmax-zmin)/nb_tranche;
ArrOfDouble res(nb_tranche),pos(nb_tranche),surface(nb_tranche);
int nb_elem=les_elems.dimension(0);
Cerr<<" Field integration using the method "<<nom_methode<<" on the domain "<<zone.domaine().le_nom() <<finl;
if (nom_methode=="debit_total")
{
nb_tranche=1;
zmax=DMAXFLOAT/2.;
zmin=-zmax;
dz=(zmax-zmin);
pos(0)=0;
}
//if (nom_methode=="integrale_en_z")
{
// Etape 1 on reordonne les triangles pour classeren z les sommets
for (int elem=0; elem<nb_elem; elem++)
{
DoubleTab zz(3,2);
for (int i=0; i<3; i++)
{
int s=les_elems(elem,i);
zz(i,1)=s;
zz(i,0)=coord(s,2);
}
qsort(zz.addr(),3,sizeof(double) * 2 , fonction_tri_data);
for (int i=0; i<3; i++)
{
int ss=(int)zz(i,1);
// if (ss!=les_elems(elem,i)) Cerr<<" coucou" <<elem<<finl;
les_elems_mod(elem,i)=ss;
}
}
//
ArrOfDouble point0(3),point1(3),point2(3);
for (int elem=0; elem<nb_elem; elem++)
{
for (int i=0; i<3; i++)
{
point0(i)=coord(les_elems(elem,0),i);
point1(i)=coord(les_elems(elem,1),i);
point2(i)=coord(les_elems(elem,2),i);
}
calcul_normal_norme(point0,point1, point2, normal);
for (int i=0; i<3; i++)
{
point0(i)=coord(les_elems_mod(elem,0),i);
point1(i)=coord(les_elems_mod(elem,1),i);
point2(i)=coord(les_elems_mod(elem,2),i);
}
for (int tranche=0; tranche<nb_tranche; tranche++)
{
double zminl=(zmin)+(zmax-zmin)/nb_tranche*tranche;
double zmaxl=zminl+dz;
pos(tranche)=(zminl+zmaxl)/2.;
double z0=coord(les_elems_mod(elem,0),2);
if (z0<=zmaxl)
{
double z2=coord(les_elems_mod(elem,2),2);
if (z2>=zminl)
{
double portion=portion_surface(point0,point1,point2,zminl,zmaxl);
double prod_scal=0;
for (int i=0; i<3; i++)
prod_scal+=valeurs(elem,i)*normal(i);
res(tranche)+=portion*prod_scal;
surface(tranche)+=portion;
}
}
}
}
}
double trace=0;
SFichier so(nom_fichier);
for (int nb=0; nb<nb_tranche; nb++)
{
trace+=res(nb);
if (surface(nb)!=0)
res(nb)/=surface(nb);
else assert(res(nb)==0);
}
Cout<<"# overall balance "<<trace<<finl;
so<<"# bilan global "<<trace<<finl;
so<<"# position, valeur moyenne, surface, flux"<<finl;
for (int nb=0; nb<nb_tranche; nb++)
so << pos(nb)<<" "<<res(nb)<<" "<<surface(nb)<<" "<<res(nb)*surface(nb)<<finl;
return is;
}
| 10,128 | 3,765 |
// Copyright (c) 2017-2019 Tkeycoin Dao. All rights reserved.
// Copyright (c) 2019-2020 TKEY DMCC LLC & Tkeycoin Dao. All rights reserved.
// Website: www.tkeycoin.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Task.hpp
#pragma once
#include <functional>
#include <chrono>
#include <ucontext.h>
#include "../utils/Shareable.hpp"
class Task final
{
public:
using Func = std::function<void()>;
using Clock = std::chrono::steady_clock;
using Duration = Clock::duration;
using Time = Clock::time_point;
private:
Func _function;
Time _until;
const char* _label;
mutable ucontext_t* _parentTaskContext;
public:
explicit Task(Func&& function, Time until, const char* label = "-");
virtual ~Task() = default;
// Разрешаем перемещение
Task(Task&& that) noexcept;
Task& operator=(Task&& that) noexcept;
// Запрещаем любое копирование
Task(const Task&) = delete;
Task& operator=(const Task&) = delete;
// Планирование времени
const Time& until() const
{
return _until;
}
// Метка задачи (имя, название и т.п., для отладки)
const char* label() const
{
return _label;
}
// Сравнение по времени
bool operator<(const Task &that) const
{
return this->_until > that._until;
}
// Исполнение
void execute();
// Пустышка (остаток от перемещения)
bool isDummy() const
{
return !_function;
}
};
| 1,856 | 661 |
#include "StdAfx.h"
#include "ShooterRecord.h"
#include "Msg.h"
#include "Resource.h"
#define SEPARATOR ";"
ShooterRecord::ShooterRecord(
LPCTSTR membership_number /* = NULL */,
LPCTSTR shooter_name /* = NULL */,
LPCTSTR license /* = NULL */,
LPCTSTR club /* = NULL */,
LPCTSTR category /* = NULL */,
__time64_t license_expiry_time /* = 0 */)
: m_membership_number(membership_number),
m_shooter_name(shooter_name),
m_license(license),
m_club(club),
m_category(category),
m_license_expiry_time(license_expiry_time)
{
}
ShooterRecord::ShooterRecord( const ShooterRecord& rec)
: m_membership_number(rec.m_membership_number),
m_shooter_name(rec.m_shooter_name),
m_license(rec.m_license),
m_club(rec.m_club),
m_category(rec.m_category),
m_license_expiry_time(rec.m_license_expiry_time)
{
}
ShooterRecord::~ShooterRecord(void)
{
}
bool ShooterRecord::operator==(const ShooterRecord& rec) const
{
return ( m_membership_number == rec.m_membership_number &&
m_shooter_name == rec.m_shooter_name &&
m_license == rec.m_license &&
m_club == rec.m_club &&
m_category == rec.m_category &&
m_license_expiry_time == rec.m_license_expiry_time );
}
CStringA ShooterRecord::ToAsciiString() const
{
CStringA result;
char buf[256];
result += m_membership_number;
result += SEPARATOR;
result += m_shooter_name;
result += SEPARATOR;
result += m_license;
result += SEPARATOR;
result += m_club;
result += SEPARATOR;
result += m_category;
if (!_i64toa_s(m_license_expiry_time, buf, 256, 10)) {
result += SEPARATOR;
result += buf;
}
return result;
}
void ShooterRecord::FromAsciiString(const char * str)
{
CStringA s(str);
CStringA token;
int curPos = 0;
bool parseError = false;
if ( !parseError )
{
// parse membership number
token = s.Tokenize(SEPARATOR, curPos);
if ( curPos > 0 )
{
m_membership_number = token;
}
else
{
parseError = true;
CString wholestr(str);
::MessageBox(NULL, CFMsg(IDS_ERR_PARSE_RECORD, _T("Membership Number"), wholestr ), CMsg(IDS_MB_ERROR), MB_OK);
}
}
if ( !parseError )
{
// parse shooter name
token = s.Tokenize(SEPARATOR, curPos);
if ( curPos > 0 )
{
m_shooter_name = token;
}
else
{
parseError = true;
CString wholestr(str);
::MessageBox(NULL, CFMsg(IDS_ERR_PARSE_RECORD, _T("Shooter Name"), wholestr ), CMsg(IDS_MB_ERROR), MB_OK);
}
}
if ( !parseError )
{
// parse license
token = s.Tokenize(SEPARATOR, curPos);
if ( curPos > 0 )
{
m_license = token;
}
else
{
parseError = true;
CString wholestr(str);
::MessageBox(NULL, CFMsg(IDS_ERR_PARSE_RECORD, _T("License"), wholestr ), CMsg(IDS_MB_ERROR), MB_OK);
}
}
if ( !parseError )
{
// parse club
token = s.Tokenize(SEPARATOR, curPos);
if ( curPos > 0 )
{
m_club = token;
}
else
{
parseError = true;
CString wholestr(str);
::MessageBox(NULL, CFMsg(IDS_ERR_PARSE_RECORD, _T("Club"), wholestr ), CMsg(IDS_MB_ERROR), MB_OK);
}
}
if ( !parseError )
{
// parse category
token = s.Tokenize(SEPARATOR, curPos);
if ( curPos > 0 )
{
m_category = token;
}
else
{
parseError = true;
CString wholestr(str);
::MessageBox(NULL, CFMsg(IDS_ERR_PARSE_RECORD, _T("Category"), wholestr ), CMsg(IDS_MB_ERROR), MB_OK);
}
}
if ( !parseError )
{
token = s.Tokenize(SEPARATOR, curPos);
if ( curPos > 0 )
{
m_license_expiry_time = _atoi64((const char *) token);
}
// optional - don't consider this a failure
//else
//{
// parseError = true;
// CString wholestr(str);
// ::MessageBox(NULL, CFMsg(IDS_ERR_PARSE_RECORD, _T("License Expiry Time"), wholestr ), CMsg(IDS_MB_ERROR), MB_OK);
//}
}
}
CString ShooterRecord::ToSearchResultString() const
{
CString result;
result.Format(_T("%-25s %-16s %-20s"),
m_shooter_name,
m_membership_number,
m_club );
return result;
} | 3,852 | 1,763 |
#include "eventmanager_p.h"
#include "cachemanager_p.h"
#include "interfacemanager_p.h"
#include "client.h"
#include "channel.h"
#include "connection.h"
#include "exception.h"
#include "teamspeakevents.h"
namespace TeamSpeakSdk {
class EventManagerPrivate
{
public:
EventManagerPrivate()
{
memset(&clientUIFunctions, 0, sizeof(struct ClientUIFunctions));
}
~EventManagerPrivate()
{
}
ClientUIFunctions clientUIFunctions;
// ClientUIFunctionsRare clientUIRareFunctions;
};
static EventManager* m_instance = Q_NULLPTR;
static EventManagerPrivate* d = Q_NULLPTR;
EventManager* EventManager::instance()
{
return m_instance;
}
EventManager::~EventManager()
{
m_instance = Q_NULLPTR;
delete d;d = Q_NULLPTR;
}
EventManager::EventManager(QObject* parent)
: QObject(parent)
{
d = new EventManagerPrivate;
d->clientUIFunctions.onConnectStatusChangeEvent = onConnectStatusChangeEventWrapper;
d->clientUIFunctions.onServerProtocolVersionEvent = onServerProtocolVersionEventWrapper;
d->clientUIFunctions.onNewChannelEvent = onNewChannelEventWrapper;
d->clientUIFunctions.onNewChannelCreatedEvent = onNewChannelCreatedEventWrapper;
d->clientUIFunctions.onDelChannelEvent = onDelChannelEventWrapper;
d->clientUIFunctions.onChannelMoveEvent = onChannelMoveEventWrapper;
d->clientUIFunctions.onUpdateChannelEvent = onUpdateChannelEventWrapper;
d->clientUIFunctions.onUpdateChannelEditedEvent = onUpdateChannelEditedEventWrapper;
d->clientUIFunctions.onUpdateClientEvent = onUpdateClientEventWrapper;
d->clientUIFunctions.onClientMoveEvent = onClientMoveEventWrapper;
d->clientUIFunctions.onClientMoveSubscriptionEvent = onClientMoveSubscriptionEventWrapper;
d->clientUIFunctions.onClientMoveTimeoutEvent = onClientMoveTimeoutEventWrapper;
d->clientUIFunctions.onClientMoveMovedEvent = onClientMoveMovedEventWrapper;
d->clientUIFunctions.onClientKickFromChannelEvent = onClientKickFromChannelEventWrapper;
d->clientUIFunctions.onClientKickFromServerEvent = onClientKickFromServerEventWrapper;
d->clientUIFunctions.onClientIDsEvent = onClientIDsEventWrapper;
d->clientUIFunctions.onClientIDsFinishedEvent = onClientIDsFinishedEventWrapper;
d->clientUIFunctions.onServerEditedEvent = onServerEditedEventWrapper;
d->clientUIFunctions.onServerUpdatedEvent = onServerUpdatedEventWrapper;
d->clientUIFunctions.onServerErrorEvent = onServerErrorEventWrapper;
d->clientUIFunctions.onServerStopEvent = onServerStopEventWrapper;
d->clientUIFunctions.onTextMessageEvent = onTextMessageEventWrapper;
d->clientUIFunctions.onTalkStatusChangeEvent = onTalkStatusChangeEventWrapper;
d->clientUIFunctions.onIgnoredWhisperEvent = onIgnoredWhisperEventWrapper;
d->clientUIFunctions.onConnectionInfoEvent = onConnectionInfoEventWrapper;
d->clientUIFunctions.onServerConnectionInfoEvent = onServerConnectionInfoEventWrapper;
d->clientUIFunctions.onChannelSubscribeEvent = onChannelSubscribeEventWrapper;
d->clientUIFunctions.onChannelSubscribeFinishedEvent = onChannelSubscribeFinishedEventWrapper;
d->clientUIFunctions.onChannelUnsubscribeEvent = onChannelUnsubscribeEventWrapper;
d->clientUIFunctions.onChannelUnsubscribeFinishedEvent = onChannelUnsubscribeFinishedEventWrapper;
d->clientUIFunctions.onChannelDescriptionUpdateEvent = onChannelDescriptionUpdateEventWrapper;
d->clientUIFunctions.onChannelPasswordChangedEvent = onChannelPasswordChangedEventWrapper;
d->clientUIFunctions.onPlaybackShutdownCompleteEvent = onPlaybackShutdownCompleteEventWrapper;
d->clientUIFunctions.onSoundDeviceListChangedEvent = onSoundDeviceListChangedEventWrapper;
d->clientUIFunctions.onEditPlaybackVoiceDataEvent = onEditPlaybackVoiceDataEventWrapper;
d->clientUIFunctions.onEditPostProcessVoiceDataEvent = onEditPostProcessVoiceDataEventWrapper;
d->clientUIFunctions.onEditMixedPlaybackVoiceDataEvent = onEditMixedPlaybackVoiceDataEventWrapper;
d->clientUIFunctions.onEditCapturedVoiceDataEvent = onEditCapturedVoiceDataEventWrapper;
d->clientUIFunctions.onCustom3dRolloffCalculationClientEvent = onCustom3dRolloffCalculationClientEventWrapper;
d->clientUIFunctions.onCustom3dRolloffCalculationWaveEvent = onCustom3dRolloffCalculationWaveEventWrapper;
d->clientUIFunctions.onUserLoggingMessageEvent = onUserLoggingMessageEventWrapper;
d->clientUIFunctions.onProvisioningSlotRequestResultEvent = onProvisioningSlotRequestResultEventWrapper;
d->clientUIFunctions.onCheckServerUniqueIdentifierEvent = onCheckServerUniqueIdentifierEventWrapper;
d->clientUIFunctions.onFileTransferStatusEvent = onFileTransferStatusEventWrapper;
d->clientUIFunctions.onFileListEvent = onFileListEventWrapper;
d->clientUIFunctions.onFileListFinishedEvent = onFileListFinishedEventWrapper;
d->clientUIFunctions.onFileInfoEvent = onFileInfoEventWrapper;
d->clientUIFunctions.onCustomPacketEncryptEvent = onCustomPacketEncryptEventWrapper;
d->clientUIFunctions.onCustomPacketDecryptEvent = onCustomPacketDecryptEventWrapper;
d->clientUIFunctions.onClientPasswordEncrypt = onClientPasswordEncryptEventWrapper;
m_instance = this;
}
ClientUIFunctions* EventManager::clientUIFunctions()
{
return &d->clientUIFunctions;
}
ClientUIFunctionsRare* EventManager::clientUIFunctionsRare()
{
return nullptr;
}
void EventManager::onConnectStatusChangeEventWrapper(uint64 serverId, int newStatus, uint errorNumber)
{
auto server = Library::getServer(serverId);
auto event = new ConnectStatusChangedEvent;
event->newStatus = static_cast<ConnectStatus>(newStatus);
event->errorNumber = ReturnCode(errorNumber);
QCoreApplication::postEvent(server, event);
}
void EventManager::onServerProtocolVersionEventWrapper(uint64 serverId, int protocolVersion)
{
auto server = Library::getServer(serverId);
auto event = new ServerProtocolVersionEvent;
event->protocolVersion = protocolVersion;
QCoreApplication::postEvent(server, event);
}
void EventManager::onNewChannelEventWrapper(uint64 serverId, uint64 channelID, uint64 channelParentID)
{
auto server = Library::getServer(serverId);
auto event = new NewChannelEvent;
event->channel = server->getChannel(channelID);
event->channelParent = server->getChannel(channelParentID);
QCoreApplication::postEvent(server, event);
}
void EventManager::onNewChannelCreatedEventWrapper(uint64 serverId, uint64 channelID, uint64 channelParentID, uint16 invokerID, const char* invokerName, const char* invokerUniqueIdentifier)
{
auto server = Library::getServer(serverId);
auto event = new NewChannelCreatedEvent;
event->channel = server->getChannel(channelID);
event->channelParent = server->getChannel(channelParentID);
event->invoker = server->getClient(invokerID);
event->invokerName = utils::to_string(invokerName);
event->invokerUniqueIdentifier = utils::to_string(invokerUniqueIdentifier);
QCoreApplication::postEvent(server, event);
}
void EventManager::onDelChannelEventWrapper(uint64 serverId, uint64 channelID, uint16 invokerID, const char* invokerName, const char* invokerUniqueIdentifier)
{
auto server = Library::getServer(serverId);
auto event = new ChannelDeletedEvent;
event->channel = server->getChannel(channelID);
event->invoker = server->getClient(invokerID);
event->invokerName = utils::to_string(invokerName);
event->invokerUniqueIdentifier = utils::to_string(invokerUniqueIdentifier);
QCoreApplication::postEvent(server, event);
}
void EventManager::onChannelMoveEventWrapper(uint64 serverId, uint64 channelID, uint64 newChannelParentID, uint16 invokerID, const char* invokerName, const char* invokerUniqueIdentifier)
{
auto server = Library::getServer(serverId);
auto event = new ChannelMovedEvent;
event->channel = server->getChannel(channelID);
event->newChannelParent = server->getChannel(newChannelParentID);
event->invoker = server->getClient(invokerID);
event->invokerName = utils::to_string(invokerName);
event->invokerUniqueIdentifier = utils::to_string(invokerUniqueIdentifier);
QCoreApplication::postEvent(server, event);
}
void EventManager::onUpdateChannelEventWrapper(uint64 serverId, uint64 channelID)
{
auto server = Library::getServer(serverId);
auto event = new ChannelUpdatedEvent;
event->channel = server->getChannel(channelID);
QCoreApplication::postEvent(server, event);
}
void EventManager::onUpdateChannelEditedEventWrapper(uint64 serverId, uint64 channelID, uint16 invokerID, const char* invokerName, const char* invokerUniqueIdentifier)
{
auto server = Library::getServer(serverId);
auto event = new ChannelEditedEvent;
event->channel = server->getChannel(channelID);
event->invoker = server->getClient(invokerID);
event->invokerName = utils::to_string(invokerName);
event->invokerUniqueIdentifier = utils::to_string(invokerUniqueIdentifier);
QCoreApplication::postEvent(server, event);
}
void EventManager::onUpdateClientEventWrapper(uint64 serverId, uint16 clientID, uint16 invokerID, const char* invokerName, const char* invokerUniqueIdentifier)
{
auto server = Library::getServer(serverId);
auto event = new ClientUpdatedEvent;
event->client = server->getClient(clientID);
event->invoker = server->getClient(invokerID);
event->invokerName = utils::to_string(invokerName);
event->invokerUniqueIdentifier = utils::to_string(invokerUniqueIdentifier);
QCoreApplication::postEvent(server, event);
}
void EventManager::onClientMoveEventWrapper(uint64 serverId, uint16 clientID, uint64 oldChannelID, uint64 newChannelID, int visibility, const char* moveMessage)
{
auto server = Library::getServer(serverId);
auto event = new ClientMovedEvent;
event->client = server->getClient(clientID);
event->oldChannel = server->getChannel(oldChannelID);
event->newChannel = server->getChannel(newChannelID);
event->visibility = static_cast<Visibility>(visibility);
event->moveMessage = utils::to_string(moveMessage);
QCoreApplication::postEvent(server, event);
}
void EventManager::onClientMoveSubscriptionEventWrapper(uint64 serverId, uint16 clientID, uint64 oldChannelID, uint64 newChannelID, int visibility)
{
auto server = Library::getServer(serverId);
auto event = new SubscriptionClientMovedEvent;
event->client = server->getClient(clientID);
event->oldChannel = server->getChannel(oldChannelID);
event->newChannel = server->getChannel(newChannelID);
event->visibility = static_cast<Visibility>(visibility);
QCoreApplication::postEvent(server, event);
}
void EventManager::onClientMoveTimeoutEventWrapper(uint64 serverId, uint16 clientID, uint64 oldChannelID, uint64 newChannelID, int visibility, const char* timeoutMessage)
{
auto server = Library::getServer(serverId);
auto event = new ClientMoveTimeoutEvent;
event->client = server->getClient(clientID);
event->oldChannel = server->getChannel(oldChannelID);
event->newChannel = server->getChannel(newChannelID);
event->visibility = static_cast<Visibility>(visibility);
event->timeoutMessage = utils::to_string(timeoutMessage);
QCoreApplication::postEvent(server, event);
}
void EventManager::onClientMoveMovedEventWrapper(uint64 serverId, uint16 clientID, uint64 oldChannelID, uint64 newChannelID, int visibility, uint16 moverID, const char* moverName, const char* moverUniqueIdentifier, const char* moveMessage)
{
auto server = Library::getServer(serverId);
auto event = new ClientMoverMovedEvent;
event->client = server->getClient(clientID);
event->oldChannel = server->getChannel(oldChannelID);
event->newChannel = server->getChannel(newChannelID);
event->visibility = static_cast<Visibility>(visibility);
event->mover = server->getClient(moverID);
event->moverName = utils::to_string(moverName);
event->moverUniqueIdentifier = utils::to_string(moverUniqueIdentifier);
event->moveMessage = utils::to_string(moveMessage);
QCoreApplication::postEvent(server, event);
}
void EventManager::onClientKickFromChannelEventWrapper(uint64 serverId, uint16 clientID, uint64 oldChannelID, uint64 newChannelID, int visibility, uint16 kickerID, const char* kickerName, const char* kickerUniqueIdentifier, const char* kickMessage)
{
auto server = Library::getServer(serverId);
auto event = new ClientKickFromChannelEvent;
event->client = server->getClient(clientID);
event->oldChannel = server->getChannel(oldChannelID);
event->newChannel = server->getChannel(newChannelID);
event->visibility = static_cast<Visibility>(visibility);
event->kicker = server->getClient(kickerID);
event->kickerName = utils::to_string(kickerName);
event->kickerUniqueIdentifier = utils::to_string(kickerUniqueIdentifier);
event->kickMessage = utils::to_string(kickMessage);
QCoreApplication::postEvent(server, event);
}
void EventManager::onClientKickFromServerEventWrapper(uint64 serverId, uint16 clientID, uint64 oldChannelID, uint64 newChannelID, int visibility, uint16 kickerID, const char* kickerName, const char* kickerUniqueIdentifier, const char* kickMessage)
{
auto server = Library::getServer(serverId);
auto event = new ClientKickFromServerEvent;
event->client = server->getClient(clientID);
event->oldChannel = server->getChannel(oldChannelID);
event->newChannel = server->getChannel(newChannelID);
event->visibility = static_cast<Visibility>(visibility);
event->kicker = server->getClient(kickerID);
event->kickerName = utils::to_string(kickerName);
event->kickerUniqueIdentifier = utils::to_string(kickerUniqueIdentifier);
event->kickMessage = utils::to_string(kickMessage);
QCoreApplication::postEvent(server, event);
}
void EventManager::onClientIDsEventWrapper(uint64 serverId, const char* uniqueClientIdentifier, uint16 clientID, const char* clientName)
{
auto server = Library::getServer(serverId);
auto event = new ClientIDsReceivedEvent;
event->client = server->getClient(clientID);
event->clientName = utils::to_string(clientName);
event->uniqueClientIdentifier = utils::to_string(uniqueClientIdentifier);
QCoreApplication::postEvent(server, event);
}
void EventManager::onClientIDsFinishedEventWrapper(uint64 serverId)
{
auto server = Library::getServer(serverId);
auto event = new ClientIDsFinishedEvent;
QCoreApplication::postEvent(server, event);
}
void EventManager::onServerEditedEventWrapper(uint64 serverId, uint16 editerID, const char* editerName, const char* editerUniqueIdentifier)
{
auto server = Library::getServer(serverId);
auto event = new ServerEditedEvent;
event->editer = server->getClient(editerID);
event->editerName = utils::to_string(editerName);
event->editerUniqueIdentifier = utils::to_string(editerUniqueIdentifier);
QCoreApplication::postEvent(server, event);
}
void EventManager::onServerUpdatedEventWrapper(uint64 serverId)
{
auto server = Library::getServer(serverId);
auto event = new ServerUpdatedEvent;
QCoreApplication::postEvent(server, event);
}
void EventManager::onServerErrorEventWrapper(uint64 serverId, const char* errorMessage, uint error, const char* returnCode, const char* extraMessage)
{
auto server = Library::getServer(serverId);
auto event = new ServerErrorEvent;
event->error = static_cast<ReturnCode>(error);
event->returnCode = utils::to_string(returnCode);
event->errorMessage = utils::to_string(errorMessage);
event->extraMessage = utils::to_string(extraMessage);
QCoreApplication::postEvent(server, event);
}
void EventManager::onServerStopEventWrapper(uint64 serverId, const char* shutdownMessage)
{
auto server = Library::getServer(serverId);
auto event = new ServerStopEvent;
event->shutdownMessage = utils::to_string(shutdownMessage);
QCoreApplication::postEvent(server, event);
}
void EventManager::onTextMessageEventWrapper(uint64 serverId, uint16 targetMode, uint16 toID, uint16 fromID, const char* fromName, const char* fromUniqueIdentifier, const char* message)
{
auto server = Library::getServer(serverId);
auto event = new TextMessageEvent;
event->from = server->getClient(fromID);
event->targetMode = static_cast<TargetMode>(targetMode);
switch (event->targetMode) {
case TargetMode::Client:
event->to = server->getClient(toID);
break;
case TargetMode::Channel:
case TargetMode::Server:
default:
event->to = Q_NULLPTR;
break;
}
event->message = utils::to_string(message);
event->fromName = utils::to_string(fromName);
event->fromUniqueIdentifier = utils::to_string(fromUniqueIdentifier);
QCoreApplication::postEvent(server, event);
}
void EventManager::onTalkStatusChangeEventWrapper(uint64 serverId, int status, int isReceivedWhisper, uint16 clientID)
{
auto server = Library::getServer(serverId);
auto event = new TalkStatusChangeEvent;
event->client = server->getClient(clientID);
event->status = static_cast<TalkStatus>(status);
event->isReceivedWhisper = isReceivedWhisper != 0;
QCoreApplication::postEvent(server, event);
}
void EventManager::onIgnoredWhisperEventWrapper(uint64 serverId, uint16 clientID)
{
auto server = Library::getServer(serverId);
auto event = new WhisperIgnoredEvent;
event->client = server->getClient(clientID);
QCoreApplication::postEvent(server, event);
}
void EventManager::onConnectionInfoEventWrapper(uint64 serverId, uint16 clientID)
{
auto server = Library::getServer(serverId);
auto event = new ConnectionInfoEvent;
event->client = server->getClient(clientID);
QCoreApplication::postEvent(server, event);
}
void EventManager::onServerConnectionInfoEventWrapper(uint64 serverId)
{
auto server = Library::getServer(serverId);
auto event = new ServerConnectionInfoEvent;
QCoreApplication::postEvent(server, event);
}
void EventManager::onChannelSubscribeEventWrapper(uint64 serverId, uint64 channelID)
{
auto server = Library::getServer(serverId);
auto event = new ChannelSubscribedEvent;
event->channel = server->getChannel(channelID);
QCoreApplication::postEvent(server, event);
}
void EventManager::onChannelSubscribeFinishedEventWrapper(uint64 serverId)
{
auto server = Library::getServer(serverId);
auto event = new ChannelSubscribesFinishedEvent;
QCoreApplication::postEvent(server, event);
}
void EventManager::onChannelUnsubscribeEventWrapper(uint64 serverId, uint64 channelID)
{
auto server = Library::getServer(serverId);
auto event = new ChannelUnsubscribedEvent;
event->channel = server->getChannel(channelID);
QCoreApplication::postEvent(server, event);
}
void EventManager::onChannelUnsubscribeFinishedEventWrapper(uint64 serverId)
{
auto server = Library::getServer(serverId);
auto event = new ChannelUnsubscribesFinishedEvent;
QCoreApplication::postEvent(server, event);
}
void EventManager::onChannelDescriptionUpdateEventWrapper(uint64 serverId, uint64 channelID)
{
auto server = Library::getServer(serverId);
auto event = new ChannelDescriptionUpdatedEvent;
event->channel = server->getChannel(channelID);
QCoreApplication::postEvent(server, event);
}
void EventManager::onChannelPasswordChangedEventWrapper(uint64 serverId, uint64 channelID)
{
auto server = Library::getServer(serverId);
auto event = new ChannelPasswordChangedEvent;
event->channel = server->getChannel(channelID);
QCoreApplication::postEvent(server, event);
}
void EventManager::onPlaybackShutdownCompleteEventWrapper(uint64 serverId)
{
auto server = Library::getServer(serverId);
auto event = new PlaybackShutdownCompletedEvent;
QCoreApplication::postEvent(server, event);
}
void EventManager::onSoundDeviceListChangedEventWrapper(const char* modeID, int playOrCap)
{
auto event = new SoundDeviceListChangedEvent;
event->modeID = utils::to_string(modeID);
event->playOrCap = playOrCap != 0;
QCoreApplication::postEvent(Library::instance(), event);
}
void EventManager::onUserLoggingMessageEventWrapper(const char* logmessage, int logLevel, const char* logChannel, uint64 logID, const char* logTime, const char* completeLogString)
{
auto server = Library::getServer(logID);
auto event = new UserLoggingMessageEvent;
event->logLevel = static_cast<LogLevel>(logLevel);
event->logmessage = utils::to_string(logmessage);
event->logChannel = utils::to_string(logChannel);
event->logTime = utils::to_string(logTime);
event->completeLogString = utils::to_string(completeLogString);
QCoreApplication::postEvent(Library::instance(), event);
}
void EventManager::onFileTransferStatusEventWrapper(uint16 transferID, uint status, const char* statusMessage, uint64 remotefileSize, uint64 serverId)
{
auto server = Library::getServer(serverId);
auto event = new FileTransferStatusReceivedEvent;
event->transfer = server->getTransfer(transferID);
event->status = static_cast<ReturnCode>(status);
event->statusMessage = utils::to_string(statusMessage);
event->remotefileSize = remotefileSize;
QCoreApplication::postEvent(server, event);
}
void EventManager::onFileListEventWrapper(uint64 serverId, uint64 channelID, const char* path, const char* name, uint64 size, uint64 datetime, int type, uint64 incompletesize, const char* returnCode)
{
auto server = Library::getServer(serverId);
auto event = new FileListReceivedEvent;
event->channel = server->getChannel(channelID);
event->path = utils::to_string(path);
event->name = utils::to_string(name);
event->size = size;
event->incompletesize = incompletesize;
event->type = static_cast<FileListType>(type);
event->datetime = utils::to_date_time(datetime);
event->returnCode = utils::to_string(returnCode);
QCoreApplication::postEvent(server, event);
}
void EventManager::onFileListFinishedEventWrapper(uint64 serverId, uint64 channelID, const char* path)
{
auto server = Library::getServer(serverId);
auto event = new FileListFinishedEvent;
event->channel = server->getChannel(channelID);
event->path = utils::to_string(path);
QCoreApplication::postEvent(server, event);
}
void EventManager::onFileInfoEventWrapper(uint64 serverId, uint64 channelID, const char* name, uint64 size, uint64 datetime)
{
auto server = Library::getServer(serverId);
auto event = new FileInfoReceivedEvent;
event->channel = server->getChannel(channelID);
event->name = utils::to_string(name);
event->size = size;
event->datetime = utils::to_date_time(datetime);
QCoreApplication::postEvent(server, event);
}
void EventManager::onEditPlaybackVoiceDataEventWrapper(uint64 serverId, uint16 clientID, short* samples, int sampleCount, int channels)
{
auto handler = Library::editPlaybackVoiceDataHandler();
if (!handler)
return;
// TODO: handler call
auto server = Library::getServer(serverId);
auto client = server->getClient(clientID);
auto vector = utils::make_vector<short>(samples, sampleCount);
auto result = handler(client, vector, channels);
utils::copy_vector(result, samples);
}
void EventManager::onEditPostProcessVoiceDataEventWrapper(
uint64 serverId, uint16 clientID,
short* samples, int sampleCount,
int channels, const uint* channelSpeakers,
uint* channelFillMask)
{
auto handler = Library::editPostProcessVoiceDataHandler();
if (!handler)
return;
// TODO: handler call
auto server = Library::getServer(serverId);
auto client = server->getClient(clientID);
auto vector_samples = utils::make_vector<short>(samples, sampleCount);
auto vector_speakers = utils::make_vector<Speakers>(channelSpeakers, channels);
auto result = handler(client, vector_samples, vector_speakers, (Speakers*)channelFillMask);
if (0 != *channelFillMask)
utils::copy_vector(result, samples);
}
void EventManager::onEditMixedPlaybackVoiceDataEventWrapper(
uint64 serverId, short* samples, int sampleCount, int channels,
const uint* channelSpeakers, uint* channelFillMask)
{
auto handler = Library::editMixedPlaybackVoiceDataHandler();
if (!handler)
return;
// TODO: handler call
auto server = Library::getServer(serverId);
auto vector_samples = utils::make_vector<short>(samples, sampleCount * channels);
auto vector_speakers = utils::make_vector<Speakers>(channelSpeakers, channels);
auto result = handler(server, vector_samples, vector_speakers, (Speakers*)channelFillMask);
if (0 != *channelFillMask)
utils::copy_vector(result, samples);
}
void EventManager::onEditCapturedVoiceDataEventWrapper(uint64 serverId, short* samples, int sampleCount, int channels, int* bytes)
{
auto handler = Library::editCapturedVoiceDataHandler();
if (!handler)
return;
// TODO: handler call
bool edited = (*bytes & 1) == 1;
bool cancel = (*bytes & 2) == 0;
auto server = Library::getServer(serverId);
auto vector_samples = utils::make_vector<short>(samples, sampleCount);
auto result = handler(server, vector_samples, channels, edited, cancel);
if (edited && cancel == false)
utils::copy_vector(result, samples);
*bytes = (edited ? 1 : 0) | (cancel ? 0 : 2);
}
void EventManager::onCustom3dRolloffCalculationClientEventWrapper(uint64 serverId, uint16 clientID, float distance, float* volume)
{
auto handler = Library::custom3dRolloffCalculationClientHandler();
if (!handler)
return;
// TODO: handler call
auto server = Library::getServer(serverId);
auto client = server->getClient(clientID);
handler(client, distance, volume);
}
void EventManager::onCustom3dRolloffCalculationWaveEventWrapper(uint64 serverId, uint64 waveHandle, float distance, float* volume)
{
auto handler = Library::custom3dRolloffCalculationWaveHandler();
if (!handler)
return;
// TODO: handler call
auto server = Library::getServer(serverId);
auto wave = server->getWaveHandle(waveHandle);
handler(wave, distance, volume);
}
void EventManager::onProvisioningSlotRequestResultEventWrapper(
uint error, uint64 requestHandle, const char* connectionKey)
{
auto key = utils::to_string(connectionKey);
}
void EventManager::onCheckServerUniqueIdentifierEventWrapper(uint64 serverId, const char* serverUniqueIdentifier, int* cancelConnect)
{
auto handler = Library::checkUniqueIdentifierHandler();
if (!handler)
return;
// TODO: handler call
auto server = Library::getServer(serverId);
auto uniqueIdentifier = utils::to_string(serverUniqueIdentifier);
auto result = handler(server, uniqueIdentifier);
*cancelConnect = result;
}
#define CUSTOM_CRYPT_KEY 123
void EventManager::onCustomPacketEncryptEventWrapper(char** dataToSend, uint* sizeOfData)
{
auto handler = Library::customPacketEncryptHandler();
if (!handler) {
#if defined(CUSTOM_CRYPT_KEY)
for (uint i = 0; i < *sizeOfData; ++i) {
(*dataToSend)[i] ^= CUSTOM_CRYPT_KEY;
}
#endif
} else {
// TODO: handler call
}
}
void EventManager::onCustomPacketDecryptEventWrapper(char** dataReceived, uint* dataReceivedSize)
{
auto handler = Library::customPacketDecryptHandler();
if (!handler) {
#if defined(CUSTOM_CRYPT_KEY)
for (uint i = 0; i < *dataReceivedSize; ++i) {
(*dataReceived)[i] ^= CUSTOM_CRYPT_KEY;
}
#endif
} else {
// TODO: handler call
}
}
void EventManager::onClientPasswordEncryptEventWrapper(uint64 serverId, const char* plaintext, char* encryptedText, int encryptedTextByteSize)
{
auto handler = Library::clientPasswordEncryptHandler();
if (!handler)
return;
// TODO: handler call
auto server = Library::getServer(serverId);
auto text = utils::to_byte(plaintext);
auto result = handler(server, text, encryptedTextByteSize - 1);
::memcpy(encryptedText, result.data(), result.size());
}
void __init_event_manager()
{
(void) new EventManager(qApp);
}
Q_COREAPP_STARTUP_FUNCTION(__init_event_manager)
} // namespace TeamSpeakSdk
| 29,874 | 8,478 |
<<<<<<< HEAD
#include<iostream>
using namespace std;
int main()
{
int a[100001],i,j,n;
cin>>n;int ct=0;
int flag[100001]={0};
for(i=0;i<n;i++)
cin>>a[i];
for(i=1;i<n;i++)
{
if(flag[i]==0&&((a[i+1]-a[i])!=(a[i]-a[i-1]))||flag[i-1]==-1)
{
ct++;
flag[i]=1;
}
else flag[i]=-1;
}
cout<<ct<<endl;
for(j=0;j<n;j++)
{
if(flag[i])cout<<a[i]<<" ";
}
cout<<endl;
return 0;
}
=======
#include<iostream>
using namespace std;
int main()
{
int a[100001],i,j,n;
cin>>n;int ct=0;
int flag[100001]={0};
for(i=0;i<n;i++)
cin>>a[i];
for(i=1;i<n;i++)
{
if(flag[i]==0&&((a[i+1]-a[i])!=(a[i]-a[i-1]))||flag[i-1]==-1)
{
ct++;
flag[i]=1;
}
else flag[i]=-1;
}
cout<<ct<<endl;
for(j=0;j<n;j++)
{
if(flag[i])cout<<a[i]<<" ";
}
cout<<endl;
return 0;
}
>>>>>>> efd4245fe427ffeefe49c72470b81a015d8dcf82
| 1,182 | 529 |
#include "i_core.h"
#include "../../../patterns.h"
#include <utils/hooking/hooking.h>
namespace SDK {
namespace ue::sys::core {
C_Core *I_Core::GetInstance() {
return hook::this_call<C_Core *>(gPatterns.I_Core__GetInstance);
}
} // namespace ue::sys::core
} // namespace SDK
| 314 | 111 |
#include <iostream>
#include <cstring>
using std::cin; using std::cout; using std::endl; using std::cerr;
using std::begin; using std::end;
using std::strcmp; using std::strcpy; using std::strcat;
int main()
{
const char a[] = "A test";
const char b[] = "about it";
char c[16];
strcpy(c, a);
strcat(c, " ");
strcat(c, b);
cout << c << endl;
} | 372 | 140 |
// Copyright (c) 2016 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Prs3d_DatumAttribute_HeaderFile
#define _Prs3d_DatumAttribute_HeaderFile
//! Enumeration defining a part of datum aspect, see Prs3d_Datum.
enum Prs3d_DatumAttribute
{
Prs3d_DA_XAxisLength = 0,
Prs3d_DA_YAxisLength,
Prs3d_DA_ZAxisLength,
Prs3d_DP_ShadingTubeRadiusPercent,
Prs3d_DP_ShadingConeRadiusPercent,
Prs3d_DP_ShadingConeLengthPercent,
Prs3d_DP_ShadingOriginRadiusPercent,
Prs3d_DP_ShadingNumberOfFacettes
};
#endif // _Prs3d_DatumAttribute_HeaderFile
| 1,122 | 390 |
// ----------------------------------------------------------------------------------------
// COPYRIGHT NOTICE
// ----------------------------------------------------------------------------------------
//
// The Source Code Store LLC
// ACTIVEGANTT SCHEDULER COMPONENT FOR C++ - ActiveGanttVC
// ActiveX Control
// Copyright (c) 2002-2017 The Source Code Store LLC
//
// All Rights Reserved. No parts of this file may be reproduced, modified or transmitted
// in any form or by any means without the written permission of the author.
//
// ----------------------------------------------------------------------------------------
#include "stdafx.h"
#include "clsXML.h"
#include "TaskBaseline_C.h"
IMPLEMENT_DYNCREATE(TaskBaseline_C, CCmdTarget)
//{5A5680D4-68DB-421F-972C-16C1C2B35985}
static const IID IID_ITaskBaseline_C = { 0x5A5680D4, 0x68DB, 0x421F, { 0x97, 0x2C, 0x16, 0xC1, 0xC2, 0xB3, 0x59, 0x85} };
//{C8E849CD-4B77-47AF-97E1-56281F8FB6F1}
IMPLEMENT_OLECREATE_FLAGS(TaskBaseline_C, "MSP2007.TaskBaseline_C", afxRegApartmentThreading, 0xC8E849CD, 0x4B77, 0x47AF, 0x97, 0xE1, 0x56, 0x28, 0x1F, 0x8F, 0xB6, 0xF1)
BEGIN_DISPATCH_MAP(TaskBaseline_C, CCmdTarget)
DISP_PROPERTY_EX_ID(TaskBaseline_C, "Count", 1, odl_GetCount, SetNotSupported, VT_I4)
DISP_PROPERTY_PARAM_ID(TaskBaseline_C, "Item", 2, odl_Item, SetNotSupported, VT_DISPATCH, VTS_BSTR)
DISP_FUNCTION_ID(TaskBaseline_C, "Add", 3, odl_Add, VT_DISPATCH, VTS_NONE)
DISP_FUNCTION_ID(TaskBaseline_C, "Clear", 4, odl_Clear, VT_EMPTY, VTS_NONE)
DISP_FUNCTION_ID(TaskBaseline_C, "Remove", 5, odl_Remove, VT_EMPTY, VTS_BSTR)
DISP_FUNCTION_ID(TaskBaseline_C, "IsNull", 6, IsNull, VT_BOOL, VTS_NONE)
DISP_FUNCTION_ID(TaskBaseline_C, "Initialize", 7, Initialize, VT_EMPTY, VTS_NONE)
DISP_DEFVALUE(TaskBaseline_C, "Item")
END_DISPATCH_MAP()
BEGIN_INTERFACE_MAP(TaskBaseline_C, CCmdTarget)
INTERFACE_PART(TaskBaseline_C, IID_ITaskBaseline_C, Dispatch)
END_INTERFACE_MAP()
BEGIN_MESSAGE_MAP(TaskBaseline_C, CCmdTarget)
END_MESSAGE_MAP()
TaskBaseline_C::TaskBaseline_C()
{
EnableAutomation();
AfxOleLockApp();
InitVars();
}
void TaskBaseline_C::Initialize(void)
{
InitVars();
}
void TaskBaseline_C::InitVars(void)
{
mp_oCollection = new clsCollectionBase("TaskBaseline");
}
TaskBaseline_C::~TaskBaseline_C()
{
delete mp_oCollection;
AfxOleUnlockApp();
}
void TaskBaseline_C::OnFinalRelease()
{
CCmdTarget::OnFinalRelease();
}
LONG TaskBaseline_C::odl_GetCount(void)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
return GetCount();
}
LONG TaskBaseline_C::GetCount(void)
{
return mp_oCollection->m_lCount();
}
IDispatch* TaskBaseline_C::odl_Item(LPCTSTR Index)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
return Item(Index)->GetIDispatch(TRUE);
}
IDispatch* TaskBaseline_C::odl_Add(void)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
return Add()->GetIDispatch(TRUE);
}
void TaskBaseline_C::odl_Clear(void)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
Clear();
}
void TaskBaseline_C::odl_Remove(LPCTSTR Index)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
Remove(Index);
}
BOOL TaskBaseline_C::IsNull(void)
{
BOOL bReturn = TRUE;
if (GetCount() > 0)
{
bReturn = FALSE;
}
return bReturn;
}
TaskBaseline* TaskBaseline_C::Item(CString Index)
{
TaskBaseline *oTaskBaseline;
oTaskBaseline = (TaskBaseline*)mp_oCollection->m_oItem(Index, MP_ITEM_1, MP_ITEM_2, MP_ITEM_3, MP_ITEM_4);
return oTaskBaseline;
}
TaskBaseline* TaskBaseline_C::Add()
{
mp_oCollection->SetAddMode(TRUE);
TaskBaseline* oTaskBaseline = new TaskBaseline();
oTaskBaseline->mp_oCollection = mp_oCollection;
mp_oCollection->m_Add(oTaskBaseline, _T(""), MP_ADD_1, MP_ADD_2, FALSE, MP_ADD_3);
return oTaskBaseline;
}
void TaskBaseline_C::Clear(void)
{
mp_oCollection->m_Clear();
}
void TaskBaseline_C::Remove(CString Index)
{
mp_oCollection->m_Remove(Index, MP_REMOVE_1, MP_REMOVE_2, MP_REMOVE_3, MP_REMOVE_4);
}
void TaskBaseline_C::ReadObjectProtected(clsXML &oXML)
{
LONG lIndex;
for (lIndex = 1; lIndex <= oXML.ReadCollectionCount(); lIndex++)
{
if (oXML.GetCollectionObjectName(lIndex) == "Baseline")
{
TaskBaseline* oTaskBaseline = new TaskBaseline();
oTaskBaseline->SetXML(oXML.ReadCollectionObject(lIndex));
mp_oCollection->SetAddMode(TRUE);
CString sKey = _T("");
oTaskBaseline->mp_oCollection = mp_oCollection;
mp_oCollection->m_Add(oTaskBaseline, sKey, MP_ADD_1, MP_ADD_2, FALSE, MP_ADD_3);
}
}
}
void TaskBaseline_C::WriteObjectProtected(clsXML &oXML)
{
LONG lIndex;
TaskBaseline* oTaskBaseline;
for (lIndex = 1; lIndex <= GetCount(); lIndex++)
{
oTaskBaseline = (TaskBaseline*) mp_oCollection->m_oReturnArrayElement(lIndex);
oXML.WriteObject(oTaskBaseline->GetXML());
}
} | 4,732 | 2,025 |
// $Id: EC_Masked_Type_Filter.cpp 1861 2011-08-31 16:18:08Z mesnierp $
#include "orbsvcs/Event/EC_Masked_Type_Filter.h"
TAO_BEGIN_VERSIONED_NAMESPACE_DECL
TAO_EC_Masked_Type_Filter::
TAO_EC_Masked_Type_Filter (CORBA::ULong source_mask,
CORBA::ULong type_mask,
CORBA::ULong source_value,
CORBA::ULong type_value)
: source_mask_ (source_mask),
type_mask_ (type_mask),
source_value_ (source_value),
type_value_ (type_value)
{
}
TAO_EC_Masked_Type_Filter::~TAO_EC_Masked_Type_Filter (void)
{
}
TAO_EC_Filter::ChildrenIterator
TAO_EC_Masked_Type_Filter::begin (void) const
{
return 0;
}
TAO_EC_Filter::ChildrenIterator
TAO_EC_Masked_Type_Filter::end (void) const
{
return 0;
}
int
TAO_EC_Masked_Type_Filter::size (void) const
{
return 0;
}
int
TAO_EC_Masked_Type_Filter::filter (const RtecEventComm::EventSet& event,
TAO_EC_QOS_Info& qos_info)
{
if (event.length () != 1)
return 0;
if ((event[0].header.type & this->type_mask_) != this->type_value_
|| (event[0].header.source & this->source_mask_) != this->source_value_)
return 0;
if (this->parent () != 0)
{
this->parent ()->push (event, qos_info);
}
return 1;
}
int
TAO_EC_Masked_Type_Filter::filter_nocopy (RtecEventComm::EventSet& event,
TAO_EC_QOS_Info& qos_info)
{
if (event.length () != 1)
return 0;
if ((event[0].header.type & this->type_mask_) != this->type_value_
|| (event[0].header.source & this->source_mask_) != this->source_value_)
return 0;
if (this->parent () != 0)
{
this->parent ()->push_nocopy (event, qos_info);
}
return 1;
}
void
TAO_EC_Masked_Type_Filter::push (const RtecEventComm::EventSet &,
TAO_EC_QOS_Info &)
{
}
void
TAO_EC_Masked_Type_Filter::push_nocopy (RtecEventComm::EventSet &,
TAO_EC_QOS_Info &)
{
}
void
TAO_EC_Masked_Type_Filter::clear (void)
{
}
CORBA::ULong
TAO_EC_Masked_Type_Filter::max_event_size (void) const
{
return 1;
}
int
TAO_EC_Masked_Type_Filter::can_match (
const RtecEventComm::EventHeader& header) const
{
if ((header.type & this->type_mask_) == this->type_value_
&& (header.source & this->source_mask_) == this->source_value_)
return 1;
return 0;
}
int
TAO_EC_Masked_Type_Filter::add_dependencies (
const RtecEventComm::EventHeader&,
const TAO_EC_QOS_Info &)
{
return 0;
}
TAO_END_VERSIONED_NAMESPACE_DECL
| 2,609 | 1,033 |
// Copyright 2016 Junbo Zhang
//
// 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
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#include "fixed-size-priority-queue.h"
using namespace std;
class Foo {
public:
Foo (int a, float b) : a_(a), b_(b) {}
friend inline std::ostream &operator<<(std::ostream &os, const Foo &foo) {
os << "(" << foo.a_ << ", " << foo.b_ << ")";
return os;
}
inline bool operator< (const Foo &other) const {
return b_ < other.b_;
}
private:
int a_;
float b_;
};
struct FooPointerCmp {
bool operator() (Foo *i, Foo *j) { return *i < *j; }
};
template<typename T>
void print_queue(fixed_size_priority_queue<T> &q) {
cout << "[size = " << q.size() << ", top = " << q.top() << "]";
for (typename fixed_size_priority_queue<T>::iterator it = q.begin(); it != q.end(); it++) {
cout << "\t" << *it;
}
cout << endl;
}
template<typename T, typename Compare>
void print_queue(fixed_size_priority_queue<T> &q) {
cout << "[size = " << q.size() << ", top = " << q.top() << "]";
for (typename fixed_size_priority_queue<T>::iterator it = q.begin(); it != q.end(); it++) {
cout << "\t" << *it;
}
cout << endl;
}
template<typename T>
void test(fixed_size_priority_queue<T> &q) {
print_queue(q);
while (! q.empty()) {
q.pop();
print_queue(q);
}
cout << endl;
}
int main(int argc, char const *argv[]) {
fixed_size_priority_queue<int> q_simple(5);
q_simple.push(2);
q_simple.push(3);
q_simple.push(1);
q_simple.push(5);
q_simple.push(5);
q_simple.push(6);
q_simple.push(2);
q_simple.push(3);
q_simple.push(1);
q_simple.push(9);
q_simple.enlarge_max_size(10);
q_simple.push(3);
q_simple.push(1);
q_simple.push(9);
test(q_simple);
fixed_size_priority_queue<Foo> q_complex(5);
q_complex.push(Foo(2, 3));
q_complex.push(Foo(3, 2));
q_complex.push(Foo(1, 5));
q_complex.push(Foo(5, 7));
q_complex.push(Foo(5, 23));
q_complex.push(Foo(6, 3));
q_complex.push(Foo(2, 6));
q_complex.push(Foo(3, 7));
q_complex.push(Foo(1, 1));
q_complex.push(Foo(9, 0));
test(q_complex);
fixed_size_priority_queue<Foo*, FooPointerCmp> q_pointer(5);
q_pointer.push(new Foo(2, 3));
q_pointer.push(new Foo(3, 2));
q_pointer.push(new Foo(1, 5));
q_pointer.push(new Foo(5, 7));
q_pointer.push(new Foo(5, 23));
q_pointer.push(new Foo(6, 3));
q_pointer.push(new Foo(2, 6));
q_pointer.push(new Foo(3, 7));
q_pointer.push(new Foo(1, 1));
q_pointer.push(new Foo(9, 0));
cout << "[size = " << q_pointer.size() << ", top = " << q_pointer.top() << "]";
for (typename fixed_size_priority_queue<Foo*, FooPointerCmp>::iterator it = q_pointer.begin(); it != q_pointer.end(); it++) {
cout << "\t" << **it;
}
cout << endl;
//test(q_pointer);
return 0;
}
| 3,363 | 1,373 |