hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d33a0984838347a942d48c5fd66c0577139d0b41 | 6,783 | cpp | C++ | SarvLibrary/Kmerize/dsk/thirdparty/gatb-core/gatb-core/src/gatb/kmer/impl/BloomAlgorithm.cpp | cwright7101/llvm_sarvavid | 7567d617a7be78fecfde71ab04ebd8e9506a64e4 | [
"MIT"
] | null | null | null | SarvLibrary/Kmerize/dsk/thirdparty/gatb-core/gatb-core/src/gatb/kmer/impl/BloomAlgorithm.cpp | cwright7101/llvm_sarvavid | 7567d617a7be78fecfde71ab04ebd8e9506a64e4 | [
"MIT"
] | null | null | null | SarvLibrary/Kmerize/dsk/thirdparty/gatb-core/gatb-core/src/gatb/kmer/impl/BloomAlgorithm.cpp | cwright7101/llvm_sarvavid | 7567d617a7be78fecfde71ab04ebd8e9506a64e4 | [
"MIT"
] | null | null | null | /*****************************************************************************
* GATB : Genome Assembly Tool Box
* Copyright (C) 2014 INRIA
* Authors: R.Chikhi, G.Rizk, E.Drezen
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************************/
#include <gatb/kmer/impl/BloomAlgorithm.hpp>
#include <gatb/system/impl/System.hpp>
#include <gatb/bank/impl/Banks.hpp>
#include <gatb/bank/impl/BankHelpers.hpp>
#include <gatb/kmer/impl/Model.hpp>
#include <gatb/kmer/impl/BloomBuilder.hpp>
#include <gatb/tools/designpattern/impl/IteratorHelpers.hpp>
#include <gatb/tools/designpattern/impl/Command.hpp>
#include <gatb/tools/collections/impl/BagFile.hpp>
#include <gatb/tools/collections/impl/BagCache.hpp>
#include <gatb/tools/collections/impl/IteratorFile.hpp>
#include <gatb/tools/misc/impl/Progress.hpp>
#include <gatb/tools/misc/impl/Property.hpp>
#include <gatb/tools/misc/impl/TimeInfo.hpp>
#include <iostream>
#include <map>
#include <math.h>
#include <gatb/tools/math/Integer.hpp>
#include <gatb/tools/math/NativeInt8.hpp>
#include <gatb/debruijn/impl/ContainerNode.hpp>
#include <gatb/tools/storage/impl/StorageTools.hpp>
// We use the required packages
using namespace std;
using namespace gatb::core::system;
using namespace gatb::core::system::impl;
using namespace gatb::core::bank;
using namespace gatb::core::bank::impl;
using namespace gatb::core::kmer;
using namespace gatb::core::kmer::impl;
using namespace gatb::core::tools::dp;
using namespace gatb::core::tools::dp::impl;
using namespace gatb::core::tools::misc;
using namespace gatb::core::tools::misc::impl;
using namespace gatb::core::tools::math;
using namespace gatb::core::tools::collections;
using namespace gatb::core::tools::collections::impl;
using namespace gatb::core::tools::storage::impl;
using namespace gatb::core::tools::math;
#define DEBUG(a) //printf a
/********************************************************************************/
namespace gatb { namespace core { namespace kmer { namespace impl {
/********************************************************************************/
static const char* progressFormat1 = "Bloom: read solid kmers ";
/*********************************************************************
** METHOD :
** PURPOSE :
** INPUT :
** OUTPUT :
** RETURN :
** REMARKS :
*********************************************************************/
template<size_t span>
BloomAlgorithm<span>::BloomAlgorithm (
Storage& storage,
Iterable<Count>* solidIterable,
size_t kmerSize,
float nbitsPerKmer,
size_t nb_cores,
BloomKind bloomKind,
IProperties* options
)
: Algorithm("bloom", nb_cores, options),
_kmerSize(kmerSize), _nbitsPerKmer(nbitsPerKmer), _bloomKind(bloomKind), _storage(storage), _solidIterable(0)
{
setSolidIterable (solidIterable);
}
/*********************************************************************
** METHOD :
** PURPOSE :
** INPUT :
** OUTPUT :
** RETURN :
** REMARKS :
*********************************************************************/
template<size_t span>
BloomAlgorithm<span>::BloomAlgorithm (tools::storage::impl::Storage& storage)
: Algorithm("bloom", 0, 0),
_kmerSize(0), _nbitsPerKmer(0), _storage(storage), _solidIterable(0)
{
/** We get the kind in the storage. */
string kind = _storage(this->getName()).getProperty ("kind");
/** We parse the type. */
parse (kind, _bloomKind);
string xmlString = _storage(this->getName()).getProperty ("xml");
stringstream ss; ss << xmlString; getInfo()->readXML (ss);
}
/*********************************************************************
** METHOD :
** PURPOSE :
** INPUT :
** OUTPUT :
** RETURN :
** REMARKS :
*********************************************************************/
template<size_t span>
BloomAlgorithm<span>::~BloomAlgorithm ()
{
setSolidIterable (0);
}
/*********************************************************************
** METHOD :
** PURPOSE :
** INPUT :
** OUTPUT :
** RETURN :
** REMARKS :
*********************************************************************/
template<size_t span>
void BloomAlgorithm<span>::execute ()
{
/** We get the number of solid kmers. */
u_int64_t solidKmersNb = _solidIterable->getNbItems();
float NBITS_PER_KMER = _nbitsPerKmer;
u_int64_t estimatedBloomSize = (u_int64_t) (solidKmersNb * NBITS_PER_KMER);
size_t nbHash = (int)floorf (0.7*NBITS_PER_KMER);
if (estimatedBloomSize ==0 ) { estimatedBloomSize = 1000; }
/** We create the kmers iterator from the solid file. */
Iterator <Count>* itKmers = createIterator<Count> (
_solidIterable->iterator(),
solidKmersNb,
progressFormat1
);
LOCAL (itKmers);
/** We use a bloom builder. */
BloomBuilder<span> builder (estimatedBloomSize, nbHash, _kmerSize, _bloomKind, getDispatcher()->getExecutionUnitsNumber());
/** We instantiate the bloom object. */
IBloom<Type>* bloom = 0;
{
TIME_INFO (getTimeInfo(), "build_from_kmers");
bloom = builder.build (itKmers);
}
LOCAL (bloom);
/** We save the bloom. */
StorageTools::singleton().saveBloom<Type> (_storage.getGroup(this->getName()), "bloom", bloom, _kmerSize);
/** We gather some statistics. */
getInfo()->add (1, "stats");
getInfo()->add (2, "kind", "%s", toString(_bloomKind));
getInfo()->add (2, "bitsize", "%ld", bloom->getBitSize());
getInfo()->add (2, "nb_hash", "%d", bloom->getNbHash());
getInfo()->add (2, "nbits_per_kmer", "%f", _nbitsPerKmer);
getInfo()->add (1, getTimeInfo().getProperties("time"));
/** We save the kind in the storage. */
_storage.getGroup(this->getName()).addProperty ("kind", toString(_bloomKind));
}
/********************************************************************************/
} } } } /* end of namespaces. */
/********************************************************************************/
| 32.927184 | 127 | 0.569512 | cwright7101 |
d33bb133a1fdb90b06f49c838296a88b112c8ecc | 925 | cpp | C++ | test/scheme.cpp | syoliver/url | 7a992f6aa758807bbcd2e92e413453da98ee0c3d | [
"BSL-1.0"
] | null | null | null | test/scheme.cpp | syoliver/url | 7a992f6aa758807bbcd2e92e413453da98ee0c3d | [
"BSL-1.0"
] | null | null | null | test/scheme.cpp | syoliver/url | 7a992f6aa758807bbcd2e92e413453da98ee0c3d | [
"BSL-1.0"
] | null | null | null | //
// Copyright (c) 2019 Vinnie Falco (vinnie.falco@gmail.com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/vinniefalco/url
//
// Test that header file is self-contained.
#include <boost/url/scheme.hpp>
#include "test_suite.hpp"
namespace boost {
namespace urls {
class scheme_test
{
public:
void
run()
{
BOOST_TEST(is_special("ftp"));
BOOST_TEST(is_special("file"));
BOOST_TEST(is_special("http"));
BOOST_TEST(is_special("https"));
BOOST_TEST(is_special("ws"));
BOOST_TEST(is_special("wss"));
BOOST_TEST(! is_special("gopher"));
BOOST_TEST(! is_special("magnet"));
BOOST_TEST(! is_special("mailto"));
}
};
TEST_SUITE(scheme_test, "boost.url.scheme");
} // urls
} // boost
| 22.560976 | 79 | 0.652973 | syoliver |
d33e7bf94074454f60e7859275d7886ea1475cd9 | 111 | cpp | C++ | Plugins~/Src/MeshSyncClientMQ/sdk_MQBoneManager.cpp | Mu-L/MeshSyncDCCPlugins | dccf716d975435e4a897964a6f6789e046119740 | [
"Apache-2.0"
] | 229 | 2020-04-16T07:44:35.000Z | 2022-03-27T16:40:30.000Z | Plugins~/Src/MeshSyncClientMQ/sdk_MQBoneManager.cpp | Mu-L/MeshSyncDCCPlugins | dccf716d975435e4a897964a6f6789e046119740 | [
"Apache-2.0"
] | 20 | 2020-05-14T00:12:15.000Z | 2022-03-10T03:34:25.000Z | Plugins~/Src/MeshSyncClientMQ/sdk_MQBoneManager.cpp | Mu-L/MeshSyncDCCPlugins | dccf716d975435e4a897964a6f6789e046119740 | [
"Apache-2.0"
] | 27 | 2020-04-17T08:34:00.000Z | 2022-03-08T00:59:31.000Z | #include "pch.h"
#include "MQPlugin.h"
#if MQPLUGIN_VERSION >= 0x0464
#include "MQBoneManager.cpp"
#endif
| 15.857143 | 32 | 0.711712 | Mu-L |
d3418780b49099787da948635bce7903710005cc | 1,853 | cpp | C++ | src/arguments.cpp | tsoding/ray-tracer | c8d189cc53445cae56bfb5e4f76926b93d0e67d5 | [
"MIT"
] | 16 | 2016-05-25T10:33:41.000Z | 2019-09-02T22:09:00.000Z | src/arguments.cpp | tsoding/ray-tracer | c8d189cc53445cae56bfb5e4f76926b93d0e67d5 | [
"MIT"
] | 67 | 2018-07-16T10:34:20.000Z | 2018-10-23T16:02:43.000Z | src/arguments.cpp | tsoding/ray-tracer | c8d189cc53445cae56bfb5e4f76926b93d0e67d5 | [
"MIT"
] | 5 | 2018-07-31T19:09:08.000Z | 2018-08-21T21:31:44.000Z | #include "./arguments.hpp"
#include <iostream>
#include <string>
Arguments::Arguments(int argc, char **argv):
m_argc(argc),
m_argv(argv),
m_threadCount(1),
m_width(800),
m_height(600) {
}
std::string Arguments::sceneFile() const {
return m_sceneFile;
}
std::string Arguments::outputFile() const {
return m_outputFile;
}
size_t Arguments::threadCount() const {
return m_threadCount;
}
size_t Arguments::width() const {
return m_width;
}
size_t Arguments::height() const {
return m_height;
}
bool Arguments::verify() {
int i = 1;
for (; i < m_argc; ++i) {
if (m_argv[i][0] == '-') {
if (m_argv[i] == std::string("-j")) {
// TODO(#83): Arguments option parsing doesn't check if the parameter of option is available
m_threadCount = std::stoul(m_argv[++i]);
} else if (m_argv[i] == std::string("-w")) {
m_width = std::stoul(m_argv[++i]);
} else if (m_argv[i] == std::string("-h")) {
m_height = std::stoul(m_argv[++i]);
} else {
std::cerr << "Unexpected option: "
<< m_argv[i]
<< std::endl;
return false;
}
} else {
break;
}
}
if (i < m_argc) {
m_sceneFile = m_argv[i++];
} else {
std::cerr << "Expected scene file"
<< std::endl;
return false;
}
if (i < m_argc) {
m_outputFile = m_argv[i++];
}
return true;
}
void Arguments::help() const {
std::cerr << "./ray-tracer "
<< "[-j <thread-count>] "
<< "[-w <width>] "
<< "[-h <height>]"
<< "<scene-file> "
<< "[output-file] "
<< std::endl;
}
| 22.876543 | 108 | 0.474366 | tsoding |
d349d7c1bc9be805df2083fb58e52e40827b1ea8 | 4,945 | cpp | C++ | src/qt/src/3rdparty/webkit/Source/WebCore/svg/SVGStyledTransformableElement.cpp | ant0ine/phantomjs | 8114d44a28134b765ab26b7e13ce31594fa81253 | [
"BSD-3-Clause"
] | 46 | 2015-01-08T14:32:34.000Z | 2022-02-05T16:48:26.000Z | src/qt/src/3rdparty/webkit/Source/WebCore/svg/SVGStyledTransformableElement.cpp | ant0ine/phantomjs | 8114d44a28134b765ab26b7e13ce31594fa81253 | [
"BSD-3-Clause"
] | 7 | 2015-01-20T14:28:12.000Z | 2017-01-18T17:21:44.000Z | src/qt/src/3rdparty/webkit/Source/WebCore/svg/SVGStyledTransformableElement.cpp | ant0ine/phantomjs | 8114d44a28134b765ab26b7e13ce31594fa81253 | [
"BSD-3-Clause"
] | 14 | 2015-10-27T06:17:48.000Z | 2020-03-03T06:15:50.000Z | /*
* Copyright (C) 2004, 2005, 2008 Nikolas Zimmermann <zimmermann@kde.org>
* Copyright (C) 2004, 2005, 2006 Rob Buis <buis@kde.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#if ENABLE(SVG)
#include "SVGStyledTransformableElement.h"
#include "AffineTransform.h"
#include "Attribute.h"
#include "RenderSVGPath.h"
#include "RenderSVGResource.h"
#include "SVGNames.h"
namespace WebCore {
// Animated property definitions
DEFINE_ANIMATED_TRANSFORM_LIST(SVGStyledTransformableElement, SVGNames::transformAttr, Transform, transform)
SVGStyledTransformableElement::SVGStyledTransformableElement(const QualifiedName& tagName, Document* document)
: SVGStyledLocatableElement(tagName, document)
{
}
SVGStyledTransformableElement::~SVGStyledTransformableElement()
{
}
AffineTransform SVGStyledTransformableElement::getCTM(StyleUpdateStrategy styleUpdateStrategy) const
{
return SVGLocatable::computeCTM(this, SVGLocatable::NearestViewportScope, styleUpdateStrategy);
}
AffineTransform SVGStyledTransformableElement::getScreenCTM(StyleUpdateStrategy styleUpdateStrategy) const
{
return SVGLocatable::computeCTM(this, SVGLocatable::ScreenScope, styleUpdateStrategy);
}
AffineTransform SVGStyledTransformableElement::animatedLocalTransform() const
{
AffineTransform matrix;
transform().concatenate(matrix);
if (m_supplementalTransform)
matrix *= *m_supplementalTransform;
return matrix;
}
AffineTransform* SVGStyledTransformableElement::supplementalTransform()
{
if (!m_supplementalTransform)
m_supplementalTransform = adoptPtr(new AffineTransform);
return m_supplementalTransform.get();
}
void SVGStyledTransformableElement::parseMappedAttribute(Attribute* attr)
{
if (SVGTransformable::isKnownAttribute(attr->name())) {
SVGTransformList newList;
if (!SVGTransformable::parseTransformAttribute(newList, attr->value()))
newList.clear();
detachAnimatedTransformListWrappers(newList.size());
setTransformBaseValue(newList);
} else
SVGStyledLocatableElement::parseMappedAttribute(attr);
}
void SVGStyledTransformableElement::svgAttributeChanged(const QualifiedName& attrName)
{
SVGStyledLocatableElement::svgAttributeChanged(attrName);
if (!SVGStyledTransformableElement::isKnownAttribute(attrName))
return;
RenderObject* object = renderer();
if (!object)
return;
object->setNeedsTransformUpdate();
RenderSVGResource::markForLayoutAndParentResourceInvalidation(object);
}
void SVGStyledTransformableElement::synchronizeProperty(const QualifiedName& attrName)
{
SVGStyledLocatableElement::synchronizeProperty(attrName);
if (attrName == anyQName() || SVGTransformable::isKnownAttribute(attrName))
synchronizeTransform();
}
bool SVGStyledTransformableElement::isKnownAttribute(const QualifiedName& attrName)
{
return SVGTransformable::isKnownAttribute(attrName) || SVGStyledLocatableElement::isKnownAttribute(attrName);
}
SVGElement* SVGStyledTransformableElement::nearestViewportElement() const
{
return SVGTransformable::nearestViewportElement(this);
}
SVGElement* SVGStyledTransformableElement::farthestViewportElement() const
{
return SVGTransformable::farthestViewportElement(this);
}
FloatRect SVGStyledTransformableElement::getBBox(StyleUpdateStrategy styleUpdateStrategy) const
{
return SVGTransformable::getBBox(this, styleUpdateStrategy);
}
RenderObject* SVGStyledTransformableElement::createRenderer(RenderArena* arena, RenderStyle*)
{
// By default, any subclass is expected to do path-based drawing
return new (arena) RenderSVGPath(this);
}
void SVGStyledTransformableElement::fillPassedAttributeToPropertyTypeMap(AttributeToPropertyTypeMap& attributeToPropertyTypeMap)
{
SVGStyledElement::fillPassedAttributeToPropertyTypeMap(attributeToPropertyTypeMap);
attributeToPropertyTypeMap.set(SVGNames::transformAttr, AnimatedTransformList);
}
void SVGStyledTransformableElement::toClipPath(Path& path) const
{
toPathData(path);
// FIXME: How do we know the element has done a layout?
path.transform(animatedLocalTransform());
}
}
#endif // ENABLE(SVG)
| 32.966667 | 128 | 0.783822 | ant0ine |
d34b9891822c636074a61aba3466baa8db63339d | 1,577 | tpp | C++ | src/base/program_options.tpp | heshu-by/likelib-ws | 85987d328dc274622f4b758afa1b6af43d15564f | [
"Apache-2.0"
] | 1 | 2020-10-23T19:09:27.000Z | 2020-10-23T19:09:27.000Z | src/base/program_options.tpp | heshu-by/likelib-ws | 85987d328dc274622f4b758afa1b6af43d15564f | [
"Apache-2.0"
] | null | null | null | src/base/program_options.tpp | heshu-by/likelib-ws | 85987d328dc274622f4b758afa1b6af43d15564f | [
"Apache-2.0"
] | 1 | 2020-12-08T11:16:30.000Z | 2020-12-08T11:16:30.000Z | #pragma once
#include "program_options.hpp"
#include "base/error.hpp"
namespace base
{
template<typename ValueType>
void ProgramOptionsParser::addOption(const std::string& flag, const std::string& help)
{
_options_description.add_options()(flag.c_str(), boost::program_options::value<ValueType>(), help.c_str());
}
template<typename ValueType>
void ProgramOptionsParser::addOption(const std::string& flag, ValueType defaultValue, const std::string& help)
{
_options_description.add_options()(
flag.c_str(), boost::program_options::value<ValueType>()->default_value(defaultValue), help.c_str());
}
template<typename ValueType>
void ProgramOptionsParser::addRequiredOption(const std::string& flag, const std::string& help)
{
_options_description.add_options()(
flag.c_str(), boost::program_options::value<ValueType>()->required(), help.c_str());
}
template<typename ValueType>
ValueType ProgramOptionsParser::getValue(const std::string& flag_name) const
{
if (!hasOption(flag_name)) {
RAISE_ERROR(base::ParsingError, std::string("No option with name: ") + flag_name);
}
try {
auto option = _options[flag_name].as<ValueType>();
return option;
}
catch (const boost::program_options::error& e) {
RAISE_ERROR(base::InvalidArgument, std::string("Incorrect option type: String"));
}
catch (const std::exception& e) {
RAISE_ERROR(base::InvalidArgument, e.what());
}
catch (...) {
RAISE_ERROR(base::InvalidArgument, "[unexpected error]");
}
}
} // namespace base
| 28.160714 | 111 | 0.700698 | heshu-by |
d34dd7b776401c3e51a2779909c902253f3aaf29 | 10,645 | cpp | C++ | ex2_ISALErasurecodeandrecovery/src/main.cpp | ingdex/isa-l | f487627d49441036fd0d40a04257745a9cb8fab0 | [
"BSD-3-Clause"
] | null | null | null | ex2_ISALErasurecodeandrecovery/src/main.cpp | ingdex/isa-l | f487627d49441036fd0d40a04257745a9cb8fab0 | [
"BSD-3-Clause"
] | null | null | null | ex2_ISALErasurecodeandrecovery/src/main.cpp | ingdex/isa-l | f487627d49441036fd0d40a04257745a9cb8fab0 | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) <2017>, Intel Corporation
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 Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 "measurements.hpp"
#include "options.h"
#include "prealloc.h"
#include "random_number_generator.h"
#include "utils.hpp"
#include <algorithm>
#include <chrono>
#include <cstring>
#include <iostream>
#include <isa-l.h>
// Create the source data buffers with random data, plus extra room for the error correction codes.
// We create a total of 'm' buffers of lenght 'len'.
// The 'k' first buffers contain the data.
// The 'm-k' remaining buffer are left uninitialized, and will store the error correction codes.
uint8_t** create_source_data(int m, int k, int len)
{
uint8_t** sources = (uint8_t**)malloc(m * sizeof(uint8_t*));
random_number_generator<uint8_t> data_generator;
for (int i = 0; i < m; ++i)
{
sources[i] = (uint8_t*)malloc(len * sizeof(uint8_t));
if (i < k)
{
int j = 0;
for (; j < len / 64 * 64; j += 64)
{
memset(&sources[i][j], data_generator.get(), 64);
}
for (; j < len; ++j)
{
sources[i][j] = (uint8_t)data_generator.get();
}
}
}
return sources;
}
// Create the error correction codes, and store them alongside the data.
std::vector<uint8_t> encode_data(int m, int k, uint8_t** sources, int len, prealloc_encode prealloc)
{
// Generate encode matrix
gf_gen_cauchy1_matrix(prealloc.encode_matrix.data(), m, k);
// Generates the expanded tables needed for fast encoding
ec_init_tables(k, m - k, &prealloc.encode_matrix[k * k], prealloc.table.data());
// Actually generated the error correction codes
ec_encode_data(
len, k, m - k, prealloc.table.data(), (uint8_t**)sources, (uint8_t**)&sources[k]);
return prealloc.encode_matrix;
}
// We randomly choose up to 2 buffers to "lose", and return the indexes of those buffers.
// Note that we can lose both part of the data or part of the error correction codes indifferently.
std::vector<int> generate_errors(int m, int errors_count)
{
random_number_generator<int> idx_generator(0, m - 1);
std::vector<int> errors{idx_generator.get(), 0};
if (errors_count == 2)
{
do
{
errors[1] = idx_generator.get();
} while (errors[1] == errors[0]);
std::sort(errors.begin(), errors.end());
}
return errors;
}
// We arrange a new array of buffers that skip the ones we "lost"
uint8_t** create_erroneous_data(int k, uint8_t** source_data, std::vector<int> errors)
{
uint8_t** erroneous_data;
erroneous_data = (uint8_t**)malloc(k * sizeof(uint8_t*));
for (int i = 0, r = 0; i < k; ++i, ++r)
{
while (std::find(errors.cbegin(), errors.cend(), r) != errors.cend())
++r;
for (int j = 0; j < k; j++)
{
erroneous_data[i] = source_data[r];
}
}
return erroneous_data;
}
// Recover the contents of the "lost" buffers
// - m : the total number of buffer, containint both the source data and the error
// correction codes
// - k : the number of buffer that contain the source data
// - erroneous_data : the original buffers without the ones we "lost"
// - errors : the indexes of the buffers we "lost"
// - encode_matrix : the matrix used to generate the error correction codes
// - len : the length (in bytes) of each buffer
// Return the recovered "lost" buffers
uint8_t** recover_data(
int m,
int k,
uint8_t** erroneous_data,
const std::vector<int>& errors,
const std::vector<uint8_t>& encode_matrix,
int len,
prealloc_recover prealloc)
{
for (int i = 0, r = 0; i < k; ++i, ++r)
{
while (std::find(errors.cbegin(), errors.cend(), r) != errors.cend())
++r;
for (int j = 0; j < k; j++)
{
prealloc.errors_matrix[k * i + j] = encode_matrix[k * r + j];
}
}
gf_invert_matrix(prealloc.errors_matrix.data(), prealloc.invert_matrix.data(), k);
for (int e = 0; e < errors.size(); ++e)
{
int idx = errors[e];
if (idx < k) // We lost one of the buffers containing the data
{
for (int j = 0; j < k; j++)
{
prealloc.decode_matrix[k * e + j] = prealloc.invert_matrix[k * idx + j];
}
}
else // We lost one of the buffer containing the error correction codes
{
for (int i = 0; i < k; i++)
{
uint8_t s = 0;
for (int j = 0; j < k; j++)
s ^= gf_mul(prealloc.invert_matrix[j * k + i], encode_matrix[k * idx + j]);
prealloc.decode_matrix[k * e + i] = s;
}
}
}
ec_init_tables(k, m - k, prealloc.decode_matrix.data(), prealloc.table.data());
ec_encode_data(len, k, (m - k), prealloc.table.data(), erroneous_data, prealloc.decoding);
return prealloc.decoding;
}
// Performs 1 storage/recovery cycle, and returns the storage and recovery time.
// - m : the total number of buffer, that will contain both the source data and the
// error correction codes
// - k : the number of buffer that will contain the source data
// - len : the length (in bytes) of each buffer
// - errors_count : the number of buffer to lose (must be equal to m-k)
measurements iteration(int m, int k, int len, int errors_count)
{
uint8_t** source_data = create_source_data(m, k, len);
prealloc_encode prealloc_encode(m, k);
auto start_storage = std::chrono::steady_clock::now();
std::vector<uint8_t> encode_matrix =
encode_data(m, k, source_data, len, std::move(prealloc_encode));
auto end_storage = std::chrono::steady_clock::now();
std::vector<int> errors = generate_errors(m, errors_count);
uint8_t** erroneous_data = create_erroneous_data(k, source_data, errors);
prealloc_recover prealloc_recover(m, k, errors.size(), len);
auto start_recovery = std::chrono::steady_clock::now();
uint8_t** decoding =
recover_data(m, k, erroneous_data, errors, encode_matrix, len, std::move(prealloc_recover));
auto end_recovery = std::chrono::steady_clock::now();
bool success = false;
for (int i = 0; i < errors.size(); ++i)
{
int ret = memcmp(source_data[errors[i]], decoding[i], len);
success = (ret == 0);
}
free(erroneous_data);
for (int i = 0; i < m; ++i)
{
free(source_data[i]);
}
free(source_data);
for (int i = 0; i < errors_count; ++i)
{
free(decoding[i]);
}
free(decoding);
if (!success)
return {std::chrono::nanoseconds{0}, std::chrono::nanoseconds{0}};
return {end_storage - start_storage, end_recovery - start_recovery};
}
int main(int argc, char* argv[])
{
using namespace std::chrono_literals;
options options = options::parse(argc, argv);
utils::display_info(options);
int m = options.buffer_count;
int k = options.buffer_count - options.lost_buffers;
int len = options.dataset_size / (options.buffer_count - options.lost_buffers);
int errors_count = options.lost_buffers;
std::cout << "[Info ] Perfoming benchmark...\n";
std::cout << "[Info ] 0 % done" << std::flush;
measurements total_measurements;
int iterations = 0;
auto start_time = std::chrono::steady_clock::now();
do
{
measurements new_measurement = iteration(m, k, len, errors_count);
if (new_measurement.storage > 0s && new_measurement.recovery > 0s)
{
++iterations;
total_measurements += new_measurement;
if (std::chrono::steady_clock::now() - start_time > 1s)
{
auto estimated_iterations =
std::min(10000l, (1s / (total_measurements.recovery / iterations)));
auto estimated_runtime =
estimated_iterations *
((std::chrono::steady_clock::now() - start_time) / iterations);
if (estimated_runtime > 5s && iterations % (estimated_iterations / 10) == 0)
std::cout << "\r[Info ] "
<< (int)(((double)iterations / estimated_iterations) * 100)
<< " % done" << std::flush;
}
}
} while (iterations < 10000 &&
(total_measurements.storage < 1s || total_measurements.recovery < 1s));
std::cout << "\r[Info ] 100 % done\n";
if (iterations > 1)
std::cout << "[Info ] Average results over " << iterations << " iterations:\n";
std::cout << "[Info ] Storage time: "
<< utils::duration_to_string(total_measurements.storage / iterations) << "\n";
std::cout << "[Info ] Recovery time: "
<< utils::duration_to_string(total_measurements.recovery / iterations) << "\n";
}
| 37.882562 | 100 | 0.607609 | ingdex |
d3590896e0df90b8defc4bcdd125e8879cad1434 | 5,290 | cpp | C++ | src/routine.cpp | gcp/CLBlast | 7c13bacf129291e3e295ecb6e833788477085fa0 | [
"Apache-2.0"
] | 1 | 2021-01-01T05:20:33.000Z | 2021-01-01T05:20:33.000Z | src/routine.cpp | gcp/CLBlast | 7c13bacf129291e3e295ecb6e833788477085fa0 | [
"Apache-2.0"
] | null | null | null | src/routine.cpp | gcp/CLBlast | 7c13bacf129291e3e295ecb6e833788477085fa0 | [
"Apache-2.0"
] | null | null | null |
// =================================================================================================
// This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. This
// project loosely follows the Google C++ styleguide and uses a tab-size of two spaces and a max-
// width of 100 characters per line.
//
// Author(s):
// Cedric Nugteren <www.cedricnugteren.nl>
//
// This file implements the Routine base class (see the header for information about the class).
//
// =================================================================================================
#include <string>
#include <vector>
#include "routine.hpp"
namespace clblast {
// =================================================================================================
// Constructor: not much here, because no status codes can be returned
Routine::Routine(Queue &queue, EventPointer event, const std::string &name,
const std::vector<std::string> &routines, const Precision precision):
precision_(precision),
routine_name_(name),
queue_(queue),
event_(event),
context_(queue_.GetContext()),
device_(queue_.GetDevice()),
device_name_(device_.Name()),
db_(queue_, routines, precision_) {
}
// =================================================================================================
// Separate set-up function to allow for status codes to be returned
StatusCode Routine::SetUp() {
// Queries the cache to see whether or not the program (context-specific) is already there
if (ProgramIsInCache(context_, precision_, routine_name_)) { return StatusCode::kSuccess; }
// Queries the cache to see whether or not the binary (device-specific) is already there. If it
// is, a program is created and stored in the cache
if (BinaryIsInCache(device_name_, precision_, routine_name_)) {
try {
auto& binary = GetBinaryFromCache(device_name_, precision_, routine_name_);
auto program = Program(device_, context_, binary);
auto options = std::vector<std::string>();
program.Build(device_, options);
StoreProgramToCache(program, context_, precision_, routine_name_);
} catch (...) { return StatusCode::kBuildProgramFailure; }
return StatusCode::kSuccess;
}
// Otherwise, the kernel will be compiled and program will be built. Both the binary and the
// program will be added to the cache.
// Inspects whether or not cl_khr_fp64 is supported in case of double precision
const auto extensions = device_.Capabilities();
if (precision_ == Precision::kDouble || precision_ == Precision::kComplexDouble) {
if (extensions.find(kKhronosDoublePrecision) == std::string::npos) {
return StatusCode::kNoDoublePrecision;
}
}
// As above, but for cl_khr_fp16 (half precision)
if (precision_ == Precision::kHalf) {
if (extensions.find(kKhronosHalfPrecision) == std::string::npos) {
return StatusCode::kNoHalfPrecision;
}
}
// Loads the common header (typedefs and defines and such)
std::string common_header =
#include "kernels/common.opencl"
;
// Collects the parameters for this device in the form of defines, and adds the precision
auto defines = db_.GetDefines();
defines += "#define PRECISION "+ToString(static_cast<int>(precision_))+"\n";
// Adds the name of the routine as a define
defines += "#define ROUTINE_"+routine_name_+"\n";
// For specific devices, use the non-IEE754 compilant OpenCL mad() instruction. This can improve
// performance, but might result in a reduced accuracy.
if (device_.IsAMD() && device_.IsGPU()) {
defines += "#define USE_CL_MAD 1\n";
}
// For specific devices, use staggered/shuffled workgroup indices.
if (device_.IsAMD() && device_.IsGPU()) {
defines += "#define USE_STAGGERED_INDICES 1\n";
}
// For specific devices add a global synchronisation barrier to the GEMM kernel to optimize
// performance through better cache behaviour
if (device_.IsARM() && device_.IsGPU()) {
defines += "#define GLOBAL_MEM_FENCE 1\n";
}
// Combines everything together into a single source string
const auto source_string = defines + common_header + source_string_;
// Compiles the kernel
try {
auto program = Program(context_, source_string);
auto options = std::vector<std::string>();
const auto build_status = program.Build(device_, options);
// Checks for compiler crashes/errors/warnings
if (build_status == BuildStatus::kError) {
const auto message = program.GetBuildInfo(device_);
fprintf(stdout, "OpenCL compiler error/warning: %s\n", message.c_str());
return StatusCode::kBuildProgramFailure;
}
if (build_status == BuildStatus::kInvalid) { return StatusCode::kInvalidBinary; }
// Store the compiled binary and program in the cache
const auto binary = program.GetIR();
StoreBinaryToCache(binary, device_name_, precision_, routine_name_);
StoreProgramToCache(program, context_, precision_, routine_name_);
} catch (...) { return StatusCode::kBuildProgramFailure; }
// No errors, normal termination of this function
return StatusCode::kSuccess;
}
// =================================================================================================
} // namespace clblast
| 40.075758 | 100 | 0.644423 | gcp |
d35a81fd226d5704dc8d311db69329fb866daf6f | 8,915 | cpp | C++ | analyzer/libs/z3/src/util/sexpr.cpp | oslab-swrc/juxta | 481cd6f01e87790041a07379805968bcf57d75f4 | [
"MIT"
] | 23 | 2016-01-06T07:01:46.000Z | 2022-02-12T15:53:20.000Z | analyzer/libs/z3/src/util/sexpr.cpp | oslab-swrc/juxta | 481cd6f01e87790041a07379805968bcf57d75f4 | [
"MIT"
] | 1 | 2019-04-02T00:42:29.000Z | 2019-04-02T00:42:29.000Z | analyzer/libs/z3/src/util/sexpr.cpp | oslab-swrc/juxta | 481cd6f01e87790041a07379805968bcf57d75f4 | [
"MIT"
] | 16 | 2016-01-06T07:01:46.000Z | 2021-11-29T11:43:16.000Z | /*++
Copyright (c) 2011 Microsoft Corporation
Module Name:
sexpr.h
Abstract:
Generic sexpr
Author:
Leonardo (leonardo) 2011-07-28
Notes:
--*/
#include"sexpr.h"
#include"vector.h"
#include"buffer.h"
#ifdef _MSC_VER
#pragma warning(disable : 4200)
#pragma warning(disable : 4355)
#endif
struct sexpr_composite : public sexpr {
unsigned m_num_chilren;
sexpr * m_children[0];
sexpr_composite(unsigned num_children, sexpr * const * children, unsigned line, unsigned pos):
sexpr(COMPOSITE, line, pos),
m_num_chilren(num_children) {
for (unsigned i = 0; i < num_children; i++) {
m_children[i] = children[i];
children[i]->inc_ref();
}
}
};
struct sexpr_numeral : public sexpr {
rational m_val;
sexpr_numeral(kind_t k, rational const & val, unsigned line, unsigned pos):
sexpr(k, line, pos),
m_val(val) {
}
sexpr_numeral(rational const & val, unsigned line, unsigned pos):
sexpr(NUMERAL, line, pos),
m_val(val) {
}
};
struct sexpr_bv : public sexpr_numeral {
unsigned m_size;
sexpr_bv(rational const & val, unsigned size, unsigned line, unsigned pos):
sexpr_numeral(BV_NUMERAL, val, line, pos),
m_size(size) {
}
};
struct sexpr_string : public sexpr {
std::string m_val;
sexpr_string(std::string const & val, unsigned line, unsigned pos):
sexpr(STRING, line, pos),
m_val(val) {
}
sexpr_string(char const * val, unsigned line, unsigned pos):
sexpr(STRING, line, pos),
m_val(val) {
}
};
struct sexpr_symbol : public sexpr {
symbol m_val;
sexpr_symbol(bool keyword, symbol const & val, unsigned line, unsigned pos):
sexpr(keyword ? KEYWORD : SYMBOL, line, pos),
m_val(val) {
}
};
sexpr::sexpr(kind_t k, unsigned line, unsigned pos):
m_kind(k),
m_ref_count(0),
m_line(line),
m_pos(pos) {
}
rational const & sexpr::get_numeral() const {
SASSERT(is_numeral() || is_bv_numeral());
return static_cast<sexpr_numeral const *>(this)->m_val;
}
unsigned sexpr::get_bv_size() const {
SASSERT(is_bv_numeral());
return static_cast<sexpr_bv const *>(this)->m_size;
}
symbol sexpr::get_symbol() const {
SASSERT(is_symbol() || is_keyword());
return static_cast<sexpr_symbol const *>(this)->m_val;
}
std::string const & sexpr::get_string() const {
SASSERT(is_string());
return static_cast<sexpr_string const *>(this)->m_val;
}
unsigned sexpr::get_num_children() const {
SASSERT(is_composite());
return static_cast<sexpr_composite const *>(this)->m_num_chilren;
}
sexpr * sexpr::get_child(unsigned idx) const {
SASSERT(idx < get_num_children());
return static_cast<sexpr_composite const *>(this)->m_children[idx];
}
sexpr * const * sexpr::get_children() const {
SASSERT(is_composite());
return static_cast<sexpr_composite const *>(this)->m_children;
}
void sexpr::display_atom(std::ostream & out) const {
switch (get_kind()) {
case sexpr::COMPOSITE:
UNREACHABLE();
case sexpr::NUMERAL:
out << static_cast<sexpr_numeral const *>(this)->m_val;
break;
case sexpr::BV_NUMERAL: {
out << '#';
unsigned bv_size = static_cast<sexpr_bv const *>(this)->m_size;
rational val = static_cast<sexpr_bv const *>(this)->m_val;
sbuffer<char> buf;
unsigned sz = 0;
if (bv_size % 4 == 0) {
out << 'x';
while (val.is_pos()) {
rational c = val % rational(16);
val = div(val, rational(16));
SASSERT(rational(0) <= c && c < rational(16));
if (c <= rational(9))
buf.push_back('0' + c.get_unsigned());
else
buf.push_back('a' + (c.get_unsigned() - 10));
sz+=4;
}
while (sz < bv_size) {
buf.push_back('0');
sz+=4;
}
}
else {
out << 'b';
while (val.is_pos()) {
rational c = val % rational(2);
val = div(val, rational(2));
SASSERT(rational(0) <= c && c < rational(2));
if (c.is_zero())
buf.push_back('0');
else
buf.push_back('1');
sz += 1;
}
while (sz < bv_size) {
buf.push_back('0');
sz += 1;
}
}
std::reverse(buf.begin(), buf.end());
buf.push_back(0);
out << buf.c_ptr();
break;
}
case sexpr::STRING:
out << "\"" << escaped(static_cast<sexpr_string const *>(this)->m_val.c_str()) << "\"";
break;
case sexpr::SYMBOL:
case sexpr::KEYWORD:
out << static_cast<sexpr_symbol const *>(this)->m_val;
break;
default:
UNREACHABLE();
}
}
void sexpr::display(std::ostream & out) const {
if (!is_composite())
display_atom(out);
vector<std::pair<sexpr_composite const *, unsigned> > todo;
todo.push_back(std::make_pair(static_cast<sexpr_composite const *>(this), 0));
while (!todo.empty()) {
loop:
sexpr_composite const * n = todo.back().first;
unsigned & idx = todo.back().second;
unsigned num = n->get_num_children();
while (idx < num) {
sexpr const * child = n->get_child(idx);
if (idx == 0)
out << "(";
else
out << " ";
idx++;
if (child->is_composite()) {
todo.push_back(std::make_pair(static_cast<sexpr_composite const *>(child), 0));
goto loop;
}
else {
child->display_atom(out);
}
}
out << ")";
todo.pop_back();
}
}
void sexpr_manager::del(sexpr * n) {
m_to_delete.push_back(n);
while (!m_to_delete.empty()) {
sexpr * n = m_to_delete.back();
m_to_delete.pop_back();
switch (n->get_kind()) {
case sexpr::COMPOSITE: {
unsigned num = n->get_num_children();
for (unsigned i = 0; i < num; i++) {
sexpr * child = n->get_child(i);
SASSERT(child->m_ref_count > 0);
child->m_ref_count--;
if (child->m_ref_count == 0)
m_to_delete.push_back(child);
}
static_cast<sexpr_composite*>(n)->~sexpr_composite();
m_allocator.deallocate(sizeof(sexpr_composite) + num * sizeof(sexpr*), n);
break;
}
case sexpr::NUMERAL:
static_cast<sexpr_numeral*>(n)->~sexpr_numeral();
m_allocator.deallocate(sizeof(sexpr_numeral), n);
break;
case sexpr::BV_NUMERAL:
static_cast<sexpr_bv*>(n)->~sexpr_bv();
m_allocator.deallocate(sizeof(sexpr_bv), n);
break;
case sexpr::STRING:
static_cast<sexpr_string*>(n)->~sexpr_string();
m_allocator.deallocate(sizeof(sexpr_string), n);
break;
case sexpr::SYMBOL:
case sexpr::KEYWORD:
static_cast<sexpr_symbol*>(n)->~sexpr_symbol();
m_allocator.deallocate(sizeof(sexpr_symbol), n);
break;
default:
UNREACHABLE();
}
}
}
sexpr_manager::sexpr_manager():
m_allocator("sexpr-manager") {
}
sexpr * sexpr_manager::mk_composite(unsigned num_children, sexpr * const * children, unsigned line, unsigned pos) {
void * mem = m_allocator.allocate(sizeof(sexpr_composite) + num_children * sizeof(sexpr*));
return new (mem) sexpr_composite(num_children, children, line, pos);
}
sexpr * sexpr_manager::mk_numeral(rational const & val, unsigned line, unsigned pos) {
return new (m_allocator.allocate(sizeof(sexpr_numeral))) sexpr_numeral(val, line, pos);
}
sexpr * sexpr_manager::mk_bv_numeral(rational const & val, unsigned bv_size, unsigned line, unsigned pos) {
return new (m_allocator.allocate(sizeof(sexpr_bv))) sexpr_bv(val, bv_size, line, pos);
}
sexpr * sexpr_manager::mk_string(std::string const & val, unsigned line, unsigned pos) {
return new (m_allocator.allocate(sizeof(sexpr_string))) sexpr_string(val, line, pos);
}
sexpr * sexpr_manager::mk_string(char const * val, unsigned line, unsigned pos) {
return new (m_allocator.allocate(sizeof(sexpr_string))) sexpr_string(val, line, pos);
}
sexpr * sexpr_manager::mk_keyword(symbol const & val, unsigned line, unsigned pos) {
return new (m_allocator.allocate(sizeof(sexpr_symbol))) sexpr_symbol(true, val, line, pos);
}
sexpr * sexpr_manager::mk_symbol(symbol const & val, unsigned line, unsigned pos) {
return new (m_allocator.allocate(sizeof(sexpr_symbol))) sexpr_symbol(false, val, line, pos);
}
| 30.530822 | 115 | 0.579248 | oslab-swrc |
d35c8e3ba7c5010219d211d66032fc183eafb3a6 | 7,551 | cc | C++ | src/pf_manager.cc | jinzy15/CourseDataBaseTHU | af3a9abc1d887c674064ab823c4b9a1dcb810630 | [
"MIT"
] | 190 | 2015-01-08T14:26:25.000Z | 2022-03-21T17:43:52.000Z | src/pf_manager.cc | jinzy15/CourseDataBaseTHU | af3a9abc1d887c674064ab823c4b9a1dcb810630 | [
"MIT"
] | 4 | 2018-11-07T17:42:31.000Z | 2018-11-22T16:23:17.000Z | src/pf_manager.cc | jinzy15/CourseDataBaseTHU | af3a9abc1d887c674064ab823c4b9a1dcb810630 | [
"MIT"
] | 91 | 2015-01-07T08:13:38.000Z | 2022-03-10T04:35:44.000Z | //
// File: pf_manager.cc
// Description: PF_Manager class implementation
// Authors: Hugo Rivero (rivero@cs.stanford.edu)
// Dallan Quass (quass@cs.stanford.edu)
//
#include <cstdio>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "pf_internal.h"
#include "pf_buffermgr.h"
//
// PF_Manager
//
// Desc: Constructor - intended to be called once at begin of program
// Handles creation, deletion, opening and closing of files.
// It is associated with a PF_BufferMgr that manages the page
// buffer and executes the page replacement policies.
//
PF_Manager::PF_Manager()
{
// Create Buffer Manager
pBufferMgr = new PF_BufferMgr(PF_BUFFER_SIZE);
}
//
// ~PF_Manager
//
// Desc: Destructor - intended to be called once at end of program
// Destroys the buffer manager.
// All files are expected to be closed when this method is called.
//
PF_Manager::~PF_Manager()
{
// Destroy the buffer manager objects
delete pBufferMgr;
}
//
// CreateFile
//
// Desc: Create a new PF file named fileName
// In: fileName - name of file to create
// Ret: PF return code
//
RC PF_Manager::CreateFile (const char *fileName)
{
int fd; // unix file descriptor
int numBytes; // return code form write syscall
// Create file for exclusive use
if ((fd = open(fileName,
#ifdef PC
O_BINARY |
#endif
O_CREAT | O_EXCL | O_WRONLY,
CREATION_MASK)) < 0)
return (PF_UNIX);
// Initialize the file header: must reserve FileHdrSize bytes in memory
// though the actual size of FileHdr is smaller
char hdrBuf[PF_FILE_HDR_SIZE];
// So that Purify doesn't complain
memset(hdrBuf, 0, PF_FILE_HDR_SIZE);
PF_FileHdr *hdr = (PF_FileHdr*)hdrBuf;
hdr->firstFree = PF_PAGE_LIST_END;
hdr->numPages = 0;
// Write header to file
if((numBytes = write(fd, hdrBuf, PF_FILE_HDR_SIZE))
!= PF_FILE_HDR_SIZE) {
// Error while writing: close and remove file
close(fd);
unlink(fileName);
// Return an error
if(numBytes < 0)
return (PF_UNIX);
else
return (PF_HDRWRITE);
}
// Close file
if(close(fd) < 0)
return (PF_UNIX);
// Return ok
return (0);
}
//
// DestroyFile
//
// Desc: Delete a PF file named fileName (fileName must exist and not be open)
// In: fileName - name of file to delete
// Ret: PF return code
//
RC PF_Manager::DestroyFile (const char *fileName)
{
// Remove the file
if (unlink(fileName) < 0)
return (PF_UNIX);
// Return ok
return (0);
}
//
// OpenFile
//
// Desc: Open the paged file whose name is "fileName". It is possible to open
// a file more than once, however, it will be treated as 2 separate files
// (different file descriptors; different buffers). Thus, opening a file
// more than once for writing may corrupt the file, and can, in certain
// circumstances, crash the PF layer. Note that even if only one instance
// of a file is for writing, problems may occur because some writes may
// not be seen by a reader of another instance of the file.
// In: fileName - name of file to open
// Out: fileHandle - refer to the open file
// this function modifies local var's in fileHandle
// to point to the file data in the file table, and to point to the
// buffer manager object
// Ret: PF_FILEOPEN or other PF return code
//
RC PF_Manager::OpenFile (const char *fileName, PF_FileHandle &fileHandle)
{
int rc; // return code
// Ensure file is not already open
if (fileHandle.bFileOpen)
return (PF_FILEOPEN);
// Open the file
if ((fileHandle.unixfd = open(fileName,
#ifdef PC
O_BINARY |
#endif
O_RDWR)) < 0)
return (PF_UNIX);
// Read the file header
{
int numBytes = read(fileHandle.unixfd, (char *)&fileHandle.hdr,
sizeof(PF_FileHdr));
if (numBytes != sizeof(PF_FileHdr)) {
rc = (numBytes < 0) ? PF_UNIX : PF_HDRREAD;
goto err;
}
}
// Set file header to be not changed
fileHandle.bHdrChanged = FALSE;
// Set local variables in file handle object to refer to open file
fileHandle.pBufferMgr = pBufferMgr;
fileHandle.bFileOpen = TRUE;
// Return ok
return 0;
err:
// Close file
close(fileHandle.unixfd);
fileHandle.bFileOpen = FALSE;
// Return error
return (rc);
}
//
// CloseFile
//
// Desc: Close file associated with fileHandle
// The file should have been opened with OpenFile().
// Also, flush all pages for the file from the page buffer
// It is an error to close a file with pages still fixed in the buffer.
// In: fileHandle - handle of file to close
// Out: fileHandle - no longer refers to an open file
// this function modifies local var's in fileHandle
// Ret: PF return code
//
RC PF_Manager::CloseFile(PF_FileHandle &fileHandle)
{
RC rc;
// Ensure fileHandle refers to open file
if (!fileHandle.bFileOpen)
return (PF_CLOSEDFILE);
// Flush all buffers for this file and write out the header
if ((rc = fileHandle.FlushPages()))
return (rc);
// Close the file
if (close(fileHandle.unixfd) < 0)
return (PF_UNIX);
fileHandle.bFileOpen = FALSE;
// Reset the buffer manager pointer in the file handle
fileHandle.pBufferMgr = NULL;
// Return ok
return 0;
}
//
// ClearBuffer
//
// Desc: Remove all entries from the buffer manager.
// This routine will be called via the system command and is only
// really useful if the user wants to run some performance
// comparison starting with an clean buffer.
// In: Nothing
// Out: Nothing
// Ret: Returns the result of PF_BufferMgr::ClearBuffer
// It is a code: 0 for success, something else for a PF error.
//
RC PF_Manager::ClearBuffer()
{
return pBufferMgr->ClearBuffer();
}
//
// PrintBuffer
//
// Desc: Display all of the pages within the buffer.
// This routine will be called via the system command.
// In: Nothing
// Out: Nothing
// Ret: Returns the result of PF_BufferMgr::PrintBuffer
// It is a code: 0 for success, something else for a PF error.
//
RC PF_Manager::PrintBuffer()
{
return pBufferMgr->PrintBuffer();
}
//
// ResizeBuffer
//
// Desc: Resizes the buffer manager to the size passed in.
// This routine will be called via the system command.
// In: The new buffer size
// Out: Nothing
// Ret: Returns the result of PF_BufferMgr::ResizeBuffer
// It is a code: 0 for success, PF_TOOSMALL when iNewSize
// would be too small.
//
RC PF_Manager::ResizeBuffer(int iNewSize)
{
return pBufferMgr->ResizeBuffer(iNewSize);
}
//------------------------------------------------------------------------------
// Three Methods for manipulating raw memory buffers. These memory
// locations are handled by the buffer manager, but are not
// associated with a particular file. These should be used if you
// want memory that is bounded by the size of the buffer pool.
//
// The PF_Manager just passes the calls down to the Buffer manager.
//------------------------------------------------------------------------------
RC PF_Manager::GetBlockSize(int &length) const
{
return pBufferMgr->GetBlockSize(length);
}
RC PF_Manager::AllocateBlock(char *&buffer)
{
return pBufferMgr->AllocateBlock(buffer);
}
RC PF_Manager::DisposeBlock(char *buffer)
{
return pBufferMgr->DisposeBlock(buffer);
}
| 26.588028 | 80 | 0.649186 | jinzy15 |
d35f6cd973ec7a2b3bdab72b31db67f7fb5e4a5c | 680 | hpp | C++ | Object.hpp | Xiangze-Li/CG_Final | 6dc33457d6890e6cff8e327b004f76e9ed7d9615 | [
"MIT"
] | 2 | 2020-07-22T01:56:41.000Z | 2022-01-08T14:59:40.000Z | Object.hpp | Xiangze-Li/CG_Final | 6dc33457d6890e6cff8e327b004f76e9ed7d9615 | [
"MIT"
] | null | null | null | Object.hpp | Xiangze-Li/CG_Final | 6dc33457d6890e6cff8e327b004f76e9ed7d9615 | [
"MIT"
] | 1 | 2021-08-04T05:03:26.000Z | 2021-08-04T05:03:26.000Z | #pragma once
#include "utils.hpp"
#include "Texture.hpp"
#include "Ray.hpp"
#include "Hit.hpp"
class Object
{
protected:
Texture *_texture;
public:
Object() : _texture(nullptr) {}
explicit Object(Texture *texture) : _texture(texture) {}
virtual ~Object() = default;
virtual bool intersect(const Ray &, Hit &) const = 0;
// @return GUARANTEE that first.x/y/z < second.x/y/z respectively.
virtual AABBcord AABB() const = 0;
Texture *texture() const { return _texture; }
};
#include "Obj_Geometry.hpp"
#include "Obj_BVH.hpp"
#include "Obj_Mesh.hpp"
#include "Obj_Group.hpp"
// #include "Obj_Bezier.hpp" CANCELLED
| 21.935484 | 72 | 0.648529 | Xiangze-Li |
d364a37c6cf138a55b515836bb987dba37474cb7 | 575 | cpp | C++ | tools/clang/test/CXX/lex/lex.literal/lex.ext/p5.cpp | clayne/DirectXShaderCompiler | 0ef9b702890b1d45f0bec5fa75481290323e14dc | [
"NCSA"
] | 1,192 | 2017-01-23T23:27:01.000Z | 2019-05-05T14:08:40.000Z | tools/clang/test/CXX/lex/lex.literal/lex.ext/p5.cpp | clayne/DirectXShaderCompiler | 0ef9b702890b1d45f0bec5fa75481290323e14dc | [
"NCSA"
] | 2,214 | 2019-05-06T22:22:53.000Z | 2022-03-31T19:38:50.000Z | tools/clang/test/CXX/lex/lex.literal/lex.ext/p5.cpp | clayne/DirectXShaderCompiler | 0ef9b702890b1d45f0bec5fa75481290323e14dc | [
"NCSA"
] | 269 | 2019-05-07T11:59:04.000Z | 2022-03-30T08:41:50.000Z | // RUN: %clang_cc1 -fsyntax-only -std=c++11 -verify %s -triple=x86_64-linux-gnu
using size_t = decltype(sizeof(int));
int &operator "" _x1 (const char *);
double &operator "" _x1 (const char *, size_t);
double &i1 = "foo"_x1;
double &i2 = u8"foo"_x1;
double &i3 = L"foo"_x1; // expected-error {{no matching literal operator for call to 'operator "" _x1' with arguments of types 'const wchar_t *' and 'unsigned long'}}
char &operator "" _x1(const wchar_t *, size_t);
char &i4 = L"foo"_x1; // ok
double &i5 = R"(foo)"_x1; // ok
double &i6 = u\
8\
R\
"(foo)"\
_\
x\
1; // ok
| 27.380952 | 166 | 0.648696 | clayne |
d36606f218f0a139490b7efa4cfa186372a5018e | 5,637 | cpp | C++ | unicode_back/character_categories/other_format.cpp | do-m-en/random_regex_string | 7ded2dcf7c03122a68e66b5db6f94403e8c9c690 | [
"BSL-1.0"
] | null | null | null | unicode_back/character_categories/other_format.cpp | do-m-en/random_regex_string | 7ded2dcf7c03122a68e66b5db6f94403e8c9c690 | [
"BSL-1.0"
] | null | null | null | unicode_back/character_categories/other_format.cpp | do-m-en/random_regex_string | 7ded2dcf7c03122a68e66b5db6f94403e8c9c690 | [
"BSL-1.0"
] | null | null | null | #include "other_format.hpp"
namespace {
constexpr std::pair<char32_t, char32_t> make_point(char32_t point)
{
return std::pair<char32_t, char32_t>(point, point);
}
static const std::vector<std::pair<char32_t, char32_t>> characters
{
make_point(0xAD),
{0x600, 0x605},
make_point(0x61C),
make_point(0x6DD),
make_point(0x70F),
make_point(0x180E),
{0x200B, 0x200F},
{0x202A, 0x202E},
{0x2060, 0x2064},
{0x2066, 0x206F},
make_point(0xFEFF),
{0xFFF9, 0xFFFB},
make_point(0x110BD),
{0x1BCA0, 0x1BCA3},
{0x1D173, 0x1D17A},
make_point(0xE0001),
{0xE0020, 0xE007F}
};
}
/*
Character Name
U+00AD SOFT HYPHEN
U+0600 ARABIC NUMBER SIGN
U+0601 ARABIC SIGN SANAH
U+0602 ARABIC FOOTNOTE MARKER
U+0603 ARABIC SIGN SAFHA
U+0604 ARABIC SIGN SAMVAT
U+0605 ARABIC NUMBER MARK ABOVE
U+061C ARABIC LETTER MARK
U+06DD ARABIC END OF AYAH
U+070F SYRIAC ABBREVIATION MARK
U+180E MONGOLIAN VOWEL SEPARATOR
U+200B ZERO WIDTH SPACE
U+200C ZERO WIDTH NON-JOINER
U+200D ZERO WIDTH JOINER
U+200E LEFT-TO-RIGHT MARK
U+200F RIGHT-TO-LEFT MARK
U+202A LEFT-TO-RIGHT EMBEDDING
U+202B RIGHT-TO-LEFT EMBEDDING
U+202C POP DIRECTIONAL FORMATTING
U+202D LEFT-TO-RIGHT OVERRIDE
U+202E RIGHT-TO-LEFT OVERRIDE
U+2060 WORD JOINER
U+2061 FUNCTION APPLICATION
U+2062 INVISIBLE TIMES
U+2063 INVISIBLE SEPARATOR
U+2064 INVISIBLE PLUS
U+2066 LEFT-TO-RIGHT ISOLATE
U+2067 RIGHT-TO-LEFT ISOLATE
U+2068 FIRST STRONG ISOLATE
U+2069 POP DIRECTIONAL ISOLATE
U+206A INHIBIT SYMMETRIC SWAPPING
U+206B ACTIVATE SYMMETRIC SWAPPING
U+206C INHIBIT ARABIC FORM SHAPING
U+206D ACTIVATE ARABIC FORM SHAPING
U+206E NATIONAL DIGIT SHAPES
U+206F NOMINAL DIGIT SHAPES
U+FEFF ZERO WIDTH NO-BREAK SPACE
U+FFF9 INTERLINEAR ANNOTATION ANCHOR
U+FFFA INTERLINEAR ANNOTATION SEPARATOR
U+FFFB INTERLINEAR ANNOTATION TERMINATOR
U+110BD KAITHI NUMBER SIGN
U+1BCA0 SHORTHAND FORMAT LETTER OVERLAP
U+1BCA1 SHORTHAND FORMAT CONTINUING OVERLAP
U+1BCA2 SHORTHAND FORMAT DOWN STEP
U+1BCA3 SHORTHAND FORMAT UP STEP
U+1D173 MUSICAL SYMBOL BEGIN BEAM
U+1D174 MUSICAL SYMBOL END BEAM
U+1D175 MUSICAL SYMBOL BEGIN TIE
U+1D176 MUSICAL SYMBOL END TIE
U+1D177 MUSICAL SYMBOL BEGIN SLUR
U+1D178 MUSICAL SYMBOL END SLUR
U+1D179 MUSICAL SYMBOL BEGIN PHRASE
U+1D17A MUSICAL SYMBOL END PHRASE
U+E0001 LANGUAGE TAG
U+E0020 TAG SPACE
U+E0021 TAG EXCLAMATION MARK
U+E0022 TAG QUOTATION MARK
U+E0023 TAG NUMBER SIGN
U+E0024 TAG DOLLAR SIGN
U+E0025 TAG PERCENT SIGN
U+E0026 TAG AMPERSAND
U+E0027 TAG APOSTROPHE
U+E0028 TAG LEFT PARENTHESIS
U+E0029 TAG RIGHT PARENTHESIS
U+E002A TAG ASTERISK
U+E002B TAG PLUS SIGN
U+E002C TAG COMMA
U+E002D TAG HYPHEN-MINUS
U+E002E TAG FULL STOP
U+E002F TAG SOLIDUS
U+E0030 TAG DIGIT ZERO
U+E0031 TAG DIGIT ONE
U+E0032 TAG DIGIT TWO
U+E0033 TAG DIGIT THREE
U+E0034 TAG DIGIT FOUR
U+E0035 TAG DIGIT FIVE
U+E0036 TAG DIGIT SIX
U+E0037 TAG DIGIT SEVEN
U+E0038 TAG DIGIT EIGHT
U+E0039 TAG DIGIT NINE
U+E003A TAG COLON
U+E003B TAG SEMICOLON
U+E003C TAG LESS-THAN SIGN
U+E003D TAG EQUALS SIGN
U+E003E TAG GREATER-THAN SIGN
U+E003F TAG QUESTION MARK
U+E0040 TAG COMMERCIAL AT
U+E0041 TAG LATIN CAPITAL LETTER A
U+E0042 TAG LATIN CAPITAL LETTER B
U+E0043 TAG LATIN CAPITAL LETTER C
U+E0044 TAG LATIN CAPITAL LETTER D
U+E0045 TAG LATIN CAPITAL LETTER E
U+E0046 TAG LATIN CAPITAL LETTER F
U+E0047 TAG LATIN CAPITAL LETTER G
U+E0048 TAG LATIN CAPITAL LETTER H
U+E0049 TAG LATIN CAPITAL LETTER I
U+E004A TAG LATIN CAPITAL LETTER J
U+E004B TAG LATIN CAPITAL LETTER K
U+E004C TAG LATIN CAPITAL LETTER L
U+E004D TAG LATIN CAPITAL LETTER M
U+E004E TAG LATIN CAPITAL LETTER N
U+E004F TAG LATIN CAPITAL LETTER O
U+E0050 TAG LATIN CAPITAL LETTER P
U+E0051 TAG LATIN CAPITAL LETTER Q
U+E0052 TAG LATIN CAPITAL LETTER R
U+E0053 TAG LATIN CAPITAL LETTER S
U+E0054 TAG LATIN CAPITAL LETTER T
U+E0055 TAG LATIN CAPITAL LETTER U
U+E0056 TAG LATIN CAPITAL LETTER V
U+E0057 TAG LATIN CAPITAL LETTER W
U+E0058 TAG LATIN CAPITAL LETTER X
U+E0059 TAG LATIN CAPITAL LETTER Y
U+E005A TAG LATIN CAPITAL LETTER Z
U+E005B TAG LEFT SQUARE BRACKET
U+E005C TAG REVERSE SOLIDUS
U+E005D TAG RIGHT SQUARE BRACKET
U+E005E TAG CIRCUMFLEX ACCENT
U+E005F TAG LOW LINE
U+E0060 TAG GRAVE ACCENT
U+E0061 TAG LATIN SMALL LETTER A
U+E0062 TAG LATIN SMALL LETTER B
U+E0063 TAG LATIN SMALL LETTER C
U+E0064 TAG LATIN SMALL LETTER D
U+E0065 TAG LATIN SMALL LETTER E
U+E0066 TAG LATIN SMALL LETTER F
U+E0067 TAG LATIN SMALL LETTER G
U+E0068 TAG LATIN SMALL LETTER H
U+E0069 TAG LATIN SMALL LETTER I
U+E006A TAG LATIN SMALL LETTER J
U+E006B TAG LATIN SMALL LETTER K
U+E006C TAG LATIN SMALL LETTER L
U+E006D TAG LATIN SMALL LETTER M
U+E006E TAG LATIN SMALL LETTER N
U+E006F TAG LATIN SMALL LETTER O
U+E0070 TAG LATIN SMALL LETTER P
U+E0071 TAG LATIN SMALL LETTER Q
U+E0072 TAG LATIN SMALL LETTER R
U+E0073 TAG LATIN SMALL LETTER S
U+E0074 TAG LATIN SMALL LETTER T
U+E0075 TAG LATIN SMALL LETTER U
U+E0076 TAG LATIN SMALL LETTER V
U+E0077 TAG LATIN SMALL LETTER W
U+E0078 TAG LATIN SMALL LETTER X
U+E0079 TAG LATIN SMALL LETTER Y
U+E007A TAG LATIN SMALL LETTER Z
U+E007B TAG LEFT CURLY BRACKET
U+E007C TAG VERTICAL LINE
U+E007D TAG RIGHT CURLY BRACKET
U+E007E TAG TILDE
U+E007F CANCEL TAG
*/
| 30.47027 | 68 | 0.716516 | do-m-en |
d36ba80beac40a29838f3c999c22bc47f59d9e0f | 27,903 | cpp | C++ | point_cloud/pcl/applications/points-pcl-calc.cpp | mission-systems-pty-ltd/snark | 2bc8a20292ee3684d3a9897ba6fee43fed8d89ae | [
"BSD-3-Clause"
] | 63 | 2015-01-14T14:38:02.000Z | 2022-02-01T09:56:03.000Z | point_cloud/pcl/applications/points-pcl-calc.cpp | NEU-LC/snark | db890f73f4c4bbe679405f3a607fd9ea373deb2c | [
"BSD-3-Clause"
] | 39 | 2015-01-21T00:57:38.000Z | 2020-04-22T04:22:35.000Z | point_cloud/pcl/applications/points-pcl-calc.cpp | NEU-LC/snark | db890f73f4c4bbe679405f3a607fd9ea373deb2c | [
"BSD-3-Clause"
] | 36 | 2015-01-15T04:17:14.000Z | 2022-02-17T17:13:35.000Z | // This file is part of snark, a generic and flexible library for robotics research
// Copyright (c) 2017 The University of Sydney
// 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 University of Sydney nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE
// GRANTED BY THIS LICENSE. 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.
/// @author Navid Pirmarzdashti
// #define PCL_NO_PRECOMPILE
#include <comma/application/command_line_options.h>
#include <comma/application/verbose.h>
#include <comma/csv/options.h>
#include <comma/csv/ascii.h>
#include <comma/csv/stream.h>
#include <comma/csv/traits.h>
#include <comma/name_value/parser.h>
#include <iostream>
#include <vector>
#include <unordered_map>
#include <fstream>
#include <Eigen/Core>
#include "../../../visiting/eigen.h"
#include <pcl/point_types.h>
#include <pcl/search/search.h>
#include <pcl/search/kdtree.h>
#include <pcl/features/normal_3d.h>
#include <pcl/segmentation/region_growing.h>
#include <pcl/registration/icp.h>
#include <pcl/filters/statistical_outlier_removal.h>
static void usage(bool detail)
{
std::cerr<<" points pcl calc operations" << std::endl;
std::cerr << std::endl;
std::cerr<< "usage: " << comma::verbose.app_name() << " <operation> [ <options> ]" << std::endl;
std::cerr << std::endl;
std::cerr<< "operations:"<< std::endl;
std::cerr<< " region-growing-segmentation"<< std::endl;
std::cerr<< " normal-estimator"<< std::endl;
std::cerr<< " statistical-outlier"<< std::endl;
std::cerr<< " iterative-closest-point"<< std::endl;
std::cerr << std::endl;
std::cerr << "options:" << std::endl;
std::cerr << " --help,-h: show help" << std::endl;
std::cerr << " --verbose,-v: show detailed messages" << std::endl;
std::cerr << " --input-fields: print input fields and exit"<<std::endl;
std::cerr << " --input-format: print input format and exit"<<std::endl;
std::cerr << " --output-fields: print output fields and exit"<<std::endl;
std::cerr << " --output-format: print output format and exit"<<std::endl;
std::cerr << std::endl;
std::cerr<< "region-growing-segmentation"<< std::endl;
std::cerr<< " fields: block,point/x,point/y,point/z,normal/x,normal/y,normal/z,normal/curvature"<< std::endl;
std::cerr<< " output: <input>,id"<< std::endl;
std::cerr<< " options:"<< std::endl;
std::cerr << " --min-cluster-size=<n>: the minimum number of points that a cluster needs to contain in order to be considered valid; default: 50"<< std::endl;
std::cerr << " --max-cluster-size=<n>: the maximum number of points that a cluster needs to contain in order to be considered valid; default 1000000"<< std::endl;
std::cerr << " --number-of-neighbours=<n>: number of nearest neighbours used for KNN (k-nearest neighbours search); default: 30"<< std::endl;
std::cerr << " --smoothness-threshold=<f>: smoothness threshold used for testing the points; default: "<<3.0 / 180.0 * M_PI<< std::endl;
std::cerr << " --curvature-threshold=<f>: residual threshold used for testing the points; default: 1.0"<< std::endl;
std::cerr << " --discard: discard points with invalid cluster, when not specified all points will be written to output, invalid points with id=0"<< std::endl;
std::cerr << std::endl;
std::cerr<< "normal-estimator"<< std::endl;
std::cerr<< " fields: block,point/x,point/y,point/z"<< std::endl;
std::cerr<< " output: <input>,x,y,z,curvature"<< std::endl;
std::cerr<< " options:"<< std::endl;
std::cerr << " --k,--k-neighbours=<n>: number of k nearest neighbors to use for the feature estimation; default: 50"<< std::endl;
std::cerr << std::endl;
std::cerr<< "statistical-outlier"<< std::endl;
std::cerr<< " fields: block,point/x,point/y,point/z"<< std::endl;
std::cerr<< " output: block,point/x,point/y,point/z"<< std::endl;
std::cerr<< " options:"<< std::endl;
std::cerr << " -k,--k-mean=<n>: number of k nearest neighbors analyze; default: 50"<< std::endl;
std::cerr << " --s,--stddev=<d>: standard deviation; default 1"<< std::endl;
std::cerr << std::endl;
std::cerr<< "iterative-closest-point"<< std::endl;
std::cerr << std::endl;
std::cerr<< " WARNING: work in progress, output format subject to change. talk to authors if you need to use icp operation"<< std::endl;
std::cerr << std::endl;
std::cerr<< " second point cloud file is passed as unnamed option"<< std::endl;
std::cerr<< " fields: block,point/x,point/y,point/z"<< std::endl;
std::cerr<< " output: <input>,matrix[16]: 4x4 affine transformation matrix"<< std::endl;
std::cerr<< " options:"<< std::endl;
std::cerr << " --iterations=<n>: maximum number of iterations; the algorithm will stop after this many iterations even if it has not converged; default 100"<< std::endl;
std::cerr << " --transformation-epsilon=<d>: distance threshold; if distance between two correspondent points is larger than this, the points will not be used for aligning"<< std::endl;
std::cerr << " --max-correspondence-distance=<d>: transformations epsilon for convergence ; if difference between two consecutive transformations are less than this, the algorithm will stop"<< std::endl;
std::cerr << " --euclidean-fitness-epsilon=<d>: error epsilon for convergence; if average Euclidean distance of points is less than this, the algorithm will stop"<< std::endl;
std::cerr << std::endl;
if(detail)
{
std::cerr << "csv options:" << std::endl;
std::cerr<< comma::csv::options::usage() << std::endl;
}
else
{
std::cerr << "use -v or --verbose to see more detail" << std::endl;
}
std::cerr << std::endl;
std::cerr << "examples" << std::endl;
std::cerr<< " cat points.csv | "<<comma::verbose.app_name()<<" normal-estimator | "<<comma::verbose.app_name()<<" region-growing-segmentation " << std::endl;
std::cerr << std::endl;
std::cerr<< " cat points1.csv | "<<comma::verbose.app_name()<<" iterative-closest-point points2.csv" << std::endl;
std::cerr << std::endl;
}
struct input_point
{
std::uint32_t block;
pcl::PointXYZ point;
input_point() : block(0) { }
};
struct input_point_normal
{
std::uint32_t block;
pcl::PointXYZ point;
pcl::Normal normal;
input_point_normal() : block(0) { }
};
struct segmentation_output
{
std::uint32_t id;
segmentation_output(std::uint32_t id=0) : id(id) { }
};
struct icp_output
{
pcl::Registration<pcl::PointXYZ,pcl::PointXYZ>::Matrix4 transformation;
};
namespace comma { namespace visiting {
template <> struct traits< pcl::PointXYZ >
{
template< typename K, typename V > static void visit( const K& k, pcl::PointXYZ& p, V& v )
{
v.apply( "x", p.x );
v.apply( "y", p.y );
v.apply( "z", p.z );
}
template< typename K, typename V > static void visit( const K& k, const pcl::PointXYZ& p, V& v )
{
v.apply( "x", p.x );
v.apply( "y", p.y );
v.apply( "z", p.z );
}
};
template <> struct traits< pcl::Normal >
{
template< typename K, typename V > static void visit( const K& k, pcl::Normal& p, V& v )
{
v.apply( "x", p.normal_x );
v.apply( "y", p.normal_y );
v.apply( "z", p.normal_z );
v.apply( "curvature", p.curvature );
}
template< typename K, typename V > static void visit( const K& k, const pcl::Normal& p, V& v )
{
v.apply( "x", p.normal_x );
v.apply( "y", p.normal_y );
v.apply( "z", p.normal_z );
v.apply( "curvature", p.curvature );
}
};
template <> struct traits< input_point >
{
template< typename K, typename V > static void visit( const K& k, input_point& p, V& v )
{
v.apply( "block", p.block );
v.apply( "point", p.point );
}
template< typename K, typename V > static void visit( const K& k, const input_point& p, V& v )
{
v.apply( "block", p.block );
v.apply( "point", p.point );
}
};
template <> struct traits< input_point_normal >
{
template< typename K, typename V > static void visit( const K& k, input_point_normal& p, V& v )
{
v.apply( "block", p.block );
v.apply( "point", p.point );
v.apply( "normal", p.normal );
}
template< typename K, typename V > static void visit( const K& k, const input_point_normal& p, V& v )
{
v.apply( "block", p.block );
v.apply( "point", p.point );
v.apply( "normal", p.normal );
}
};
template <> struct traits< segmentation_output >
{
template< typename K, typename V > static void visit( const K& k, segmentation_output& p, V& v )
{
v.apply( "id", p.id);
}
template< typename K, typename V > static void visit( const K& k, const segmentation_output& p, V& v )
{
v.apply( "id", p.id);
}
};
template <> struct traits< icp_output >
{
template< typename K, typename V > static void visit( const K& k, icp_output& p, V& v )
{
v.apply( "transformation", p.transformation );
}
template< typename K, typename V > static void visit( const K& k, const icp_output& p, V& v )
{
v.apply( "transformation", p.transformation );
}
};
} } // namespace comma { namespace visiting {
class app_i
{
public:
virtual ~app_i() { }
virtual void print_input_fields()=0;
virtual void print_input_format()=0;
virtual void print_output_fields()=0;
virtual void print_output_format()=0;
virtual void run()=0;
};
struct pointXYZ_hash
{
std::size_t operator() ( pcl::PointXYZ const& point ) const
{
std::size_t result = 0;
boost::hash_combine( result, point.x );
boost::hash_combine( result, point.y );
boost::hash_combine( result, point.z );
return result;
}
};
struct pointXYZ_equalto
{
bool operator() ( pcl::PointXYZ const& lhs, pcl::PointXYZ const& rhs ) const
{
return lhs.x == rhs.x
&& lhs.y == rhs.y
&& lhs.z == rhs.z;
}
};
template< typename T, typename S >
class filter_app_t : public app_i
{
public:
typedef T input_t;
typedef S output_t;
protected:
comma::csv::options csv;
std::unordered_map< pcl::PointXYZ, std::string, pointXYZ_hash, pointXYZ_equalto > buffer;
std::size_t reserve;
virtual void clear()=0;
virtual void push_back(const input_t& p)=0;
virtual void process()=0;
//process cloud
virtual void write_output(comma::csv::output_stream<output_t>& os)=0;
public:
filter_app_t(const comma::command_line_options& options) : csv(options)
{
csv.full_xpath=true;
reserve=options.value<std::size_t>("--reserve",10000);
}
virtual void run()
{
input_t default_input;
comma::csv::input_stream<input_t> is( std::cin, csv, default_input);
comma::csv::output_stream<output_t> os(std::cout,csv.binary(),true,csv.flush);
std::uint32_t block=0;
buffer.reserve(reserve);
while( is.ready() || std::cin.good() )
{
const input_t* p=is.read();
if ( (!p || block != p->block ) && buffer.size() )
{
process();
write_output(os);
//reset
buffer.clear();
clear();
}
if(!p){break;}
block=p->block;
buffer.emplace( p->point, is.last() );
push_back(*p);
}
}
void print_input_fields()
{
std::cout<<comma::join( comma::csv::names<input_t>(true), ',' ) << std::endl;
}
void print_input_format()
{
std::cout<<comma::csv::format::value<input_t>() << std::endl;
}
void print_output_fields()
{
std::cout<<comma::join( comma::csv::names<output_t>(true), ',' ) << std::endl;
}
void print_output_format()
{
std::cout<<comma::csv::format::value<output_t>() << std::endl;
}
};
template<typename T,typename S>
class app_t : public app_i
{
public:
typedef T input_t;
typedef S output_t;
protected:
comma::csv::options csv;
input_t default_input;
std::vector<std::string> buffer;
std::size_t reserve;
virtual void clear()=0;
virtual void push_back(const input_t& p)=0;
virtual void process()=0;
//process cloud
virtual void write_output(comma::csv::output_stream<output_t>& os)=0;
public:
app_t(const comma::command_line_options& options) : csv(options)
{
csv.full_xpath=true;
reserve=options.value<std::size_t>("--reserve",10000);
}
virtual void run()
{
comma::csv::input_stream<input_t> is( std::cin, csv, default_input);
comma::csv::output_stream<output_t> os( std::cout, csv.binary(), true, csv.flush );
std::uint32_t block=0;
buffer.reserve(reserve);
while( is.ready() || std::cin.good() )
{
const input_t* p=is.read();
if ( (!p || block != p->block ) && buffer.size() )
{
process();
write_output(os);
//reset
buffer.clear();
clear();
}
if(!p){break;}
block=p->block;
buffer.push_back(is.last());
push_back(*p);
}
}
void print_input_fields()
{
std::cout<<comma::join( comma::csv::names<input_t>(true), ',' ) << std::endl;
}
void print_input_format()
{
std::cout<<comma::csv::format::value<input_t>() << std::endl;
}
void print_output_fields()
{
std::cout<<comma::join( comma::csv::names<output_t>(true), ',' ) << std::endl;
}
void print_output_format()
{
std::cout<<comma::csv::format::value<output_t>() << std::endl;
}
};
struct normal_estimator : public app_t<input_point,pcl::Normal>
{
typename pcl::PointCloud<pcl::PointXYZ>::Ptr cloud;
typename pcl::PointCloud<pcl::Normal> normals;
int k;
normal_estimator(const comma::command_line_options& options) : app_t(options),
cloud(new pcl::PointCloud<pcl::PointXYZ>())
{
k=options.value<int>("--k,--k-neighbours",50);
}
void clear()
{
cloud->clear();
normals.clear();
}
void push_back(const input_t& p)
{
cloud->push_back(p.point);
}
void process()
{
pcl::search::Search<pcl::PointXYZ>::Ptr tree(new pcl::search::KdTree<pcl::PointXYZ>);
pcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> normal_estimator;
normal_estimator.setSearchMethod(tree);
normal_estimator.setInputCloud(cloud);
normal_estimator.setKSearch(k);
normal_estimator.compute(normals);
}
void write_output(comma::csv::output_stream<output_t>& os)
{
for(std::size_t i=0;i<buffer.size()&&i<normals.size();i++)
{
os.append(buffer[i],normals[i]);
}
}
};
struct statistical_outlier : public filter_app_t<input_point,input_point>
{
typename pcl::PointCloud<pcl::PointXYZ>::Ptr cloud;
typename pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_filtered;
using base_type = filter_app_t< input_point, input_point >;
int kmean;
double stddev;
statistical_outlier(const comma::command_line_options& options) : base_type(options),
cloud(new pcl::PointCloud<pcl::PointXYZ>()),
cloud_filtered( new pcl::PointCloud< pcl::PointXYZ>() )
{
kmean=options.value<int>("-k,--k-mean",50);
stddev = options.value< double >( "-s,--stddev", 1.0 );
}
void clear()
{
cloud->clear();
cloud_filtered->clear();
}
void push_back(const input_t& p)
{
cloud->push_back(p.point);
}
void process()
{
pcl::StatisticalOutlierRemoval<pcl::PointXYZ> sor;
sor.setInputCloud (cloud);
sor.setMeanK (kmean);
sor.setStddevMulThresh (1.0);
sor.filter (*cloud_filtered);
}
void write_output(comma::csv::output_stream<output_t>& os)
{
for( auto const& pi : cloud_filtered->points )
{
auto const oi = buffer.find( pi );
if( buffer.end() != oi )
{
std::cout.write( &oi->second[ 0 ], oi->second.size() );
if( !csv.binary() ) { std::cout << "\n"; }
if( csv.flush ) { std::cout.flush(); }
}
}
}
};
struct iterative_closest_point : public app_t<input_point,icp_output>
{
typedef typename pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_ptr;
std::pair<cloud_ptr,cloud_ptr> clouds;
icp_output output;
int iterations;
boost::optional<double> transformation_epsilon;
boost::optional<double> max_correspondence_distance;
boost::optional<double> euclidean_fitness_epsilon;
comma::csv::options second_csv;
iterative_closest_point(const comma::command_line_options& options, const comma::csv::options& second) : app_t(options),
clouds(cloud_ptr(new pcl::PointCloud<pcl::PointXYZ>()),cloud_ptr(new pcl::PointCloud<pcl::PointXYZ>())), second_csv(second)
{
iterations=options.value<int>("--iterations",100);
transformation_epsilon=options.optional<double>("--transformation-epsilon");
max_correspondence_distance=options.optional<double>("--max-correspondence-distance");
euclidean_fitness_epsilon=options.optional<double>("--euclidean-fitness-epsilon");
second_csv.full_xpath=true;
}
void run()
{
comma::csv::input_stream<input_t> is(std::cin,csv,default_input);
std::ifstream ifs(second_csv.filename);
if(!ifs.is_open()) { COMMA_THROW( comma::exception, "failed to open file: "<<second_csv.filename); }
comma::csv::input_stream<input_t> is2(ifs,second_csv);
comma::csv::output_stream<output_t> os(std::cout,csv.binary(),true,csv.flush);
std::uint32_t block=0;
buffer.reserve(reserve);
bool read1=is.ready() || std::cin.good();
bool read2=is2.ready() || ifs.good();
const input_t* p1=NULL;
const input_t* p2=NULL;
while(is.ready() || std::cin.good() || is2.ready() || ifs.good())
{
if(read1)
{
p1=is.read();
if(!p1 || block != p1->block) { read1=false; }
}
if(read2)
{
p2=is2.read();
if(!p2 || block != p2->block) { read2=false; }
}
if(!read1 && !read2 && buffer.size())
{
process();
write_output(os);
//reset
buffer.clear();
clear();
read1=is.ready() || std::cin.good();
read2=is2.ready() || ifs.good();
}
if(!p1&&!p2){break;}
if(p1)
{
block=p1->block;
buffer.push_back(is.last());
}
push_back(p1,p2);
}
}
void clear()
{
clouds.first->clear();
clouds.second->clear();
output=icp_output();
cloud_registered->clear();
}
void push_back(const input_t& p) { COMMA_THROW(comma::exception,"invalid method called!"); }
void push_back(const input_t* p1,const input_t* p2)
{
if(p1) { clouds.first->push_back(p1->point); }
if(p2) { clouds.second->push_back(p2->point); }
}
cloud_ptr cloud_registered;
void process()
{
pcl::IterativeClosestPoint<pcl::PointXYZ,pcl::PointXYZ> icp;
cloud_registered.reset(new pcl::PointCloud<pcl::PointXYZ>());
icp.setInputSource(clouds.first);
icp.setInputTarget(clouds.second);
icp.setMaximumIterations(iterations);
if(max_correspondence_distance)
{
comma::verbose<<"max_correspondence_distance "<<*max_correspondence_distance<<std::endl;
icp.setMaxCorrespondenceDistance(*max_correspondence_distance);
}
if(transformation_epsilon) { icp.setTransformationEpsilon(*transformation_epsilon); }
if(euclidean_fitness_epsilon) { icp.setEuclideanFitnessEpsilon(*euclidean_fitness_epsilon); }
icp.align(*cloud_registered);
output.transformation=icp.getFinalTransformation();
}
void write_output(comma::csv::output_stream<output_t>& os)
{
for(std::size_t i=0;i<buffer.size();i++)
{
os.append(buffer[i],output);
}
}
};
struct region_growing_segmentation : public app_t<input_point_normal,segmentation_output>
{
typename pcl::PointCloud<pcl::PointXYZ>::Ptr cloud;
typename pcl::PointCloud<pcl::Normal>::Ptr normals;
std::vector<output_t> outputs;
int min_cluster_size;
int max_cluster_size;
unsigned number_of_neighbours;
float smoothness_threshold;
float curvature_threshold;
bool discard;
region_growing_segmentation(const comma::command_line_options& options) : app_t(options),
cloud(new pcl::PointCloud<pcl::PointXYZ>()), normals(new pcl::PointCloud <pcl::Normal>)
{
min_cluster_size=options.value<int>("--min-cluster-size",50);
max_cluster_size=options.value<int>("--max-cluster-size",1000000);
number_of_neighbours=options.value<unsigned>("--number-of-neighbours",30);
smoothness_threshold=options.value<float>("--smoothness-threshold",3.0 / 180.0 * M_PI);
curvature_threshold=options.value<float>("--curvature-threshold",1.0);
discard=options.exists("--discard");
cloud->points.reserve(reserve);
}
void clear()
{
cloud->clear();
normals->clear();
outputs.clear();
}
void push_back(const input_t& p)
{
cloud->push_back(p.point);
normals->push_back(p.normal);
}
void process()
{
std::vector<pcl::PointIndices> clusters;
pcl::search::Search<pcl::PointXYZ>::Ptr tree(new pcl::search::KdTree<pcl::PointXYZ>);
pcl::RegionGrowing<pcl::PointXYZ, pcl::Normal> reg;
// comma::verbose<<"min,max,k "<<min_cluster_size<<" "<<max_cluster_size<<" "<<number_of_neighbours<<std::endl;
reg.setMinClusterSize(min_cluster_size);
reg.setMaxClusterSize(max_cluster_size);
reg.setSearchMethod(tree);
reg.setNumberOfNeighbours(number_of_neighbours);
reg.setInputCloud(cloud);
//reg.setIndices (indices);
reg.setInputNormals(normals);
reg.setSmoothnessThreshold(smoothness_threshold);
reg.setCurvatureThreshold(curvature_threshold);
reg.extract(clusters);
outputs.resize(buffer.size(),segmentation_output(0));
comma::verbose<<"clusters.size() "<<clusters.size()<<" clusters[0].indices.size() "<<clusters[0].indices.size()<<std::endl;
for(std::uint32_t i=0;i<clusters.size();i++)
{
for(auto j : clusters[i].indices)
{
outputs[j].id=i+1;
}
}
}
void write_output(comma::csv::output_stream<output_t>& os)
{
for(std::size_t i=0;i<buffer.size()&&i<outputs.size();i++)
{
if( !discard || outputs[i].id)
{
os.append(buffer[i],outputs[i]);
}
}
}
};
// todo:
// change template parameter to subclass and use T::input_t, T::output_t instead of T and S
// add bash completion
// mkdir points-pcl-calc
// mv app* to points-pcl-calc/app.h or common.h
// normal estimator
// mv to points-pcl-calc/feature.h
// input fields: accept x,y,z translate to point/x ... (see view-points for example)
// region growing segmentation
// mv to points-pcl-calc/segmentation.h
// input fields: accept x,y,z translate to point/x ... (see view-points for example)
// do we need to support point double precision for above? (do we need both float and double, or just double)
// mv icp to points-pcl-calc/registration.h
int main(int argc,char** argv)
{
comma::command_line_options options(argc,argv,usage);
try
{
const std::vector< std::string >& unnamed=options.unnamed( "--verbose,-v,--input-fields,--input-format,--output-fields,--output-format,--discard","-.*" );
if(unnamed.size()<1) { COMMA_THROW( comma::exception, "expected an operation, got none"); }
const std::string& operation=unnamed[0];
std::unique_ptr<app_i> app;
if(operation=="iterative-closest-point")
{
if(unnamed.size()!=2) { COMMA_THROW( comma::exception, "expected one input stream, got "<<unnamed.size()-1<<" "<< comma::join(unnamed,',') ); }
comma::name_value::parser parser("filename",';','=',false);
app.reset(new iterative_closest_point(options,parser.get<comma::csv::options>(unnamed[1])));
}
else
{
if(unnamed.size()!=1) { COMMA_THROW( comma::exception, "expected an operation, got "<<unnamed.size()<<" "<< comma::join(unnamed,',') ); }
if(operation=="region-growing-segmentation")
{
app.reset(new region_growing_segmentation(options));
}
else if(operation=="normal-estimator")
{
app.reset(new normal_estimator(options));
}
else if(operation=="statistical-outlier")
{
app.reset(new statistical_outlier(options));
}
else
{
std::cerr<<comma::verbose.app_name()<<": unrecognized operation "<<operation<<std::endl;
return 1;
}
}
if(options.exists("--input-fields")) { app->print_input_fields(); return 0; }
if(options.exists("--input-format")) { app->print_input_format(); return 0; }
if(options.exists("--output-fields")) { app->print_output_fields(); return 0; }
if(options.exists("--output-format")) { app->print_output_format(); return 0; }
app->run();
return 0;
}
catch( std::exception& ex )
{
std::cerr << comma::verbose.app_name() << ": exception: " << ex.what() << std::endl;
}
catch( ... )
{
std::cerr << comma::verbose.app_name() << ": " << "unknown exception" << std::endl;
}
return 1;
}
| 37.808943 | 213 | 0.6061 | mission-systems-pty-ltd |
d36c891c8cba712fb90e067aa9173c862c8ba09a | 1,003 | cpp | C++ | BOJ/boj10871.cpp | SukJinKim/Algo-Rhythm | db78de61643e9110ff0e721124a744e3b0ae27f0 | [
"MIT"
] | null | null | null | BOJ/boj10871.cpp | SukJinKim/Algo-Rhythm | db78de61643e9110ff0e721124a744e3b0ae27f0 | [
"MIT"
] | null | null | null | BOJ/boj10871.cpp | SukJinKim/Algo-Rhythm | db78de61643e9110ff0e721124a744e3b0ae27f0 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <climits>
#include <algorithm>
using namespace std;
int w[10][10];
int route[10];
int mn = INT_MAX;
int main()
{
int n, tmp, src, dest;
bool possible, necessary;
scanf("%d", &n);
for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) scanf("%d", &w[i][j]);
for(int i = 0; i < n; i++) route[i] = i;
do
{
tmp = 0;
possible = true;
necessary = true;
for(int i = 1; i <= n; i++)
{
src = route[i - 1 % n];
dest = route[i % n];
if(!w[src][dest])
{
possible = false;
break;
}
tmp += w[src][dest];
if(tmp > mn)
{
necessary = false;
break;
}
}
if(!possible || !necessary) continue;
mn = min(mn, tmp);
} while (next_permutation(route, route + n));
printf("%d\n", mn);
return 0;
} | 19.288462 | 82 | 0.401795 | SukJinKim |
d36e937a9dcdf0811fcdb26b65fa1591b5ea25fc | 39 | hpp | C++ | src/boost_numeric_ublas_fwd.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 10 | 2018-03-17T00:58:42.000Z | 2021-07-06T02:48:49.000Z | src/boost_numeric_ublas_fwd.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 2 | 2021-03-26T15:17:35.000Z | 2021-05-20T23:55:08.000Z | src/boost_numeric_ublas_fwd.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 4 | 2019-05-28T21:06:37.000Z | 2021-07-06T03:06:52.000Z | #include <boost/numeric/ublas/fwd.hpp>
| 19.5 | 38 | 0.769231 | miathedev |
d37668c5c67a86224709a7f9157c3b17028e6c1d | 829 | cpp | C++ | Intro_a_C++/codcad-5-questao01.cpp | taylorkcantalice/intro_a_programacao | 141e33f0b6cc227a4cc7b75701b603fcf53e2378 | [
"MIT"
] | null | null | null | Intro_a_C++/codcad-5-questao01.cpp | taylorkcantalice/intro_a_programacao | 141e33f0b6cc227a4cc7b75701b603fcf53e2378 | [
"MIT"
] | null | null | null | Intro_a_C++/codcad-5-questao01.cpp | taylorkcantalice/intro_a_programacao | 141e33f0b6cc227a4cc7b75701b603fcf53e2378 | [
"MIT"
] | null | null | null | /**
============================================================================
Nome : codcad-5-questao01.cpp
Autor : Taylor Klaus Cantalice Nobrega - 20200004268 (UFPB)
Versao : 1.0
Copyright : Your copyright notice
Descricao : Titulo
============================================================================
**/
#include <iostream>
using namespace std;
string title(string F){
int i;
if(F[0] >= 'a' && F[0] <= 'z'){
F[0] = (char)(F[0]-32);
}
for(i = 1; i <= F.size(); i++){
if(F[i-1] != ' ' && F[i] >= 'A' && F[i] <= 'Z'){
F[i] = (char)(F[i]+32);
}
if(F[i-1] == ' ' && F[i] >= 'a' && F[i] <= 'z'){
F[i] = (char)(F[i]-32);
}
}
return F;
}
int main(){
string F;
getline(cin, F);
cout << title(F) << "\n";
}
| 20.725 | 77 | 0.349819 | taylorkcantalice |
c96b1fd93b62c37e2aac83768642b471e45b5e59 | 2,820 | cpp | C++ | src/SharpProj/CoordinateReferenceSystemInfo.cpp | AmpScm/ProjSharp | d112527174a3e5f9864b9f94e12c288322a5765e | [
"Apache-2.0"
] | 5 | 2021-02-15T13:56:34.000Z | 2022-03-22T10:49:01.000Z | src/SharpProj/CoordinateReferenceSystemInfo.cpp | AmpScm/SharpProj | ab16164635930d357bcbc81b8bd71d308b6b105e | [
"Apache-2.0"
] | 9 | 2021-03-05T15:32:58.000Z | 2022-02-24T08:44:16.000Z | src/SharpProj/CoordinateReferenceSystemInfo.cpp | FObermaier/SharpProj | d112527174a3e5f9864b9f94e12c288322a5765e | [
"Apache-2.0"
] | 4 | 2021-02-16T12:41:54.000Z | 2022-02-25T09:34:22.000Z | #include "pch.h"
#include "ProjObject.h"
#include "CoordinateReferenceSystem.h"
#include "CoordinateReferenceSystemInfo.h"
private ref class CRSComparer : System::Collections::Generic::IComparer<CoordinateReferenceSystemInfo^>
{
public:
// Inherited via IComparer
virtual int Compare(SharpProj::Proj::CoordinateReferenceSystemInfo^ x, SharpProj::Proj::CoordinateReferenceSystemInfo^ y)
{
int n = StringComparer::OrdinalIgnoreCase->Compare(x->Authority, y->Authority);
if (n != 0)
return n;
int xi, yi;
if (int::TryParse(x->Code, xi) && int::TryParse(y->Code, yi))
{
n = xi - yi;
if (n != 0)
return n;
}
return StringComparer::OrdinalIgnoreCase->Compare(x->Name, y->Name);
}
static initonly CRSComparer^ Instance = gcnew CRSComparer();
};
ReadOnlyCollection<CoordinateReferenceSystemInfo^>^ ProjContext::GetCoordinateReferenceSystems(CoordinateReferenceSystemFilter^ filter)
{
if (!filter)
throw gcnew ArgumentNullException("filter");
std::string auth_name;
if (filter->Authority)
auth_name = ::utf8_string(filter->Authority);
PROJ_CRS_LIST_PARAMETERS* params = proj_get_crs_list_parameters_create();
try
{
auto types = filter->Types->ToArray();
pin_ptr<ProjType> pTypes;
if (types->Length)
{
pTypes = &types[0];
params->typesCount = types->Length;
params->types = reinterpret_cast<PJ_TYPE*>(pTypes);
}
params->allow_deprecated = filter->AllowDeprecated;
if (filter->CoordinateArea)
{
params->bbox_valid = true;
params->west_lon_degree = filter->CoordinateArea->WestLongitude;
params->south_lat_degree = filter->CoordinateArea->SouthLatitude;
params->east_lon_degree = filter->CoordinateArea->EastLongitude;
params->north_lat_degree = filter->CoordinateArea->NorthLatitude;
params->crs_area_of_use_contains_bbox = filter->CompletelyContainsArea;
}
int count;
array<CoordinateReferenceSystemInfo^> ^result;
PROJ_CRS_INFO** infoList = proj_get_crs_info_list_from_database(this, auth_name.length() ? auth_name.c_str() : nullptr, params, &count);
try
{
result = gcnew array<CoordinateReferenceSystemInfo^>(count);
for (int i = 0; i < count; i++)
result[i] = gcnew CoordinateReferenceSystemInfo(infoList[i], this);
}
finally
{
proj_crs_info_list_destroy(infoList);
}
Array::Sort(result, CRSComparer::Instance);
return Array::AsReadOnly(result);
}
finally
{
proj_get_crs_list_parameters_destroy(params);
}
}
ReadOnlyCollection<CoordinateReferenceSystemInfo^>^ ProjContext::GetCoordinateReferenceSystems()
{
return GetCoordinateReferenceSystems(gcnew CoordinateReferenceSystemFilter());
}
CoordinateReferenceSystem^ CoordinateReferenceSystemInfo::Create(ProjContext^ ctx)
{
if (!ctx)
ctx = _ctx;
return CoordinateReferenceSystem::CreateFromDatabase(Authority, Code, ctx);
}
| 26.857143 | 138 | 0.746454 | AmpScm |
c96c3f49204bcdb41a405d09d5fc5ffe1e4bb7a0 | 410 | hxx | C++ | src/ast/var-dec.hxx | MrMaDGaME/Tiger | f31f73cd386b3ccb3e02abe7b23a3de09d70bd0f | [
"MIT"
] | null | null | null | src/ast/var-dec.hxx | MrMaDGaME/Tiger | f31f73cd386b3ccb3e02abe7b23a3de09d70bd0f | [
"MIT"
] | null | null | null | src/ast/var-dec.hxx | MrMaDGaME/Tiger | f31f73cd386b3ccb3e02abe7b23a3de09d70bd0f | [
"MIT"
] | null | null | null | /**
** \file ast/var-dec.hxx
** \brief Inline methods of ast::VarDec.
*/
#pragma once
#include <ast/var-dec.hh>
namespace ast
{
inline const NameTy* VarDec::type_name_get() const { return type_name_; }
inline NameTy* VarDec::type_name_get() { return type_name_; }
inline const Exp* VarDec::init_get() const { return init_; }
inline Exp* VarDec::init_get() { return init_; }
} // namespace ast
| 20.5 | 75 | 0.680488 | MrMaDGaME |
c96ce84afd4912c40842e1083dc762d863fa5b35 | 2,429 | cc | C++ | chromecast/crash/linux/crash_uploader.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | chromecast/crash/linux/crash_uploader.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | chromecast/crash/linux/crash_uploader.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <sys/resource.h>
#include <memory>
#include <utility>
#include "base/at_exit.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/message_loop/message_pump_type.h"
#include "base/task/single_thread_task_executor.h"
#include "base/threading/platform_thread.h"
#include "base/time/time.h"
#include "chromecast/base/cast_paths.h"
#include "chromecast/base/cast_sys_info_util.h"
#include "chromecast/base/chromecast_switches.h"
#include "chromecast/crash/linux/minidump_uploader.h"
#include "chromecast/public/cast_sys_info.h"
#include "chromecast/system/reboot/reboot_util.h"
#include "third_party/crashpad/crashpad/client/crashpad_info.h"
namespace {
// Upload crash dump for every 60 seconds.
const int kUploadRetryIntervalDefault = 60;
} // namespace
int main(int argc, char** argv) {
base::AtExitManager exit_manager;
base::CommandLine::Init(argc, argv);
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
chromecast::RebootUtil::Initialize(command_line->argv());
chromecast::RegisterPathProvider();
logging::InitLogging(logging::LoggingSettings());
// Allow the system crash handler to handle our own crashes.
crashpad::CrashpadInfo::GetCrashpadInfo()
->set_system_crash_reporter_forwarding(crashpad::TriState::kEnabled);
LOG(INFO) << "Starting crash uploader...";
// Nice +19. Crash uploads are not time critical and we don't want to
// interfere with user playback.
setpriority(PRIO_PROCESS, 0, 19);
// Create the main task executor.
base::SingleThreadTaskExecutor io_task_executor(base::MessagePumpType::IO);
std::unique_ptr<chromecast::CastSysInfo> sys_info =
chromecast::CreateSysInfo();
std::string server_url(
command_line->GetSwitchValueASCII(switches::kCrashServerUrl));
chromecast::MinidumpUploader uploader(sys_info.get(), server_url);
while (true) {
if (!uploader.UploadAllMinidumps())
LOG(ERROR) << "Failed to process minidumps";
if (uploader.reboot_scheduled())
chromecast::RebootUtil::RebootNow(
chromecast::RebootShlib::CRASH_UPLOADER);
base::PlatformThread::Sleep(
base::TimeDelta::FromSeconds(kUploadRetryIntervalDefault));
}
return EXIT_SUCCESS;
}
| 32.824324 | 77 | 0.751338 | mghgroup |
c96cee3eba689d43bbd8a0995b96497062a7ed47 | 1,188 | cpp | C++ | hashtable.cpp | AbhinavDutta/syncmer | 38c67e858143b12ea44817d581607703738aabd0 | [
"MIT"
] | 3 | 2020-10-01T12:47:06.000Z | 2021-02-10T19:51:33.000Z | hashtable.cpp | AbhinavDutta/syncmer | 38c67e858143b12ea44817d581607703738aabd0 | [
"MIT"
] | null | null | null | hashtable.cpp | AbhinavDutta/syncmer | 38c67e858143b12ea44817d581607703738aabd0 | [
"MIT"
] | 2 | 2020-10-09T08:42:18.000Z | 2021-04-12T10:12:52.000Z | #include "myutils.h"
#include "syncmerindex.h"
#include "alpha.h"
void SyncmerIndex::CountPlus()
{
asserta(m_PlusCounts == 0);
m_PlusCounts = myalloc(byte, m_SlotCount);
zero(m_PlusCounts, m_SlotCount);
const uint K = GetKmerCount();
for (uint SeqPos = 0; SeqPos < K; ++SeqPos)
{
if (IsSyncmer(SeqPos))
{
uint64 Kmer = m_Kmers[SeqPos];
uint64 Hash = KmerToHash(Kmer);
uint64 Slot = Hash%m_SlotCount;
if (m_PlusCounts[Slot] < 255)
++m_PlusCounts[Slot];
}
}
}
void SyncmerIndex::SetHashTable(uint SlotCount)
{
m_SlotCount = SlotCount;
m_HashTable.clear();
m_HashTable.resize(m_SlotCount, UINT32_MAX);
CountPlus();
const uint K = GetKmerCount();
for (uint SeqPos = 0; SeqPos < K; ++SeqPos)
{
if (IsSyncmer(SeqPos))
{
uint64 Kmer = m_Kmers[SeqPos];
uint64 Hash = KmerToHash(Kmer);
uint64 Slot = Hash%m_SlotCount;
if (m_PlusCounts[Slot] == 1)
{
asserta(Slot < SIZE(m_HashTable));
m_HashTable[Slot] = SeqPos;
}
}
}
}
uint32 SyncmerIndex::GetPos(uint64 Slot) const
{
asserta(Slot < SIZE(m_HashTable));
uint32 Pos = m_HashTable[Slot];
return Pos;
}
| 21.6 | 48 | 0.635522 | AbhinavDutta |
c9716b287ca13a6b2409202474074533a40e2a67 | 1,924 | cpp | C++ | engine/game/helpers/CallbackObject.cpp | ClayHanson/B4v21-Public-Repo | c812aa7bf2ecb267e02969c85f0c9c2a29be0d28 | [
"MIT"
] | 1 | 2020-08-18T19:45:34.000Z | 2020-08-18T19:45:34.000Z | engine/game/helpers/CallbackObject.cpp | ClayHanson/B4v21-Launcher-Public-Repo | c812aa7bf2ecb267e02969c85f0c9c2a29be0d28 | [
"MIT"
] | null | null | null | engine/game/helpers/CallbackObject.cpp | ClayHanson/B4v21-Launcher-Public-Repo | c812aa7bf2ecb267e02969c85f0c9c2a29be0d28 | [
"MIT"
] | null | null | null | #include "game/helpers/CallbackObject.h"
IMPLEMENT_CONOBJECT(CallbackObject);
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CallbackObject::CallbackObject()
{
}
CallbackObject::~CallbackObject()
{
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
void CallbackObject::Reset()
{
mEvent.ClearListeners();
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ConsoleMethod(CallbackObject, AddListener, bool, 3, 3, "(string func)")
{
return object->mEvent.AddListener(CALLBACK_EVENT_LFUNC() {
const char** newArgv = new const char*[argc + 1];
newArgv[0] = (const char*)userData;
// Read the arguments
for (int i = 0; i < argc; i++)
newArgv[i + 1] = CALLBACK_EVENT_ARG(const char*);
Con::execute(argc + 1, newArgv);
delete[] newArgv;
}, (void*)StringTable->insert(argv[2]));
}
ConsoleMethod(CallbackObject, RemoveListener, bool, 3, 3, "(string func)")
{
for (U32 i = 0; i < object->mEvent.GetListenerCount(); i++)
{
CallbackEvent::EventAction* aObj = object->mEvent.GetListener(i);
if (aObj->userData == NULL || dStricmp((StringTableEntry)aObj->userData, argv[2]))
continue;
// Remove it!
CallbackEvent::EventFunction func = aObj->funcPtr;
object->mEvent.RemoveListener(func);
return true;
}
// Fail
return false;
}
ConsoleMethod(CallbackObject, Invoke, void, 3, 2, "([args])")
{
object->mEvent.Invoke(argc - 2, argv + 2);
} | 32.066667 | 228 | 0.43763 | ClayHanson |
c9733107b5e38a4e2d9d2844d3d99970e480bd54 | 6,744 | hpp | C++ | deps/src/boost_1_65_1/boost/numeric/odeint/iterator/n_step_iterator.hpp | shreyasvj25/turicreate | 32e84ca16aef8d04aff3d49ae9984bd49326bffd | [
"BSD-3-Clause"
] | 11,356 | 2017-12-08T19:42:32.000Z | 2022-03-31T16:55:25.000Z | deps/src/boost_1_65_1/boost/numeric/odeint/iterator/n_step_iterator.hpp | shreyasvj25/turicreate | 32e84ca16aef8d04aff3d49ae9984bd49326bffd | [
"BSD-3-Clause"
] | 2,402 | 2017-12-08T22:31:01.000Z | 2022-03-28T19:25:52.000Z | deps/src/boost_1_65_1/boost/numeric/odeint/iterator/n_step_iterator.hpp | shreyasvj25/turicreate | 32e84ca16aef8d04aff3d49ae9984bd49326bffd | [
"BSD-3-Clause"
] | 1,343 | 2017-12-08T19:47:19.000Z | 2022-03-26T11:31:36.000Z |
/*
[auto_generated]
boost/numeric/odeint/iterator/n_step_iterator.hpp
[begin_description]
Iterator for iterating through the solution of an ODE with constant step size performing exactly n steps.
[end_description]
Copyright 2009-2013 Karsten Ahnert
Copyright 2009-2013 Mario Mulansky
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or
copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_NUMERIC_ODEINT_ITERATOR_N_STEP_ITERATOR_HPP_INCLUDED
#define BOOST_NUMERIC_ODEINT_ITERATOR_N_STEP_ITERATOR_HPP_INCLUDED
#include <boost/numeric/odeint/util/stepper_traits.hpp>
#include <boost/numeric/odeint/stepper/stepper_categories.hpp>
#include <boost/numeric/odeint/iterator/detail/ode_iterator_base.hpp>
#include <boost/numeric/odeint/iterator/impl/n_step_iterator_impl.hpp>
namespace boost {
namespace numeric {
namespace odeint {
/* use the n_step_iterator_impl with the right tags */
template< class Stepper , class System , class State
#ifndef DOXYGEN_SKIP
, class StepperTag = typename base_tag< typename traits::stepper_category< Stepper >::type >::type
#endif
>
class n_step_iterator : public n_step_iterator_impl<
n_step_iterator< Stepper , System , State , StepperTag > ,
Stepper , System , State , detail::ode_state_iterator_tag , StepperTag
>
{
typedef typename traits::time_type< Stepper >::type time_type;
typedef n_step_iterator< Stepper , System , State , StepperTag > iterator_type;
public:
n_step_iterator( Stepper stepper , System sys , State &s , time_type t , time_type dt , size_t num_of_steps )
: n_step_iterator_impl< iterator_type , Stepper , System , State , detail::ode_state_iterator_tag , StepperTag >( stepper , sys , s , t , dt , num_of_steps )
{}
n_step_iterator( Stepper stepper , System sys , State &s )
: n_step_iterator_impl< iterator_type , Stepper , System , State , detail::ode_state_iterator_tag , StepperTag >( stepper , sys , s )
{}
};
/* make functions */
template< class Stepper , class System , class State >
n_step_iterator< Stepper , System, State > make_n_step_iterator_begin(
Stepper stepper ,
System system ,
State &x ,
typename traits::time_type< Stepper >::type t ,
typename traits::time_type< Stepper >::type dt ,
size_t num_of_steps )
{
return n_step_iterator< Stepper , System , State >( stepper , system , x , t , dt , num_of_steps );
}
template< class Stepper , class System , class State >
n_step_iterator< Stepper , System , State > make_n_step_iterator_end(
Stepper stepper ,
System system ,
State &x )
{
return n_step_iterator< Stepper , System , State >( stepper , system , x );
}
template< class Stepper , class System , class State >
std::pair< n_step_iterator< Stepper , System , State > , n_step_iterator< Stepper , System , State > >
make_n_step_range(
Stepper stepper ,
System system ,
State &x ,
typename traits::time_type< Stepper >::type t ,
typename traits::time_type< Stepper >::type dt ,
size_t num_of_steps )
{
return std::make_pair(
n_step_iterator< Stepper , System , State >( stepper , system , x , t , dt , num_of_steps ) ,
n_step_iterator< Stepper , System , State >( stepper , system , x )
);
}
/**
* \class n_step_iterator
*
* \brief ODE Iterator with constant step size. The value type of this iterator is the state type of the stepper.
*
* Implements an iterator representing the solution of an ODE starting from t
* with n steps and a constant step size dt.
* After each iteration the iterator dereferences to the state x at the next
* time t+dt.
* This iterator can be used with Steppers and
* DenseOutputSteppers and it always makes use of the all the given steppers
* capabilities. A for_each over such an iterator range behaves similar to
* the integrate_n_steps routine.
*
* n_step_iterator is a model of single-pass iterator.
*
* The value type of this iterator is the state type of the stepper. Hence one can only access the state and not the current time.
*
* \tparam Stepper The stepper type which should be used during the iteration.
* \tparam System The type of the system function (ODE) which should be solved.
* \tparam State The state type of the ODE.
*/
/**
* \fn make_n_step_iterator_begin( Stepper stepper , System system , State &x , typename traits::time_type< Stepper >::type t , typename traits::time_type< Stepper >::type dt , size_t num_of_steps )
*
* \brief Factory function for n_step_iterator. Constructs a begin iterator.
*
* \param stepper The stepper to use during the iteration.
* \param system The system function (ODE) to solve.
* \param x The initial state. const_step_iterator stores a reference of s and changes its value during the iteration.
* \param t The initial time.
* \param dt The initial time step.
* \param num_of_steps The number of steps to be executed.
* \returns The n-step iterator.
*/
/**
* \fn make_n_step_iterator_end( Stepper stepper , System system , State &x )
* \brief Factory function for n_step_iterator. Constructs an end iterator.
*
* \param stepper The stepper to use during the iteration.
* \param system The system function (ODE) to solve.
* \param x The initial state. const_step_iterator stores a reference of s and changes its value during the iteration.
* \returns The const_step_iterator.
*/
/**
* \fn make_n_step_range( Stepper stepper , System system , State &x , typename traits::time_type< Stepper >::type t , typename traits::time_type< Stepper >::type dt , , size_t num_of_steps )
*
* \brief Factory function to construct a single pass range of n-step iterators. A range is here a pair
* of n_step_iterator.
*
* \param stepper The stepper to use during the iteration.
* \param system The system function (ODE) to solve.
* \param x The initial state. const_step_iterator store a reference of s and changes its value during the iteration.
* \param t The initial time.
* \param dt The initial time step.
* \param num_of_steps The number of steps to be executed.
* \returns The n-step range.
*/
} // namespace odeint
} // namespace numeric
} // namespace boost
#endif // BOOST_NUMERIC_ODEINT_ITERATOR_CONST_N_STEP_ITERATOR_HPP_INCLUDED
| 39.905325 | 202 | 0.684757 | shreyasvj25 |
c97332498ccd07583227ed9ca41e9db365b90297 | 5,760 | cpp | C++ | src/custom/impl/param.cpp | Olalaye/MegEngine | 695d24f24517536e6544b07936d189dbc031bbce | [
"Apache-2.0"
] | 5,168 | 2020-03-19T06:10:04.000Z | 2022-03-31T11:11:54.000Z | src/custom/impl/param.cpp | Olalaye/MegEngine | 695d24f24517536e6544b07936d189dbc031bbce | [
"Apache-2.0"
] | 286 | 2020-03-25T01:36:23.000Z | 2022-03-31T10:26:33.000Z | src/custom/impl/param.cpp | Olalaye/MegEngine | 695d24f24517536e6544b07936d189dbc031bbce | [
"Apache-2.0"
] | 515 | 2020-03-19T06:10:05.000Z | 2022-03-30T09:15:59.000Z | /**
* \file src/custom/impl/param.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 "megbrain/common.h"
#if MGB_CUSTOM_OP
#include <limits>
#include <map>
#include <sstream>
#include "megbrain/custom/param.h"
#include "megbrain/utils/hash.h"
using namespace mgb;
namespace custom {
class ParamSchemaImpl {
std::string m_name;
std::string m_desc;
ParamVal m_default;
friend ParamSchema;
};
class ParamInfoImpl {
std::vector<ParamSchema> m_meta;
uint32_t TAG;
friend ParamInfo;
};
class ParamImpl {
std::unordered_map<std::string, ParamVal> m_vals;
ParamImpl() = default;
ParamImpl(const ParamImpl& rhs) = default;
ParamImpl& operator=(const ParamImpl& rhs) {
mgb_assert(
m_vals.size() == rhs.m_vals.size(),
"params of different op, assignment failed!");
for (const auto& kv : rhs.m_vals) {
auto iter = m_vals.find(kv.first);
mgb_assert(
iter != m_vals.end(), "params of different op, assignment failed!");
iter->second = kv.second;
}
return *this;
}
friend Param;
};
CUSTOM_PIMPL_CLS_DEFINE(ParamSchema)
ParamSchema::ParamSchema(
const std::string& name, const ParamVal& value, const std::string& desc)
: m_impl(new ParamSchemaImpl(), impl_deleter<ParamSchemaImpl>) {
TypedRef(ParamSchemaImpl, m_impl.get()).m_name = name;
TypedRef(ParamSchemaImpl, m_impl.get()).m_default = value;
TypedRef(ParamSchemaImpl, m_impl.get()).m_desc = desc;
}
const std::string& ParamSchema::name(void) const {
return TypedRef(ParamSchemaImpl, m_impl.get()).m_name;
}
const std::string& ParamSchema::desc(void) const {
return TypedRef(ParamSchemaImpl, m_impl.get()).m_desc;
}
const ParamVal& ParamSchema::default_val(void) const {
return TypedRef(ParamSchemaImpl, m_impl.get()).m_default;
}
ParamDynType ParamSchema::type(void) const {
return TypedRef(ParamSchemaImpl, m_impl.get()).m_default.type();
}
std::string ParamSchema::str(void) const {
std::stringstream ss;
ss << "name: " << TypedRef(ParamSchemaImpl, m_impl.get()).m_name
<< "\ndesc: " << TypedRef(ParamSchemaImpl, m_impl.get()).m_desc << "\n"
<< TypedRef(ParamSchemaImpl, m_impl.get()).m_default.str();
return ss.str();
}
CUSTOM_PIMPL_CLS_DEFINE(ParamInfo)
void ParamInfo::set_tag(const std::string& hash_str) {
const char* ptr = hash_str.c_str();
TypedRef(ParamInfoImpl, m_impl.get()).TAG = 0;
for (size_t i = 0; i < hash_str.size(); i++) {
TypedRef(ParamInfoImpl, m_impl.get()).TAG =
mgb::hash_pair_combine(
TypedRef(ParamInfoImpl, m_impl.get()).TAG,
mgb::hash(*(ptr++))) %
std::numeric_limits<uint32_t>::max();
}
}
void ParamInfo::set_meta(const std::vector<ParamSchema>& meta) {
TypedRef(ParamInfoImpl, m_impl.get()).m_meta = meta;
}
uint32_t ParamInfo::tag(void) const {
return TypedRef(ParamInfoImpl, m_impl.get()).TAG;
}
std::vector<ParamSchema>& ParamInfo::meta(void) {
return TypedRef(ParamInfoImpl, m_impl.get()).m_meta;
}
const std::vector<ParamSchema>& ParamInfo::meta(void) const {
return TypedRef(ParamInfoImpl, m_impl.get()).m_meta;
}
CUSTOM_PIMPL_CLS_DEFINE(Param)
Param::Param(const ParamInfo& info) : m_impl(new ParamImpl(), impl_deleter<ParamImpl>) {
for (const auto& schema : info.meta()) {
TypedRef(ParamImpl, m_impl.get())
.m_vals.emplace(schema.name(), schema.default_val());
}
}
ParamVal& Param::operator[](const std::string& name) {
return TypedRef(ParamImpl, m_impl.get()).m_vals.find(name)->second;
}
const ParamVal& Param::operator[](const std::string& name) const {
return TypedRef(ParamImpl, m_impl.get()).m_vals.find(name)->second;
}
const std::unordered_map<std::string, ParamVal>& Param::raw() const {
return TypedRef(ParamImpl, m_impl.get()).m_vals;
}
bool Param::exist(const std::string& name) const {
return TypedRef(ParamImpl, m_impl.get()).m_vals.find(name) !=
TypedRef(ParamImpl, m_impl.get()).m_vals.end();
}
std::string Param::to_bytes(void) const {
std::string res;
std::map<std::string, ParamVal> ordered_vals(
TypedRef(ParamImpl, m_impl.get()).m_vals.begin(),
TypedRef(ParamImpl, m_impl.get()).m_vals.end());
for (auto&& kv : ordered_vals) {
res += ParamVal::to_bytes(kv.second);
}
return res;
}
void Param::from_bytes(const std::string& bytes) {
std::map<std::string, ParamVal> ordered_vals(
TypedRef(ParamImpl, m_impl.get()).m_vals.begin(),
TypedRef(ParamImpl, m_impl.get()).m_vals.end());
size_t offset = 0;
for (auto& kv : ordered_vals) {
kv.second = ParamVal::from_bytes(bytes, offset);
}
TypedRef(ParamImpl, m_impl.get()).m_vals.clear();
TypedRef(ParamImpl, m_impl.get())
.m_vals.insert(ordered_vals.begin(), ordered_vals.end());
mgb_assert(offset == bytes.size(), "wrong data loader");
}
bool operator==(const Param& lhs, const Param& rhs) {
if (lhs.raw().size() != rhs.raw().size())
return false;
for (const auto& kv : lhs.raw()) {
auto riter = rhs.raw().find(kv.first);
if (riter == rhs.raw().end() || !((kv.second) == riter->second)) {
return false;
}
}
return true;
}
} // namespace custom
#endif
| 30.315789 | 89 | 0.648958 | Olalaye |
c973846e06c6fb3bd8684ac920902619a14478ad | 3,469 | cpp | C++ | nwol/label.cpp | asm128/nwol | a28d6df356bec817393adcd2e6573a65841832e2 | [
"MIT"
] | 3 | 2017-06-05T13:49:43.000Z | 2017-06-19T22:31:58.000Z | nwol/label.cpp | asm128/nwol | a28d6df356bec817393adcd2e6573a65841832e2 | [
"MIT"
] | 1 | 2017-06-19T12:36:46.000Z | 2017-06-30T22:34:06.000Z | nwol/label.cpp | asm128/nwol | a28d6df356bec817393adcd2e6573a65841832e2 | [
"MIT"
] | null | null | null | /// Copyright 2016-2017 - asm128
//#pragma warning(disable:4005)
#include "nwol_label.h"
#include "nwol_label_manager.h"
#include "stype.h"
#include <string>
//------------------------------------------------------------------- gsyslabel ---------------------------------------------------------------------------------------------------------
nwol::gsyslabel::gsyslabel (const char_t* label, uint32_t size) {
LabelManager = getSystemLabelManager();
error_if(errored(LabelManager->AddLabel(label, size, *this)), "Failed to store label!");
}
//------------------------------------------------------------------- glabel ---------------------------------------------------------------------------------------------------------
nwol::glabel::glabel (const char_t* label, uint32_t size) : LabelManager(getLabelManager()) { error_if(errored(LabelManager->AddLabel(label, size, *this)), "Failed to store label!"); }
bool nwol::glabel::operator == (const nwol::glabel& other) const noexcept {
if(Count != other.Count ) return false;
else if(0 == Count && Count == other.Count ) return true; // Empty labels are always equal regardless the Data pointer
else if(Data == other.Data ) return true;
else if(LabelManager == other.LabelManager ) return false;
else return 0 == memcmp(Data, other.Data, Count);
}
uint32_t nwol::glabel::save (byte_t* out_pMemoryBuffer) const {
static constexpr const uint32_t headerBytes = (uint32_t)sizeof(uint32_t);
const uint32_t arrayBytes = (uint32_t)(Count * sizeof(char_t));
if(out_pMemoryBuffer) {
*(uint32_t*)out_pMemoryBuffer = Count;
if(arrayBytes)
::memcpy(&out_pMemoryBuffer[headerBytes], Data, arrayBytes);
}
return headerBytes + arrayBytes;
}
::nwol::error_t nwol::glabel::load (const byte_t* in_pMemoryBuffer) {
ree_if(0 == in_pMemoryBuffer, "Cannot load label from a null pointer!");
const uint32_t headerBytes = (uint32_t)sizeof(uint32_t);
const uint32_t labelSize = *(const uint32_t*)in_pMemoryBuffer;
*this = labelSize ? ::nwol::glabel((const char_t*)&in_pMemoryBuffer[headerBytes], labelSize) : ::nwol::glabel::statics().empty;
return headerBytes + labelSize;
}
::nwol::error_t nwol::glabel::save (FILE* out_pMemoryBuffer) const {
nwol_necall(sint32(Count).write(out_pMemoryBuffer), "Failed to write label to file! Label: '%s'.", begin());
if(Count) {
ree_if(Count != (int32_t)fwrite(begin(), sizeof(char_t), Count, out_pMemoryBuffer), "Failed to write label to file! Label: '%s'.", begin());
}
return 0;
}
::nwol::error_t nwol::glabel::load (FILE* in_pMemoryBuffer) {
sint32 labelSize = {};
nwol_necall(labelSize.read(in_pMemoryBuffer), "%s", "Failed to read label from file!");
if(labelSize) {
::nwol::auto_nwol_free a;
a.Handle = (char_t*)::nwol::nwol_malloc(labelSize);
ree_if(0 == a, "Failed to allocate memory for label of size %u.", (uint32_t)labelSize);
if(labelSize != (int32_t)fread(a, sizeof(char_t), labelSize, in_pMemoryBuffer), "%s", "Failed to read label from file!") {
error_printf("Failed to read from file label of size: %u bytes.", labelSize);
*this = ::nwol::glabel::statics().empty;
return -1;
}
*this = ::nwol::glabel((const char_t*)a.Handle, labelSize);
}
return 0;
} | 51.014706 | 201 | 0.586913 | asm128 |
c974dc64623b9ddae78acb9d3b4c44b9bc5a6355 | 1,543 | hpp | C++ | plugins/d3d9/include/sge/d3d9/texture/planar.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | plugins/d3d9/include/sge/d3d9/texture/planar.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | plugins/d3d9/include/sge/d3d9/texture/planar.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef SGE_D3D9_TEXTURE_PLANAR_HPP_INCLUDED
#define SGE_D3D9_TEXTURE_PLANAR_HPP_INCLUDED
#include <sge/d3d9/d3dinclude.hpp>
#include <sge/d3d9/surface/d3d_unique_ptr.hpp>
#include <sge/d3d9/texture/basic.hpp>
#include <sge/d3d9/texture/planar_basic.hpp>
#include <sge/renderer/texture/planar.hpp>
#include <sge/renderer/texture/planar_parameters.hpp>
#include <sge/renderer/texture/mipmap/level.hpp>
#include <fcppt/noncopyable.hpp>
#include <fcppt/unique_ptr_decl.hpp>
#include <fcppt/config/external_begin.hpp>
#include <vector>
#include <fcppt/config/external_end.hpp>
namespace sge
{
namespace d3d9
{
namespace texture
{
class planar : public sge::d3d9::texture::planar_basic
{
FCPPT_NONCOPYABLE(planar);
public:
planar(IDirect3DDevice9 &, sge::renderer::texture::planar_parameters const &);
~planar() override;
private:
sge::renderer::texture::planar::nonconst_buffer &
level(sge::renderer::texture::mipmap::level) override;
sge::renderer::texture::planar::const_buffer const &
level(sge::renderer::texture::mipmap::level) const override;
sge::d3d9::surface::d3d_unique_ptr get_level(sge::renderer::texture::mipmap::level);
typedef std::vector<fcppt::unique_ptr<sge::renderer::texture::planar::nonconst_buffer>>
level_vector;
level_vector const levels_;
};
}
}
}
#endif
| 26.603448 | 89 | 0.751782 | cpreh |
c97ab7aaeacb44c4bf54b7b2431f33a7c07d7a2f | 2,359 | cpp | C++ | Lab-Assignments/Data-Structure-Lab/Assignment-8/Question-5.cpp | Hics0000/Console-Based-Cpp-Programs | 6a7658a302d19b9d623ff7c5de5bc456c2d5ab69 | [
"MIT"
] | null | null | null | Lab-Assignments/Data-Structure-Lab/Assignment-8/Question-5.cpp | Hics0000/Console-Based-Cpp-Programs | 6a7658a302d19b9d623ff7c5de5bc456c2d5ab69 | [
"MIT"
] | 1 | 2021-10-05T17:00:52.000Z | 2021-10-05T17:00:52.000Z | Lab-Assignments/Data-Structure-Lab/Assignment-8/Question-5.cpp | Hics0000/Console-Based-Cpp-Programs | 6a7658a302d19b9d623ff7c5de5bc456c2d5ab69 | [
"MIT"
] | 7 | 2021-06-13T08:15:26.000Z | 2021-10-05T17:02:10.000Z | #include <bits/stdc++.h>
#include <climits>
using namespace std;
void swap(int *x, int *y);
class MinHeap
{
int *harr;
int capacity;
int heap_size;
public:
MinHeap(int capacity);
void MinHeapify(int);
int parent(int i) { return (i - 1) / 2; }
int left(int i) { return (2 * i + 1); }
int right(int i) { return (2 * i + 2); }
int DeleteMin();
void ChangeKey(int i, int new_val);
int getMin() { return harr[0]; }
void DeleteKey(int i);
void Insert(int k);
int Size()
{
return heap_size;
}
};
MinHeap::MinHeap(int cap)
{
heap_size = 0;
capacity = cap;
harr = new int[cap];
}
void MinHeap::Insert(int k)
{
if (heap_size == capacity)
{
cout << "\nOverflow: Could not Insert\n";
return;
}
heap_size++;
int i = heap_size - 1;
harr[i] = k;
while (i != 0 && harr[parent(i)] > harr[i])
{
swap(&harr[i], &harr[parent(i)]);
i = parent(i);
}
}
void MinHeap::ChangeKey(int i, int new_val)
{
harr[i] = new_val;
while (i != 0 && harr[parent(i)] > harr[i])
{
swap(&harr[i], &harr[parent(i)]);
i = parent(i);
}
}
int MinHeap::DeleteMin()
{
if (heap_size <= 0)
return INT_MAX;
if (heap_size == 1)
{
heap_size--;
return harr[0];
}
int root = harr[0];
harr[0] = harr[heap_size - 1];
heap_size--;
MinHeapify(0);
return root;
}
void MinHeap::DeleteKey(int i)
{
ChangeKey(i, INT_MIN);
DeleteMin();
}
void MinHeap::MinHeapify(int i)
{
int l = left(i);
int r = right(i);
int smallest = i;
if (l < heap_size && harr[l] < harr[i])
smallest = l;
if (r < heap_size && harr[r] < harr[smallest])
smallest = r;
if (smallest != i)
{
swap(&harr[i], &harr[smallest]);
MinHeapify(smallest);
}
}
void swap(int *x, int *y)
{
int Temp = *x;
*x = *y;
*y = Temp;
}
int main()
{
int n = 100;
cin >> n;
int arr[n];
MinHeap MHeap(n);
n = 100;
for (int i = 0; i < n; i++)
{
cin >> arr[i];
MHeap.Insert(arr[i]);
}
cout << "enter number of small elements you want to print";
int k;
cin >> k;
for (int i = 0; i < k; i++)
{
cout << MHeap.DeleteMin() << " ";
}
return 0;
}
| 16.268966 | 63 | 0.50106 | Hics0000 |
c97b3c821773dee94f10dd4361d672edbe6199ad | 35,387 | cpp | C++ | Source/AllProjects/Drivers/IR/USBUIRT/USBUIRTS_DriverImpl.cpp | DeanRoddey/CQC | 3c494db7cf89c6ba73c2c1bd9327b7a8d061072a | [
"MIT"
] | 51 | 2020-12-26T18:17:16.000Z | 2022-03-15T04:29:35.000Z | Source/AllProjects/Drivers/IR/USBUIRT/USBUIRTS_DriverImpl.cpp | DeanRoddey/CQC | 3c494db7cf89c6ba73c2c1bd9327b7a8d061072a | [
"MIT"
] | null | null | null | Source/AllProjects/Drivers/IR/USBUIRT/USBUIRTS_DriverImpl.cpp | DeanRoddey/CQC | 3c494db7cf89c6ba73c2c1bd9327b7a8d061072a | [
"MIT"
] | 4 | 2020-12-28T07:24:39.000Z | 2021-12-29T12:09:37.000Z | //
// FILE NAME: USBUIRTS_DriverImpl.cpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 09/12/2003
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2020
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This file implements the bulk of the driver implementation. Some of it
// is provided by the common IR server driver base class.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include "USBUIRTS.hpp"
// ---------------------------------------------------------------------------
// Magic macros
// ---------------------------------------------------------------------------
RTTIDecls(TUSBUIRTSDriver,TBaseIRSrvDriver)
// ---------------------------------------------------------------------------
// Local data
// ---------------------------------------------------------------------------
namespace USBUIRTS_DriverImpl
{
// Our file format version marker
const tCIDLib::TCard4 c4FmtVersion = 1;
//
// Most button presses will cause multiple IR events, which is a problem,
// because we only can deal with one of them. So we set a minimum
// interval and will throw away events until this minimum interval has
// passed. So we define here the interval.
//
const tCIDLib::TCard4 c4MinEventInterval = 250;
}
// ---------------------------------------------------------------------------
// Local callback methods that we tell the UIRT to call
// ---------------------------------------------------------------------------
extern "C" tCIDLib::TVoid __stdcall
USBUIRTRecCallback( const tCIDLib::TSCh* const pszIREventStr
, tCIDLib::TVoid* const pUserData)
{
// The user data is a pointer to the driver impl object
TUSBUIRTSDriver* psdrvTar = static_cast<TUSBUIRTSDriver*>(pUserData);
//
// If the current time is not past the next event time, we just assume
// this is a bogus 2nd, 3rd, etc... event, and we ignore it. Else, we
// take it and reset the next event time.
//
const tCIDLib::TCard4 c4CurTime = TTime::c4Millis();
if (c4CurTime < psdrvTar->c4NextEventTime())
return;
// We are keeping this one, so set the next event time
psdrvTar->c4NextEventTime(c4CurTime + USBUIRTS_DriverImpl::c4MinEventInterval);
//
// Tell the driver about it. He will either store it as training data
// if in training mode, or queue it for processing if not in training
// mode.
//
psdrvTar->HandleRecEvent(TString(pszIREventStr));
}
extern "C" tCIDLib::TVoid __stdcall
ProgressCallback(const tCIDLib::TCard4
, const tCIDLib::TCard4
, const tCIDLib::TCard4
, tCIDLib::TVoid* const)
{
// We aren't using the progress callback at this time
}
// ---------------------------------------------------------------------------
// CLASS: THostMonSDriver
// PREFIX: drv
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// THostMonSDriver: Constructors and Destructor
// ---------------------------------------------------------------------------
TUSBUIRTSDriver::TUSBUIRTSDriver(const TCQCDriverObjCfg& cqcdcToLoad) :
TBaseIRSrvDriver(cqcdcToLoad)
, m_bGotBlastTrainingData(kCIDLib::False)
, m_bGotRecTrainingData(kCIDLib::False)
, m_bBlastTrainingMode(kCIDLib::False)
, m_bRecTrainingMode(kCIDLib::False)
, m_c4FldIdFirmwareVer(kCIDLib::c4MaxCard)
, m_c4FldIdInvoke(kCIDLib::c4MaxCard)
, m_c4FldIdTrainingMode(kCIDLib::c4MaxCard)
, m_c4NextEventTime(0)
, m_c4PollCount(0)
, m_colRecKeyQ(tCIDLib::EMTStates::Unsafe)
, m_hUIRT(kUSBUIRT::hInvalid)
, m_pfnGetInfoProc(nullptr)
, m_pfnGetUIRTInfoProc(nullptr)
, m_pfnLearnProc(nullptr)
, m_pfnOpenProc(nullptr)
, m_pfnSetCfgProc(nullptr)
, m_pfnSetRecCBProc(nullptr)
, m_pfnTransmitProc(nullptr)
, m_pmodSupport(nullptr)
, m_strErr_NoDevice(kUIRTSErrs::errcDev_NoDevice, facUSBUIRTS())
, m_strErr_NoResp(kUIRTSErrs::errcDev_NoResp, facUSBUIRTS())
, m_strErr_NoDLL(kUIRTSErrs::errcDev_NoDLL, facUSBUIRTS())
, m_strErr_Version(kUIRTSErrs::errcDev_Version, facUSBUIRTS())
, m_strErr_Unknown(kUIRTSErrs::errcDev_Unknown, facUSBUIRTS())
, m_thrLearn
(
TString(L"USB-UIRTLearnThread_") + cqcdcToLoad.strMoniker()
, TMemberFunc<TUSBUIRTSDriver>(this, &TUSBUIRTSDriver::eLearnThread)
)
{
//
// Make sure that we were configured for an 'other' connection. Otherwise,
// its a bad configuration.
//
if (cqcdcToLoad.conncfgReal().clsIsA() != TCQCOtherConnCfg::clsThis())
{
// Note that we are throwing a CQCKit error here!
facCQCKit().ThrowErr
(
CID_FILE
, CID_LINE
, kKitErrs::errcDrv_BadConnCfgType
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Config
, cqcdcToLoad.conncfgReal().clsIsA()
, clsIsA()
, TCQCOtherConnCfg::clsThis()
);
}
}
TUSBUIRTSDriver::~TUSBUIRTSDriver()
{
}
// ---------------------------------------------------------------------------
// TUSBUIRTSDriver: Public, inherited methods
// ---------------------------------------------------------------------------
//
// If it's one we posted to ourself, store the data. Else just pass it to
// the base IR driver class.
//
tCIDLib::TCard4
TUSBUIRTSDriver::c4SendCmd(const TString& strCmdId, const TString& strParms)
{
if (strCmdId == kUSBUIRTS::pszCmd_UIRTData)
{
//
// If we are in receiver training mode we have to store it as
// training data. Else, if we aren't in blaster training mode, we
// want to queue it as an event to process.
//
if (m_bRecTrainingMode)
{
m_bGotRecTrainingData = kCIDLib::True;
m_strRecTrainData = strParms;
}
else
{
if (!m_bBlastTrainingMode)
m_colRecKeyQ.objPut(strParms);
}
return 0;
}
return TParent::c4SendCmd(strCmdId, strParms);
}
// ---------------------------------------------------------------------------
// TUSBUIRTSDriver: Public, non-virtual methods
// ---------------------------------------------------------------------------
tCIDLib::TCard4 TUSBUIRTSDriver::c4NextEventTime() const
{
return m_c4NextEventTime;
}
tCIDLib::TCard4 TUSBUIRTSDriver::c4NextEventTime(const tCIDLib::TCard4 c4ToSet)
{
m_c4NextEventTime = c4ToSet;
return m_c4NextEventTime;
}
//
// NOTE!!!!!
//
// This is called from the USB UIRT callback. It is NOT a CQC thread, so
// we have to do the minimum work possible just to queue up the passed
// event string because, if anything goes wrong, it will inevitably invoke
// some code that assumes it is running in a CQC thread.
//
// Since it does come asynchronously from the UIRT calling us back, we
// just post ourself an async command using the existing async driver command
// infrastructure.
//
tCIDLib::TVoid TUSBUIRTSDriver::HandleRecEvent(const TString& strEventStr)
{
pdcmdQSendCmd
(
kUSBUIRTS::pszCmd_UIRTData, strEventStr, tCQCKit::EDrvCmdWaits::NoWait
);
}
// ---------------------------------------------------------------------------
// TUSBUIRTSDriver: Protected, inherited methods
// ---------------------------------------------------------------------------
tCIDLib::TBoolean TUSBUIRTSDriver::bBlastTrainingMode()
{
// No need to lock for this simple check
return m_bBlastTrainingMode;
}
tCIDLib::TBoolean
TUSBUIRTSDriver::bCheckBlastTrainingData(tCIDLib::TCard4& c4DataBytes
, THeapBuf& mbufToFill)
{
// If we aren't online, then throw
CheckOnline(CID_FILE, CID_LINE);
if (m_bGotBlastTrainingData)
{
//
// We got something, so copy it over and clear the flags. Be sure
// to copy the nul, so that when the data is returned later, we can
// just send it as is.
//
c4DataBytes = TRawStr::c4StrLen(m_pchBlastTrainData) + 1;
mbufToFill.CopyIn(m_pchBlastTrainData, c4DataBytes);
m_bBlastTrainingMode = kCIDLib::False;
m_bGotBlastTrainingData = kCIDLib::False;
bStoreBoolFld(m_c4FldIdTrainingMode, kCIDLib::False, kCIDLib::True);
return kCIDLib::True;
}
c4DataBytes = 0;
return kCIDLib::False;
}
tCIDLib::TBoolean
TUSBUIRTSDriver::bCheckRecTrainingData(TString& strKeyToFill)
{
// If we aren't online, then throw, else lock and do it
CheckOnline(CID_FILE, CID_LINE);
if (m_bGotRecTrainingData)
{
// We have some, so copy to output and clear our stuff
strKeyToFill = m_strRecTrainData;
m_bGotRecTrainingData = kCIDLib::False;
m_strRecTrainData.Clear();
return kCIDLib::True;
}
return kCIDLib::False;
}
tCIDLib::TBoolean
TUSBUIRTSDriver::bCvtManualBlastData(const TString& strText
, tCIDLib::TCard4& c4DataBytes
, THeapBuf& mbufToFill
, TString& strError)
{
//
// Use a regular expression to validate the data, which must be a
// sequence of one or more sets of 4 hex digits, separated by spaces
// but the last one doesn't have to have any space after it, and
// should not because the client should streaming leading and trailng
// space.
//
if (!facCQCIR().bIsValidUIRTBlastData(strText))
{
strError.LoadFromMsg
(
kIRErrs::errcFmt_BadIRDataFormat, facCQCIR(), TString(L"UIRT")
);
return kCIDLib::False;
}
//
// For us, it has to be in Pronto format, since that's our native
// format and the only alternative format that this method has to
// accept. So we just convert it to the desired ultimate format,
// which is single byte ASCII characters with a null terminator. So
// we just do a simple transcode by taking the low byte of each char.
//
const tCIDLib::TCard4 c4Len = strText.c4Length();
CIDAssert(c4Len != 0, L"The incoming IR data length was zero");
for (c4DataBytes = 0; c4DataBytes< c4Len; c4DataBytes++)
mbufToFill.PutCard1(tCIDLib::TCard1(strText[c4DataBytes]), c4DataBytes);
// Add the null terminator
mbufToFill.PutCard1(0, c4DataBytes++);
return kCIDLib::True;
}
tCIDLib::TBoolean TUSBUIRTSDriver::bGetCommResource(TThread&)
{
// Try to find the UIRT library if not done so far
if (m_hUIRT == kUSBUIRT::hInvalid)
m_hUIRT = m_pfnOpenProc();
return (m_hUIRT != kUSBUIRT::hInvalid);
}
tCIDLib::TBoolean TUSBUIRTSDriver::bRecTrainingMode()
{
// No need to lock for this simple check
return m_bRecTrainingMode;
}
tCIDLib::TBoolean TUSBUIRTSDriver::bResetConnection()
{
// If we aren't online, then throw, else lock and do it
CheckOnline(CID_FILE, CID_LINE);
//
// The device doesn't require anything, but we want to get ourselves
// out of any training modes and clear the event queue.
//
ExitBlastTrainingMode();
ExitRecTrainingMode();
ClearEventQ();
return kCIDLib::True;
}
tCIDLib::TCard4 TUSBUIRTSDriver::c4InvokeFldId() const
{
return m_c4FldIdInvoke;
}
//
// The later UIRTs have three zones, with the open air one being
// zone one, a second one being on the back and third one that you
// can access as well.
//
tCIDLib::TCard4 TUSBUIRTSDriver::c4ZoneCount() const
{
return 3;
}
tCIDLib::TVoid TUSBUIRTSDriver::ClearBlastTrainingData()
{
// If we aren't online, then throw, else lock and do it
CheckOnline(CID_FILE, CID_LINE);
m_bGotBlastTrainingData = kCIDLib::False;
}
tCIDLib::TVoid TUSBUIRTSDriver::ClearRecTrainingData()
{
// If we aren't online, then throw, else lock and do it
CheckOnline(CID_FILE, CID_LINE);
m_bGotRecTrainingData = kCIDLib::False;
m_strRecTrainData.Clear();
}
tCQCKit::ECommResults TUSBUIRTSDriver::eConnectToDevice(TThread&)
{
//
// If we got the comm resource, we are connected, but get the firmware
// info and set that field now. If this fails, then something really
// bad has happened, since it should be doable even if there's no
// hardware attached, so return lostcommres.
//
TUIRTInfo Info;
if (!m_pfnGetUIRTInfoProc(m_hUIRT, &Info))
return tCQCKit::ECommResults::LostCommRes;
TString strFW(L"USB-UIRT FWVer=");
strFW.AppendFormatted(Info.c4FWVersion >> 8);
strFW.Append(kCIDLib::chPeriod);
strFW.AppendFormatted(Info.c4FWVersion & 0xFF);
strFW.Append(L", ProtoVer=");
strFW.AppendFormatted(Info.c4ProtVersion >> 8);
strFW.Append(kCIDLib::chPeriod);
strFW.AppendFormatted(Info.c4ProtVersion & 0xFF);
strFW.Append(L", Date=");
strFW.AppendFormatted(tCIDLib::TCard4(Info.c1Year + 2000));
strFW.Append(kCIDLib::chForwardSlash);
strFW.AppendFormatted(Info.c1Month);
strFW.Append(kCIDLib::chForwardSlash);
strFW.AppendFormatted(Info.c1Day);
// Lock for field write and set the field
bStoreStringFld(m_c4FldIdFirmwareVer, strFW, kCIDLib::True);
// Set the receiver callback
m_pfnSetRecCBProc(m_hUIRT, USBUIRTRecCallback, this);
// And set the flags
m_pfnSetCfgProc(m_hUIRT, kUSBUIRT::c4Cfg_LEDRX | kUSBUIRT::c4Cfg_LEDTX);
return tCQCKit::ECommResults::Success;
}
tCQCKit::EDrvInitRes TUSBUIRTSDriver::eInitializeImpl()
{
// Call the base IR driver first
TParent::eInitializeImpl();
//
// We have to load the USB-UIRT interface DLL dynamically, and look
// up the APIs we are going to call. We need to build the path to
// the DLL and check that it exists before we try to load it. It
// will be in the bin directory.
//
// This is not one of our facilities, so we have to just build up
// the raw name ourself, we can't use the CIDlib methods. We just
// find it in the system path.
//
TPathStr pathLibName;
TFindBuf fndbUULib;
if (!TFileSys::bExistsInSysPath(kUSBUIRTS::pszSupportDLL, fndbUULib))
{
// Log this so that they'll know why
if (eVerboseLevel() >= tCQCKit::EVerboseLvls::Medium)
{
facUSBUIRTS().LogMsg
(
CID_FILE
, CID_LINE
, kUIRTSErrs::errcComm_DLLNotFound
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::NotFound
);
}
return tCQCKit::EDrvInitRes::Failed;
}
//
// And try to load this module if we haven't already. It's a third party
// module, so we use the ctor that takes the path to load from specifically
// and no CIDLib stuff.
//
if (!m_pmodSupport)
{
try
{
m_pmodSupport = new TModule(fndbUULib.pathFileName(), kCIDLib::True);
}
catch(const TError& errToCatch)
{
if (eVerboseLevel() >= tCQCKit::EVerboseLvls::Medium)
{
LogError(errToCatch, tCQCKit::EVerboseLvls::Medium);
facUSBUIRTS().LogMsg
(
CID_FILE
, CID_LINE
, kUIRTSErrs::errcComm_DLLNotLoaded
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::NotFound
);
}
return tCQCKit::EDrvInitRes::Failed;
}
catch(...)
{
if (eVerboseLevel() >= tCQCKit::EVerboseLvls::Medium)
{
facUSBUIRTS().LogMsg
(
CID_FILE
, CID_LINE
, kUIRTSErrs::errcComm_DLLNotLoaded
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::NotFound
);
}
return tCQCKit::EDrvInitRes::Failed;
}
}
// Load up all of the entry points we need to use
try
{
m_pfnCloseProc = reinterpret_cast<TUUIRTClose>
(
m_pmodSupport->pfnGetFuncPtr("UUIRTClose")
);
m_pfnGetInfoProc = reinterpret_cast<TUUIRTGetDrvInfo>
(
m_pmodSupport->pfnGetFuncPtr("UUIRTGetDrvInfo")
);
m_pfnGetUIRTInfoProc = reinterpret_cast<TUUIRTGetUUIRTInfo>
(
m_pmodSupport->pfnGetFuncPtr("UUIRTGetUUIRTInfo")
);
m_pfnLearnProc = reinterpret_cast<TUUIRTLearnIR>
(
m_pmodSupport->pfnGetFuncPtr("UUIRTLearnIR")
);
m_pfnOpenProc = reinterpret_cast<TUUIRTOpen>
(
m_pmodSupport->pfnGetFuncPtr("UUIRTOpen")
);
m_pfnSetCfgProc = reinterpret_cast<TUUIRTSetUUIRTConfig>
(
m_pmodSupport->pfnGetFuncPtr("UUIRTSetUUIRTConfig")
);
m_pfnSetRecCBProc = reinterpret_cast<TUUIRTSetRecCB>
(
m_pmodSupport->pfnGetFuncPtr("UUIRTSetReceiveCallback")
);
m_pfnTransmitProc = reinterpret_cast<TUUIRTTransmitIR>
(
m_pmodSupport->pfnGetFuncPtr("UUIRTTransmitIR")
);
}
catch(...)
{
if (eVerboseLevel() >= tCQCKit::EVerboseLvls::Medium)
{
facUSBUIRTS().LogMsg
(
CID_FILE
, CID_LINE
, kUIRTSErrs::errcComm_FuncsNotLoaded
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::NotFound
);
}
return tCQCKit::EDrvInitRes::Failed;
}
//
// Register our couple of fields. We just provide one that indicates
// the training mode state, so that the client can display an
// indicator that shows whether the driver is in training mode or not.
//
tCQCKit::TFldDefList colFlds(8);
TCQCFldDef flddCmd;
//
// Do readable fields for the standard fields that an IR driver
// has to provide. The invoke field must be an 'always write' field
// since it exists just to invoke IR data sending.
//
flddCmd.Set
(
TFacCQCIR::strFldName_FirmwareVer
, tCQCKit::EFldTypes::String
, tCQCKit::EFldAccess::Read
);
colFlds.objAdd(flddCmd);
flddCmd.Set
(
TFacCQCIR::strFldName_Invoke
, tCQCKit::EFldTypes::String
, tCQCKit::EFldAccess::Write
);
flddCmd.bAlwaysWrite(kCIDLib::True);
colFlds.objAdd(flddCmd);
flddCmd.Set
(
TFacCQCIR::strFldName_TrainingState
, tCQCKit::EFldTypes::Boolean
, tCQCKit::EFldAccess::Read
);
colFlds.objAdd(flddCmd);
// Tell our base class about our fields
SetFields(colFlds);
// Look up the ids of our fields, for efficiency
m_c4FldIdFirmwareVer = pflddFind
(
TFacCQCIR::strFldName_FirmwareVer, kCIDLib::True
)->c4Id();
m_c4FldIdInvoke = pflddFind
(
TFacCQCIR::strFldName_Invoke, kCIDLib::True
)->c4Id();
m_c4FldIdTrainingMode = pflddFind
(
TFacCQCIR::strFldName_TrainingState, kCIDLib::True
)->c4Id();
//
// Set the poll time a little faster than normal. This is a very
// interactive device, and it has a good fast speed. Set the recon
// time pretty slow since we would only ever fail if the hardware is
// not present, so no need to keep banging away fast.
//
SetPollTimes(50, 10000);
//
// Crank up the actions processing thread if not already running. It
// runs until we are unloaded pulling events out of the queue and
// processing them.
//
StartActionsThread();
//
// In our case we want to go to 'wait for config' mode, not wait for
// comm res, since we need to get configuration before we can go online.
//
return tCQCKit::EDrvInitRes::WaitConfig;
}
tCQCKit::ECommResults TUSBUIRTSDriver::ePollDevice(TThread&)
{
tCQCKit::ECommResults eRetVal = tCQCKit::ECommResults::Success;
//
// If we aren't in blaster or training mode, then let's bump the poll
// count, and every so many times through, ping the device to make
// sure it's still there.
//
if (!m_bBlastTrainingMode && !m_bRecTrainingMode)
{
//
// Every so many times through, we ping the device to make sure
// it's still there. This should be about every 10 seconds at
// our poll rate.
//
m_c4PollCount++;
if (m_c4PollCount > 200)
{
TUIRTInfo Info;
if (!m_pfnGetUIRTInfoProc(m_hUIRT, &Info))
eRetVal = tCQCKit::ECommResults::LostCommRes;
m_c4PollCount = 0;
}
}
const tCIDLib::TCard4 c4RecKeyCnt = m_colRecKeyQ.c4ElemCount();
if (eRetVal != tCQCKit::ECommResults::Success)
{
// We are losing the connection so flush the queue
m_colRecKeyQ.RemoveAll();
}
else if (c4RecKeyCnt)
{
//
// If there are any queued receiver keys, queue them up on
// our parent class.
//
// BEAR in mind we have a lock above. But all we are doing here
// is just passing in soem data to be queued up.
//
TString strKey;
while (m_colRecKeyQ.bGetNextMv(strKey, 0))
QueueRecEvent(strKey);
}
return eRetVal;
}
tCIDLib::TVoid TUSBUIRTSDriver::EnterBlastTrainingMode()
{
// If we aren't online, then throw, else lock and do it
CheckOnline(CID_FILE, CID_LINE);
// If we are already in training mode, then that's an error
if (m_bBlastTrainingMode)
{
facCQCIR().ThrowErr
(
CID_FILE
, CID_LINE
, kIRErrs::errcTrain_AlreadyTraining
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Already
);
}
//
// We make them wait until all the queued events are processed before
// they can do any training.
//
WaitForActions();
//
// Go into training mode. Since it's a blocking call on the USB-UIRT,
// we spin off a thread to do the work. When it exits, it'll set
// the got data flag appropriately.
//
m_bGotBlastTrainingData = kCIDLib::False;
m_bBlastTrainingMode = kCIDLib::True;
m_thrLearn.Start();
// Look for field access and update the training mode field
bStoreBoolFld
(
m_c4FldIdTrainingMode
, m_bRecTrainingMode || m_bBlastTrainingMode
, kCIDLib::True
);
}
tCIDLib::TVoid TUSBUIRTSDriver::EnterRecTrainingMode()
{
// Can't already be in training mode
if (m_bRecTrainingMode)
{
facCQCIR().ThrowErr
(
CID_FILE
, CID_LINE
, kIRErrs::errcTrain_AlreadyTraining
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Already
, strMoniker()
);
}
//
// We make them wait until all the queued events are processed before
// they can do any training.
//
WaitForActions();
// Set the record training mode flag and clear the data flags
m_bRecTrainingMode = kCIDLib::True;
m_bGotRecTrainingData = kCIDLib::False;
m_strRecTrainData.Clear();
// And then update the training mode field
bStoreBoolFld
(
m_c4FldIdTrainingMode
, m_bRecTrainingMode || m_bBlastTrainingMode
, kCIDLib::True
);
}
tCIDLib::TVoid TUSBUIRTSDriver::ExitBlastTrainingMode()
{
//
// Set the flag that the learn procedure uses as an abort flag. This
// will cause the thread to exit.
//
m_c4CancelLearn = 1;
// Wait for the learning thread to exit
try
{
if (m_thrLearn.bIsRunning())
m_thrLearn.eWaitForDeath(2000);
}
catch(const TError& errToCatch)
{
if (eVerboseLevel() >= tCQCKit::EVerboseLvls::Low)
{
LogError(errToCatch, tCQCKit::EVerboseLvls::Low);
facCQCIR().ThrowErr
(
CID_FILE
, CID_LINE
, kIRErrs::errcTrain_StopTrainThread
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::CantDo
, strMoniker()
);
}
}
// Clear the flags first, then update the training mode field
m_bBlastTrainingMode = kCIDLib::False;
m_bGotBlastTrainingData = kCIDLib::False;
bStoreBoolFld
(
m_c4FldIdTrainingMode
, m_bRecTrainingMode || m_bBlastTrainingMode
, kCIDLib::True
);
}
tCIDLib::TVoid TUSBUIRTSDriver::ExitRecTrainingMode()
{
// Clear our own flags
m_bRecTrainingMode = kCIDLib::False;
m_bGotRecTrainingData = kCIDLib::False;
// And then update the training mode field
bStoreBoolFld
(
m_c4FldIdTrainingMode
, m_bRecTrainingMode || m_bBlastTrainingMode
, kCIDLib::True
);
// The UIRT is not in any special mode for this, so nothing more to do
}
// We have to format the data for the indicated command to text
tCIDLib::TVoid
TUSBUIRTSDriver::FormatBlastData(const TIRBlasterCmd& irbcFmt
, TString& strToFill)
{
//
// The data is just the text as ASCII, so we can do a cheap transcode
// to the string by just expanding each byte.
//
// In our case it has a null on it, so don't copy that.
//
const tCIDLib::TCard4 c4Count = irbcFmt.c4DataLen();
strToFill.Clear();
if (c4Count)
{
const tCIDLib::TCard1* pc1Src = irbcFmt.mbufData().pc1Data();
for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count - 1; c4Index++)
strToFill.Append(tCIDLib::TCh(*pc1Src++));
}
}
tCIDLib::TVoid
TUSBUIRTSDriver::InvokeBlastCmd(const TString& strDevice
, const TString& strCmd
, const tCIDLib::TCard4 c4ZoneNum)
{
//
// We can check the zone number up front without locking. They are
// zero based.
//
if (c4ZoneNum >= c4ZoneCount())
{
facCQCIR().ThrowErr
(
CID_FILE
, CID_LINE
, kIRErrs::errcBlast_BadZone
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::CantDo
, TCardinal(c4ZoneNum + 1)
, strMoniker()
);
}
// If we aren't online, then throw
CheckOnline(CID_FILE, CID_LINE);
// We can't allow this if either training mode is active
if (m_bRecTrainingMode || m_bBlastTrainingMode)
{
facCQCIR().ThrowErr
(
CID_FILE
, CID_LINE
, kIRErrs::errcTrain_BusyTraining
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::CantDo
, strMoniker()
);
}
// Look up the command
tCIDLib::TCard4 c4Repeat;
const TIRBlasterCmd& irbcInvoke = irbcFromName(strDevice, strCmd, c4Repeat);
// And send it
SendIRData(irbcInvoke.mbufData(), irbcInvoke.c4DataLen(), c4Repeat, c4ZoneNum);
// Reset the poll counter since we ust verified that it's alive
m_c4PollCount = 0;
}
tCIDLib::TVoid TUSBUIRTSDriver::ReleaseCommResource()
{
try
{
// If we have a handle, then try to close it
if (m_hUIRT != kUSBUIRT::hInvalid)
{
m_pfnCloseProc(m_hUIRT);
m_hUIRT = kUSBUIRT::hInvalid;
}
}
catch(TError& errToCatch)
{
LogError(errToCatch, tCQCKit::EVerboseLvls::Medium, CID_FILE, CID_LINE);
}
}
tCIDLib::TVoid
TUSBUIRTSDriver::SendBlasterData(const tCIDLib::TCard4 c4DataBytes
, const TMemBuf& mbufToSend
, const tCIDLib::TCard4 c4ZoneNum
, const tCIDLib::TCard4 c4RepeatCount)
{
// We can check the zone number up front without locking
if (c4ZoneNum >= c4ZoneCount())
{
facCQCIR().ThrowErr
(
CID_FILE
, CID_LINE
, kIRErrs::errcBlast_BadZone
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::CantDo
, TCardinal(c4ZoneNum + 1)
, strMoniker()
);
}
// If we aren't online, then throw, else lock and do it
CheckOnline(CID_FILE, CID_LINE);
// We can't allow this if either training mode is active
if (m_bRecTrainingMode || m_bBlastTrainingMode)
{
facCQCIR().ThrowErr
(
CID_FILE
, CID_LINE
, kIRErrs::errcTrain_BusyTraining
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::CantDo
, strMoniker()
);
}
// Send the data
SendIRData(mbufToSend, c4DataBytes, c4RepeatCount, c4ZoneNum);
}
tCIDLib::TVoid TUSBUIRTSDriver::TerminateImpl()
{
// If we are in blaster training mode, we have to get out
if (m_bBlastTrainingMode && !m_c4CancelLearn)
{
m_c4CancelLearn = 1;
// Wait for the thread to exit
try
{
if (m_thrLearn.bIsRunning())
m_thrLearn.eWaitForDeath(2000);
}
catch(TError& errToCatch)
{
if (eVerboseLevel() >= tCQCKit::EVerboseLvls::Low)
{
LogError(errToCatch, tCQCKit::EVerboseLvls::Low, CID_FILE, CID_LINE);
facCQCIR().LogMsg
(
CID_FILE
, CID_LINE
, kIRErrs::errcTrain_StopTrainThread
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Term
, strMoniker()
);
}
}
}
// Unload the module if we loaded it
if (m_pmodSupport)
{
try
{
delete m_pmodSupport;
m_pmodSupport = 0;
}
catch(TError& errToCatch)
{
LogError(errToCatch, tCQCKit::EVerboseLvls::Low, CID_FILE, CID_LINE);
}
}
// And call the base IR driver class last
TParent::TerminateImpl();
}
// ---------------------------------------------------------------------------
// TUSBUIRTSDriver: Private, non-virtual methods
// ---------------------------------------------------------------------------
tCIDLib::EExitCodes
TUSBUIRTSDriver::eLearnThread(TThread& thrThis, tCIDLib::TVoid*)
{
// Let the calling thread go
thrThis.Sync();
//
// We don't have to loop or anything here. We are just going to make
// one blocking call.
//
try
{
m_c4CancelLearn = 0;
const tCIDLib::TSInt iRes = m_pfnLearnProc
(
m_hUIRT
, kUSBUIRT::c4IRFmt_Pronto
, m_pchBlastTrainData
, ProgressCallback
, 0
, &m_c4CancelLearn
, 0
, 0
, 0
);
if (iRes)
{
//
// If we didn't get out due to a cancel, then set the flag
// indicating we have data, and set the next event time so
// that if they don't react quickly, we won't pick up any
// other events that come in due to the button they are
// pressing.
//
if (!m_c4CancelLearn)
m_bGotBlastTrainingData = kCIDLib::True;
m_c4NextEventTime = TTime::c4Millis() + 1000;
}
else
{
// We got an error so log it
TKrnlError kerrUUIRT = TKrnlError::kerrLast();
facCQCIR().LogKrnlErr
(
CID_FILE
, CID_LINE
, kIRErrs::errcTrain_TrainError
, kerrUUIRT
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Internal
, strMoniker()
, strUUIRTErr(kerrUUIRT.errcHostId())
);
}
}
catch(...)
{
facCQCIR().LogMsg
(
CID_FILE
, CID_LINE
, kIRErrs::errcTrain_TrainUExcept
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Internal
, strMoniker()
);
}
return tCIDLib::EExitCodes::Normal;
}
const TString&
TUSBUIRTSDriver::strUUIRTErr(const tCIDLib::TOSErrCode errcToLoad)
{
switch(errcToLoad)
{
case kUSBUIRT::c4Err_NoDevice :
return m_strErr_NoDevice;
break;
case kUSBUIRT::c4Err_NoResp :
return m_strErr_NoResp;
break;
case kUSBUIRT::c4Err_NoDLL :
return m_strErr_NoDLL;
break;
case kUSBUIRT::c4Err_Version :
return m_strErr_Version;
break;
};
return m_strErr_Unknown;
}
tCIDLib::TVoid
TUSBUIRTSDriver::SendIRData(const TMemBuf& mbufData
, const tCIDLib::TCard4 c4Bytes
, const tCIDLib::TCard4 c4RepeatCount
, const tCIDLib::TCard4 c4ZoneNum)
{
//
// Map the zone number to the UIRT's zone number. We have to map
// our Zone 0 to its Z3 (which is the front open air blaster), so
// that we maintain backwards compability with the pre-zone support
// version of this driver.
//
// Our mapping is:
//
// Zone 0 : Z3
// Zone 1 : Z1
// Zone 2 : Z2
//
tCIDLib::TSCh chZone;
switch(c4ZoneNum)
{
case 1 :
chZone = '1';
break;
case 2 :
chZone = '2';
break;
default :
chZone = '3';
break;
};
//
// Our data is an ASCII string, but it's stored as binary data and
// the null cannot be stored on it, so we have to put on on, which
// requires making a local buffer. We have to prepend the zone stuff
// before it.
//
tCIDLib::TSCh* pszData = new tCIDLib::TSCh[c4Bytes + 3];
pszData[0] = kCIDLib::chLatin_Z;
pszData[1] = chZone;
TRawMem::CopyMemBuf(pszData + 2, mbufData.pc1Data(), c4Bytes);
pszData[c4Bytes + 2] = 0;
TArrayJanitor<tCIDLib::TSCh> janBuf(pszData);
// And send the data
tCIDLib::TSInt iRet = m_pfnTransmitProc
(
m_hUIRT
, pszData
, kUSBUIRT::c4IRFmt_Pronto
, c4RepeatCount
, 0
, 0
, 0
, 0
);
if (!iRet)
{
TKrnlError kerrUUIRT = TKrnlError::kerrLast();
facCQCIR().ThrowKrnlErr
(
CID_FILE
, CID_LINE
, kIRErrs::errcDev_DevError
, kerrUUIRT
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::Internal
, strMoniker()
, strUUIRTErr(kerrUUIRT.errcHostId())
);
}
}
| 28.934587 | 85 | 0.574137 | DeanRoddey |
c97c9a5cc4291dae894effa8b9782c4ea2d12dd5 | 483 | cpp | C++ | Source/KInk/Private/Hangar/Lifesteal.cpp | DanySpin97/KInk | e9f65cfe20aab39a09467bf8e96e0cc06697a29f | [
"MIT"
] | 4 | 2016-11-30T04:39:51.000Z | 2018-06-29T06:38:27.000Z | Source/KInk/Private/Hangar/Lifesteal.cpp | DanySpin97/KInk | e9f65cfe20aab39a09467bf8e96e0cc06697a29f | [
"MIT"
] | null | null | null | Source/KInk/Private/Hangar/Lifesteal.cpp | DanySpin97/KInk | e9f65cfe20aab39a09467bf8e96e0cc06697a29f | [
"MIT"
] | null | null | null | // Copyright (c) 2016 WiseDragonStd
#include "KInk.h"
#include "Lifesteal.h"
ALifesteal::ALifesteal()
{
Weapon = EWeapon::WFireGun;
}
void ALifesteal::ActivatePowerUp()
{
Super::ActivatePowerUp();
Cast<ACustomPlayerState>(GetWorld()->GetFirstPlayerController()->PlayerState)->Lifesteal += LifestealAdded;
}
void ALifesteal::DeactivatePowerUp()
{
Cast<ACustomPlayerState>(GetWorld()->GetFirstPlayerController()->PlayerState)->Lifesteal -= LifestealAdded;
K2_DestroyActor();
} | 23 | 108 | 0.761905 | DanySpin97 |
c981f5818431a97aad440abe3d029195e7cb5872 | 4,395 | cpp | C++ | src/solidity-frontend/pattern_check.cpp | maktheus/esbmc | 26c2a1e9e45f737e8423aaa1a2cadbc832d17fbe | [
"BSD-3-Clause"
] | null | null | null | src/solidity-frontend/pattern_check.cpp | maktheus/esbmc | 26c2a1e9e45f737e8423aaa1a2cadbc832d17fbe | [
"BSD-3-Clause"
] | null | null | null | src/solidity-frontend/pattern_check.cpp | maktheus/esbmc | 26c2a1e9e45f737e8423aaa1a2cadbc832d17fbe | [
"BSD-3-Clause"
] | null | null | null | #include <solidity-frontend/pattern_check.h>
#include <stdlib.h>
pattern_checker::pattern_checker(
const nlohmann::json &_ast_nodes,
const std::string &_target_func,
const messaget &msg)
: ast_nodes(_ast_nodes), target_func(_target_func), msg(msg)
{
}
bool pattern_checker::do_pattern_check()
{
// TODO: add more functions here to perform more pattern-based checks
msg.status(fmt::format("Checking function {} ...", target_func.c_str()));
unsigned index = 0;
for(nlohmann::json::const_iterator itr = ast_nodes.begin();
itr != ast_nodes.end();
++itr, ++index)
{
if(
(*itr).contains("kind") && (*itr).contains("nodeType") &&
(*itr).contains("name"))
{
// locate the target function
if(
(*itr)["kind"].get<std::string>() == "function" &&
(*itr)["nodeType"].get<std::string>() == "FunctionDefinition" &&
(*itr)["name"].get<std::string>() == target_func)
return start_pattern_based_check(*itr);
}
}
return false;
}
bool pattern_checker::start_pattern_based_check(const nlohmann::json &func)
{
// SWC-115: Authorization through tx.origin
check_authorization_through_tx_origin(func);
return false;
}
void pattern_checker::check_authorization_through_tx_origin(
const nlohmann::json &func)
{
// looking for the pattern require(tx.origin == <VarDeclReference>)
const nlohmann::json &body_stmt = func["body"]["statements"];
msg.progress(
" - Pattern-based checking: SWC-115 Authorization through tx.origin");
msg.debug("statements in function body array ... \n");
unsigned index = 0;
for(nlohmann::json::const_iterator itr = body_stmt.begin();
itr != body_stmt.end();
++itr, ++index)
{
msg.status(fmt::format(" checking function body stmt {}", index));
if(itr->contains("nodeType"))
{
if((*itr)["nodeType"].get<std::string>() == "ExpressionStatement")
{
const nlohmann::json &expr = (*itr)["expression"];
if(expr["nodeType"] == "FunctionCall")
{
if(expr["kind"] == "functionCall")
{
check_require_call(expr);
}
}
}
}
}
}
void pattern_checker::check_require_call(const nlohmann::json &expr)
{
// Checking the authorization argument of require() function
if(expr["expression"]["nodeType"].get<std::string>() == "Identifier")
{
if(expr["expression"]["name"].get<std::string>() == "require")
{
const nlohmann::json &call_args = expr["arguments"];
// Search for tx.origin in BinaryOperation (==) as used in require(tx.origin == <VarDeclReference>)
// There should be just one argument, the BinaryOpration expression.
// Checking 1 argument as in require(<leftExpr> == <rightExpr>)
if(call_args.size() == 1)
{
check_require_argument(call_args);
}
}
}
}
void pattern_checker::check_require_argument(const nlohmann::json &call_args)
{
// This function is used to check the authorization argument of require() funciton
const nlohmann::json &arg_expr = call_args[0];
// look for BinaryOperation "=="
if(arg_expr["nodeType"].get<std::string>() == "BinaryOperation")
{
if(arg_expr["operator"].get<std::string>() == "==")
{
const nlohmann::json &left_expr = arg_expr["leftExpression"];
// Search for "tx", "." and "origin". First, confirm the nodeType is MemeberAccess
// If the nodeType was NOT MemberAccess, accessing "memberName" would throw an exception !
if(
left_expr["nodeType"].get<std::string>() ==
"MemberAccess") // tx.origin is of the type MemberAccess expression
{
check_tx_origin(left_expr);
}
} // end of "=="
} // end of "BinaryOperation"
}
void pattern_checker::check_tx_origin(const nlohmann::json &left_expr)
{
// This function is used to check the Tx.origin pattern used in BinOp expr
if(left_expr["memberName"].get<std::string>() == "origin")
{
if(left_expr["expression"]["nodeType"].get<std::string>() == "Identifier")
{
if(left_expr["expression"]["name"].get<std::string>() == "tx")
{
//assert(!"Found vulnerability SWC-115 Authorization through tx.origin");
msg.error(
"Found vulnerability SWC-115 Authorization through tx.origin");
msg.error("VERIFICATION FAILED");
exit(EXIT_SUCCESS);
}
}
}
}
| 31.847826 | 105 | 0.636633 | maktheus |
c98408bf2920f46c134c379826dc10e57f1d109a | 152 | hpp | C++ | higan/processor/arm/disassembler.hpp | ameer-bauer/higan-097 | a4a28968173ead8251cfa7cd6b5bf963ee68308f | [
"Info-ZIP"
] | 3 | 2016-03-23T01:17:36.000Z | 2019-10-25T06:41:09.000Z | higan/processor/arm/disassembler.hpp | ameer-bauer/higan-097 | a4a28968173ead8251cfa7cd6b5bf963ee68308f | [
"Info-ZIP"
] | null | null | null | higan/processor/arm/disassembler.hpp | ameer-bauer/higan-097 | a4a28968173ead8251cfa7cd6b5bf963ee68308f | [
"Info-ZIP"
] | null | null | null | auto disassemble_arm_instruction(uint32 pc) -> string;
auto disassemble_thumb_instruction(uint32 pc) -> string;
auto disassemble_registers() -> string;
| 38 | 56 | 0.809211 | ameer-bauer |
c9871c91855e4eb966b8fe3d07a7362f569b0aed | 594 | hpp | C++ | include/depthai/common/CameraBoardSocket.hpp | SpectacularAI/depthai-core | 7516ca0d179c5f0769ecdab0020ac3a6de09cab9 | [
"MIT"
] | null | null | null | include/depthai/common/CameraBoardSocket.hpp | SpectacularAI/depthai-core | 7516ca0d179c5f0769ecdab0020ac3a6de09cab9 | [
"MIT"
] | null | null | null | include/depthai/common/CameraBoardSocket.hpp | SpectacularAI/depthai-core | 7516ca0d179c5f0769ecdab0020ac3a6de09cab9 | [
"MIT"
] | null | null | null | #pragma once
#include <ostream>
#include "depthai-shared/common/CameraBoardSocket.hpp"
namespace dai {
inline std::ostream& operator<<(std::ostream& out, const CameraBoardSocket& socket) {
switch(socket) {
case CameraBoardSocket::AUTO:
out << "AUTO";
break;
case CameraBoardSocket::RGB:
out << "RGB";
break;
case CameraBoardSocket::LEFT:
out << "LEFT";
break;
case CameraBoardSocket::RIGHT:
out << "RIGHT";
break;
}
return out;
}
} // namespace dai | 22 | 85 | 0.552189 | SpectacularAI |
c98921e4c917408cb2305561d730e9d24c06342c | 233 | cpp | C++ | cplusplus/cplusplus/main.cpp | youshihou/art | 7921dd58d303baef12de1558dace342e3dcdb924 | [
"MIT"
] | null | null | null | cplusplus/cplusplus/main.cpp | youshihou/art | 7921dd58d303baef12de1558dace342e3dcdb924 | [
"MIT"
] | null | null | null | cplusplus/cplusplus/main.cpp | youshihou/art | 7921dd58d303baef12de1558dace342e3dcdb924 | [
"MIT"
] | null | null | null | //
// main.cpp
// cplusplus-learning
//
// Created by Ankui on 6/12/20.
// Copyright © 2020 Ankui. All rights reserved.
//
#include <iostream>
using namespace std;
int main(int argc, const char * argv[]) {
return 0;
}
| 14.5625 | 48 | 0.626609 | youshihou |
c98922f898ddda43aa5c1b282d9c5446d1b9e7ff | 2,562 | cpp | C++ | src/software/geom/spline.cpp | matthewberends/Software | 4681c7cffc9c1ca8f739ea692daffc490a8c1910 | [
"MIT"
] | null | null | null | src/software/geom/spline.cpp | matthewberends/Software | 4681c7cffc9c1ca8f739ea692daffc490a8c1910 | [
"MIT"
] | null | null | null | src/software/geom/spline.cpp | matthewberends/Software | 4681c7cffc9c1ca8f739ea692daffc490a8c1910 | [
"MIT"
] | null | null | null | #include "software/geom/spline.h"
Spline::Spline(const std::vector<Point>& points) : knots(points)
{
initLinearSegments(points);
}
Spline::Spline(const std::initializer_list<Point>& points) : knots(points)
{
initLinearSegments(points);
}
Point Spline::valueAt(double val) const
{
if (val < 0.0 || val > 1.0)
{
std::stringstream ss;
ss << "Tried to evaluate spline at " << val
<< ", which is outside of domain of the spline: [0,1]";
throw std::invalid_argument(ss.str());
}
Point retval;
if (segments.empty())
{
retval = knots.front();
}
else
{
// Note: this could be more performant with binary search
auto seg_it = std::find_if(segments.begin(), segments.end(),
[&](const SplineSegment& sseg) {
return (val >= sseg.start && val <= sseg.end);
});
if (seg_it == segments.end())
{
std::stringstream ss;
ss << "Tried to evaluate spline at " << val
<< ", which was not in any interval of any segment";
throw std::runtime_error(ss.str());
}
retval = Point(seg_it->x.valueAt(val), seg_it->y.valueAt(val));
}
return retval;
}
size_t Spline::size(void) const
{
return knots.size();
}
const std::vector<Point> Spline::getKnots(void) const
{
return knots;
}
const Point Spline::startPoint(void) const
{
return knots.front();
}
const Point Spline::endPoint(void) const
{
return knots.back();
}
void Spline::initLinearSegments(const std::vector<Point>& points)
{
if (points.size() == 0)
{
throw std::runtime_error("Cannot create spline with no points");
}
else if (points.size() > 1)
{
// only splines with more than one point can have segments
for (size_t i = 1; i < points.size(); i++)
{
double input_start = (i - 1) / ((double)points.size() - 1);
double input_end = (i) / ((double)points.size() - 1);
Polynomial poly_x = Polynomial(std::make_pair(input_start, points[i - 1].x()),
std::make_pair(input_end, points[i].x()));
Polynomial poly_y = Polynomial(std::make_pair(input_start, points[i - 1].y()),
std::make_pair(input_end, points[i].y()));
segments.push_back(SplineSegment(poly_x, poly_y, input_start, input_end));
}
}
}
| 27.548387 | 90 | 0.546838 | matthewberends |
c98b00bb80bfbf6b9c21c3faa781990cf2d19139 | 7,081 | cpp | C++ | IGC/VectorCompiler/unittests/SPIRVConversions/SPIRVConversionsTest.cpp | kurapov-peter/intel-graphics-compiler | 98f7c938df0617912288385d243d6918135f0713 | [
"Intel",
"MIT"
] | 440 | 2018-01-30T00:43:22.000Z | 2022-03-24T17:28:37.000Z | IGC/VectorCompiler/unittests/SPIRVConversions/SPIRVConversionsTest.cpp | kurapov-peter/intel-graphics-compiler | 98f7c938df0617912288385d243d6918135f0713 | [
"Intel",
"MIT"
] | 225 | 2018-02-02T03:10:47.000Z | 2022-03-31T10:50:37.000Z | IGC/VectorCompiler/unittests/SPIRVConversions/SPIRVConversionsTest.cpp | kurapov-peter/intel-graphics-compiler | 98f7c938df0617912288385d243d6918135f0713 | [
"Intel",
"MIT"
] | 138 | 2018-01-30T08:15:11.000Z | 2022-03-22T14:16:39.000Z | /*========================== begin_copyright_notice ============================
Copyright (C) 2019-2021 Intel Corporation
SPDX-License-Identifier: MIT
============================= end_copyright_notice ===========================*/
#include "llvm/ADT/StringRef.h"
#include "llvm/GenXIntrinsics/GenXIntrinsics.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/Error.h"
#include "LLVMSPIRVLib.h"
#include "llvm/Target/TargetMachine.h"
#include "gtest/gtest.h"
#include "llvmWrapper/IR/DerivedTypes.h"
#include <strstream>
#include <memory>
using namespace llvm;
namespace {
static GenXIntrinsic::ID BeginGenXID = llvm::GenXIntrinsic::genx_3d_load;
static GenXIntrinsic::ID EndGenXID = llvm::GenXIntrinsic::genx_zzzzend;
// Currently returns some fixed types.
Type *generateAnyType(Intrinsic::IITDescriptor::ArgKind AK, LLVMContext &Ctx) {
using namespace Intrinsic;
switch (AK) {
case IITDescriptor::AK_Any:
case IITDescriptor::AK_AnyInteger:
return Type::getInt32Ty(Ctx);
case IITDescriptor::AK_AnyFloat:
return Type::getDoubleTy(Ctx);
case IITDescriptor::AK_AnyPointer:
return Type::getInt32PtrTy(Ctx);
case IITDescriptor::AK_AnyVector:
return IGCLLVM::FixedVectorType::get(Type::getInt32Ty(Ctx), 8);
}
llvm_unreachable("All types should be handled");
}
void generateOverloadedTypes(GenXIntrinsic::ID Id, LLVMContext &Ctx,
SmallVectorImpl<Type *> &Tys) {
using namespace Intrinsic;
SmallVector<IITDescriptor, 8> Table;
GenXIntrinsic::getIntrinsicInfoTableEntries(Id, Table);
for (unsigned i = 0, e = Table.size(); i != e; ++i) {
auto Desc = Table[i];
if (Desc.Kind != IITDescriptor::Argument)
continue;
size_t ArgNum = Desc.getArgumentNumber();
Tys.resize(std::max(ArgNum + 1, Tys.size()));
Tys[ArgNum] = generateAnyType(Desc.getArgumentKind(), Ctx);
}
}
static std::string ty2s(Type* ty) {
std::string type_str;
llvm::raw_string_ostream rso(type_str);
ty->print(rso, true);
return rso.str();
}
static std::string k2s(std::map<std::string, Attribute::AttrKind>& s,
Attribute::AttrKind kkk) {
for (const auto& i: s) {
if (i.second == kkk)
return i.first;
}
return "n/a";
}
class SpirvConvertionsTest : public testing::Test {
protected:
void SetUp() override {
M_.reset(new Module("Test_Module", Ctx_));
M_->setTargetTriple("spir64-unknown-unknown");
}
void TearDown() override {
M_.reset();
}
Module* Retranslate(LLVMContext& ctx, std::string& err) {
err.clear();
std::stringstream ss;
writeSpirv(M_.get(), ss, err);
if (!err.empty())
return nullptr;
std::string s_sv_ir = ss.str();
std::istrstream ir_stream(s_sv_ir.data(), s_sv_ir.size());
Module* result = nullptr;
readSpirv(ctx, ir_stream, result, err);
if (!err.empty())
return nullptr;
return result;
}
LLVMContext Ctx_;
std::unique_ptr<Module> M_;
std::set<std::string> FN_;
};
TEST_F(SpirvConvertionsTest, IntrinsicAttrs) {
Type *FArgTy[] = {Type::getInt32PtrTy(Ctx_)};
FunctionType *FT = FunctionType::get(Type::getVoidTy(Ctx_), FArgTy, false);
Function *F = Function::Create(FT, Function::ExternalLinkage, "", M_.get());
BasicBlock *BB = BasicBlock::Create(Ctx_, "", F);
IRBuilder<> Builder(BB);
for (unsigned id = BeginGenXID; id < EndGenXID; ++id) {
GenXIntrinsic::ID XID = static_cast<GenXIntrinsic::ID>(id);
SmallVector<Type *, 8> Tyss;
generateOverloadedTypes(XID, Ctx_, Tyss);
Function* f = GenXIntrinsic::getGenXDeclaration(M_.get(), XID, Tyss);
SmallVector<Value *, 8> Args;
for (Type* ty: f->getFunctionType()->params()) {
Value* arg = llvm::Constant::getNullValue(ty);
Args.push_back(arg);
FN_.insert(f->getName().str());
/*
std::cout << "name: " << f->getName().str() << "\n";
Type* aty = arg->getType();
std::cout << " param_type: " << ty2s(ty) << ' ' << (void*)ty << "\n";
std::cout << " arg_type: " << ty2s(aty) << ' ' << (void*)aty << "\n";
*/
}
Builder.CreateCall(f, Args);
}
llvm::Error merr = M_->materializeAll();
if (merr)
FAIL() << "materialization a module resulted in failure: " << merr << "\n";
std::string err;
LLVMContext C;
Module* M = Retranslate(C, err);
if (!M) {
FAIL() << "failure during retranslation: " << err << "\n";
return;
}
// M_->dump();
// M->dump();
for (const std::string& fname :FN_) {
// std::cout << "processing <" << fname << ">" << "\n";
Function* fl = M->getFunction(fname);
Function* fr = M_->getFunction(fname);
if (!fl)
FAIL() << "could not find <" << fname << "> in the converted Module\n";
if (!fr)
FAIL() << "could not find <" << fname << "> in the original Module\n";
// fl->getAttributes().dump();
// fr->getAttributes().dump();
for (unsigned i = Attribute::None; i < Attribute::EndAttrKinds; ++i) {
Attribute::AttrKind att = (Attribute::AttrKind)i;
EXPECT_TRUE(fl->hasFnAttribute(att) == fr->hasFnAttribute(att));
}
}
}
TEST_F(SpirvConvertionsTest, FunctionAttrs) {
// TODO: think about how one can test all attributes. Right now the problem
// is that I don't know how to diffirentiate between attributes which require
// a value from those that don't.
std::map<std::string, Attribute::AttrKind> kinds = {
{ "Convergent", Attribute::Convergent },
{ "NoReturn", Attribute::NoReturn },
{ "NoInline", Attribute::NoInline },
{ "NoUnwind", Attribute::NoUnwind },
{ "ReadNone", Attribute::ReadNone },
{ "SafeStack", Attribute::SafeStack },
{ "WriteOnly", Attribute::WriteOnly },
};
for (const auto& k : kinds) {
Type *FArgTy[] = {Type::getInt32PtrTy(Ctx_)};
FunctionType *FT = FunctionType::get(Type::getVoidTy(Ctx_), FArgTy, false);
Function* test_f =
Function::Create(FT, Function::ExternalLinkage, k.first, M_.get());
for (unsigned i = Attribute::None; i < Attribute::EndAttrKinds; ++i) {
if (test_f->hasFnAttribute((Attribute::AttrKind)i)) {
test_f->removeFnAttr((Attribute::AttrKind)i);
}
}
test_f->addFnAttr(k.second);
BasicBlock *aux_BB = BasicBlock::Create(Ctx_, "", test_f);
IRBuilder<> aux_Builder(aux_BB);
}
std::string err;
LLVMContext C;
Module* M = Retranslate(C, err);
if (!M) {
FAIL() << "failure during retranslation: " << err << "\n";
return;
}
for (const auto& k : kinds) {
Function* fl = M->getFunction(k.first);
Function* fr = M_->getFunction(k.first);
for (unsigned i = Attribute::None; i < Attribute::EndAttrKinds; ++i) {
Attribute::AttrKind att = (Attribute::AttrKind)i;
if ((fl->hasFnAttribute(att) != fr->hasFnAttribute(att))) {
FAIL() << "Attriubute mismatch for <" << k.first << "> at attr:" <<
i << " (" << k2s(kinds, att) << ")\n";
}
}
}
// M_->dump();
// M->dump();
}
} // namespace
| 29.627615 | 80 | 0.622511 | kurapov-peter |
c993af02c107507b647798e639984858881faf6c | 7,444 | cpp | C++ | Sources/Elastos/Frameworks/Droid/Support/V4/src/elastos/droid/support/v4/view/MotionEventCompat.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/Frameworks/Droid/Support/V4/src/elastos/droid/support/v4/view/MotionEventCompat.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Frameworks/Droid/Support/V4/src/elastos/droid/support/v4/view/MotionEventCompat.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// 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 "elastos/droid/support/v4/view/MotionEventCompat.h"
#include "elastos/droid/support/v4/view/MotionEventCompatEclair.h"
#include "elastos/droid/os/Build.h"
#include <elastos/utility/logging/Logger.h>
using Elastos::Droid::Os::Build;
using Elastos::Droid::Support::V4::View::EIID_IMotionEventVersionImpl;
using Elastos::Utility::Logging::Logger;
namespace Elastos {
namespace Droid {
namespace Support {
namespace V4 {
namespace View {
//=================================================================
// MotionEventCompat::StaticInitializer
//=================================================================
MotionEventCompat::StaticInitializer::StaticInitializer()
{
if (Build::VERSION::SDK_INT >= 5) {
IMPL = new EclairMotionEventVersionImpl();
}
else {
IMPL = new BaseMotionEventVersionImpl();
}
}
//=================================================================
// MotionEventCompat::BaseMotionEventVersionImpl
//=================================================================
CAR_INTERFACE_IMPL(MotionEventCompat::BaseMotionEventVersionImpl, Object, IMotionEventVersionImpl)
ECode MotionEventCompat::BaseMotionEventVersionImpl::FindPointerIndex(
/* [in] */ IMotionEvent* event,
/* [in] */ Int32 pointerId,
/* [out] */ Int32* index)
{
VALIDATE_NOT_NULL(index)
*index = -1;
if (pointerId == 0) {
// id 0 == index 0 and vice versa.
*index = 0;
}
return NOERROR;
}
ECode MotionEventCompat::BaseMotionEventVersionImpl::GetPointerId(
/* [in] */ IMotionEvent* event,
/* [in] */ Int32 pointerIndex,
/* [out] */ Int32* id)
{
VALIDATE_NOT_NULL(id)
if (pointerIndex == 0) {
// index 0 == id 0 and vice versa.
*id = 0;
return NOERROR;
}
*id = -1;
Logger::E("BaseMotionEventVersionImpl", "Pre-Eclair does not support multiple pointers");
return E_INDEX_OUT_OF_BOUNDS_EXCEPTION;
}
ECode MotionEventCompat::BaseMotionEventVersionImpl::GetX(
/* [in] */ IMotionEvent* event,
/* [in] */ Int32 pointerIndex,
/* [out] */ Float* x)
{
VALIDATE_NOT_NULL(x)
if (pointerIndex == 0) {
return event->GetX(x);
}
*x = -1;
Logger::E("BaseMotionEventVersionImpl", "Pre-Eclair does not support multiple pointers");
return E_INDEX_OUT_OF_BOUNDS_EXCEPTION;
}
ECode MotionEventCompat::BaseMotionEventVersionImpl::GetY(
/* [in] */ IMotionEvent* event,
/* [in] */ Int32 pointerIndex,
/* [out] */ Float* y)
{
VALIDATE_NOT_NULL(y)
if (pointerIndex == 0) {
return event->GetY(y);
}
*y = -1;
Logger::E("BaseMotionEventVersionImpl", "Pre-Eclair does not support multiple pointers");
return E_INDEX_OUT_OF_BOUNDS_EXCEPTION;
}
ECode MotionEventCompat::BaseMotionEventVersionImpl::GetPointerCount(
/* [in] */ IMotionEvent* event,
/* [out] */ Int32* count)
{
VALIDATE_NOT_NULL(count)
*count = 1;
return NOERROR;
}
//=================================================================
// MotionEventCompat::EclairMotionEventVersionImpl
//=================================================================
CAR_INTERFACE_IMPL(MotionEventCompat::EclairMotionEventVersionImpl, Object, IMotionEventVersionImpl)
ECode MotionEventCompat::EclairMotionEventVersionImpl::FindPointerIndex(
/* [in] */ IMotionEvent* event,
/* [in] */ Int32 pointerId,
/* [out] */ Int32* index)
{
VALIDATE_NOT_NULL(index)
return MotionEventCompatEclair::FindPointerIndex(event, pointerId, index);
}
ECode MotionEventCompat::EclairMotionEventVersionImpl::GetPointerId(
/* [in] */ IMotionEvent* event,
/* [in] */ Int32 pointerIndex,
/* [out] */ Int32* id)
{
VALIDATE_NOT_NULL(id)
return MotionEventCompatEclair::GetPointerId(event, pointerIndex, id);
}
ECode MotionEventCompat::EclairMotionEventVersionImpl::GetX(
/* [in] */ IMotionEvent* event,
/* [in] */ Int32 pointerIndex,
/* [out] */ Float* x)
{
VALIDATE_NOT_NULL(x)
return MotionEventCompatEclair::GetX(event, pointerIndex, x);
}
ECode MotionEventCompat::EclairMotionEventVersionImpl::GetY(
/* [in] */ IMotionEvent* event,
/* [in] */ Int32 pointerIndex,
/* [out] */ Float* y)
{
VALIDATE_NOT_NULL(y)
return MotionEventCompatEclair::GetY(event, pointerIndex, y);
}
ECode MotionEventCompat::EclairMotionEventVersionImpl::GetPointerCount(
/* [in] */ IMotionEvent* event,
/* [out] */ Int32* count)
{
VALIDATE_NOT_NULL(count)
return MotionEventCompatEclair::GetPointerCount(event, count);
}
//=================================================================
// MotionEventCompat
//=================================================================
AutoPtr<IMotionEventVersionImpl> MotionEventCompat::IMPL;
MotionEventCompat::StaticInitializer MotionEventCompat::sInitializer;
const Int32 MotionEventCompat::ACTION_MASK;
const Int32 MotionEventCompat::ACTION_POINTER_DOWN;
const Int32 MotionEventCompat::ACTION_POINTER_UP;
const Int32 MotionEventCompat::ACTION_HOVER_MOVE;
const Int32 MotionEventCompat::ACTION_SCROLL;
const Int32 MotionEventCompat::ACTION_POINTER_INDEX_MASK;
const Int32 MotionEventCompat::ACTION_POINTER_INDEX_SHIFT;
const Int32 MotionEventCompat::ACTION_HOVER_ENTER;
const Int32 MotionEventCompat::ACTION_HOVER_EXIT;
Int32 MotionEventCompat::GetActionMasked(
/* [in] */ IMotionEvent* event)
{
Int32 action;
event->GetAction(&action);
return action & ACTION_MASK;
}
Int32 MotionEventCompat::GetActionIndex(
/* [in] */ IMotionEvent* event)
{
Int32 action;
event->GetAction(&action);
return (action & ACTION_POINTER_INDEX_MASK) >> ACTION_POINTER_INDEX_SHIFT;
}
Int32 MotionEventCompat::FindPointerIndex(
/* [in] */ IMotionEvent* event,
/* [in] */ Int32 pointerId)
{
Int32 index;
IMPL->FindPointerIndex(event, pointerId, &index);
return index;
}
Int32 MotionEventCompat::GetPointerId(
/* [in] */ IMotionEvent* event,
/* [in] */ Int32 pointerIndex)
{
Int32 id;
IMPL->GetPointerId(event, pointerIndex, &id);
return id;
}
Float MotionEventCompat::GetX(
/* [in] */ IMotionEvent* event,
/* [in] */ Int32 pointerIndex)
{
Float x;
IMPL->GetX(event, pointerIndex, &x);
return x;
}
Float MotionEventCompat::GetY(
/* [in] */ IMotionEvent* event,
/* [in] */ Int32 pointerIndex)
{
Float y;
IMPL->GetY(event, pointerIndex, &y);
return y;
}
Int32 MotionEventCompat::GetPointerCount(
/* [in] */ IMotionEvent* event)
{
Int32 count;
IMPL->GetPointerCount(event, &count);
return count;
}
} // namespace View
} // namespace V4
} // namespace Support
} // namespace Droid
} // namespace Elastos
| 29.895582 | 100 | 0.635411 | jingcao80 |
c995886ef90dfe5fec483adb02c06dde94ecedd9 | 4,750 | cpp | C++ | src/solutions/untexturedobjects/gl/drawloop.cpp | michaelmarks/apitest | d252e949f82cc005d2cb443de9d08bb8d984cabc | [
"Unlicense"
] | 172 | 2015-01-05T15:36:14.000Z | 2022-03-11T10:57:23.000Z | src/solutions/untexturedobjects/gl/drawloop.cpp | michaelmarks/apitest | d252e949f82cc005d2cb443de9d08bb8d984cabc | [
"Unlicense"
] | 19 | 2015-02-19T00:48:36.000Z | 2020-02-21T01:23:26.000Z | src/solutions/untexturedobjects/gl/drawloop.cpp | michaelmarks/apitest | d252e949f82cc005d2cb443de9d08bb8d984cabc | [
"Unlicense"
] | 28 | 2015-01-08T12:16:18.000Z | 2020-05-30T18:07:36.000Z | #include "pch.h"
#include "drawloop.h"
#include "framework/gfx_gl.h"
// --------------------------------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------------------------
UntexturedObjectsGLDrawLoop::UntexturedObjectsGLDrawLoop()
: m_ib()
, m_vb()
, m_varray()
, m_drawid()
, m_prog()
, m_transform_buffer()
{ }
// --------------------------------------------------------------------------------------------------------------------
bool UntexturedObjectsGLDrawLoop::Init(const std::vector<UntexturedObjectsProblem::Vertex>& _vertices,
const std::vector<UntexturedObjectsProblem::Index>& _indices,
size_t _objectCount)
{
if (!UntexturedObjectsSolution::Init(_vertices, _indices, _objectCount)) {
return false;
}
// Program
const char* kUniformNames[] = { "ViewProjection", nullptr };
m_prog = CreateProgramT("cubes_gl_multi_draw_vs.glsl",
"cubes_gl_multi_draw_fs.glsl",
kUniformNames, &mUniformLocation);
if (m_prog == 0) {
console::warn("Unable to initialize solution '%s', shader compilation/linking failed.", GetName().c_str());
return false;
}
glGenVertexArrays(1, &m_varray);
glBindVertexArray(m_varray);
// Buffers
glGenBuffers(1, &m_vb);
glBindBuffer(GL_ARRAY_BUFFER, m_vb);
glBufferData(GL_ARRAY_BUFFER, _vertices.size() * sizeof(UntexturedObjectsProblem::Vertex), &*_vertices.begin(), GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(UntexturedObjectsProblem::Vertex), (void*) offsetof(UntexturedObjectsProblem::Vertex, pos));
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(UntexturedObjectsProblem::Vertex), (void*) offsetof(UntexturedObjectsProblem::Vertex, color));
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
std::vector<uint32_t> drawids(_objectCount);
for (uint32_t i = 0; i < _objectCount; ++i) {
drawids[i] = i;
}
glGenBuffers(1, &m_drawid);
glBindBuffer(GL_ARRAY_BUFFER, m_drawid);
glBufferData(GL_ARRAY_BUFFER, drawids.size() * sizeof(uint32_t), drawids.data(), GL_STATIC_DRAW);
glVertexAttribIPointer(2, 1, GL_UNSIGNED_INT, sizeof(uint32_t), 0);
glVertexAttribDivisor(2, 1);
glEnableVertexAttribArray(2);
glGenBuffers(1, &m_ib);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ib);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, _indices.size() * sizeof(UntexturedObjectsProblem::Index), &*_indices.begin(), GL_STATIC_DRAW);
glGenBuffers(1, &m_transform_buffer);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, m_transform_buffer);
return GLRenderer::GetApiError() == GL_NO_ERROR;
}
// --------------------------------------------------------------------------------------------------------------------
void UntexturedObjectsGLDrawLoop::Render(const std::vector<Matrix>& _transforms)
{
size_t count = _transforms.size();
assert(count <= mObjectCount);
// Program
Vec3 dir = { -0.5f, -1, 1 };
Vec3 at = { 0, 0, 0 };
Vec3 up = { 0, 0, 1 };
dir = normalize(dir);
Vec3 eye = at - 250 * dir;
Matrix view = matrix_look_at(eye, at, up);
Matrix view_proj = mProj * view;
glUseProgram(m_prog);
glUniformMatrix4fv(mUniformLocation.ViewProjection, 1, GL_TRUE, &view_proj.x.x);
// Rasterizer State
glEnable(GL_CULL_FACE);
glCullFace(GL_FRONT);
glDisable(GL_SCISSOR_TEST);
// Blend State
glDisable(GL_BLEND);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
// Depth Stencil State
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, m_transform_buffer);
glBufferData(GL_SHADER_STORAGE_BUFFER, _transforms.size() * sizeof(Matrix), &*_transforms.begin(), GL_DYNAMIC_DRAW);
for (size_t u = 0; u < count; ++u) {
glDrawElementsInstancedBaseInstance(GL_TRIANGLES, mIndexCount, GL_UNSIGNED_SHORT, nullptr, 1, u);
}
}
// --------------------------------------------------------------------------------------------------------------------
void UntexturedObjectsGLDrawLoop::Shutdown()
{
glDisableVertexAttribArray(2);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(0);
glDeleteBuffers(1, &m_ib);
glDeleteBuffers(1, &m_vb);
glDeleteVertexArrays(1, &m_varray);
glDeleteBuffers(1, &m_drawid);
glDeleteBuffers(1, &m_transform_buffer);
glDeleteProgram(m_prog);
}
| 37.698413 | 153 | 0.584632 | michaelmarks |
c99a63623f4ce3fa4894067ee5b48bfac0f876d4 | 555 | cc | C++ | simctty/main_web.cc | skip2/simctty | 0de7a58f77a14367361637601816bf6c657f96a2 | [
"MIT"
] | 4 | 2016-10-01T00:13:13.000Z | 2020-06-10T10:09:56.000Z | simctty/main_web.cc | skip2/simctty | 0de7a58f77a14367361637601816bf6c657f96a2 | [
"MIT"
] | null | null | null | simctty/main_web.cc | skip2/simctty | 0de7a58f77a14367361637601816bf6c657f96a2 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include "simctty/system.h"
int main(int argc, char** argv) {
System system;
uint64 cycle_count = 0;
const uint64 cycles_per_iteration = 20000000 / 1000;
fprintf(stdout, "Running\n");
if (!system.LoadImageFile("vmlinux.bin", 0x100)) {
fprintf(stderr, "Unable to load image\n");
return EXIT_FAILURE;
}
while (system.Run(cycles_per_iteration)) {
cycle_count += cycles_per_iteration;
while (system.GetUART()->CanRead()) {
fprintf(stderr, "%c", system.GetUART()->Read());
}
}
return 1;
}
| 19.821429 | 54 | 0.654054 | skip2 |
c99c85a7c469b6f6329eacc2be26f3cb09a856ee | 928 | cpp | C++ | src/videowidget.cpp | radzevich/VSPlayer | b645589460cfc0ca4e5eae6ad4b0b1c1d4fc5c87 | [
"Apache-2.0"
] | 1 | 2020-07-07T01:41:22.000Z | 2020-07-07T01:41:22.000Z | src/videowidget.cpp | radzevich/VSPlayer | b645589460cfc0ca4e5eae6ad4b0b1c1d4fc5c87 | [
"Apache-2.0"
] | null | null | null | src/videowidget.cpp | radzevich/VSPlayer | b645589460cfc0ca4e5eae6ad4b0b1c1d4fc5c87 | [
"Apache-2.0"
] | null | null | null | #include "videowidget.h"
#include <QMouseEvent>
VideoWidget::VideoWidget(QWidget *parent)
: QVideoWidget(parent)
{
setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
QPalette p = palette();
p.setColor(QPalette::Window, Qt::black);
setPalette(p);
setAttribute(Qt::WA_OpaquePaintEvent);
}
void VideoWidget::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_Escape && isFullScreen()) {
setFullScreen(false);
event->accept();
} else if (event->key() == Qt::Key_Enter && event->modifiers() & Qt::Key_Alt) {
setFullScreen(!isFullScreen());
event->accept();
} else {
QVideoWidget::keyPressEvent(event);
}
}
void VideoWidget::mouseDoubleClickEvent(QMouseEvent *event)
{
setFullScreen(!isFullScreen());
event->accept();
}
void VideoWidget::mousePressEvent(QMouseEvent *event)
{
QVideoWidget::mousePressEvent(event);
}
| 23.2 | 83 | 0.665948 | radzevich |
c99ffecc9ddb304c52d3daa18a88de9186d05572 | 371 | hpp | C++ | source/ioc/PSCSup/ao.hpp | binp-dev/ferrite | 1b9b7d1d4915c6c900728b8e1710052b9768d45e | [
"MIT"
] | null | null | null | source/ioc/PSCSup/ao.hpp | binp-dev/ferrite | 1b9b7d1d4915c6c900728b8e1710052b9768d45e | [
"MIT"
] | null | null | null | source/ioc/PSCSup/ao.hpp | binp-dev/ferrite | 1b9b7d1d4915c6c900728b8e1710052b9768d45e | [
"MIT"
] | null | null | null | #pragma once
#include <aoRecord.h>
#include "value.hpp"
#include <record/value.hpp>
class AoRecord final : public EpicsOutputValueRecord<int32_t, aoRecord>, public virtual OutputValueRecord<int32_t> {
public:
inline explicit AoRecord(aoRecord *raw) : EpicsOutputValueRecord<int32_t, aoRecord>(raw) {}
[[nodiscard]] virtual int32_t value() const override;
};
| 24.733333 | 116 | 0.754717 | binp-dev |
c9a3c9c6d12ee0a8736938d745cc99dfc6b4809c | 4,217 | cpp | C++ | B4860-V6/b4860-v6.si4project/Backup/hub(3044).cpp | miaopei/B4860-test | a1a38f6ed80594e6d3090939e4bf3df4e1bdad25 | [
"MIT"
] | null | null | null | B4860-V6/b4860-v6.si4project/Backup/hub(3044).cpp | miaopei/B4860-test | a1a38f6ed80594e6d3090939e4bf3df4e1bdad25 | [
"MIT"
] | null | null | null | B4860-V6/b4860-v6.si4project/Backup/hub(3044).cpp | miaopei/B4860-test | a1a38f6ed80594e6d3090939e4bf3df4e1bdad25 | [
"MIT"
] | null | null | null | /*************************************************************************
> File Name: hub_client.cpp
> Author: miaopei
> Mail: miaopei@baicells.com
> Created Time: 2020年02月12日 星期三 11时16分50秒
************************************************************************/
#include <iostream>
#include <string.h>
#include "hub.h"
using namespace uv;
using namespace std;
HUB::HUB(uv::EventLoop* loop)
:TcpClient(loop),
sockAddr(nullptr)
{
setConnectStatusCallback(std::bind(&HUB::onConnect, this, std::placeholders::_1));
setMessageCallback(std::bind(&HUB::RecvMesg, this, std::placeholders::_1, std::placeholders::_2));
}
void HUB::connectToServer(uv::SocketAddr& addr)
{
sockAddr = std::make_shared<uv::SocketAddr>(addr);
connect(addr);
}
void HUB::reConnect()
{
uv::Timer* timer = new uv::Timer(loop_, 500, 0, [this](uv::Timer* ptr)
{
connect(*(sockAddr.get()));
ptr->close([](uv::Timer* ptr)
{
delete ptr;
});
});
timer->start();
}
void HUB::sendTestMessage()
{
// packet 封装
#if 1
std::string data = "key=value&key2=value2";
uv::PacketIR packetir;
packetir.SetHead(to_string(uv::PacketIR::HUB),
to_string(uv::PacketIR::TO_BBU),
to_string(uv::PacketIR::REQUEST),
to_string(uv::PacketIR::MSG_CONNECT),
to_string(uv::PacketIR::RRUID_2),
to_string(uv::PacketIR::PORT_0),
to_string(uv::PacketIR::UPORT_4));
packetir.PackMessage(data, data.length());
std::cout << "封装 packet:" << std::endl;
std::cout << "\tPacket: " << packetir.GetPacket() << std::endl;
std::cout << "\tHead: " << packetir.GetHead() << std::endl;
std::cout << "\tSource: " << packetir.GetSource() << std::endl;
std::cout << "\tDestination: " << packetir.GetDestination() << std::endl;
std::cout << "\tState: " << packetir.GetState() << std::endl;
std::cout << "\tMsgID: " << packetir.GetMsgID() << std::endl;
std::cout << "\tRRUID: " << packetir.GetRRUID() << std::endl;
std::cout << "\tPort: " << packetir.GetPort() << std::endl;
std::cout << "\tUPort: " << packetir.GetUPort() << std::endl;
std::cout << "\tLength: " << packetir.GetLength() << std::endl;
std::cout << "\tData: " << packetir.GetData() << std::endl;
std::cout << "\tData Length: " << data.length() << std::endl;
std::string send_buf = packetir.GetPacket();
write(send_buf.c_str(), send_buf.length());
#endif
}
void HUB::onConnect(ConnectStatus status)
{
if(status != ConnectStatus::OnConnectSuccess)
{
reConnect();
} else {
sendTestMessage();
}
}
void HUB::newMessage(const char* buf, ssize_t size)
{
std::cout << "HUB newMessage: " << std::string(buf, size) << std::endl;
#if 0
if(uv::GlobalConfig::BufferModeStatus == uv::GlobalConfig::NoBuffer)
{
write(buf, (unsigned int)size);
} else {
auto packetbuf = getCurrentBuf();
if(nullptr != packetbuf)
{
packetbuf->append(buf, static_cast<int>(size));
uv::Packet packet;
while(0 == packetbuf->readPacket(packet))
{
write(packet.Buffer().c_str(), (unsigned)packet.PacketSize(), nullptr);
}
}
}
#endif
}
void HUB::RecvMesg(const char* buf, ssize_t size)
{
std::cout << "HUB Recv Msg: " << std::string(buf, size) << std::endl;
//string msg = "ttt";
//write(msg.c_str(), msg.length());
}
void HUB::SendMesg(const char* buf, ssize_t size)
{
std::cout << "Client::SendMesg" << std::endl;
if(uv::GlobalConfig::BufferModeStatus == uv::GlobalConfig::NoBuffer)
{
writeInLoop(buf, (unsigned int)size, nullptr);
} else {
auto packetbuf = getCurrentBuf();
if(nullptr != packetbuf)
{
packetbuf->append(buf, static_cast<int>(size));
uv::Packet packet;
while(0 == packetbuf->readPacket(packet))
{
write(packet.Buffer().c_str(), (unsigned)packet.PacketSize(), nullptr);
}
}
}
}
void HUB::SendMesgThread()
{
sendTestMessage();
}
| 29.284722 | 102 | 0.553711 | miaopei |
c9a782c1fe1c1af5b9627e30bd010014d0854c75 | 443 | cpp | C++ | src/backends/sdl/system/event/wait.cpp | freundlich/libawl | 0d51f388a6b662373058cb51a24ef25ed826fa0f | [
"BSL-1.0"
] | null | null | null | src/backends/sdl/system/event/wait.cpp | freundlich/libawl | 0d51f388a6b662373058cb51a24ef25ed826fa0f | [
"BSL-1.0"
] | null | null | null | src/backends/sdl/system/event/wait.cpp | freundlich/libawl | 0d51f388a6b662373058cb51a24ef25ed826fa0f | [
"BSL-1.0"
] | null | null | null | #include <awl/backends/sdl/exception.hpp>
#include <awl/backends/sdl/system/event/wait.hpp>
#include <fcppt/text.hpp>
#include <fcppt/config/external_begin.hpp>
#include <SDL_events.h>
#include <fcppt/config/external_end.hpp>
SDL_Event awl::backends::sdl::system::event::wait()
{
SDL_Event result;
if (SDL_WaitEvent(&result) == 0)
{
throw awl::backends::sdl::exception{FCPPT_TEXT("SDL_WaitEvent failed!")};
}
return result;
}
| 23.315789 | 77 | 0.724605 | freundlich |
c9a97d9e835fd97a63f4622a646a0355d279fd56 | 4,660 | cpp | C++ | app/lib/gt_core/src/trainer.cpp | my-repositories/GameTrainer | fd307e0bd6e0ef74e8b3195ad6394c71e2fac555 | [
"MIT"
] | 3 | 2018-10-11T13:37:42.000Z | 2021-03-23T21:54:02.000Z | app/lib/gt_core/src/trainer.cpp | my-repositories/GameTrainer | fd307e0bd6e0ef74e8b3195ad6394c71e2fac555 | [
"MIT"
] | null | null | null | app/lib/gt_core/src/trainer.cpp | my-repositories/GameTrainer | fd307e0bd6e0ef74e8b3195ad6394c71e2fac555 | [
"MIT"
] | null | null | null | #include <gt_core/trainer.hpp>
#include <gt_os/window-finder.hpp>
#include <gt_os/window-enumerator.hpp>
namespace gt::core {
Trainer::Trainer(std::string&& trainerTitle, os::OsApi *osApi)
: title(trainerTitle) {
os::setConsoleTitle(this->title.c_str());
this->osApi = osApi;
}
Trainer::~Trainer() = default;
bool Trainer::trainerIsRunning() const {
os::WindowEnumerator windowEnumerator(this->osApi);
os::WindowFinder windowFinder(&windowEnumerator);
os::WindowManager windowManager(this->osApi, &windowFinder);
return windowManager.isOpened(this->title);
}
void Trainer::showOpenedWindow() const {
os::WindowEnumerator windowEnumerator(this->osApi);
os::WindowFinder windowFinder(&windowEnumerator);
os::WindowManager windowManager(this->osApi, &windowFinder);
windowManager.show(this->title);
}
void Trainer::start() const {
lua::LuaWrapper lua;
void (*lambada)(xml::CheatEntry *, float) = [](xml::CheatEntry *entry,
float valueToAdd) {
DWORD processId = os::getProcessIdByName("KillingFloor.exe");
Game game(processId, &os::OsApi::getInstance());
game.updateValue(entry, valueToAdd);
};
lua.registerFunction("addValueTo", lambada);
// TODO: remove unused parameter for stopMP3.
lua.registerFunction("stopMP3", os::stopMP3);
lua.registerFunction("playMP3", os::playMP3);
lua.registerFunction("playWAV", os::playWAV);
lua.registerFunction("readFile", lua::LuaWrapper::createUserData);
loadLuaState(lua);
const auto registeredKeys = lua.getVector<int>((char *)"registeredKeys");
const char *processName = *lua.getValue<char *>((char *)"processName");
std::cout << processName << std::endl;
os::KeyboardWatcher keyboardWatcher(registeredKeys, this->osApi);
for (;; os::sleep(50)) {
// TODO: remove it!
if (keyboardWatcher.isKeyDown(VK_F12)) {
break;
}
// TODO: uncomment it!
// Close Trainer IF GAME is NOT RUNNING
// if (!gameIsRunning())
// {
// break;
// }
// TODO: uncomment it!
// // Continue IF GAME is not active || PLAYER is DEAD
// if (!GameOnFocus() || game->PlayerIsDead())
// {
// Sleep(1000);
// continue;
// }
// // Rewrite data if FREEZE FLAG enabled
// if (bGodMode)
// {
// game->UpdateData1();
// }
// if (bNoReload)
// {
// game->UpdateData2();
// }
for (const int key : registeredKeys) {
if (keyboardWatcher.isKeyPressed(key)) {
lua.callFunction("handleKey", key,
keyboardWatcher.isKeyDown(VK_SHIFT),
keyboardWatcher.isKeyDown(VK_CONTROL),
keyboardWatcher.isKeyDown(VK_MENU));
}
}
}
}
bool Trainer::chooseConfig() const {
std::cout << "method 'Trainer::chooseConfig' is not implemented yet!"
<< std::endl;
return true;
}
bool Trainer::gameIsRunning() const {
std::cout << "method 'Trainer::gameIsRunning' is not implemented yet!"
<< std::endl;
return true;
}
void loadLuaState(lua::LuaWrapper &lua) {
#if DEBUG
constexpr char *script = (char *)R"(
keyCodes = {
VK_F5 = 0x74,
VK_F6 = 0x75,
VK_F7 = 0x76,
VK_F8 = 0x77,
VK_F9 = 0x78
}
api = {
playSound = playSound,
addValueTo = addValueTo,
readFile = readFile
}
processName = 'KillingFloor.exe'
entries = api.readFile('KillingFloor.CT')
registeredKeys = {
keyCodes.VK_F6,
keyCodes.VK_F7,
keyCodes.VK_F8,
keyCodes.VK_F9
}
function handleKey (key, shift, ctrl, alt)
if key == keyCodes.VK_F6 then
print('god mode')
api.playSound('sounds/on.wav')
elseif key == keyCodes.VK_F7 then
print('no reload')
api.playSound('sounds/on.wav')
elseif key == keyCodes.VK_F8 then
api.addValueTo(entries.money, 1000)
print('increase money')
api.playSound('sounds/money.wav')
elseif key == keyCodes.VK_F9 and shift and ctrl and alt then
print('level up for all perks')
api.playSound('sounds/experience.wav')
end
end
function tick()
-- addValueTo(entries.armor, 100)
end
)";
lua.loadString(script);
#else
lua.loadFile("scripts/KillingFloor.lua");
#endif
}
} // namespace gt::core
| 28.072289 | 77 | 0.583262 | my-repositories |
c9ac6d0aff5e734df80b8d02b9bc3dad3e1b610a | 1,308 | cpp | C++ | src/main.cpp | ithamsteri/homework_05 | 713cb2558bd66fbbbaea656d96f430ed3be0551a | [
"MIT"
] | null | null | null | src/main.cpp | ithamsteri/homework_05 | 713cb2558bd66fbbbaea656d96f430ed3be0551a | [
"MIT"
] | 2 | 2018-09-22T13:27:08.000Z | 2018-10-16T16:42:52.000Z | src/main.cpp | ithamsteri/homework_05 | 713cb2558bd66fbbbaea656d96f430ed3be0551a | [
"MIT"
] | null | null | null | #include "DocumentController.h"
#include "DocumentModel.h"
#include "DocumentView.h"
#include "storages/SVG_Storage.h"
#include <iostream>
#include <string>
int main(int, char *[]) {
// ***************************
// * Setup MVC components *
// ***************************
DocumentModel model;
DocumentView view(model);
DocumentController controller(model, view);
// ****************************
// * Work with empty document *
// ****************************
controller.addShape(Shape::Circle, "x=100;y=323;radius=3");
controller.addShape(Shape::Rectangle, "x=10;y=30;width=100;height=390");
controller.clear();
// *****************************************
// * Load from storage and modify document *
// *****************************************
SVGStorage storage;
controller.load(&storage, "filename: funny.svg");
auto rect_id = controller.addShape(Shape::Rectangle, "x=100;y=10;width=140;height=30");
auto circle_id = controller.addShape(Shape::Circle, "x=10;y=5;radius=12");
controller.removeShape(rect_id);
std::clog << "Serialized data of Circle: " << controller.getShape(circle_id) << '\n';
// save to storage with new filename
controller.save(&storage, "filename: funny_new.svg");
return 0;
}
| 33.538462 | 91 | 0.560398 | ithamsteri |
c9af0bc0a6b59a70ac6d8389b7936f9559638e00 | 212 | cpp | C++ | chapter-7/7.39.cpp | zero4drift/Cpp-Primer-5th-Exercises | d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f | [
"MIT"
] | null | null | null | chapter-7/7.39.cpp | zero4drift/Cpp-Primer-5th-Exercises | d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f | [
"MIT"
] | null | null | null | chapter-7/7.39.cpp | zero4drift/Cpp-Primer-5th-Exercises | d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f | [
"MIT"
] | null | null | null | // Illegal
// it will introduce a ambiguous-like call, when there is a statememt trying to define a object of Sales_data class type but without arguments, compiler does not know which one is better to be called.
| 70.666667 | 200 | 0.787736 | zero4drift |
c9b0645c63044fa0174cbf257e6a4a1e32bf15df | 1,152 | cpp | C++ | Codeforces Round #303 (Div. 2)/B. Equidistant String/B. Equidistant String/main.cpp | anirudha-ani/Codeforces | 6c7f64257939d44b1c2ec9dd202f1c9f899f1cad | [
"Apache-2.0"
] | null | null | null | Codeforces Round #303 (Div. 2)/B. Equidistant String/B. Equidistant String/main.cpp | anirudha-ani/Codeforces | 6c7f64257939d44b1c2ec9dd202f1c9f899f1cad | [
"Apache-2.0"
] | null | null | null | Codeforces Round #303 (Div. 2)/B. Equidistant String/B. Equidistant String/main.cpp | anirudha-ani/Codeforces | 6c7f64257939d44b1c2ec9dd202f1c9f899f1cad | [
"Apache-2.0"
] | null | null | null | //
// main.cpp
// B. Equidistant String
//
// Created by Anirudha Paul on 5/21/15.
// Copyright (c) 2015 Anirudha Paul. All rights reserved.
//
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
int main(int argc, const char * argv[])
{
string first ;
string second ;
cin.clear();
getline(cin,first);
cin.clear();
getline(cin,second);
char answer[100000];
long long length = first.length();
int same = 0 ;
int notSame = 0;
for (int i = 0 ; i < length ; i++)
{
if (first[i] == second[i])
{
same++;
answer[i] = first[i];
}
else
{
notSame++;
if (notSame%2 == 0)
{
answer[i] = first[i];
}
else
{
answer[i] = second[i];
}
}
}
if (notSame % 2 != 0)
{
printf("impossible");
}
else
{
for (int i = 0 ; i < length ; i++)
printf("%c" , answer[i]);
}
printf("\n");
return 0;
}
| 16.695652 | 58 | 0.422743 | anirudha-ani |
c9b1b9994010f3e31021925d781504d7a507db83 | 2,813 | hpp | C++ | include/lz_end_toolkit/construct_lcp.hpp | dkempa/lz-end-toolkit | d0a0bd0fd3ec6adc1df198190d588fbaa8ae7496 | [
"MIT"
] | 1 | 2021-06-24T07:27:41.000Z | 2021-06-24T07:27:41.000Z | include/lz_end_toolkit/construct_lcp.hpp | dkempa/lz-end-toolkit | d0a0bd0fd3ec6adc1df198190d588fbaa8ae7496 | [
"MIT"
] | null | null | null | include/lz_end_toolkit/construct_lcp.hpp | dkempa/lz-end-toolkit | d0a0bd0fd3ec6adc1df198190d588fbaa8ae7496 | [
"MIT"
] | null | null | null | /**
* @file construct_lcp.hpp
* @section LICENCE
*
* This file is part of LZ-End Toolkit v0.1.0
* See: https://github.com/dominikkempa/lz-end-toolkit
*
* Published in:
* Dominik Kempa and Dmitry Kosolobov:
* LZ-End Parsing in Compressed Space.
* Data Compression Conference (DCC), IEEE, 2017.
*
* Copyright (C) 2016-2021
* Dominik Kempa <dominik.kempa (at) gmail.com>
* Dmitry Kosolobov <dkosolobov (at) mail.ru>
*
* 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.
**/
#ifndef __LZ_END_TOOLKIT_CONSTRUCT_LCP_HPP_INCLUDED
#define __LZ_END_TOOLKIT_CONSTRUCT_LCP_HPP_INCLUDED
#include <cstdint>
#include "../utils/utils.hpp"
namespace lz_end_toolkit_private {
template<typename char_type,
typename sa_int_type,
typename lcp_int_type>
void construct_lcp(
const char_type *text,
std::uint64_t text_length,
const sa_int_type *sa,
lcp_int_type *lcp_array) {
lcp_int_type *phi = lcp_array;
lcp_int_type *plcp = utils::allocate_array<lcp_int_type>(text_length);
std::uint64_t phi_undefined_index = sa[0];
for (std::uint64_t i = 1; i < text_length; ++i) {
std::uint64_t addr = sa[i];
phi[addr] = sa[i - 1];
}
std::uint64_t lcp = 0;
for (std::uint64_t i = 0; i < text_length; ++i) {
if (i == phi_undefined_index) {
plcp[i] = 0;
continue;
}
std::uint64_t j = phi[i];
while (i + lcp < text_length && j + lcp < text_length
&& text[i + lcp] == text[j + lcp]) ++lcp;
plcp[i] = (lcp_int_type)lcp;
if (lcp > 0)
--lcp;
}
for (std::uint64_t i = 0; i < text_length; ++i) {
std::uint64_t addr = sa[i];
lcp_array[i] = plcp[addr];
}
utils::deallocate(plcp);
}
} // namespace lz_end_toolkit_private
#endif // __LZ_END_TOOLKIT_CONSTRUCT_LCP_HPP_INCLUDED
| 29.925532 | 72 | 0.697476 | dkempa |
c9b2936735b10c9b2c937d3d48b25bb37c81c1c8 | 19,805 | cpp | C++ | modules/radicon_helios/d_radicon_helios_trigger.cpp | nbeaver/mx-trunk | 8f9305f42cc5b12b77ba0354680bb317d779165d | [
"X11",
"MIT"
] | null | null | null | modules/radicon_helios/d_radicon_helios_trigger.cpp | nbeaver/mx-trunk | 8f9305f42cc5b12b77ba0354680bb317d779165d | [
"X11",
"MIT"
] | null | null | null | modules/radicon_helios/d_radicon_helios_trigger.cpp | nbeaver/mx-trunk | 8f9305f42cc5b12b77ba0354680bb317d779165d | [
"X11",
"MIT"
] | 2 | 2016-11-21T05:10:10.000Z | 2019-11-14T11:35:45.000Z | /*
* Name: d_radicon_helios_trigger.c
*
* Purpose: MX pulse generator driver to generate a trigger pulse for the
* Radicon Helios detectors using the Pleora iPORT PLC.
*
* Author: William Lavender
*
*------------------------------------------------------------------------
*
* Copyright 2011 Illinois Institute of Technology
*
* See the file "LICENSE" for information on usage and redistribution
* of this file, and for a DISCLAIMER OF ALL WARRANTIES.
*
*/
#define MXD_RADICON_HELIOS_TRIGGER_DEBUG FALSE
#define MXD_RADICON_HELIOS_TRIGGER_DEBUG_BUSY FALSE
#include <stdio.h>
#include "mx_util.h"
#include "mx_record.h"
#include "mx_image.h"
#include "mx_video_input.h"
#include "mx_area_detector.h"
#include "mx_pulse_generator.h"
#include "i_pleora_iport.h"
#include "d_pleora_iport_vinput.h"
#include "d_radicon_helios.h"
#include "d_radicon_helios_trigger.h"
/* Initialize the pulse generator driver jump table. */
MX_RECORD_FUNCTION_LIST mxd_rh_trigger_record_function_list = {
NULL,
mxd_rh_trigger_create_record_structures,
NULL,
NULL,
NULL,
mxd_rh_trigger_open
};
MX_PULSE_GENERATOR_FUNCTION_LIST mxd_rh_trigger_pulser_function_list = {
mxd_rh_trigger_is_busy,
mxd_rh_trigger_arm,
NULL,
mxd_rh_trigger_stop,
NULL,
mxd_rh_trigger_get_parameter,
mxd_rh_trigger_set_parameter
};
/* MX MBC trigger timer data structures. */
MX_RECORD_FIELD_DEFAULTS mxd_rh_trigger_record_field_defaults[] = {
MX_RECORD_STANDARD_FIELDS,
MX_PULSE_GENERATOR_STANDARD_FIELDS,
MXD_RADICON_HELIOS_TRIGGER_STANDARD_FIELDS
};
long mxd_rh_trigger_num_record_fields
= sizeof( mxd_rh_trigger_record_field_defaults )
/ sizeof( mxd_rh_trigger_record_field_defaults[0] );
MX_RECORD_FIELD_DEFAULTS *mxd_rh_trigger_rfield_def_ptr
= &mxd_rh_trigger_record_field_defaults[0];
/*=======================================================================*/
static mx_status_type
mxd_rh_trigger_get_pointers( MX_PULSE_GENERATOR *pulser,
MX_RADICON_HELIOS_TRIGGER **rh_trigger,
MX_RADICON_HELIOS **radicon_helios,
MX_PLEORA_IPORT_VINPUT **pleora_iport_vinput,
MX_PLEORA_IPORT **pleora_iport,
const char *calling_fname )
{
static const char fname[] = "mxd_rh_trigger_get_pointers()";
MX_RADICON_HELIOS_TRIGGER *rh_trigger_ptr;
MX_RECORD *radicon_helios_record;
MX_RADICON_HELIOS *radicon_helios_ptr;
MX_RECORD *video_input_record;
MX_PLEORA_IPORT_VINPUT *pleora_iport_vinput_ptr;
MX_RECORD *pleora_iport_record;
if ( pulser == (MX_PULSE_GENERATOR *) NULL ) {
return mx_error( MXE_NULL_ARGUMENT, fname,
"The MX_PULSE_GENERATOR pointer passed by '%s' was NULL",
calling_fname );
}
rh_trigger_ptr = (MX_RADICON_HELIOS_TRIGGER *)
pulser->record->record_type_struct;
if ( rh_trigger_ptr == (MX_RADICON_HELIOS_TRIGGER *) NULL ) {
return mx_error( MXE_CORRUPT_DATA_STRUCTURE, fname,
"The MX_RADICON_HELIOS_TRIGGER pointer for pulse generator "
"record '%s' passed by '%s' is NULL",
pulser->record->name, calling_fname );
}
if ( rh_trigger != (MX_RADICON_HELIOS_TRIGGER **) NULL ) {
*rh_trigger = rh_trigger_ptr;
}
radicon_helios_record = rh_trigger_ptr->radicon_helios_record;
if ( radicon_helios_record == (MX_RECORD *) NULL ) {
return mx_error( MXE_CORRUPT_DATA_STRUCTURE, fname,
"The radicon_helios_record pointer for pulse generator '%s' "
"is NULL.", pulser->record->name );
}
radicon_helios_ptr = (MX_RADICON_HELIOS *)
radicon_helios_record->record_type_struct;
if ( radicon_helios_ptr == (MX_RADICON_HELIOS *) NULL ) {
return mx_error( MXE_CORRUPT_DATA_STRUCTURE, fname,
"The MX_RADICON_HELIOS pointer for record '%s' "
"used by '%s' is NULL.",
radicon_helios_record->name,
pulser->record->name );
}
if ( radicon_helios != (MX_RADICON_HELIOS **) NULL ) {
*radicon_helios = radicon_helios_ptr;
}
video_input_record = radicon_helios_ptr->video_input_record;
if ( video_input_record == (MX_RECORD *) NULL ) {
return mx_error( MXE_CORRUPT_DATA_STRUCTURE, fname,
"The video_input_record pointer for area detector '%s' "
"used by '%s' is NULL.",
radicon_helios_record->name,
pulser->record->name );
}
pleora_iport_vinput_ptr = (MX_PLEORA_IPORT_VINPUT *)
video_input_record->record_type_struct;
if ( pleora_iport_vinput_ptr == (MX_PLEORA_IPORT_VINPUT *) NULL ) {
return mx_error( MXE_CORRUPT_DATA_STRUCTURE, fname,
"The MX_PLEORA_IPORT_VINPUT pointer for video input '%s' "
"used by area detector '%s' and pulse generator '%s' is NULL.",
video_input_record->name,
radicon_helios_record->name,
pulser->record->name );
}
if ( pleora_iport_vinput != (MX_PLEORA_IPORT_VINPUT **) NULL ) {
*pleora_iport_vinput = pleora_iport_vinput_ptr;
}
if ( pleora_iport != (MX_PLEORA_IPORT **) NULL ) {
pleora_iport_record =
pleora_iport_vinput_ptr->pleora_iport_record;
if ( pleora_iport_record == (MX_RECORD *) NULL ) {
return mx_error( MXE_CORRUPT_DATA_STRUCTURE, fname,
"The pleora_iport_record pointer for video input '%s' "
"used by area detector '%s' and pulse generator '%s' "
"is NULL.",
video_input_record->name,
radicon_helios_record->name,
pulser->record->name );
}
*pleora_iport = (MX_PLEORA_IPORT *)
pleora_iport_record->record_type_struct;
if ( (*pleora_iport) == (MX_PLEORA_IPORT *) NULL ) {
return mx_error( MXE_CORRUPT_DATA_STRUCTURE, fname,
"The MX_PLEORA_IPORT pointer for Pleora iPORT '%s' "
"used by video input '%s', area detector '%s', and "
"pulse generator '%s' is NULL.",
pleora_iport_record->name,
video_input_record->name,
radicon_helios_record->name,
pulser->record->name );
}
}
return MX_SUCCESSFUL_RESULT;
}
/*=======================================================================*/
MX_EXPORT mx_status_type
mxd_rh_trigger_create_record_structures( MX_RECORD *record )
{
static const char fname[] =
"mxd_rh_trigger_create_record_structures()";
MX_PULSE_GENERATOR *pulser;
MX_RADICON_HELIOS_TRIGGER *rh_trigger;
/* Allocate memory for the necessary structures. */
pulser = (MX_PULSE_GENERATOR *) malloc( sizeof(MX_PULSE_GENERATOR) );
if ( pulser == NULL ) {
return mx_error( MXE_OUT_OF_MEMORY, fname,
"Cannot allocate memory for MX_PULSE_GENERATOR structure." );
}
rh_trigger = (MX_RADICON_HELIOS_TRIGGER *)
malloc( sizeof(MX_RADICON_HELIOS_TRIGGER) );
if ( rh_trigger == NULL ) {
return mx_error( MXE_OUT_OF_MEMORY, fname,
"Cannot allocate memory for MX_RADICON_HELIOS_TRIGGER structure." );
}
/* Now set up the necessary pointers. */
record->record_class_struct = pulser;
record->record_type_struct = rh_trigger;
record->class_specific_function_list
= &mxd_rh_trigger_pulser_function_list;
pulser->record = record;
rh_trigger->record = record;
rh_trigger->preset_value = 0;
return MX_SUCCESSFUL_RESULT;
}
MX_EXPORT mx_status_type
mxd_rh_trigger_open( MX_RECORD *record )
{
static const char fname[] = "mxd_rh_trigger_open()";
MX_PULSE_GENERATOR *pulser;
MX_RADICON_HELIOS_TRIGGER *rh_trigger;
MX_RADICON_HELIOS *radicon_helios;
MX_PLEORA_IPORT_VINPUT *pleora_iport_vinput;
MX_PLEORA_IPORT *pleora_iport;
mx_status_type mx_status;
if ( record == (MX_RECORD *) NULL ) {
return mx_error( MXE_NULL_ARGUMENT, fname,
"The MX_RECORD pointer passed was NULL." );
}
pulser = (MX_PULSE_GENERATOR *) record->record_class_struct;
mx_status = mxd_rh_trigger_get_pointers( pulser, &rh_trigger,
&radicon_helios, &pleora_iport_vinput,
&pleora_iport, fname );
if ( mx_status.code != MXE_SUCCESS )
return mx_status;
CyGrabber *grabber = pleora_iport_vinput->grabber;
if ( grabber == NULL ) {
return mx_error( MXE_INITIALIZATION_ERROR, fname,
"No grabber has been connected for record '%s'.",
pleora_iport_vinput->record->name );
}
CyDevice &device = grabber->GetDevice();
/* The PLC is to be configured as follows:
*
* PC remote control bit 0 (I5) is connected to pulse generator 1's
* trigger input (Q8) which is configured to run when the input
* is high. The output of pulse generator 1 (I6) is connected to
* the count up input (Q17) of the general purpose counter. The
* general purpose counter is configured to generate the gate pulse
* (I3) for Counter 0 greater than zero. The gate pulse is sent
* to Q1. PC remote control bit 1 (I4) is used to clear the counter
* via Q11.
*/
/*-------------------------------------------------------------------*/
/* Initialize the values of the remote control bits to all clear. */
CyDeviceExtension *rcbits_extension = &device.GetExtension(
CY_DEVICE_EXT_GPIO_CONTROL_BITS );
rcbits_extension->SetParameter( CY_GPIO_CONTROL_BITS_CLEAR, 0xf );
rcbits_extension->SetParameter( CY_GPIO_CONTROL_BITS_SET, 0 );
rcbits_extension->SaveToDevice();
/*-------------------------------------------------------------------*/
/* Configure pulse generator 1 to generate a 1 kHz pulse train
* that is triggered when its trigger input is high.
*/
CyDeviceExtension *pg_extension = &device.GetExtension(
CY_DEVICE_EXT_PULSE_GENERATOR + 1 );
pg_extension->SetParameter( CY_PULSE_GEN_PARAM_GRANULARITY, 1666 );
pg_extension->SetParameter( CY_PULSE_GEN_PARAM_WIDTH, 10 );
pg_extension->SetParameter( CY_PULSE_GEN_PARAM_DELAY, 9 );
pg_extension->SetParameter( CY_PULSE_GEN_PARAM_PERIODIC, false );
pg_extension->SetParameter( CY_PULSE_GEN_PARAM_TRIGGER_MODE, 1 );
pg_extension->SaveToDevice();
/*-------------------------------------------------------------------*/
/* Configure the counter. The increment, decrement, and clear inputs
* are triggered on the rising edge of the input. The clear input
* is configured for Q11. The counter compare value is initialized
* to 0.
*/
CyDeviceExtension *ctr_extension = &device.GetExtension(
CY_DEVICE_EXT_COUNTER );
ctr_extension->SetParameter( CY_COUNTER_PARAM_UP_EVENT, 1 );
ctr_extension->SetParameter( CY_COUNTER_PARAM_DOWN_EVENT, 1 );
ctr_extension->SetParameter( CY_COUNTER_PARAM_CLEAR_EVENT, 1 );
ctr_extension->SetParameter( CY_COUNTER_PARAM_CLEAR_INPUT, 5 );
ctr_extension->SetParameter( CY_COUNTER_PARAM_COMPARE_VALUE, 0 );
ctr_extension->SaveToDevice();
/*-------------------------------------------------------------------*/
/* Configure the Signal Routing Block and the PLC's Lookup Table
* for the pulse generator. Note that I0, I1, I2, and I7 are
* already in use by the 'radicon_helios' driver.
*/
CyDeviceExtension *lut_extension =
&device.GetExtension( CY_DEVICE_EXT_GPIO_LUT );
/* NOTE: The source of the values of the second parameter to the
* SetParameter() calls below is described in a comment block
* before the start of the mxd_radicon_helios_open() function in
* d_radicon_helios.cpp.
*/
/* Connect "Counter 0 Greater" to I3. */
lut_extension->SetParameter( CY_GPIO_LUT_PARAM_INPUT_CONFIG3, 15 );
/* Connect "PLC control bit 1" to I4. (counter clear) */
lut_extension->SetParameter( CY_GPIO_LUT_PARAM_INPUT_CONFIG4, 0 );
/* Connect "PLC control bit 0" to I5. (pulse generator trigger) */
lut_extension->SetParameter( CY_GPIO_LUT_PARAM_INPUT_CONFIG5, 0 );
/* Connect "Pulse generator 1 output" to I6. (counter up) */
lut_extension->SetParameter( CY_GPIO_LUT_PARAM_INPUT_CONFIG6, 0 );
lut_extension->SaveToDevice();
/*-------------------------------------------------------------------*/
/* Set the trigger input low and the trigger output low. */
mxd_pleora_iport_vinput_set_rcbit( pleora_iport_vinput, 0, 0 );
char lut_program_low[] =
"Q1=0\r\n"
"Q8=I5\r\n";
mxd_pleora_iport_vinput_send_lookup_table_program( pleora_iport_vinput,
lut_program_low );
/* Connect pulse generator 1 output to the counter "up" input
* and connect PLC control input 1 to the counter's clear input.
*/
char lut_program_clear[] =
"Q11=I4\r\n"
"Q17=I6\r\n";
mxd_pleora_iport_vinput_send_lookup_table_program( pleora_iport_vinput,
lut_program_clear );
/* Clear the counter. */
mxd_pleora_iport_vinput_set_rcbit( pleora_iport_vinput, 1, 1 );
mx_msleep(1000);
mxd_pleora_iport_vinput_set_rcbit( pleora_iport_vinput, 1, 0 );
/* Enable the trigger output by connecting it to the output of
* the counter.
*
* The counter generates a 'greater than' signal, but what we
* actually need is a 'less than' signal. So what we do is to
* invert the output of the counter plus do a logical 'and' with
* the pulse generator trigger.
*/
char lut_program_out[] = "Q1=I5 & !I3\r\n";
mxd_pleora_iport_vinput_send_lookup_table_program( pleora_iport_vinput,
lut_program_out );
return MX_SUCCESSFUL_RESULT;
}
MX_EXPORT mx_status_type
mxd_rh_trigger_is_busy( MX_PULSE_GENERATOR *pulser )
{
static const char fname[] = "mxd_rh_trigger_is_busy()";
MX_RADICON_HELIOS_TRIGGER *rh_trigger;
MX_RADICON_HELIOS *radicon_helios;
MX_PLEORA_IPORT_VINPUT *pleora_iport_vinput;
MX_PLEORA_IPORT *pleora_iport;
__int64 current_value;
mx_status_type mx_status;
mx_status = mxd_rh_trigger_get_pointers( pulser, &rh_trigger,
&radicon_helios, &pleora_iport_vinput,
&pleora_iport, fname );
if ( mx_status.code != MXE_SUCCESS )
return mx_status;
CyGrabber *grabber = pleora_iport_vinput->grabber;
if ( grabber == NULL ) {
return mx_error( MXE_INITIALIZATION_ERROR, fname,
"No grabber has been connected for record '%s'.",
pleora_iport_vinput->record->name );
}
CyDevice &device = grabber->GetDevice();
/* If the counter has not reached the specified counter value,
* then it is still busy.
*/
CyDeviceExtension *ctr_extension = &device.GetExtension(
CY_DEVICE_EXT_COUNTER );
ctr_extension->LoadFromDevice();
ctr_extension->GetParameter( CY_COUNTER_PARAM_CURRENT_VALUE,
current_value );
if ( current_value <= rh_trigger->preset_value ) {
pulser->busy = TRUE;
} else {
pulser->busy = FALSE;
/* Deassert the input trigger for the pulse generator. */
mxd_pleora_iport_vinput_set_rcbit( pleora_iport_vinput, 0, 0 );
}
#if MXD_RADICON_HELIOS_TRIGGER_DEBUG_BUSY
MX_DEBUG(-2,("%s: busy = %d, current_value = %lu, preset_value = %lu",
fname, pulser->busy,
(unsigned long) current_value,
rh_trigger->preset_value));
#endif
return mx_status;
}
MX_EXPORT mx_status_type
mxd_rh_trigger_start( MX_PULSE_GENERATOR *pulser )
{
static const char fname[] = "mxd_rh_trigger_start()";
MX_RADICON_HELIOS_TRIGGER *rh_trigger;
MX_RADICON_HELIOS *radicon_helios;
MX_PLEORA_IPORT_VINPUT *pleora_iport_vinput;
MX_PLEORA_IPORT *pleora_iport;
double gate_time_in_seconds;
unsigned long gate_time_in_milliseconds;
mx_status_type mx_status;
mx_status = mxd_rh_trigger_get_pointers( pulser, &rh_trigger,
&radicon_helios, &pleora_iport_vinput,
&pleora_iport, fname );
if ( mx_status.code != MXE_SUCCESS )
return mx_status;
gate_time_in_seconds = pulser->pulse_width;
gate_time_in_milliseconds = mx_round( 1000.0 * gate_time_in_seconds );
rh_trigger->preset_value = gate_time_in_milliseconds;
/* Clear the counter. */
CyGrabber *grabber = pleora_iport_vinput->grabber;
if ( grabber == NULL ) {
return mx_error( MXE_INITIALIZATION_ERROR, fname,
"No grabber has been connected for record '%s'.",
pleora_iport_vinput->record->name );
}
mxd_pleora_iport_vinput_set_rcbit( pleora_iport_vinput, 1, 1 );
mxd_pleora_iport_vinput_set_rcbit( pleora_iport_vinput, 1, 0 );
/* Update the counter compare value. */
CyDevice &device = grabber->GetDevice();
CyDeviceExtension *ctr_extension = &device.GetExtension(
CY_DEVICE_EXT_COUNTER );
ctr_extension->SetParameter( CY_COUNTER_PARAM_COMPARE_VALUE,
gate_time_in_milliseconds );
ctr_extension->SaveToDevice();
/* Assert the input trigger for the pulse generator. */
mxd_pleora_iport_vinput_set_rcbit( pleora_iport_vinput, 0, 1 );
#if MXD_RADICON_HELIOS_TRIGGER_DEBUG
MX_DEBUG(-2,("%s: '%s' started with preset %lu",
fname, pulser->record->name, rh_trigger->preset_value));
#endif
return mx_status;
}
MX_EXPORT mx_status_type
mxd_rh_trigger_stop( MX_PULSE_GENERATOR *pulser )
{
static const char fname[] = "mxd_rh_trigger_stop()";
MX_RADICON_HELIOS_TRIGGER *rh_trigger;
MX_RADICON_HELIOS *radicon_helios;
MX_PLEORA_IPORT_VINPUT *pleora_iport_vinput;
MX_PLEORA_IPORT *pleora_iport;
mx_status_type mx_status;
mx_status = mxd_rh_trigger_get_pointers( pulser, &rh_trigger,
&radicon_helios, &pleora_iport_vinput,
&pleora_iport, fname );
if ( mx_status.code != MXE_SUCCESS )
return mx_status;
#if MXD_RADICON_HELIOS_TRIGGER_DEBUG
MX_DEBUG(-2,("%s: Stopping pulse generator '%s'.",
fname, pulser->record->name ));
#endif
CyGrabber *grabber = pleora_iport_vinput->grabber;
if ( grabber == NULL ) {
return mx_error( MXE_INITIALIZATION_ERROR, fname,
"No grabber has been connected for record '%s'.",
pleora_iport_vinput->record->name );
}
/* Stop counting. */
mxd_pleora_iport_vinput_set_rcbit( pleora_iport_vinput, 0, 0 );
mx_msleep(500);
/* Clear the counter. */
mxd_pleora_iport_vinput_set_rcbit( pleora_iport_vinput, 1, 1 );
mx_msleep(500);
mxd_pleora_iport_vinput_set_rcbit( pleora_iport_vinput, 1, 0 );
return MX_SUCCESSFUL_RESULT;
}
MX_EXPORT mx_status_type
mxd_rh_trigger_get_parameter( MX_PULSE_GENERATOR *pulser )
{
static const char fname[] = "mxd_rh_trigger_get_parameter()";
MX_RADICON_HELIOS_TRIGGER *rh_trigger = NULL;
MX_RADICON_HELIOS *radicon_helios;
MX_PLEORA_IPORT_VINPUT *pleora_iport_vinput;
MX_PLEORA_IPORT *pleora_iport;
mx_status_type mx_status;
mx_status = mxd_rh_trigger_get_pointers( pulser, &rh_trigger,
&radicon_helios, &pleora_iport_vinput,
&pleora_iport, fname );
if ( mx_status.code != MXE_SUCCESS )
return mx_status;
#if MXD_RADICON_HELIOS_TRIGGER_DEBUG
MX_DEBUG(-2,
("%s invoked for PULSE_GENERATOR '%s', parameter type '%s' (%ld)",
fname, pulser->record->name,
mx_get_field_label_string( pulser->record,
pulser->parameter_type ),
pulser->parameter_type));
#endif
switch( pulser->parameter_type ) {
case MXLV_PGN_NUM_PULSES:
break;
case MXLV_PGN_PULSE_WIDTH:
break;
case MXLV_PGN_PULSE_DELAY:
break;
case MXLV_PGN_MODE:
break;
case MXLV_PGN_PULSE_PERIOD:
break;
default:
return
mx_pulse_generator_default_get_parameter_handler( pulser );
}
#if MXD_RADICON_HELIOS_TRIGGER_DEBUG
MX_DEBUG(-2,("%s complete.", fname));
#endif
return MX_SUCCESSFUL_RESULT;
}
MX_EXPORT mx_status_type
mxd_rh_trigger_set_parameter( MX_PULSE_GENERATOR *pulser )
{
static const char fname[] = "mxd_rh_trigger_set_parameter()";
MX_RADICON_HELIOS_TRIGGER *rh_trigger;
MX_RADICON_HELIOS *radicon_helios;
MX_PLEORA_IPORT_VINPUT *pleora_iport_vinput;
MX_PLEORA_IPORT *pleora_iport;
mx_status_type mx_status;
mx_status = mxd_rh_trigger_get_pointers( pulser, &rh_trigger,
&radicon_helios, &pleora_iport_vinput,
&pleora_iport, fname );
if ( mx_status.code != MXE_SUCCESS )
return mx_status;
#if MXD_RADICON_HELIOS_TRIGGER_DEBUG
MX_DEBUG(-2,
("%s invoked for PULSE_GENERATOR '%s', parameter type '%s' (%ld)",
fname, pulser->record->name,
mx_get_field_label_string( pulser->record,
pulser->parameter_type ),
pulser->parameter_type));
#endif
switch( pulser->parameter_type ) {
case MXLV_PGN_NUM_PULSES:
pulser->num_pulses = 1;
break;
case MXLV_PGN_PULSE_WIDTH:
/* This value is used by the start() routine above. */
break;
case MXLV_PGN_PULSE_DELAY:
pulser->pulse_delay = 0;
break;
case MXLV_PGN_MODE:
pulser->mode = MXF_PGN_SQUARE_WAVE;
break;
case MXLV_PGN_PULSE_PERIOD:
pulser->pulse_period = pulser->pulse_width;
break;
default:
return
mx_pulse_generator_default_set_parameter_handler( pulser );
}
#if MXD_RADICON_HELIOS_TRIGGER_DEBUG
MX_DEBUG( 2,("%s complete.", fname));
#endif
return MX_SUCCESSFUL_RESULT;
}
| 28.092199 | 75 | 0.731532 | nbeaver |
c9b81cd331ad5210896565bec4cb1c7dbf932421 | 9,011 | hpp | C++ | console/src/boost_1_78_0/libs/interprocess/test/named_condition_test_helpers.hpp | vany152/FilesHash | 39f282807b7f1abc56dac389e8259ee3bb557a8d | [
"MIT"
] | 1 | 2019-10-27T21:15:52.000Z | 2019-10-27T21:15:52.000Z | console/src/boost_1_78_0/libs/interprocess/test/named_condition_test_helpers.hpp | vany152/FilesHash | 39f282807b7f1abc56dac389e8259ee3bb557a8d | [
"MIT"
] | null | null | null | console/src/boost_1_78_0/libs/interprocess/test/named_condition_test_helpers.hpp | vany152/FilesHash | 39f282807b7f1abc56dac389e8259ee3bb557a8d | [
"MIT"
] | 1 | 2021-08-24T08:49:34.000Z | 2021-08-24T08:49:34.000Z | //////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2021-2021. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/interprocess for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_INTERPROCESS_TEST_NAMED_CONDITION_HELPERS_HEADER
#define BOOST_INTERPROCESS_TEST_NAMED_CONDITION_HELPERS_HEADER
#include <boost/interprocess/detail/config_begin.hpp>
namespace boost { namespace interprocess { namespace test {
template<class NamedCondition>
struct condition_deleter
{
std::string name;
~condition_deleter()
{
if(name.empty())
NamedCondition::remove(test::add_to_process_id_name("named_condition"));
else
NamedCondition::remove(name.c_str());
}
};
#if defined(BOOST_INTERPROCESS_WCHAR_NAMED_RESOURCES)
template<class NamedCondition>
struct condition_deleter_w
{
std::string name;
~condition_deleter_w()
{
if(name.empty())
NamedCondition::remove(test::add_to_process_id_name(L"named_condition"));
else
NamedCondition::remove(name.c_str());
}
};
#endif //#if defined(BOOST_INTERPROCESS_WCHAR_NAMED_RESOURCES)
inline std::string num_to_string(int n)
{ std::stringstream s; s << n; return s.str(); }
//This wrapper is necessary to have a default constructor
//in generic mutex_test_template functions
template<class NamedCondition>
class named_condition_test_wrapper
: public condition_deleter<NamedCondition>, public NamedCondition
{
public:
named_condition_test_wrapper()
: NamedCondition(open_or_create,
(test::add_to_process_id_name("test_cond") + num_to_string(count)).c_str())
{
condition_deleter<NamedCondition>::name += test::add_to_process_id_name("test_cond");
condition_deleter<NamedCondition>::name += num_to_string(count);
++count;
}
~named_condition_test_wrapper()
{ --count; }
template <typename L>
void wait(L& lock)
{
ipcdetail::internal_mutex_lock<L> internal_lock(lock);
NamedCondition::wait(internal_lock);
}
template <typename L, typename Pr>
void wait(L& lock, Pr pred)
{
ipcdetail::internal_mutex_lock<L> internal_lock(lock);
NamedCondition::wait(internal_lock, pred);
}
template <typename L, typename TimePoint>
bool timed_wait(L& lock, const TimePoint &abs_time)
{
ipcdetail::internal_mutex_lock<L> internal_lock(lock);
return NamedCondition::timed_wait(internal_lock, abs_time);
}
template <typename L, typename TimePoint, typename Pr>
bool timed_wait(L& lock, const TimePoint &abs_time, Pr pred)
{
ipcdetail::internal_mutex_lock<L> internal_lock(lock);
return NamedCondition::timed_wait(internal_lock, abs_time, pred);
}
template <typename L, class TimePoint>
cv_status wait_until(L& lock, const TimePoint &abs_time)
{
ipcdetail::internal_mutex_lock<L> internal_lock(lock);
return NamedCondition::wait_until(internal_lock, abs_time);
}
template <typename L, class TimePoint, typename Pr>
bool wait_until(L& lock, const TimePoint &abs_time, Pr pred)
{
ipcdetail::internal_mutex_lock<L> internal_lock(lock);
return NamedCondition::wait_until(internal_lock, abs_time, pred);
}
static int count;
};
template<class NamedCondition>
int named_condition_test_wrapper<NamedCondition>::count = 0;
//This wrapper is necessary to have a common constructor
//in generic named_creation_template functions
template<class NamedCondition>
class named_condition_creation_test_wrapper
: public condition_deleter<NamedCondition>, public NamedCondition
{
public:
named_condition_creation_test_wrapper(create_only_t)
: NamedCondition(create_only, test::add_to_process_id_name("named_condition"))
{ ++count_; }
named_condition_creation_test_wrapper(open_only_t)
: NamedCondition(open_only, test::add_to_process_id_name("named_condition"))
{ ++count_; }
named_condition_creation_test_wrapper(open_or_create_t)
: NamedCondition(open_or_create, test::add_to_process_id_name("named_condition"))
{ ++count_; }
~named_condition_creation_test_wrapper() {
if(--count_){
ipcdetail::interprocess_tester::
dont_close_on_destruction(static_cast<NamedCondition&>(*this));
}
}
static int count_;
};
template<class NamedCondition>
int named_condition_creation_test_wrapper<NamedCondition>::count_ = 0;
#if defined(BOOST_INTERPROCESS_WCHAR_NAMED_RESOURCES)
//This wrapper is necessary to have a common constructor
//in generic named_creation_template functions
template<class NamedCondition>
class named_condition_creation_test_wrapper_w
: public condition_deleter_w<NamedCondition>, public NamedCondition
{
public:
named_condition_creation_test_wrapper_w(create_only_t)
: NamedCondition(create_only, test::add_to_process_id_name(L"named_condition"))
{ ++count_; }
named_condition_creation_test_wrapper_w(open_only_t)
: NamedCondition(open_only, test::add_to_process_id_name(L"named_condition"))
{ ++count_; }
named_condition_creation_test_wrapper_w(open_or_create_t)
: NamedCondition(open_or_create, test::add_to_process_id_name(L"named_condition"))
{ ++count_; }
~named_condition_creation_test_wrapper_w() {
if(--count_){
ipcdetail::interprocess_tester::
dont_close_on_destruction(static_cast<NamedCondition&>(*this));
}
}
static int count_;
};
template<class NamedCondition>
int named_condition_creation_test_wrapper_w<NamedCondition>::count_ = 0;
#endif //#if defined(BOOST_INTERPROCESS_WCHAR_NAMED_RESOURCES)
template<class NamedMutex>
struct mutex_deleter
{
std::string name;
~mutex_deleter()
{
if(name.empty())
NamedMutex::remove(test::add_to_process_id_name("named_mutex"));
else
NamedMutex::remove(name.c_str());
}
};
//This wrapper is necessary to have a default constructor
//in generic mutex_test_template functions
template<class NamedMutex>
class named_mutex_test_wrapper
: public mutex_deleter<NamedMutex>, public NamedMutex
{
public:
named_mutex_test_wrapper()
: NamedMutex(open_or_create,
(test::add_to_process_id_name("test_mutex") + num_to_string(count)).c_str())
{
mutex_deleter<NamedMutex>::name += test::add_to_process_id_name("test_mutex");
mutex_deleter<NamedMutex>::name += num_to_string(count);
++count;
}
typedef NamedMutex internal_mutex_type;
internal_mutex_type &internal_mutex()
{ return *this; }
~named_mutex_test_wrapper()
{ --count; }
static int count;
};
template<class NamedMutex>
int named_mutex_test_wrapper<NamedMutex>::count = 0;
template<class NamedCondition, class NamedMutex>
int test_named_condition()
{
int ret = 0;
BOOST_TRY{
//Remove previous mutexes and conditions
NamedMutex::remove(test::add_to_process_id_name("test_mutex0"));
NamedCondition::remove(test::add_to_process_id_name("test_cond0"));
NamedCondition::remove(test::add_to_process_id_name("test_cond1"));
NamedCondition::remove(test::add_to_process_id_name("named_condition"));
NamedMutex::remove(test::add_to_process_id_name("named_mutex"));
test::test_named_creation<test::named_condition_creation_test_wrapper<NamedCondition> >();
#if defined(BOOST_INTERPROCESS_WCHAR_NAMED_RESOURCES)
//Remove previous mutexes and conditions
NamedMutex::remove(test::add_to_process_id_name("test_mutex0"));
NamedCondition::remove(test::add_to_process_id_name("test_cond0"));
NamedCondition::remove(test::add_to_process_id_name("test_cond1"));
NamedCondition::remove(test::add_to_process_id_name("named_condition"));
NamedMutex::remove(test::add_to_process_id_name("named_mutex"));
test::test_named_creation<test::named_condition_creation_test_wrapper_w<NamedCondition> >();
#endif
test::do_test_condition<test::named_condition_test_wrapper<NamedCondition>
,test::named_mutex_test_wrapper<NamedMutex> >();
}
BOOST_CATCH(std::exception &ex){
std::cout << ex.what() << std::endl;
ret = 1;
} BOOST_CATCH_END
NamedMutex::remove(test::add_to_process_id_name("test_mutex0"));
NamedCondition::remove(test::add_to_process_id_name("test_cond0"));
NamedCondition::remove(test::add_to_process_id_name("test_cond1"));
NamedCondition::remove(test::add_to_process_id_name("named_condition"));
NamedMutex::remove(test::add_to_process_id_name("named_mutex"));
return ret;
}
}}} //namespace boost { namespace interprocess { namespace test {
#include <boost/interprocess/detail/config_end.hpp>
#endif //BOOST_INTERPROCESS_TEST_NAMED_CONDITION_HELPERS_HEADER
| 32.767273 | 98 | 0.72356 | vany152 |
c9ba58d381284e7e4438af2d088127afbc94aa8f | 6,191 | cc | C++ | tensorflow/core/kernels/remote_fused_graph_execute_utils_test.cc | Dashhh/tensorflow | 1708b92bb923e420d746a56baafc7d4ddcd5e05e | [
"Apache-2.0"
] | 5 | 2017-10-02T05:56:47.000Z | 2022-03-25T04:31:19.000Z | tensorflow/core/kernels/remote_fused_graph_execute_utils_test.cc | Dashhh/tensorflow | 1708b92bb923e420d746a56baafc7d4ddcd5e05e | [
"Apache-2.0"
] | null | null | null | tensorflow/core/kernels/remote_fused_graph_execute_utils_test.cc | Dashhh/tensorflow | 1708b92bb923e420d746a56baafc7d4ddcd5e05e | [
"Apache-2.0"
] | 8 | 2016-05-09T15:08:29.000Z | 2020-06-11T18:04:52.000Z | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/remote_fused_graph_execute_utils.h"
#include "tensorflow/cc/framework/scope.h"
#include "tensorflow/cc/ops/const_op.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/test.h"
namespace tensorflow {
const string NAME_A = "a";
const string NAME_B = "b";
const string NAME_A_PLUS_B = "a_plus_b";
constexpr float NODE_A_VAL = 2.0f;
constexpr float NODE_B_VAL = 3.0f;
constexpr float VALUE_TOLERANCE_FLOAT = 1e-8f;
static Output BuildAddOps(const Scope& scope, const Input& x, const Input& y) {
EXPECT_TRUE(scope.ok());
auto _x = ops::AsNodeOut(scope, x);
EXPECT_TRUE(scope.ok());
auto _y = ops::AsNodeOut(scope, y);
EXPECT_TRUE(scope.ok());
Node* ret;
const auto unique_name = scope.GetUniqueNameForOp("Add");
auto builder = NodeBuilder(unique_name, "Add").Input(_x).Input(_y);
scope.UpdateBuilder(&builder);
scope.UpdateStatus(builder.Finalize(scope.graph(), &ret));
EXPECT_TRUE(scope.ok());
return Output(ret, 0);
}
static GraphDef CreateAddGraphDef() {
Scope root = Scope::NewRootScope();
Output node_a = ops::Const(root.WithOpName(NAME_A), NODE_A_VAL);
Output node_b = ops::Const(root.WithOpName(NAME_B), NODE_B_VAL);
Output node_add = BuildAddOps(root.WithOpName(NAME_A_PLUS_B), node_a, node_b);
GraphDef def;
TF_CHECK_OK(root.ToGraphDef(&def));
return def;
}
TEST(RemoteFusedGraphExecuteUtils, DryRunAddGraphA) {
GraphDef def = CreateAddGraphDef();
std::pair<string, Tensor> input_node_info;
input_node_info.first = NAME_A;
input_node_info.second = Tensor(DT_FLOAT, {});
input_node_info.second.scalar<float>()() = 1.0f;
const std::vector<std::pair<string, Tensor>> inputs{input_node_info};
std::vector<string> outputs = {NAME_B, NAME_A_PLUS_B};
std::vector<tensorflow::Tensor> output_tensors;
Status status = RemoteFusedGraphExecuteUtils::DryRunInference(
def, inputs, outputs, false /* initialize_by_zero */, &output_tensors);
ASSERT_TRUE(status.ok()) << status;
EXPECT_EQ(outputs.size(), output_tensors.size());
EXPECT_NEAR(NODE_B_VAL, output_tensors.at(0).scalar<float>()(),
VALUE_TOLERANCE_FLOAT);
EXPECT_NEAR(1.0f + NODE_B_VAL, output_tensors.at(1).scalar<float>()(),
VALUE_TOLERANCE_FLOAT);
}
TEST(RemoteFusedGraphExecuteUtils, DryRunAddGraphAUninitialized) {
GraphDef def = CreateAddGraphDef();
std::pair<string, Tensor> input_node_info;
input_node_info.first = NAME_A;
input_node_info.second = Tensor(DT_FLOAT, {});
const std::vector<std::pair<string, Tensor>> inputs{input_node_info};
std::vector<string> outputs = {NAME_B, NAME_A_PLUS_B};
std::vector<tensorflow::Tensor> output_tensors;
Status status = RemoteFusedGraphExecuteUtils::DryRunInference(
def, inputs, outputs, true /* initialize_by_zero */, &output_tensors);
ASSERT_TRUE(status.ok()) << status;
EXPECT_EQ(outputs.size(), output_tensors.size());
EXPECT_NEAR(NODE_B_VAL, output_tensors.at(0).scalar<float>()(),
VALUE_TOLERANCE_FLOAT);
EXPECT_NEAR(NODE_B_VAL, output_tensors.at(1).scalar<float>()(),
VALUE_TOLERANCE_FLOAT);
}
TEST(RemoteFusedGraphExecuteUtils, DryRunAddGraphAB) {
GraphDef def = CreateAddGraphDef();
std::pair<string, Tensor> input_node_info_a;
input_node_info_a.first = NAME_A;
input_node_info_a.second = Tensor(DT_FLOAT, {});
input_node_info_a.second.scalar<float>()() = NODE_A_VAL;
std::pair<string, Tensor> input_node_info_b;
input_node_info_b.first = NAME_B;
input_node_info_b.second = Tensor(DT_FLOAT, {});
input_node_info_b.second.scalar<float>()() = NODE_B_VAL;
const std::vector<std::pair<string, Tensor>> inputs{input_node_info_a,
input_node_info_b};
std::vector<string> outputs = {NAME_A_PLUS_B};
std::vector<tensorflow::Tensor> output_tensors;
Status status = RemoteFusedGraphExecuteUtils::DryRunInference(
def, inputs, outputs, false /* initialize_by_zero */, &output_tensors);
ASSERT_TRUE(status.ok()) << status;
EXPECT_EQ(outputs.size(), output_tensors.size());
EXPECT_NEAR(NODE_A_VAL + NODE_B_VAL, output_tensors.at(0).scalar<float>()(),
VALUE_TOLERANCE_FLOAT);
}
TEST(RemoteFusedGraphExecuteUtils, DryRunAddGraphForAllNodes) {
// Set Node "a" as an input with value (= 1.0f)
std::pair<string, Tensor> input_node_info_a;
input_node_info_a.first = NAME_A;
input_node_info_a.second = Tensor(DT_FLOAT, {});
input_node_info_a.second.scalar<float>()() = 1.0f;
// Setup dryrun arguments
const std::vector<std::pair<string, Tensor>> inputs{input_node_info_a};
RemoteFusedGraphExecuteUtils::TensorShapeMap output_tensor_info;
GraphDef def = CreateAddGraphDef();
// dryrun
const Status status = RemoteFusedGraphExecuteUtils::DryRunInferenceForAllNode(
def, inputs, false /* initialize_by_zero */, &output_tensor_info);
ASSERT_TRUE(status.ok()) << status;
// Assert output node count
ASSERT_EQ(3, output_tensor_info.size());
ASSERT_EQ(1, output_tensor_info.count(NAME_A));
ASSERT_EQ(1, output_tensor_info.count(NAME_B));
ASSERT_EQ(1, output_tensor_info.count(NAME_A_PLUS_B));
EXPECT_EQ(DT_FLOAT, output_tensor_info.at(NAME_B).first);
EXPECT_EQ(DT_FLOAT, output_tensor_info.at(NAME_A_PLUS_B).first);
const TensorShape& shape_b = output_tensor_info.at(NAME_B).second;
const TensorShape& shape_a_b = output_tensor_info.at(NAME_A_PLUS_B).second;
EXPECT_EQ(0, shape_b.dims());
EXPECT_EQ(0, shape_a_b.dims());
}
} // namespace tensorflow
| 41.831081 | 80 | 0.730738 | Dashhh |
c9bcd662975e6308d22fd1ae527e282d25623673 | 1,342 | cpp | C++ | src/All2DEngine/All2D/All2D_Controller.cpp | ldornbusch/All2D_Base | c790293b3030de97f65d62f6617222c42d18fa6a | [
"Apache-2.0"
] | null | null | null | src/All2DEngine/All2D/All2D_Controller.cpp | ldornbusch/All2D_Base | c790293b3030de97f65d62f6617222c42d18fa6a | [
"Apache-2.0"
] | null | null | null | src/All2DEngine/All2D/All2D_Controller.cpp | ldornbusch/All2D_Base | c790293b3030de97f65d62f6617222c42d18fa6a | [
"Apache-2.0"
] | null | null | null | #include "All2D_Controller.h"
#include "All2D_System.h"
All2D_Controller::All2D_Controller(std::string name) :xContainer("name"){
imgFrameBuffer.resize(All2D_System::fixedX,All2D_System::fixedY);
requestLoad();
}
All2D_Controller::~All2D_Controller(){
imgFrameBuffer.finish();
}
void All2D_Controller::init()
{
// init sound engine instance
All2D_System::sound->init();
}
bool All2D_Controller::masterPaint(Image& backBuffer)
{
bool retVal=false;
retVal=paint(backBuffer);
All2D_System::spriteManager.paint(backBuffer);
All2D_System::spriteManager.clear();
return retVal;
}
bool All2D_Controller::handleEvent(Event *evt)
{
switch (evt->Type)
{
case MM_KEYDOWN:
{
char a=(char)evt->wData;
switch (a) {
case sf::Keyboard::BackSpace:
case sf::Keyboard::Escape:
case sf::Keyboard::F12:
isExit = true;
break;
case sf::Keyboard::F:
isFullscreen=!isFullscreen;
MessageManager::handleEvent(new Event(MM_SETFULLSCREEN,(int)isFullscreen,0));
break;
default:
break;
}
}
break;
default:
break;
}
return xContainer::handleEvent(evt);
}
| 23.137931 | 97 | 0.586438 | ldornbusch |
c9c018adb71a3e5f0990a8daad2ab057a02adb3c | 3,742 | cpp | C++ | src/designer/formdesigner/formwindowsettings.cpp | leaderit/ananas-qt4 | 6830bf5074b316582a38f6bed147a1186dd7cc95 | [
"MIT"
] | 1 | 2021-03-16T21:47:41.000Z | 2021-03-16T21:47:41.000Z | src/designer/formdesigner/formwindowsettings.cpp | leaderit/ananas-qt4 | 6830bf5074b316582a38f6bed147a1186dd7cc95 | [
"MIT"
] | null | null | null | src/designer/formdesigner/formwindowsettings.cpp | leaderit/ananas-qt4 | 6830bf5074b316582a38f6bed147a1186dd7cc95 | [
"MIT"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 1992-2006 Trolltech ASA. All rights reserved.
**
** This file is part of the Qt Designer of the Qt Toolkit.
**
** This file may be used under the terms of the GNU General Public
** License version 2.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of
** this file. Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
** http://www.trolltech.com/products/qt/opensource.html
**
** If you are unsure which license is appropriate for your use, please
** review the following information:
** http://www.trolltech.com/products/qt/licensing.html or contact the
** sales department at sales@trolltech.com.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
****************************************************************************/
#include "formwindowsettings.h"
#include <QtDesigner/QtDesigner>
#include <QtGui/QStyle>
FormWindowSettings::FormWindowSettings(QDesignerFormWindowInterface *parent)
: QDialog(parent), m_formWindow(parent)
{
ui.setupUi(this);
int defaultMargin = INT_MIN, defaultSpacing = INT_MIN;
formWindow()->layoutDefault(&defaultMargin, &defaultSpacing);
QStyle *style = formWindow()->style();
ui.defaultMarginSpinBox->setValue(style->pixelMetric(QStyle::PM_DefaultChildMargin, 0));
ui.defaultSpacingSpinBox->setValue(style->pixelMetric(QStyle::PM_DefaultLayoutSpacing, 0));
if (defaultMargin != INT_MIN || defaultMargin != INT_MIN) {
ui.layoutDefaultGroupBox->setChecked(true);
if (defaultMargin != INT_MIN)
ui.defaultMarginSpinBox->setValue(defaultMargin);
if (defaultSpacing != INT_MIN)
ui.defaultSpacingSpinBox->setValue(defaultSpacing);
} else {
ui.layoutDefaultGroupBox->setChecked(false);
}
QString marginFunction, spacingFunction;
formWindow()->layoutFunction(&marginFunction, &spacingFunction);
if (!marginFunction.isEmpty() || !spacingFunction.isEmpty()) {
ui.layoutFunctionGroupBox->setChecked(true);
ui.marginFunctionLineEdit->setText(marginFunction);
ui.spacingFunctionLineEdit->setText(spacingFunction);
} else {
ui.layoutFunctionGroupBox->setChecked(false);
}
QString pixFunction = formWindow()->pixmapFunction();
ui.pixmapFunctionGroupBox->setChecked(!pixFunction.isEmpty());
ui.pixmapFunctionLineEdit->setText(pixFunction);
ui.authorLineEdit->setText(formWindow()->author());
foreach (QString includeHint, formWindow()->includeHints()) {
if (includeHint.isEmpty())
continue;
ui.includeHintsTextEdit->append(includeHint);
}
}
FormWindowSettings::~FormWindowSettings()
{
}
QDesignerFormWindowInterface *FormWindowSettings::formWindow() const
{
return m_formWindow;
}
void FormWindowSettings::accept()
{
formWindow()->setAuthor(ui.authorLineEdit->text());
if (ui.pixmapFunctionGroupBox->isChecked())
formWindow()->setPixmapFunction(ui.pixmapFunctionLineEdit->text());
if (ui.layoutDefaultGroupBox->isChecked())
formWindow()->setLayoutDefault(ui.defaultMarginSpinBox->value(), ui.defaultSpacingSpinBox->value());
if (ui.layoutFunctionGroupBox->isChecked())
formWindow()->setLayoutFunction(ui.marginFunctionLineEdit->text(), ui.spacingFunctionLineEdit->text());
formWindow()->setIncludeHints(ui.includeHintsTextEdit->toPlainText().split(QLatin1String("\n")));
formWindow()->setDirty(true);
QDialog::accept();
}
| 35.980769 | 111 | 0.696152 | leaderit |
c9c1aa4f19e6498de34a61175dd7cf8af1f60929 | 9,006 | cpp | C++ | src/sample.cpp | reedacartwright/emdel | 58ea9d4db89c4a1852ba5405ef73c2eca6539ce3 | [
"MIT"
] | null | null | null | src/sample.cpp | reedacartwright/emdel | 58ea9d4db89c4a1852ba5405ef73c2eca6539ce3 | [
"MIT"
] | 1 | 2020-12-03T16:50:15.000Z | 2021-03-23T22:51:19.000Z | src/sample.cpp | reedacartwright/emdel | 58ea9d4db89c4a1852ba5405ef73c2eca6539ce3 | [
"MIT"
] | null | null | null | /***************************************************************************
* Copyright (C) 2007 by Reed A. Cartwright *
* reed@scit.us *
* *
* Permission is hereby granted, free of charge, to any person obtaining *
* a copy of this software and associated documentation files (the *
* "Software"), to deal in the Software without restriction, including *
* without limitation the rights to use, copy, modify, merge, publish, *
* distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to *
* the following conditions: *
* *
* The above copyright notice and this permission notice shall be *
* included in all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, *
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR *
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, *
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR *
* OTHER DEALINGS IN THE SOFTWARE. *
***************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#define _USE_MATH_DEFINES
#include <iostream>
#include <boost/math/special_functions/zeta.hpp>
#include "sample.h"
#include "sample_k2p.h"
#include "ccvector.h"
#include "series.h"
#include "invert_matrix.h"
#include "table.h"
#include "emdel.h"
using namespace std;
void sample_k2p_zeta::preallocate(size_t maxa, size_t maxd)
{
p.resize(maxa+1,maxd+1,0.0);
}
void sample_k2p_zeta::presample_step(const params_type ¶ms, const sequence &seq_a, const sequence &seq_d)
{
size_t sz_max = std::max(sz_height, sz_width);
size_t sz_anc = seq_a.size();
size_t sz_dec = seq_d.size();
sa = seq_a;
sd = seq_d;
const model_type &model = get_model();
p(0,0) = prob_scale;
for(size_t d = 1; d <= sz_dec; ++d) {
p(0,d) = 0.0;
for(size_t k = d; k > 0; --k)
p(0,d) += p(0,d-k)*model.p_indel_size[k];
}
for(size_t a = 1; a <= sz_anc; ++a) {
p(a,0) = 0.0;
for(size_t k = a; k > 0; --k)
p(a,0) += p(a-k,0)*model.p_indel_size[k];
}
for(size_t a=1;a<=sz_anc;++a) {
for(size_t d=1;d<= sz_dec;++d) {
double pt = p(a-1,d-1)*model.p_substitution[sa[a-1]][sd[d-1]];
for(size_t k = d; k > 0; --k)
pt += p(a,d-k)*model.p_indel_size[k];
for(size_t k = a; k > 0; --k)
pt += p(a-k,d)*model.p_indel_size[k];
p(a,d) = pt;
}
}
}
void sample_k2p_zeta::sample_once(std::string &seq_a, std::string &seq_d)
{
size_t a = sa.size();
size_t d = sd.size();
seq_a.clear();
seq_d.clear();
const model_type &model = get_model();
while(a != 0 || d != 0) {
double u = p(a,d)*myrand.uniform01();
double t = (a > 0 && d > 0) ? p(a-1,d-1)*model.p_substitution[sa[a-1]][sd[d-1]] : 0.0;
if(u < t) {
// match
a = a-1;
d = d-1;
seq_a.append(1, ccNuc[sa[a]]);
seq_d.append(1, ccNuc[sd[d]]);
} else {
for(size_t k = 1; k <= a || k <= d; ++k) {
if(k <= a) {
t += p(a-k,d)*model.p_indel_size[k];
if(u < t) {
// gap in d
seq_d.append(k, '-');
while(k--) seq_a.append(1, ccNuc[sa[--a]]);
break;
}
}
if(k <= d)
{
t += p(a,d-k)*model.p_indel_size[k];
if(u < t) {
// gap in a
seq_a.append(k, '-');
while(k--) seq_d.append(1, ccNuc[sd[--d]]);
break;
}
}
}
}
//seq_a.append(1,',');
//seq_d.append(1,',');
}
reverse(seq_a.begin(), seq_a.end());
reverse(seq_d.begin(), seq_d.end());
}
void sample_k2p_geo::preallocate(size_t maxa, size_t maxd)
{
p.resize(maxa+1,maxd+1,0.0);
}
void sample_k2p_geo::presample_step(const params_type ¶ms, const sequence &seq_a, const sequence &seq_d)
{
size_t sz_max = std::max(sz_height, sz_width);
size_t sz_anc = seq_a.size();
size_t sz_dec = seq_d.size();
sa = seq_a;
sd = seq_d;
const model_type &model = get_model();
double row_cache = 0.0;
vector<double> col_cache(sz_dec+1, 0.0);
p(0,0) = prob_scale;
for(size_t d = 1; d <= sz_dec; ++d) {
row_cache *= model.p_extend;
row_cache += p(0,d-1)*model.p_open;
p(0,d) = row_cache;
}
row_cache = 0.0;
for(size_t a = 1; a <= sz_anc; ++a) {
row_cache *= model.p_extend;
row_cache += p(a-1,0)*model.p_open;
p(a,0) = row_cache;
}
for(size_t a=1;a<=sz_anc;++a) {
row_cache = 0.0;
for(size_t d=1;d<= sz_dec;++d) {
double pt = p(a-1,d-1)*model.p_substitution[sa[a-1]][sd[d-1]];
row_cache *= model.p_extend;
row_cache += p(a,d-1)*model.p_open;
pt += row_cache;
col_cache[d] *= model.p_extend;
col_cache[d] += p(a-1,d)*model.p_open;
pt += col_cache[d];
p(a,d) = pt;
}
}
}
void sample_k2p_geo::sample_once(std::string &seq_a, std::string &seq_d)
{
size_t a = sa.size();
size_t d = sd.size();
seq_a.clear();
seq_d.clear();
const model_type &model = get_model();
while(a != 0 || d != 0) {
double u = p(a,d)*myrand.uniform01();
double t = (a > 0 && d > 0) ? p(a-1,d-1)*model.p_substitution[sa[a-1]][sd[d-1]] : 0.0;
if(u < t) {
// match
a = a-1;
d = d-1;
seq_a.append(1, ccNuc[sa[a]]);
seq_d.append(1, ccNuc[sd[d]]);
} else {
for(size_t k = 1; k <= a || k <= d; ++k) {
if(k <= a) {
t += p(a-k,d)*model.p_indel_size[k];
if(u < t) {
// gap in d
seq_d.append(k, '-');
while(k--) seq_a.append(1, ccNuc[sa[--a]]);
break;
}
}
if(k <= d)
{
t += p(a,d-k)*model.p_indel_size[k];
if(u < t) {
// gap in a
seq_a.append(k, '-');
while(k--) seq_d.append(1, ccNuc[sd[--d]]);
break;
}
}
}
}
//seq_a.append(1,',');
//seq_d.append(1,',');
}
reverse(seq_a.begin(), seq_a.end());
reverse(seq_d.begin(), seq_d.end());
}
// Draw from Zipf distribution, with parameter a > 1.0
// Devroye Luc (1986) Non-uniform random variate generation.
// Springer-Verlag: Berlin. p551
inline unsigned int rand_zipf(double a)
{
double b = pow(2.0, a-1.0);
double x,t;
do {
x = floor(pow(myrand.uniform01(), -1.0/(a-1.0)));
t = pow(1.0+1.0/x, a-1.0);
} while( myrand.uniform01()*x*(t-1.0)*b >= t*(b-1.0));
return (unsigned int)x;
}
const char g_nuc[] = "ACGT";
const char g_nuc2[] = "ACGT" "GTAC" "TGCA" "CATG";
void gen_sample_k2p_zeta::sample_once(std::string &seq_a, std::string &seq_d)
{
seq_a.clear();
seq_d.clear();
const model_type &model = get_model();
const double z = get_params()[model_k2p_zeta::pZ];
while(1) {
double p = myrand.uniform01();
if(p < model.p_2h) {
// M
unsigned int x = myrand.uniform(4);
seq_a.append(1, g_nuc[x]);
p = myrand.uniform01();
if(p < model.p_match) {
seq_d.append(1, g_nuc2[x]);
} else if(p < model.p_match+model.p_ts) {
seq_d.append(1, g_nuc2[x+4]);
} else if(p < 1.0 - 0.5*model.p_ts) {
seq_d.append(1, g_nuc2[x+8]);
} else {
seq_d.append(1, g_nuc2[x+12]);
}
} else if(p < model.p_2h+model.p_2g) {
// U
unsigned int x;
do {
x = rand_zipf(z);
} while(x > nmax);
seq_d.append(x, '-');
while(x--) {
seq_a.append(1, g_nuc[myrand.uniform(4)]);
}
} else if(p < 1.0-model.p_end) {
// V
unsigned int x;
do {
x = rand_zipf(z);
} while(x > nmax);
seq_a.append(x, '-');
while(x--) {
seq_d.append(1, g_nuc[myrand.uniform(4)]);
}
} else {
// E
break;
}
}
}
void gen_sample_k2p_geo::sample_once(std::string &seq_a, std::string &seq_d)
{
seq_a.clear();
seq_d.clear();
const model_type &model = get_model();
const double q = 1.0/get_params()[model_k2p_geo::pQ];
while(1) {
double p = myrand.uniform01();
if(p < model.p_2h) {
// M
unsigned int x = myrand.uniform(4);
seq_a.append(1, g_nuc[x]);
p = myrand.uniform01();
if(p < model.p_match) {
seq_d.append(1, g_nuc2[x]);
} else if(p < model.p_match+model.p_ts) {
seq_d.append(1, g_nuc2[x+4]);
} else if(p < 1.0 - 0.5*model.p_ts) {
seq_d.append(1, g_nuc2[x+8]);
} else {
seq_d.append(1, g_nuc2[x+12]);
}
} else if(p < model.p_2h+model.p_2g) {
// U
unsigned int x = myrand.geometric(q);
seq_d.append(x, '-');
while(x--) {
seq_a.append(1, g_nuc[myrand.uniform(4)]);
}
} else if(p < 1.0-model.p_end) {
// V
unsigned int x = myrand.geometric(q);
seq_a.append(x, '-');
while(x--) {
seq_d.append(1, g_nuc[myrand.uniform(4)]);
}
} else {
// E
break;
}
}
}
| 26.333333 | 109 | 0.550411 | reedacartwright |
c9c295d4d2c79c930df838912f575323a9610940 | 25,283 | cpp | C++ | sdktools/debuggers/drwatson/ui.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | sdktools/debuggers/drwatson/ui.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | sdktools/debuggers/drwatson/ui.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (c) 1993-2002 Microsoft Corporation
Module Name:
ui.cpp
Abstract:
This function implements the ui (dialog) that controls the
options maintenace for drwatson.
Author:
Wesley Witt (wesw) 1-May-1993
Environment:
User Mode
--*/
#include "pch.cpp"
void
InitializeDialog(
HWND hwnd
);
void
InitializeCrashList(
HWND hwnd
);
BOOL
GetDialogValues(
HWND hwnd
);
INT_PTR
CALLBACK
LogFileViewerDialogProc(
HWND hwnd,
UINT message,
WPARAM wParam,
LPARAM lParam
);
INT_PTR
CALLBACK
DrWatsonDialogProc (
HWND hwnd,
UINT message,
WPARAM wParam,
LPARAM lParam
);
PTSTR
ExpandPath(
PTSTR lpPath
);
const
DWORD
DrWatsonHelpIds[] = {
ID_LOGPATH_TEXT, IDH_LOG_FILE_PATH,
ID_LOGPATH, IDH_LOG_FILE_PATH,
ID_BROWSE_LOGPATH, IDH_BROWSE,
ID_CRASH_DUMP_TEXT, IDH_CRASH_DUMP,
ID_CRASH_DUMP, IDH_CRASH_DUMP,
ID_BROWSE_CRASH, IDH_BROWSE,
ID_WAVEFILE_TEXT, IDH_WAVE_FILE,
ID_WAVE_FILE, IDH_WAVE_FILE,
ID_BROWSE_WAVEFILE, IDH_BROWSE,
ID_DUMP_TYPE_TEXT, IDH_CRASH_DUMP_TYPE,
ID_DUMP_TYPE_FULLMINI, IDH_CRASH_DUMP_FULL,
ID_DUMP_TYPE_MINI, IDH_CRASH_DUMP_MINI,
ID_DUMP_TYPE_FULL_OLD, IDH_CRASH_DUMP_NT4FULL,
ID_INSTRUCTIONS, IDH_NUMBER_OF_INSTRUCTIONS,
ID_NUM_CRASHES, IDH_NUMBER_OF_ERRORS_TO_SAVE,
ID_DUMPSYMBOLS, IDH_DUMP_SYMBOL_TABLE,
ID_DUMPALLTHREADS, IDH_DUMP_ALL_THREAD_CONTEXTS,
ID_APPENDTOLOGFILE, IDH_APPEND_TO_EXISTING_LOGFILE,
ID_VISUAL, IDH_VISUAL_NOTIFICATION,
ID_SOUND, IDH_SOUND_NOTIFICATION,
ID_CRASH, IDH_CREATE_CRASH_DUMP_FILE,
ID_LOGFILE_VIEW, IDH_VIEW,
ID_CLEAR, IDH_CLEAR,
ID_CRASHES, IDH_APPLICATION_ERRORS,
ID_TEST_WAVE, IDH_WAVE_FILE,
psh15, IDH_INDEX,
0, 0
};
void
DrWatsonWinMain(
void
)
/*++
Routine Description:
This is the entry point for DRWTSN32
Arguments:
None.
Return Value:
None.
--*/
{
HWND hwnd;
MSG msg;
HINSTANCE hInst;
WNDCLASS wndclass;
hInst = GetModuleHandle( NULL );
wndclass.style = CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc = (WNDPROC)DrWatsonDialogProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = DLGWINDOWEXTRA;
wndclass.hInstance = hInst;
wndclass.hIcon = LoadIcon( hInst, MAKEINTRESOURCE(APPICON) );
wndclass.hCursor = LoadCursor( NULL, IDC_ARROW );
wndclass.hbrBackground = (HBRUSH) (COLOR_3DFACE + 1);
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = _T("DrWatsonDialog");
RegisterClass( &wndclass );
hwnd = CreateDialog( hInst,
MAKEINTRESOURCE( DRWATSONDIALOG ),
0,
DrWatsonDialogProc
);
if (hwnd == NULL) {
return;
}
ShowWindow( hwnd, SW_SHOWNORMAL );
while (GetMessage (&msg, NULL, 0, 0)) {
if (!IsDialogMessage( hwnd, &msg )) {
TranslateMessage (&msg) ;
DispatchMessage (&msg) ;
}
}
return;
}
INT_PTR
CALLBACK
DrWatsonDialogProc (
HWND hwnd,
UINT message,
WPARAM wParam,
LPARAM lParam
)
/*++
Routine Description:
Window procedure for the DRWTSN32.EXE main user interface.
Arguments:
hwnd - window handle to the dialog box
message - message number
wParam - first message parameter
lParam - second message parameter
Return Value:
TRUE - did not process the message
FALSE - did process the message
--*/
{
DWORD helpId;
DWORD ctlId;
UINT Checked;
_TCHAR szCurrDir[MAX_PATH];
_TCHAR szWave[MAX_PATH];
_TCHAR szDump[MAX_PATH];
_TCHAR szHelpFileName[MAX_PATH];
PTSTR p;
PDWORD pdw;
switch (message) {
case WM_CREATE:
return 0;
case WM_INITDIALOG:
SubclassControls( hwnd );
InitializeDialog( hwnd );
return 1;
case WM_HELP: // F1 key and ?
ctlId = ((LPHELPINFO)lParam)->iCtrlId;
helpId = IDH_INDEX;
for (pdw = (PDWORD)DrWatsonHelpIds; *pdw; pdw+=2) {
if (*pdw == ctlId) {
helpId = pdw[1];
break;
}
}
if ( helpId == IDH_BROWSE ) {
_tcscpy( szHelpFileName, _T("windows.hlp") );
}
else {
GetWinHelpFileName( szHelpFileName,
sizeof(szHelpFileName) / sizeof(_TCHAR) );
}
WinHelp( (HWND)((LPHELPINFO) lParam)->hItemHandle,
szHelpFileName,
HELP_WM_HELP,
(DWORD_PTR)(LPVOID)DrWatsonHelpIds );
return TRUE;
case WM_CONTEXTMENU: // right mouse click
if( hwnd == (HWND) wParam ) {
POINT pt;
GetCursorPos(&pt);
ScreenToClient(hwnd, &pt);
wParam = (WPARAM) ChildWindowFromPoint(hwnd, pt);
}
ctlId = GetDlgCtrlID((HWND)wParam);
helpId = IDH_INDEX;
for (pdw = (PDWORD)DrWatsonHelpIds; *pdw; pdw+=2) {
if (*pdw == ctlId) {
helpId = pdw[1];
break;
}
}
if ( helpId == IDH_BROWSE ) {
_tcscpy( szHelpFileName, _T("windows.hlp") );
}
else {
GetWinHelpFileName( szHelpFileName,
sizeof(szHelpFileName) / sizeof(_TCHAR) );
}
WinHelp((HWND)wParam,
szHelpFileName,
HELP_CONTEXTMENU,
(DWORD_PTR)DrWatsonHelpIds
);
return TRUE;
case WM_ACTIVATEAPP:
case WM_SETFOCUS:
SetFocusToCurrentControl();
return 0;
case WM_SYSCOMMAND:
if (wParam == ID_ABOUT) {
_TCHAR title[256];
_TCHAR extra[256];
LoadRcStringBuf( IDS_ABOUT_TITLE, title, _tsizeof(title) );
LoadRcStringBuf( IDS_ABOUT_EXTRA, extra, _tsizeof(extra) );
ShellAbout( hwnd,
title,
extra,
LoadIcon( GetModuleHandle(NULL), MAKEINTRESOURCE(APPICON) )
);
return 0;
}
break;
case WM_COMMAND:
switch (wParam) {
case IDOK:
if (GetDialogValues( hwnd )) {
HtmlHelp( NULL, NULL, HH_CLOSE_ALL, 0);
PostQuitMessage( 0 );
}
break;
case IDCANCEL:
HtmlHelp( NULL, NULL, HH_CLOSE_ALL, 0);
PostQuitMessage( 0 );
break;
case ID_BROWSE_LOGPATH:
GetDlgItemText( hwnd, ID_LOGPATH, szCurrDir, MAX_PATH );
p = ExpandPath( szCurrDir );
if (p) {
lstrcpyn( szCurrDir, p, _tsizeof(szCurrDir) );
free( p );
}
EnableWindow( GetDlgItem( hwnd, ID_BROWSE_LOGPATH ), FALSE );
if (BrowseForDirectory(hwnd, szCurrDir, _tsizeof(szCurrDir) )) {
SetDlgItemText( hwnd, ID_LOGPATH, szCurrDir );
}
EnableWindow( GetDlgItem( hwnd, ID_BROWSE_LOGPATH ), TRUE );
SetFocus( GetDlgItem(hwnd, ID_BROWSE_LOGPATH) );
return FALSE;
break;
case ID_BROWSE_WAVEFILE:
szWave[0] = _T('\0');
GetDlgItemText( hwnd, ID_WAVE_FILE, szWave, MAX_PATH );
EnableWindow( GetDlgItem( hwnd, ID_BROWSE_WAVEFILE ), FALSE );
if (GetWaveFileName(hwnd, szWave, _tsizeof(szWave) )) {
SetDlgItemText( hwnd, ID_WAVE_FILE, szWave );
}
EnableWindow( GetDlgItem( hwnd, ID_BROWSE_WAVEFILE ), TRUE );
SetFocus( GetDlgItem(hwnd, ID_BROWSE_WAVEFILE) );
return FALSE;
break;
case ID_BROWSE_CRASH:
szDump[0] = _T('\0');
GetDlgItemText( hwnd, ID_CRASH_DUMP, szDump, MAX_PATH );
EnableWindow( GetDlgItem( hwnd, ID_BROWSE_CRASH ), FALSE );
if (GetDumpFileName(hwnd, szDump, _tsizeof(szDump) )) {
SetDlgItemText( hwnd, ID_CRASH_DUMP, szDump );
}
EnableWindow( GetDlgItem( hwnd, ID_BROWSE_CRASH ), TRUE );
SetFocus( GetDlgItem(hwnd, ID_BROWSE_CRASH) );
return FALSE;
break;
case ID_CLEAR:
ElClearAllEvents();
InitializeCrashList( hwnd );
break;
case ID_TEST_WAVE:
GetDlgItemText( hwnd, ID_WAVE_FILE, szWave, sizeof(szWave) / sizeof(_TCHAR) );
PlaySound( szWave, NULL, SND_FILENAME );
break;
case ID_LOGFILE_VIEW:
DialogBoxParam( GetModuleHandle( NULL ),
MAKEINTRESOURCE( LOGFILEVIEWERDIALOG ),
hwnd,
LogFileViewerDialogProc,
SendMessage((HWND)GetDlgItem(hwnd,ID_CRASHES),
LB_GETCURSEL,0,0)
);
break;
case IDHELP:
//
// call HtmlHelp
//
GetHtmlHelpFileName( szHelpFileName, sizeof(szHelpFileName) / sizeof(_TCHAR) );
HtmlHelp( hwnd,
szHelpFileName,
HH_DISPLAY_TOPIC,
(DWORD_PTR)(IDHH_INDEX)
);
SetFocus( GetDlgItem(hwnd, IDHELP) );
break;
default:
if (((HWND)lParam == GetDlgItem( hwnd, ID_CRASHES )) &&
(HIWORD( wParam ) == LBN_DBLCLK)) {
DialogBoxParam( GetModuleHandle( NULL ),
MAKEINTRESOURCE( LOGFILEVIEWERDIALOG ),
hwnd,
LogFileViewerDialogProc,
SendMessage((HWND)lParam,LB_GETCURSEL,0,0)
);
}
if (((HWND)lParam == GetDlgItem( hwnd, ID_CRASH )) &&
(HIWORD( wParam ) == BN_CLICKED)) {
Checked = IsDlgButtonChecked( hwnd, ID_CRASH );
EnableWindow( GetDlgItem( hwnd, ID_CRASH_DUMP_TEXT ), Checked == 1 );
EnableWindow( GetDlgItem( hwnd, ID_CRASH_DUMP ), Checked == 1 );
EnableWindow( GetDlgItem( hwnd, ID_BROWSE_CRASH ), Checked == 1 );
EnableWindow( GetDlgItem( hwnd, ID_DUMP_TYPE_TEXT ), Checked == 1 );
EnableWindow( GetDlgItem( hwnd, ID_DUMP_TYPE_FULL_OLD ), Checked == 1 );
EnableWindow( GetDlgItem( hwnd, ID_DUMP_TYPE_MINI ), Checked == 1 );
EnableWindow( GetDlgItem( hwnd, ID_DUMP_TYPE_FULLMINI ), Checked == 1 );
}
if (((HWND)lParam == GetDlgItem( hwnd, ID_SOUND )) &&
(HIWORD( wParam ) == BN_CLICKED)) {
Checked = IsDlgButtonChecked( hwnd, ID_SOUND );
EnableWindow( GetDlgItem( hwnd, ID_WAVEFILE_TEXT ), Checked == 1 );
EnableWindow( GetDlgItem( hwnd, ID_WAVE_FILE ), Checked == 1 );
EnableWindow( GetDlgItem( hwnd, ID_BROWSE_WAVEFILE ), Checked == 1 );
}
break;
}
break;
case IDH_WAVE_FILE:
//
// call HtmlHelp
//
GetHtmlHelpFileName( szHelpFileName, sizeof(szHelpFileName) / sizeof(_TCHAR) );
HtmlHelp(hwnd,
szHelpFileName,
HH_DISPLAY_TOPIC,
(DWORD_PTR)(IDHH_WAVEFILE)
);
break;
case IDH_CRASH_DUMP:
//
// call HtmlHelp
//
GetHtmlHelpFileName( szHelpFileName, sizeof(szHelpFileName) / sizeof(_TCHAR) );
HtmlHelp( hwnd,
szHelpFileName,
HH_DISPLAY_TOPIC,
(DWORD_PTR)(IDHH_LOGFILELOCATION)
);
break;
case WM_DESTROY:
HtmlHelp( NULL, NULL, HH_CLOSE_ALL, 0);
PostQuitMessage( 0 );
return 0;
}
return DefWindowProc( hwnd, message, wParam, lParam );
}
BOOL
CALLBACK
EnumCrashes(
PCRASHINFO crashInfo
)
/*++
Routine Description:
Enumeration function for crash records. This function is called
once for each crash record. This function places the formatted
crash data in a listbox.
Arguments:
crashInfo - pointer to a CRASHINFO structure
Return Value:
TRUE - caller should continue calling the enum procedure
FALSE - caller should stop calling the enum procedure
--*/
{
SIZE size;
_TCHAR buf[1024];
_sntprintf( buf, _tsizeof(buf),
_T("%s %08x %s(%08p)"),
crashInfo->crash.szAppName,
crashInfo->crash.dwExceptionCode,
crashInfo->crash.szFunction,
(PVOID)crashInfo->crash.dwAddress);
buf[_tsizeof(buf) - 1] = 0;
SendMessage( crashInfo->hList, LB_ADDSTRING, 0, (LPARAM)buf );
GetTextExtentPoint( crashInfo->hdc, buf, _tcslen(buf), &size );
if (size.cx > (LONG)crashInfo->cxExtent) {
crashInfo->cxExtent = size.cx;
}
return TRUE;
}
void
InitializeCrashList(
HWND hwnd
)
/*++
Routine Description:
Initializes the listbox that contains the crash information.
Arguments:
None.
Return Value:
None.
--*/
{
CRASHINFO crashInfo;
TEXTMETRIC tm;
HFONT hFont;
crashInfo.hList = GetDlgItem( hwnd, ID_CRASHES );
SendMessage( crashInfo.hList, LB_RESETCONTENT, FALSE, 0L );
SendMessage( crashInfo.hList, WM_SETREDRAW, FALSE, 0L );
crashInfo.hdc = GetDC( crashInfo.hList );
crashInfo.cxExtent = 0;
ElEnumCrashes( &crashInfo, EnumCrashes );
hFont = (HFONT)SendMessage( crashInfo.hList, WM_GETFONT, 0, 0L );
if (hFont != NULL) {
SelectObject( crashInfo.hdc, hFont );
}
if (crashInfo.hdc != NULL) {
GetTextMetrics( crashInfo.hdc, &tm );
ReleaseDC( crashInfo.hList, crashInfo.hdc );
}
SendMessage( crashInfo.hList, LB_SETHORIZONTALEXTENT, crashInfo.cxExtent, 0L );
SendMessage( crashInfo.hList, WM_SETREDRAW, TRUE, 0L );
return;
}
void
InitializeDialog(
HWND hwnd
)
/*++
Routine Description:
Initializes the DRWTSN32 user interface dialog with the values
stored in the registry.
Arguments:
hwnd - window handle to the dialog
Return Value:
None.
--*/
{
OPTIONS o;
_TCHAR buf[256];
HMENU hMenu;
RegInitialize( &o );
SetDlgItemText( hwnd, ID_LOGPATH, o.szLogPath );
SetDlgItemText( hwnd, ID_WAVE_FILE, o.szWaveFile );
SetDlgItemText( hwnd, ID_CRASH_DUMP, o.szCrashDump );
_stprintf( buf, _T("%d"), o.dwMaxCrashes );
SetDlgItemText( hwnd, ID_NUM_CRASHES, buf );
_stprintf( buf, _T("%d"), o.dwInstructions );
SetDlgItemText( hwnd, ID_INSTRUCTIONS, buf );
SendMessage( GetDlgItem( hwnd, ID_DUMPSYMBOLS ), BM_SETCHECK, o.fDumpSymbols, 0 );
SendMessage( GetDlgItem( hwnd, ID_DUMPALLTHREADS ), BM_SETCHECK, o.fDumpAllThreads, 0 );
SendMessage( GetDlgItem( hwnd, ID_APPENDTOLOGFILE ), BM_SETCHECK, o.fAppendToLogFile, 0 );
SendMessage( GetDlgItem( hwnd, ID_VISUAL ), BM_SETCHECK, o.fVisual, 0 );
SendMessage( GetDlgItem( hwnd, ID_SOUND ), BM_SETCHECK, o.fSound, 0 );
SendMessage( GetDlgItem( hwnd, ID_CRASH ), BM_SETCHECK, o.fCrash, 0 );
SendMessage( GetDlgItem( hwnd, ID_DUMP_TYPE_FULL_OLD ), BM_SETCHECK, o.dwType == FullDump, 0 );
SendMessage( GetDlgItem( hwnd, ID_DUMP_TYPE_MINI ), BM_SETCHECK, o.dwType == MiniDump, 0 );
SendMessage( GetDlgItem( hwnd, ID_DUMP_TYPE_FULLMINI ), BM_SETCHECK, o.dwType == FullMiniDump, 0 );
if (waveOutGetNumDevs() == 0) {
EnableWindow( GetDlgItem( hwnd, ID_WAVEFILE_TEXT ), FALSE );
EnableWindow( GetDlgItem( hwnd, ID_WAVE_FILE ), FALSE );
EnableWindow( GetDlgItem( hwnd, ID_BROWSE_WAVEFILE ), FALSE );
}
else {
EnableWindow( GetDlgItem( hwnd, ID_WAVEFILE_TEXT ), o.fSound );
EnableWindow( GetDlgItem( hwnd, ID_WAVE_FILE ), o.fSound );
EnableWindow( GetDlgItem( hwnd, ID_BROWSE_WAVEFILE ), o.fSound );
}
EnableWindow( GetDlgItem( hwnd, ID_CRASH_DUMP_TEXT ), o.fCrash );
EnableWindow( GetDlgItem( hwnd, ID_CRASH_DUMP ), o.fCrash );
EnableWindow( GetDlgItem( hwnd, ID_BROWSE_CRASH ), o.fCrash );
EnableWindow( GetDlgItem( hwnd, ID_DUMP_TYPE_TEXT ), o.fCrash );
EnableWindow( GetDlgItem( hwnd, ID_DUMP_TYPE_FULL_OLD ), o.fCrash );
EnableWindow( GetDlgItem( hwnd, ID_DUMP_TYPE_MINI ), o.fCrash );
EnableWindow( GetDlgItem( hwnd, ID_DUMP_TYPE_FULLMINI ), o.fCrash );
InitializeCrashList( hwnd );
if (SendMessage( GetDlgItem( hwnd, ID_CRASHES ), LB_GETCOUNT, 0 ,0 ) == 0) {
EnableWindow( GetDlgItem( hwnd, ID_CLEAR ), FALSE );
EnableWindow( GetDlgItem( hwnd, ID_LOGFILE_VIEW ), FALSE );
}
hMenu = GetSystemMenu( hwnd, FALSE );
if (hMenu != NULL) {
AppendMenu( hMenu, MF_SEPARATOR, 0, NULL );
AppendMenu( hMenu, MF_STRING, ID_ABOUT, LoadRcString( IDS_ABOUT ) );
}
return;
}
BOOL
GetDialogValues(
HWND hwnd
)
/*++
Routine Description:
Retrieves the values in the DRWTSN32 dialog controls and saves
them in the registry.
Arguments:
hwnd - window handle to the dialog
Return Value:
TRUE - all values were retrieved and saved
FALSE - an error occurred
--*/
{
OPTIONS o;
_TCHAR buf[256];
DWORD dwFa;
PTSTR p,p1;
_TCHAR szDrive [_MAX_DRIVE];
_TCHAR szDir [_MAX_DIR];
_TCHAR szPath [MAX_PATH];
RegInitialize( &o );
GetDlgItemText( hwnd, ID_LOGPATH, buf, sizeof(buf) / sizeof(_TCHAR) );
p = ExpandPath( buf );
if (p) {
dwFa = GetFileAttributes( p );
free( p );
} else {
dwFa = GetFileAttributes( buf );
}
if ((dwFa == 0xffffffff) || (!(dwFa&FILE_ATTRIBUTE_DIRECTORY))) {
NonFatalError( LoadRcString(IDS_INVALID_PATH) );
return FALSE;
}
if (_tcslen(buf) > 0) {
_tcscpy( o.szLogPath, buf );
}
o.fCrash = SendMessage( GetDlgItem( hwnd, ID_CRASH ), BM_GETCHECK, 0, 0 ) ? TRUE : FALSE;
GetDlgItemText( hwnd, ID_CRASH_DUMP, buf, sizeof(buf) / sizeof(_TCHAR) );
if (o.fCrash) {
p = ExpandPath( buf );
if (p) {
dwFa = GetFileAttributes( p );
free( p );
} else {
dwFa = GetFileAttributes( buf );
}
if (dwFa == 0xffffffff) {
//
// file does not exist, check to see if the dir is ok
//
p = ExpandPath( buf );
if (p) {
p1 = p;
} else {
p1 = buf;
}
_tsplitpath( p1, szDrive, szDir, NULL, NULL );
_tmakepath( szPath, szDrive, szDir, NULL, NULL );
if (p) {
free( p );
}
dwFa = GetFileAttributes( szPath );
if (dwFa == 0xffffffff) {
NonFatalError( LoadRcString(IDS_INVALID_CRASH_PATH) );
return FALSE;
}
} else if (dwFa & FILE_ATTRIBUTE_DIRECTORY) {
NonFatalError( LoadRcString(IDS_INVALID_CRASH_PATH) );
return FALSE;
}
if (_tcslen(buf) > 0) {
_tcscpy( o.szCrashDump, buf );
}
if (SendMessage( GetDlgItem( hwnd, ID_DUMP_TYPE_FULL_OLD ), BM_GETCHECK, 0, 0 )) {
o.dwType = FullDump;
} else if (SendMessage( GetDlgItem( hwnd, ID_DUMP_TYPE_MINI ), BM_GETCHECK, 0, 0 )) {
o.dwType = MiniDump;
} else if (SendMessage( GetDlgItem( hwnd, ID_DUMP_TYPE_FULLMINI ), BM_GETCHECK, 0, 0 )) {
o.dwType = FullMiniDump;
}
}
GetDlgItemText( hwnd, ID_WAVE_FILE, buf, sizeof(buf) / sizeof(_TCHAR) );
if (_tcslen(buf) > 0) {
dwFa = GetFileAttributes( buf );
if ((dwFa == 0xffffffff) || (dwFa&FILE_ATTRIBUTE_DIRECTORY)) {
NonFatalError( LoadRcString(IDS_INVALID_WAVE) );
return FALSE;
}
}
_tcscpy( o.szWaveFile, buf );
GetDlgItemText( hwnd, ID_NUM_CRASHES, buf, sizeof(buf) / sizeof(_TCHAR) );
o.dwMaxCrashes = (DWORD) _ttol( buf );
GetDlgItemText( hwnd, ID_INSTRUCTIONS, buf, sizeof(buf) / sizeof(_TCHAR) );
o.dwInstructions = (DWORD) _ttol( buf );
o.fDumpSymbols = SendMessage( GetDlgItem( hwnd, ID_DUMPSYMBOLS ), BM_GETCHECK, 0, 0 ) ? TRUE : FALSE;
o.fDumpAllThreads = SendMessage( GetDlgItem( hwnd, ID_DUMPALLTHREADS ), BM_GETCHECK, 0, 0 ) ? TRUE : FALSE;
o.fAppendToLogFile = SendMessage( GetDlgItem( hwnd, ID_APPENDTOLOGFILE ), BM_GETCHECK, 0, 0 ) ? TRUE : FALSE;
o.fVisual = SendMessage( GetDlgItem( hwnd, ID_VISUAL ), BM_GETCHECK, 0, 0 ) ? TRUE : FALSE;
o.fSound = SendMessage( GetDlgItem( hwnd, ID_SOUND ), BM_GETCHECK, 0, 0 ) ? TRUE : FALSE;
RegSave( &o );
return TRUE;
}
BOOL
CALLBACK
EnumCrashesForViewer(
PCRASHINFO crashInfo
)
/*++
Routine Description:
Enumeration function for crash records. This function is called
once for each crash record. This function looks for s specific crash
that is identified by the crashIndex.
Arguments:
crashInfo - pointer to a CRASHINFO structure
Return Value:
TRUE - caller should continue calling the enum procedure
FALSE - caller should stop calling the enum procedure
--*/
{
PWSTR p;
if ((crashInfo->dwIndex == crashInfo->dwIndexDesired) &&
(crashInfo->dwCrashDataSize > 0) ) {
p = (PWSTR)crashInfo->pCrashData;
crashInfo->pCrashData = (PBYTE)
calloc( crashInfo->dwCrashDataSize+10, sizeof(BYTE) );
if (crashInfo->pCrashData != NULL) {
if (IsTextUnicode(p, crashInfo->dwCrashDataSize, NULL)) {
WideCharToMultiByte(CP_ACP, WC_SEPCHARS | WC_COMPOSITECHECK,
p, crashInfo->dwCrashDataSize,
(LPSTR)crashInfo->pCrashData, crashInfo->dwCrashDataSize + 10, NULL, NULL);
} else {
memcpy( crashInfo->pCrashData, p, crashInfo->dwCrashDataSize+10 );
}
crashInfo->pCrashData[crashInfo->dwCrashDataSize] = 0;
}
return FALSE;
}
crashInfo->dwIndex++;
return TRUE;
}
INT_PTR
CALLBACK
LogFileViewerDialogProc(
HWND hwnd,
UINT message,
WPARAM wParam,
LPARAM lParam
)
/*++
Routine Description:
Window procedure for the log file viewer dialog box.
Arguments:
hwnd - window handle to the dialog box
message - message number
wParam - first message parameter
lParam - second message parameter
Return Value:
TRUE - did not process the message
FALSE - did process the message
--*/
{
static CRASHINFO crashInfo;
HFONT hFont;
switch (message) {
case WM_INITDIALOG:
hFont = (HFONT)GetStockObject( SYSTEM_FIXED_FONT );
Assert( hFont != NULL );
SendDlgItemMessage( hwnd,
ID_LOGFILE_VIEW,
WM_SETFONT,
(WPARAM) hFont,
(LPARAM) FALSE
);
crashInfo.dwIndex = 0;
crashInfo.dwIndexDesired = (DWORD)lParam;
ElEnumCrashes( &crashInfo, EnumCrashesForViewer );
if (crashInfo.dwIndex != crashInfo.dwIndexDesired) {
MessageBeep( 0 );
EndDialog( hwnd, 0 );
return FALSE;
}
SetDlgItemTextA( hwnd, ID_LOGFILE_VIEW,
(LPSTR)crashInfo.pCrashData );
return TRUE;
case WM_COMMAND:
if (wParam == IDOK) {
free( crashInfo.pCrashData );
EndDialog( hwnd, 0 );
}
break;
case WM_CLOSE:
free( crashInfo.pCrashData );
EndDialog( hwnd, 0 );
return TRUE;
}
return FALSE;
}
| 28.796128 | 114 | 0.550053 | npocmaka |
c9c2f6e2229def0108b5fd997e66ce34830c3522 | 3,625 | cpp | C++ | tests/cache_performance_test.cpp | gatehouse/cppcms | 61da055ffeb349b4eda14bc9ac393af9ce842364 | [
"MIT"
] | 388 | 2017-03-01T07:39:21.000Z | 2022-03-30T19:38:41.000Z | tests/cache_performance_test.cpp | gatehouse/cppcms | 61da055ffeb349b4eda14bc9ac393af9ce842364 | [
"MIT"
] | 81 | 2017-03-08T20:28:00.000Z | 2022-01-23T08:19:31.000Z | tests/cache_performance_test.cpp | gatehouse/cppcms | 61da055ffeb349b4eda14bc9ac393af9ce842364 | [
"MIT"
] | 127 | 2017-03-05T21:53:40.000Z | 2022-02-25T02:31:01.000Z | ///////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2008-2012 Artyom Beilis (Tonkikh) <artyomtnk@yahoo.com>
//
// See accompanying file COPYING.TXT file for licensing details.
//
///////////////////////////////////////////////////////////////////////////////
#include "test.h"
#include "cache_storage.h"
#include "base_cache.h"
#include <booster/intrusive_ptr.h>
#include <booster/posix_time.h>
#include <cppcms/config.h>
#include <iostream>
#include <booster/auto_ptr_inc.h>
#include <time.h>
#include <iomanip>
#include <stdlib.h>
#include <cppcms/urandom.h>
extern "C" void do_store( cppcms::impl::base_cache &c,
std::string const &key,
std::string const &value,
std::set<std::string> const &tr)
{
c.store(key,value,tr,time(0)+1000);
}
unsigned long long rand_val()
{
cppcms::urandom_device rd;
unsigned long long v;
rd.generate(&v,sizeof(v));
return v;
}
void cache_tester(booster::intrusive_ptr<cppcms::impl::base_cache> cache)
{
std::string page;
page.reserve(16384);
while(page.size() < 16384) {
page+="x";
}
unsigned long long rnd[10][10];
for(int i=0;i<10;i++)
for(int j=0;j<10;j++)
rnd[i][j]=rand_val();
int limit = 10000;
double store = 0;
double store2 = 0;
int store_count=0;
double rise = 0,rise2=0;
int rise_count=0;
for(int i=0;i<limit;i++) {
std::string key;
std::set<std::string> triggers;
for(int j=0;j<10;j++) {
std::ostringstream ss;
ss << "trigger_" << j <<"_" << i % 10;
//ss << "t" << rnd[j][i % 10];
triggers.insert(ss.str());
}
std::ostringstream ss;
ss << "key_" << i;
//ss << rand_val();
key=ss.str();
{
booster::ptime start = booster::ptime::now();
do_store(*cache,key,page,triggers);
//cache->store(key,page,triggers,time(0)+100);
booster::ptime end = booster::ptime::now();
double m = booster::ptime::to_number(end-start);
store +=m;
store2 += m*m;
store_count ++;
}
if(i % 1000 == 999) {
std::ostringstream ss;
ss << "trigger_0_" << ((i + 324) % 10000 / 1000);
//ss << "t" << rnd[0][((i + 324) % 10000 / 1000)];
std::string t=ss.str();
{
booster::ptime start = booster::ptime::now();
cache->rise(t);
booster::ptime end = booster::ptime::now();
double m = booster::ptime::to_number(end-start);
rise +=m;
rise2 += m*m;
rise_count ++;
}
}
}
double mean_store = store / store_count * 1e6;
double std_store = sqrt(store2 / store_count - (store / store_count) * ( store / store_count)) * 1e6;
std::cout <<std::fixed<< "Store " <<std::setprecision(1)<< std::setw(16)<< mean_store << " +/- " <<std::setw(16)<< std_store << std::endl;
double mean_rise = rise / rise_count * 1e6;
double std_rise = sqrt(rise2 / rise_count - (rise / rise_count) * ( rise / rise_count)) * 1e6;
std::cout << "Rise " <<std::setprecision(1)<<std::setw(16)<< mean_rise << " +/- " <<std::setw(16)<< std_rise << std::endl;
}
int main()
{
try {
std::locale::global(std::locale(""));
std::cout.imbue(std::locale());
std::cout << "Testing thread cache... "<< std::endl;
cache_tester(cppcms::impl::thread_cache_factory(10000));
#if !defined(CPPCMS_WIN32) && !defined(CPPCMS_NO_PREFOK_CACHE)
std::cout << "Testing process cache... " << std::endl;
cache_tester(cppcms::impl::process_cache_factory(512*1024*1024,10000));
#endif
}
catch(std::exception const &e) {
std::cerr << "\nFail " << e.what() << std::endl;
return 1;
}
return 0;
}
| 28.769841 | 139 | 0.569103 | gatehouse |
c9c8816e1c7c99169aceff2eb5d3d636528d120d | 17,914 | cpp | C++ | source/tests/suite-utf8-normalize-decompose.cpp | zypeh/utf8rewind | 46dd600a4716f80debbe4bbbe4a5b19daf0e2cb2 | [
"MIT"
] | 5 | 2021-02-07T08:19:59.000Z | 2021-11-18T01:17:01.000Z | source/tests/suite-utf8-normalize-decompose.cpp | zypeh/utf8rewind | 46dd600a4716f80debbe4bbbe4a5b19daf0e2cb2 | [
"MIT"
] | 1 | 2020-05-25T08:59:35.000Z | 2020-05-25T14:59:09.000Z | source/tests/suite-utf8-normalize-decompose.cpp | zypeh/utf8rewind | 46dd600a4716f80debbe4bbbe4a5b19daf0e2cb2 | [
"MIT"
] | 1 | 2022-03-27T05:53:28.000Z | 2022-03-27T05:53:28.000Z | #include "tests-base.hpp"
extern "C" {
#include "../internal/database.h"
};
#include "../helpers/helpers-strings.hpp"
TEST(Utf8NormalizeDecompose, BasicLatinSingle)
{
/*
U+007A
Y
0
*/
const char* i = "z";
size_t is = strlen(i);
char o[256] = { 0 };
size_t os = 255;
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(1, utf8normalize(i, is, o, os, UTF8_NORMALIZE_DECOMPOSE, &errors));
EXPECT_UTF8EQ("z", o);
EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}
TEST(Utf8NormalizeDecompose, BasicLatinMultiple)
{
/*
U+0048 U+006F U+006D U+0065
Y Y Y Y
0 0 0 0
*/
const char* i = "Home";
size_t is = strlen(i);
char o[256] = { 0 };
size_t os = 255;
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(4, utf8normalize(i, is, o, os, UTF8_NORMALIZE_DECOMPOSE, &errors));
EXPECT_UTF8EQ("Home", o);
EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}
TEST(Utf8NormalizeDecompose, BasicLatinCompatibility)
{
/*
U+0073 U+0074 U+0065 U+0070
Y Y Y Y
0 0 0 0
*/
const char* i = "step";
size_t is = strlen(i);
char o[256] = { 0 };
size_t os = 255;
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(4, utf8normalize(i, is, o, os, UTF8_NORMALIZE_DECOMPOSE | UTF8_NORMALIZE_COMPATIBILITY, &errors));
EXPECT_UTF8EQ("step", o);
EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}
TEST(Utf8NormalizeDecompose, BasicLatinAmountOfBytes)
{
/*
U+0024 U+0020 U+0034 U+002E U+0032 U+0035 U+0020 U+0070 U+0065 U+0072 U+0020 U+0070 U+006F U+0075 U+006E U+0064
Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
*/
const char* i = "$ 4.25 per pound";
size_t is = strlen(i);
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(16, utf8normalize(i, is, nullptr, 0, UTF8_NORMALIZE_DECOMPOSE, &errors));
EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}
TEST(Utf8NormalizeDecompose, BasicLatinNotEnoughSpace)
{
/*
U+0052 U+0061 U+0069 U+006E U+0079 U+0020 U+0064 U+0061 U+0079
Y Y Y Y Y Y Y Y Y
0 0 0 0 0 0 0 0 0
*/
const char* i = "Rainy day";
size_t is = strlen(i);
char o[256] = { 0 };
size_t os = 4;
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(4, utf8normalize(i, is, o, os, UTF8_NORMALIZE_DECOMPOSE, &errors));
EXPECT_UTF8EQ("Rain", o);
EXPECT_ERROREQ(UTF8_ERR_NOT_ENOUGH_SPACE, errors);
}
TEST(Utf8NormalizeDecompose, MultiByteUnaffectedSingle)
{
/*
U+00B5
Y
0
*/
const char* i = "\xC2\xB5";
size_t is = strlen(i);
char o[256] = { 0 };
size_t os = 255;
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(2, utf8normalize(i, is, o, os, UTF8_NORMALIZE_DECOMPOSE, &errors));
EXPECT_UTF8EQ("\xC2\xB5", o);
EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}
TEST(Utf8NormalizeDecompose, MultiByteUnaffectedMultiple)
{
/*
U+1AA8 U+1A80 U+1A87
Y Y Y
0 0 0
*/
const char* i = "\xE1\xAA\xA8\xE1\xAA\x80\xE1\xAA\x87";
size_t is = strlen(i);
char o[256] = { 0 };
size_t os = 255;
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(9, utf8normalize(i, is, o, os, UTF8_NORMALIZE_DECOMPOSE, &errors));
EXPECT_UTF8EQ("\xE1\xAA\xA8\xE1\xAA\x80\xE1\xAA\x87", o);
EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}
TEST(Utf8NormalizeDecompose, MultiByteUnaffectedCompatibility)
{
/*
U+2E3A U+2AE0 U+2B49
Y Y Y
0 0 0
*/
const char* i = "\xE2\xB8\xBA\xE2\xAB\xA0\xE2\xAD\x89";
size_t is = strlen(i);
char o[256] = { 0 };
size_t os = 255;
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(9, utf8normalize(i, is, o, os, UTF8_NORMALIZE_DECOMPOSE | UTF8_NORMALIZE_COMPATIBILITY, &errors));
EXPECT_UTF8EQ("\xE2\xB8\xBA\xE2\xAB\xA0\xE2\xAD\x89", o);
EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}
TEST(Utf8NormalizeDecompose, MultiByteUnaffectedAmountOfBytes)
{
/*
U+2181 U+2145 U+2086
Y Y Y
0 0 0
*/
const char* i = "\xE2\x86\x81\xE2\x85\x85\xE2\x82\x86";
size_t is = strlen(i);
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(9, utf8normalize(i, is, nullptr, 0, UTF8_NORMALIZE_DECOMPOSE, &errors));
EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}
TEST(Utf8NormalizeDecompose, MultiByteUnaffectedNotEnoughSpace)
{
/*
U+2035 U+2106 U+2090 U+2104
Y Y Y Y
0 0 0 0
*/
const char* i = "\xE2\x80\xB5\xE2\x84\x86\xE2\x82\x90\xE2\x84\x84";
size_t is = strlen(i);
char o[256] = { 0 };
size_t os = 8;
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(6, utf8normalize(i, is, o, os, UTF8_NORMALIZE_DECOMPOSE, &errors));
EXPECT_UTF8EQ("\xE2\x80\xB5\xE2\x84\x86", o);
EXPECT_ERROREQ(UTF8_ERR_NOT_ENOUGH_SPACE, errors);
}
TEST(Utf8NormalizeDecompose, MultiByteDecomposeSingle)
{
/*
U+0958
N
0
*/
const char* i = "\xE0\xA5\x98";
size_t is = strlen(i);
char o[256] = { 0 };
size_t os = 255;
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(6, utf8normalize(i, is, o, os, UTF8_NORMALIZE_DECOMPOSE, &errors));
EXPECT_UTF8EQ("\xE0\xA4\x95\xE0\xA4\xBC", o);
EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}
TEST(Utf8NormalizeDecompose, MultiByteDecomposeSingleCompatibility)
{
/*
U+3316 U+327C U+323E U+01C4
N N N N
0 0 0 0
*/
const char* i = "\xE3\x8C\x96\xE3\x89\xBC\xE3\x88\xBE\xC7\x84";
size_t is = strlen(i);
char o[256] = { 0 };
size_t os = 255;
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(42, utf8normalize(i, is, o, os, UTF8_NORMALIZE_DECOMPOSE | UTF8_NORMALIZE_COMPATIBILITY, &errors));
EXPECT_UTF8EQ("\xE3\x82\xAD\xE3\x83\xAD\xE3\x83\xA1\xE3\x83\xBC\xE3\x83\x88\xE3\x83\xAB\xE1\x84\x8E\xE1\x85\xA1\xE1\x86\xB7\xE1\x84\x80\xE1\x85\xA9(\xE8\xB3\x87)DZ\xCC\x8C", o);
EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}
TEST(Utf8NormalizeDecompose, MultiByteDecomposeSingleAmountOfBytes)
{
/*
U+01FA
N
0
*/
const char* i = "\xC7\xBA";
size_t is = strlen(i);
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(5, utf8normalize(i, is, nullptr, 0, UTF8_NORMALIZE_DECOMPOSE, &errors));
EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}
TEST(Utf8NormalizeDecompose, MultiByteDecomposeSingleNotEnoughSpace)
{
/*
U+1E08
N
0
*/
const char* i = "\xE1\xB8\x88";
size_t is = strlen(i);
char o[256] = { 0 };
size_t os = 4;
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(3, utf8normalize(i, is, o, os, UTF8_NORMALIZE_DECOMPOSE, &errors));
EXPECT_UTF8EQ("C\xCC\xA7", o);
EXPECT_ERROREQ(UTF8_ERR_NOT_ENOUGH_SPACE, errors);
}
TEST(Utf8NormalizeDecompose, MultiByteDecomposeSequenceSingleOrdered)
{
/*
U+0108 U+0301
N Y
0 230
*/
const char* i = "\xC4\x88\xCC\x81";
size_t is = strlen(i);
char o[256] = { 0 };
size_t os = 255;
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(5, utf8normalize(i, is, o, os, UTF8_NORMALIZE_DECOMPOSE, &errors));
EXPECT_UTF8EQ("C\xCC\x82\xCC\x81", o);
EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}
TEST(Utf8NormalizeDecompose, MultiByteDecomposeSequenceSingleUnordered)
{
/*
U+0041 U+0304 U+031D
Y Y Y
0 230 220
*/
const char* i = "A\xCC\x84\xCC\x9D";
size_t is = strlen(i);
char o[256] = { 0 };
size_t os = 255;
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(5, utf8normalize(i, is, o, os, UTF8_NORMALIZE_DECOMPOSE, &errors));
EXPECT_UTF8EQ("A\xCC\x9D\xCC\x84", o);
EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}
TEST(Utf8NormalizeDecompose, MultiByteDecomposeSequenceMultipleOrdered)
{
/*
U+0202 U+0315 U+038E U+0301
N Y N Y
0 232 0 230
*/
const char* i = "\xC8\x82\xCC\x95\xCE\x8E\xCC\x81";
size_t is = strlen(i);
char o[256] = { 0 };
size_t os = 255;
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(11, utf8normalize(i, is, o, os, UTF8_NORMALIZE_DECOMPOSE, &errors));
EXPECT_UTF8EQ("A\xCC\x91\xCC\x95\xCE\xA5\xCC\x81\xCC\x81", o);
EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}
TEST(Utf8NormalizeDecompose, MultiByteDecomposeSequenceMultipleUnordered)
{
/*
U+00CA U+0347 U+00C3 U+035C U+0348 U+00ED U+031B
N Y N Y Y N Y
0 220 0 233 220 0 216
*/
const char* i = "\xC3\x8A\xCD\x87\xC3\x83\xCD\x9C\xCD\x88\xC3\xAD\xCC\x9B";
size_t is = strlen(i);
char o[256] = { 0 };
size_t os = 255;
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(17, utf8normalize(i, is, o, os, UTF8_NORMALIZE_DECOMPOSE, &errors));
EXPECT_UTF8EQ("E\xCD\x87\xCC\x82" "A\xCD\x88\xCC\x83\xCD\x9C" "i\xCC\x9B\xCC\x81", o);
EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}
TEST(Utf8NormalizeDecompose, MultiByteDecomposeSequenceCompatibility)
{
/*
U+0174 U+0306
N Y
0 230
*/
const char* i = "\xC5\xB4\xCC\x86";
size_t is = strlen(i);
char o[256] = { 0 };
size_t os = 255;
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(5, utf8normalize(i, is, o, os, UTF8_NORMALIZE_DECOMPOSE | UTF8_NORMALIZE_COMPATIBILITY, &errors));
EXPECT_UTF8EQ("W\xCC\x82\xCC\x86", o);
EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}
TEST(Utf8NormalizeDecompose, MultiByteDecomposeSequenceAmountOfBytes)
{
/*
U+00C7 U+0301 U+0347
N Y Y
0 230 220
*/
const char* i = "\xC3\x87\xCC\x81\xCD\x87";
size_t is = strlen(i);
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(7, utf8normalize(i, is, nullptr, 0, UTF8_NORMALIZE_DECOMPOSE, &errors));
EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}
TEST(Utf8NormalizeDecompose, MultiByteDecomposeSequenceNotEnoughSpace)
{
/*
U+00C3 U+035C U+0348
N Y Y
0 233 220
*/
const char* i = "\xC3\x83\xCD\x9C\xCD\x88";
size_t is = strlen(i);
char o[256] = { 0 };
size_t os = 6;
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(5, utf8normalize(i, is, o, os, UTF8_NORMALIZE_DECOMPOSE, &errors));
EXPECT_UTF8EQ("A\xCD\x88\xCC\x83", o);
EXPECT_ERROREQ(UTF8_ERR_NOT_ENOUGH_SPACE, errors);
}
TEST(Utf8NormalizeDecompose, HangulUnaffectedSingle)
{
/*
U+11BD
Y
0
*/
const char* i = "\xE1\x86\xBD";
size_t is = strlen(i);
char o[256] = { 0 };
size_t os = 255;
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(3, utf8normalize(i, is, o, os, UTF8_NORMALIZE_DECOMPOSE, &errors));
EXPECT_UTF8EQ("\xE1\x86\xBD", o);
EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}
TEST(Utf8NormalizeDecompose, HangulUnaffectedMultiple)
{
/*
U+1100 U+116A U+11B2
Y Y Y
0 0 0
*/
const char* i = "\xE1\x84\x80\xE1\x85\xAA\xE1\x86\xB2";
size_t is = strlen(i);
char o[256] = { 0 };
size_t os = 255;
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(9, utf8normalize(i, is, o, os, UTF8_NORMALIZE_DECOMPOSE, &errors));
EXPECT_UTF8EQ("\xE1\x84\x80\xE1\x85\xAA\xE1\x86\xB2", o);
EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}
TEST(Utf8NormalizeDecompose, HangulUnaffectedCompatibility)
{
/*
U+1103 U+116A U+11AD
Y Y Y
0 0 0
*/
const char* i = "\xE1\x84\x83\xE1\x85\xAA\xE1\x86\xAD";
size_t is = strlen(i);
char o[256] = { 0 };
size_t os = 255;
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(9, utf8normalize(i, is, o, os, UTF8_NORMALIZE_DECOMPOSE | UTF8_NORMALIZE_COMPATIBILITY, &errors));
EXPECT_UTF8EQ("\xE1\x84\x83\xE1\x85\xAA\xE1\x86\xAD", o);
EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}
TEST(Utf8NormalizeDecompose, HangulUnaffectedAmountOfBytes)
{
/*
U+116A U+11AA
Y Y
0 0
*/
const char* i = "\xE1\x85\xAA\xE1\x86\xAA";
size_t is = strlen(i);
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(6, utf8normalize(i, is, nullptr, 0, UTF8_NORMALIZE_DECOMPOSE, &errors));
EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}
TEST(Utf8NormalizeDecompose, HangulUnaffectedNotEnoughSpace)
{
/*
U+1100 U+116A U+11BD U+1100 U+1169 U+11BF
Y Y Y Y Y Y
0 0 0 0 0 0
*/
const char* i = "\xE1\x84\x80\xE1\x85\xAA\xE1\x86\xBD\xE1\x84\x80\xE1\x85\xA9\xE1\x86\xBF";
size_t is = strlen(i);
char o[256] = { 0 };
size_t os = 9;
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(9, utf8normalize(i, is, o, os, UTF8_NORMALIZE_DECOMPOSE, &errors));
EXPECT_UTF8EQ("\xE1\x84\x80\xE1\x85\xAA\xE1\x86\xBD", o);
EXPECT_ERROREQ(UTF8_ERR_NOT_ENOUGH_SPACE, errors);
}
TEST(Utf8NormalizeDecompose, HangulDecomposeSingleTwoCodepoints)
{
/*
U+AC70
N
0
*/
const char* i = "\xEA\xB1\xB0";
size_t is = strlen(i);
char o[256] = { 0 };
size_t os = 255;
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(6, utf8normalize(i, is, o, os, UTF8_NORMALIZE_DECOMPOSE, &errors));
EXPECT_UTF8EQ("\xE1\x84\x80\xE1\x85\xA5", o);
EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}
TEST(Utf8NormalizeDecompose, HangulDecomposeSingleThreeCodepoints)
{
/*
U+AD83
N
0
*/
const char* i = "\xEA\xB6\x83";
size_t is = strlen(i);
char o[256] = { 0 };
size_t os = 255;
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(9, utf8normalize(i, is, o, os, UTF8_NORMALIZE_DECOMPOSE, &errors));
EXPECT_UTF8EQ("\xE1\x84\x80\xE1\x85\xAE\xE1\x86\xBE", o);
EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}
TEST(Utf8NormalizeDecompose, HangulDecomposeSequenceMultiple)
{
/*
U+ACE0 U+1100 U+1169 U+11B0 U+ACFC
N Y Y Y N
0 0 0 0 0
*/
const char* i = "\xEA\xB3\xA0\xE1\x84\x80\xE1\x85\xA9\xE1\x86\xB0\xEA\xB3\xBC";
size_t is = strlen(i);
char o[256] = { 0 };
size_t os = 255;
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(21, utf8normalize(i, is, o, os, UTF8_NORMALIZE_DECOMPOSE, &errors));
EXPECT_UTF8EQ("\xE1\x84\x80\xE1\x85\xA9\xE1\x84\x80\xE1\x85\xA9\xE1\x86\xB0\xE1\x84\x80\xE1\x85\xAA", o);
EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}
TEST(Utf8NormalizeDecompose, HangulDecomposeCompatibility)
{
/*
U+B3C7 U+B3A8 U+11AA U+B397
N N Y N
0 0 0 0
*/
const char* i = "\xEB\x8F\x87\xEB\x8E\xA8\xE1\x86\xAA\xEB\x8E\x97";
size_t is = strlen(i);
char o[256] = { 0 };
size_t os = 255;
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(27, utf8normalize(i, is, o, os, UTF8_NORMALIZE_DECOMPOSE | UTF8_NORMALIZE_COMPATIBILITY, &errors));
EXPECT_UTF8EQ("\xE1\x84\x83\xE1\x85\xA9\xE1\x86\xAA\xE1\x84\x83\xE1\x85\xA8\xE1\x86\xAA\xE1\x84\x83\xE1\x85\xA7\xE1\x86\xB2", o);
EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}
TEST(Utf8NormalizeDecompose, HangulDecomposeAmountOfBytes)
{
/*
U+AD8C U+B434 U+B04B
N N N
0 0 0
*/
const char* i = "\xEA\xB6\x8C\xEB\x90\xB4\xEB\x81\x8B";
size_t is = strlen(i);
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(24, utf8normalize(i, is, nullptr, 0, UTF8_NORMALIZE_DECOMPOSE, &errors));
EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}
TEST(Utf8NormalizeDecompose, HangulDecomposeNotEnoughSpace)
{
/*
U+AD12 U+1100 U+116B U+11B1
N Y Y Y
0 0 0 0
*/
const char* i = "\xEA\xB4\x92\xE1\x84\x80\xE1\x85\xAB\xE1\x86\xB1";
size_t is = strlen(i);
char o[256] = { 0 };
size_t os = 6;
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(6, utf8normalize(i, is, o, os, UTF8_NORMALIZE_DECOMPOSE, &errors));
EXPECT_UTF8EQ("\xE1\x84\x80\xE1\x85\xAA", o);
EXPECT_ERROREQ(UTF8_ERR_NOT_ENOUGH_SPACE, errors);
}
TEST(Utf8NormalizeDecompose, InvalidCodepointSingle)
{
/*
U+FFFD
Y
0
*/
const char* i = "\xF4";
size_t is = strlen(i);
char o[256] = { 0 };
size_t os = 255;
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(3, utf8normalize(i, is, o, os, UTF8_NORMALIZE_DECOMPOSE, &errors));
EXPECT_UTF8EQ("\xEF\xBF\xBD", o);
EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}
TEST(Utf8NormalizeDecompose, InvalidCodepointMultiple)
{
/*
U+FFFD U+FFFD U+FFFD
Y Y Y
0 0 0
*/
const char* i = "\xEA\xF4\xC8";
size_t is = strlen(i);
char o[256] = { 0 };
size_t os = 255;
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(9, utf8normalize(i, is, o, os, UTF8_NORMALIZE_DECOMPOSE, &errors));
EXPECT_UTF8EQ("\xEF\xBF\xBD\xEF\xBF\xBD\xEF\xBF\xBD", o);
EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}
TEST(Utf8NormalizeDecompose, InvalidCodepointCompatibility)
{
/*
U+FFFD U+FFFD U+FFFD
Y Y Y
0 0 0
*/
const char* i = "\xDA\xCF\xFE";
size_t is = strlen(i);
char o[256] = { 0 };
size_t os = 255;
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(9, utf8normalize(i, is, o, os, UTF8_NORMALIZE_DECOMPOSE | UTF8_NORMALIZE_COMPATIBILITY, &errors));
EXPECT_UTF8EQ("\xEF\xBF\xBD\xEF\xBF\xBD\xEF\xBF\xBD", o);
EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}
TEST(Utf8NormalizeDecompose, InvalidCodepointAmountOfBytes)
{
/*
U+FFFD U+FFFD U+FFFD
Y Y Y
0 0 0
*/
const char* i = "\xCA\xE8\x80\xDF";
size_t is = strlen(i);
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(9, utf8normalize(i, is, nullptr, 0, UTF8_NORMALIZE_DECOMPOSE, &errors));
EXPECT_ERROREQ(UTF8_ERR_NONE, errors);
}
TEST(Utf8NormalizeDecompose, InvalidCodepointNotEnoughSpace)
{
/*
U+FFFD U+FFFD U+FFFD U+FFFD
Y Y Y Y
0 0 0 0
*/
const char* i = "\xEB\xEC\xEF\x88\xF4";
size_t is = strlen(i);
char o[256] = { 0 };
size_t os = 7;
int32_t errors = UTF8_ERR_NONE;
EXPECT_EQ(6, utf8normalize(i, is, o, os, UTF8_NORMALIZE_DECOMPOSE, &errors));
EXPECT_UTF8EQ("\xEF\xBF\xBD\xEF\xBF\xBD", o);
EXPECT_ERROREQ(UTF8_ERR_NOT_ENOUGH_SPACE, errors);
} | 26 | 179 | 0.621134 | zypeh |
c9c8abef1d7be380680f741273078e1f0f8070f9 | 39,784 | cpp | C++ | admin/wmi/wbem/providers/win32provider/common/session.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | admin/wmi/wbem/providers/win32provider/common/session.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | admin/wmi/wbem/providers/win32provider/common/session.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //=============================================================================
// session.cpp -- implementation of session collection class.
//
// Copyright (c) 1998-2002 Microsoft Corporation, All Rights Reserved
//=============================================================================
#include <nt.h>
#include <ntrtl.h>
#include <nturtl.h>
#include <ntobapi.h>
#define _WINNT_ // have what is needed from above
#pragma warning (disable: 4786)
#include "precomp.h"
#include <map>
#include <vector>
#include <comdef.h>
#include "chstring.h"
#include "session.h"
#include <ProvExce.h>
#include <AssertBreak.h>
#include <wbemcli.h>
#include <ntsecapi.h>
#ifdef _WIN32_WINNT
#define SECURITY_WIN32
#else
#define SECURITY_WIN16
#endif
#include <sspi.h>
#include "ctoken.h"
#include <autoptr.h>
#include <ScopeGuard.h>
typedef SECURITY_STATUS (SEC_ENTRY *PFN_LSA_ENUMERATE_LOGON_SESSIONS)
(
OUT PULONG LogonSessionCount,
OUT PLUID* LogonSessionList
);
typedef SECURITY_STATUS (SEC_ENTRY *PFN_LSA_GET_LOGON_SESSION_DATA)
(
IN PLUID LogonId,
OUT PSECURITY_LOGON_SESSION_DATA* ppLogonSessionData
);
typedef NTSTATUS (*PFN_LSA_FREE_RETURN_BUFFER)
(
IN PVOID Buffer
);
//*****************************************************************************
// CUserSessionCollection functions
//*****************************************************************************
CUserSessionCollection::CUserSessionCollection()
{
Refresh();
}
CUserSessionCollection::CUserSessionCollection(
const CUserSessionCollection& sescol)
{
m_usr2ses.clear();
USER_SESSION_ITERATOR sourceIter;
for(sourceIter = sescol.m_usr2ses.begin();
sourceIter != sescol.m_usr2ses.end();
sourceIter++)
{
m_usr2ses.insert(
USER_SESSION_MAP::value_type(
sourceIter->first,
sourceIter->second));
}
}
DWORD CUserSessionCollection::Refresh()
{
DWORD dwRet = ERROR_SUCCESS;
// Empty out previous contents...
m_usr2ses.clear();
dwRet = CollectSessions();
return dwRet;
}
DWORD CUserSessionCollection::CollectSessions()
{
DWORD dwRet = ERROR_SUCCESS;
std::vector<CProcess> vecProcesses;
SmartCloseHandle hProcess;
SmartCloseHandle hToken;
TOKEN_STATISTICS tokstats;
PTOKEN_USER ptokusr = NULL;
DWORD dwRetSize = 0L;
PSID psidUsr = NULL;
CHString chstrUsr;
LUID luidSes;
// Enable the debug privilege...
EnablePrivilegeOnCurrentThread(SE_DEBUG_NAME);
// Get a list of all running processes...
dwRet = GetProcessList(vecProcesses);
if(dwRet == ERROR_SUCCESS)
{
// For each member of the process list...
for(long m = 0L;
m < vecProcesses.size();
m++)
{
// open the process...
::SetLastError(ERROR_SUCCESS);
dwRet = ERROR_SUCCESS;
hProcess = ::OpenProcess(
PROCESS_QUERY_INFORMATION,
FALSE,
vecProcesses[m].GetPID());
if(hProcess == NULL)
{
dwRet = ::GetLastError();
}
// get the process token...
if(hProcess != NULL &&
dwRet == ERROR_SUCCESS)
{
::SetLastError(ERROR_SUCCESS);
dwRet = ERROR_SUCCESS;
if(!::OpenProcessToken(
hProcess,
TOKEN_QUERY,
&hToken))
{
dwRet = ::GetLastError();
}
}
// get the token statistics...
if(hToken != NULL &&
dwRet == ERROR_SUCCESS)
{
::SetLastError(ERROR_SUCCESS);
dwRet = ERROR_SUCCESS;
if(!::GetTokenInformation(
hToken,
TokenStatistics,
&tokstats,
sizeof(TOKEN_STATISTICS),
&dwRetSize))
{
dwRet = ::GetLastError();
}
}
//
// smart token user
//
wmilib::auto_buffer < BYTE > smartptokusr;
// get the token user sid...
if(dwRet == ERROR_SUCCESS)
{
// the token user struct varries
// in size depending on the size
// of the sid in the SID_AND_ATTRIBUTES
// structure, so need to allocate
// it dynamically.
if(!::GetTokenInformation(
hToken,
TokenUser,
NULL,
0L,
&dwRetSize))
{
dwRet = ::GetLastError();
}
if(dwRet == ERROR_INSUFFICIENT_BUFFER)
{
smartptokusr.reset ( new BYTE [ dwRetSize ] ) ;
ptokusr = (PTOKEN_USER) smartptokusr.get () ;
DWORD dwTmp = dwRetSize;
if(!::GetTokenInformation(
hToken,
TokenUser,
ptokusr,
dwTmp,
&dwRetSize))
{
dwRet = ::GetLastError();
}
else
{
dwRet = ERROR_SUCCESS ;
}
}
}
if(ptokusr != NULL)
{
if(dwRet == ERROR_SUCCESS)
{
psidUsr = (ptokusr->User).Sid;
// from the token statistics, get
// the TokenID LUID of the session...
luidSes.LowPart = tokstats.AuthenticationId.LowPart;
luidSes.HighPart = tokstats.AuthenticationId.HighPart;
// try to find the session of the
// process in the multimap...
USER_SESSION_ITERATOR usiter;
if(FindSessionInternal(
luidSes,
usiter))
{
// try to find the process id in the
// session's process vector...
CSession sesTmp(usiter->second);
CProcess* procTmp = NULL;
bool fFoundIt = false;
for(long z = 0L;
z < sesTmp.m_vecProcesses.size() && !fFoundIt;
z++)
{
if((DWORD)(sesTmp.m_vecProcesses[z].GetPID()) ==
vecProcesses[m].GetPID())
{
fFoundIt = true;
}
}
// If we didn't find the process in the
// session's list of processes, add it in...
if(!fFoundIt)
{
(usiter->second).m_vecProcesses.push_back(
CProcess(vecProcesses[m]));
}
}
else // no such session in the map, so add an entry
{
// Create new CSession(tokenid LUID), and
// add process to the session's process vector...
CSession sesNew(luidSes);
sesNew.m_vecProcesses.push_back(
vecProcesses[m]);
// add CUser(user sid) to map.first and the
// CSession just created to map.second...
CUser cuTmp(psidUsr);
if(cuTmp.IsValid())
{
m_usr2ses.insert(
USER_SESSION_MAP::value_type(
cuTmp,
sesNew));
}
else
{
LogErrorMessage2(
L"Token of process %d contains an invalid sid",
vecProcesses[m].GetPID());
}
}
}
}
} // next process
}
// There may have been sessions not associated
// with any processes. To get these, we will
// use LSA.
CollectNoProcessesSessions();
return dwRet;
}
void CUserSessionCollection::Copy(
CUserSessionCollection& out) const
{
out.m_usr2ses.clear();
USER_SESSION_ITERATOR meIter;
for(meIter = m_usr2ses.begin();
meIter != m_usr2ses.end();
meIter++)
{
out.m_usr2ses.insert(
USER_SESSION_MAP::value_type(
meIter->first,
meIter->second));
}
}
// Support enumeration of users. Returns
// a newly allocated copy of what was in
// the map (caller must free).
CUser* CUserSessionCollection::GetFirstUser(
USER_SESSION_ITERATOR& pos)
{
CUser* cusrRet = NULL;
if(!m_usr2ses.empty())
{
pos = m_usr2ses.begin();
cusrRet = new CUser(pos->first);
}
return cusrRet;
}
// Returns a newly allocated CUser*, which
// the caller must free.
CUser* CUserSessionCollection::GetNextUser(
USER_SESSION_ITERATOR& pos)
{
// Users are the non-unique part of
// the map, so we need to go through
// the map until the next user entry
// comes up.
CUser* usrRet = NULL;
while(pos != m_usr2ses.end())
{
CHString chstrSidCur;
pos->first.GetSidString(chstrSidCur);
pos++;
if(pos != m_usr2ses.end())
{
CHString chstrSidNext;
pos->first.GetSidString(chstrSidNext);
// Return the first instance where
// the next user is different from
// the current one.
if(chstrSidNext.CompareNoCase(chstrSidCur) != 0)
{
usrRet = new CUser(pos->first);
break;
}
}
}
return usrRet;
}
// Support enumeration of sessions
// belonging to a particular user.
CSession* CUserSessionCollection::GetFirstSessionOfUser(
CUser& usr,
USER_SESSION_ITERATOR& pos)
{
CSession* csesRet = NULL;
if(!m_usr2ses.empty())
{
pos = m_usr2ses.find(usr);
if(pos != m_usr2ses.end())
{
csesRet = new CSession(pos->second);
}
}
return csesRet;
}
CSession* CUserSessionCollection::GetNextSessionOfUser(
USER_SESSION_ITERATOR& pos)
{
// Sessions are the unique part of
// the map, so we just need to get
// the next one as long as pos.first
// matches usr...
CSession* sesRet = NULL;
if(pos != m_usr2ses.end())
{
CHString chstrUsr1;
CHString chstrUsr2;
(pos->first).GetSidString(chstrUsr1);
pos++;
if(pos != m_usr2ses.end())
{
(pos->first).GetSidString(chstrUsr2);
if(chstrUsr1.CompareNoCase(chstrUsr2) == 0)
{
sesRet = new CSession(pos->second);
}
}
}
return sesRet;
}
// Support enumeration of all sessions. Returns a
// newly allocated CSession*, which the caller
// must free.
CSession* CUserSessionCollection::GetFirstSession(
USER_SESSION_ITERATOR& pos)
{
CSession* csesRet = NULL;
if(!m_usr2ses.empty())
{
pos = m_usr2ses.begin();
csesRet = new CSession(pos->second);
}
return csesRet;
}
// Returns a newly allocated CSession* that the
// caller must free.
CSession* CUserSessionCollection::GetNextSession(
USER_SESSION_ITERATOR& pos)
{
// Sessions are the unique part of
// the map, so we just need to get
// the next one...
CSession* sesRet = NULL;
if(pos != m_usr2ses.end())
{
pos++;
if(pos != m_usr2ses.end())
{
sesRet = new CSession(pos->second);
}
}
return sesRet;
}
// Support finding a particular session.
// This internal version hands back an iterator
// on our member map that points to the found
// instance if found (when the function returns
// true. If the function returns
// false, the iterator points to the end of our
// map.
bool CUserSessionCollection::FindSessionInternal(
LUID& luidSes,
USER_SESSION_ITERATOR& usiOut)
{
bool fFoundIt = false;
for(usiOut = m_usr2ses.begin();
usiOut != m_usr2ses.end();
usiOut++)
{
LUID luidTmp = (usiOut->second).GetLUID();
if(luidTmp.HighPart == luidSes.HighPart &&
luidTmp.LowPart == luidSes.LowPart)
{
fFoundIt = true;
break;
}
}
return fFoundIt;
}
// Support finding a particular session - external
// callers can call this one, and are given a new
// CSession* they can play with.
CSession* CUserSessionCollection::FindSession(
LUID& luidSes)
{
CSession* psesRet = NULL;
USER_SESSION_ITERATOR pos;
if(FindSessionInternal(
luidSes,
pos))
{
psesRet = new CSession(pos->second);
}
return psesRet;
}
CSession* CUserSessionCollection::FindSession(
__int64 i64luidSes)
{
LUID luidSes = *((LUID*)(&i64luidSes));
return FindSession(luidSes);
}
// Support enumeration of processes
// belonging to a particular user. Returns
// newly allocated CProcess* which the caller
// must free.
CProcess* CUserSessionCollection::GetFirstProcessOfUser(
CUser& usr,
USER_SESSION_PROCESS_ITERATOR& pos)
{
CProcess* cprocRet = NULL;
CHString chstrUsrSidStr;
CHString chstrTmp;
if(!m_usr2ses.empty())
{
usr.GetSidString(chstrUsrSidStr);
pos.usIter = m_usr2ses.find(usr);
while(pos.usIter != m_usr2ses.end())
{
// Get the sid string of the user we
// are at and see whether the strings
// are the same (e.g., whether this is a
// session associated with the specified
// user)...
(pos.usIter)->first.GetSidString(chstrTmp);
if(chstrUsrSidStr.CompareNoCase(chstrTmp) == 0)
{
// Now check that the session of the user
// we are on has processes...
if(!(((pos.usIter)->second).m_vecProcesses.empty()))
{
pos.procIter =
((pos.usIter)->second).m_vecProcesses.begin();
cprocRet = new CProcess(*(pos.procIter));
}
else
{
// the session for this user has
// no processes, so go to the next
// session...
(pos.usIter)++;
}
}
}
}
return cprocRet;
}
// Returns a newly allocated CProcess* that the
// caller must free.
CProcess* CUserSessionCollection::GetNextProcessOfUser(
USER_SESSION_PROCESS_ITERATOR& pos)
{
CProcess* cprocRet = NULL;
CHString chstrCurUsr;
CHString chstrNxtSesUsr;
if(pos.usIter != m_usr2ses.end())
{
(pos.usIter)->first.GetSidString(chstrCurUsr);
while(pos.usIter != m_usr2ses.end())
{
// First try to get the next process
// within the current session. If we
// were at the end of the list of processes
// for the current session, go to the
// next session...
(pos.procIter)++;
// Of course, if we have moved on
// to a different user, then stop.
(pos.usIter)->first.GetSidString(chstrNxtSesUsr);
if(chstrCurUsr.CompareNoCase(chstrNxtSesUsr) == 0)
{
if(pos.procIter ==
((pos.usIter)->second).m_vecProcesses.end())
{
(pos.usIter)++;
}
else
{
cprocRet = new CProcess(*(pos.procIter));
}
}
}
}
return cprocRet;
}
// Support enumeration of all processes. Returns
// newly allocated CProcess* which the caller
// must free.
CProcess* CUserSessionCollection::GetFirstProcess(
USER_SESSION_PROCESS_ITERATOR& pos)
{
CProcess* cprocRet = NULL;
if(!m_usr2ses.empty())
{
pos.usIter = m_usr2ses.begin();
while(pos.usIter != m_usr2ses.end())
{
if(!(((pos.usIter)->second).m_vecProcesses.empty()))
{
pos.procIter =
((pos.usIter)->second).m_vecProcesses.begin();
cprocRet = new CProcess(*(pos.procIter));
}
else
{
(pos.usIter)++;
}
}
}
return cprocRet;
}
// Returns a newly allocated CProcess* that the
// caller must free.
CProcess* CUserSessionCollection::GetNextProcess(
USER_SESSION_PROCESS_ITERATOR& pos)
{
CProcess* cprocRet = NULL;
while(pos.usIter != m_usr2ses.end())
{
// First try to get the next process
// within the current session. If we
// were at the end of the list of processes
// for the current session, go to the
// next session...
(pos.procIter)++;
if(pos.procIter ==
((pos.usIter)->second).m_vecProcesses.end())
{
(pos.usIter)++;
}
else
{
cprocRet = new CProcess(*(pos.procIter));
}
}
return cprocRet;
}
// This helper enumerates the current set of processes
// and ads each process id as a DWORD in the vector.
DWORD CUserSessionCollection::GetProcessList( std::vector<CProcess>& vecProcesses ) const
{
DWORD dwRet = ERROR_SUCCESS;
// First, load up ntdll...
HMODULE hLib = NULL;
PFN_NT_QUERY_SYSTEM_INFORMATION pfnNtQuerySystemInformation = NULL;
hLib = LoadLibraryW(L"NTDLL.DLL");
if(hLib != NULL)
{
//
// auto FreeLibrary
//
ON_BLOCK_EXIT ( FreeLibrary, hLib ) ;
// Get proc address of NtQuerySystemInformation...
pfnNtQuerySystemInformation = (PFN_NT_QUERY_SYSTEM_INFORMATION)
GetProcAddress(
hLib,
"NtQuerySystemInformation");
if(pfnNtQuerySystemInformation != NULL)
{
// Ready to rock. Enable debug priv...
EnablePrivilegeOnCurrentThread(SE_DEBUG_NAME);
DWORD dwProcessInformationSize = 0;
SYSTEM_PROCESS_INFORMATION* ProcessInformation = NULL;
//
// smart ProcessInformation
//
wmilib::auto_buffer < BYTE > SmartProcessInformation;
// Get the process information...
BOOL fRetry = TRUE;
while(fRetry)
{
dwRet = pfnNtQuerySystemInformation(
SystemProcessInformation,
ProcessInformation,
dwProcessInformationSize,
NULL);
if(dwRet == STATUS_INFO_LENGTH_MISMATCH)
{
dwProcessInformationSize += 32768;
SmartProcessInformation.reset ( new BYTE [ dwProcessInformationSize ] );
ProcessInformation = (SYSTEM_PROCESS_INFORMATION*)SmartProcessInformation.get () ;
}
else
{
fRetry = FALSE;
}
}
// If we got the process information, process it...
if(ProcessInformation != NULL &&
dwRet == ERROR_SUCCESS)
{
SYSTEM_PROCESS_INFORMATION* CurrentInformation = NULL;
DWORD dwNextOffset;
CurrentInformation = ProcessInformation;
bool fContinue = true;
while(CurrentInformation != NULL &&
fContinue)
{
{
CProcess cptmp(
HandleToUlong(CurrentInformation->UniqueProcessId),
(CurrentInformation->ImageName).Buffer);
vecProcesses.push_back(cptmp);
}
dwNextOffset = CurrentInformation->NextEntryOffset;
if(dwNextOffset)
{
CurrentInformation = (SYSTEM_PROCESS_INFORMATION*)
(((BYTE*) CurrentInformation) + dwNextOffset);
}
else
{
fContinue = false;
}
}
}
}
}
else
{
LogErrorMessage(L"Failed to load library ntdll.dll");
}
return dwRet;
}
// Implementation lifted from dllutils.cpp.
DWORD CUserSessionCollection::EnablePrivilegeOnCurrentThread(
LPCTSTR szPriv) const
{
SmartCloseHandle hToken = NULL;
TOKEN_PRIVILEGES tkp;
BOOL bLookup = FALSE;
DWORD dwLastError = ERROR_SUCCESS;
// Try to open the thread token.
if (::OpenThreadToken(
GetCurrentThread(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
FALSE,
&hToken))
{
{
bLookup = ::LookupPrivilegeValue(
NULL,
szPriv,
&tkp.Privileges[0].Luid);
}
if (bLookup)
{
tkp.PrivilegeCount = 1;
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
// Clear the last error.
SetLastError(0);
// Turn it on
::AdjustTokenPrivileges(
hToken,
FALSE,
&tkp,
0,
(PTOKEN_PRIVILEGES) NULL,
0);
dwLastError = GetLastError();
}
}
else
{
dwLastError = ::GetLastError();
}
// We have to check GetLastError() because
// AdjustTokenPrivileges lies about
// its success but GetLastError() doesn't.
return dwLastError;
}
bool CUserSessionCollection::IsSessionMapped(
LUID& luidSes)
{
bool fRet = false;
USER_SESSION_ITERATOR usiter;
usiter = m_usr2ses.begin();
for(usiter = m_usr2ses.begin();
usiter != m_usr2ses.end() && !fRet;
usiter++)
{
LUID luidTmp = (usiter->second).GetLUID();
if(luidTmp.HighPart == luidSes.HighPart &&
luidTmp.LowPart == luidSes.LowPart)
{
fRet = true;
}
}
return fRet;
}
bool CUserSessionCollection::IsSessionMapped(
__int64 i64luidSes)
{
LUID luidSes = *((LUID*)(&i64luidSes));
return IsSessionMapped(luidSes);
}
// Collects sessions that have no associated
// process. Uses LSA to enumerate sessions,
// then checks to see if we have each session
// already. If we don't, adds it to our map.
DWORD CUserSessionCollection::CollectNoProcessesSessions()
{
DWORD dwRet = ERROR_SUCCESS;
ULONG ulLogonSessionCount = 0L;
PLUID pluidLogonSessions = NULL;
HMODULE hLib = NULL;
PFN_LSA_ENUMERATE_LOGON_SESSIONS pfnEnumLogonSessions = NULL;
PFN_LSA_GET_LOGON_SESSION_DATA pfnGetLogonSessionData = NULL;
PFN_LSA_FREE_RETURN_BUFFER pfnLsaFreeReturnBuffer = NULL;
// Doing a load library here rather than using the
// resource manager, as SECURITYAPI.CPP defines us
// to point to SECURITY.DLL, not SECUR32.DLL for the
// W2K case.
hLib = ::LoadLibraryW(L"SECUR32.DLL");
if(hLib)
{
//
// auto FreeLibrary
//
ON_BLOCK_EXIT ( FreeLibrary, hLib ) ;
pfnEnumLogonSessions =
(PFN_LSA_ENUMERATE_LOGON_SESSIONS) ::GetProcAddress(
hLib,
"LsaEnumerateLogonSessions");
pfnGetLogonSessionData =
(PFN_LSA_GET_LOGON_SESSION_DATA) ::GetProcAddress(
hLib,
"LsaGetLogonSessionData");
pfnLsaFreeReturnBuffer =
(PFN_LSA_FREE_RETURN_BUFFER) ::GetProcAddress(
hLib,
"LsaFreeReturnBuffer");
if(pfnEnumLogonSessions &&
pfnGetLogonSessionData &&
pfnLsaFreeReturnBuffer)
{
dwRet = pfnEnumLogonSessions(
&ulLogonSessionCount,
&pluidLogonSessions);
if(dwRet == ERROR_SUCCESS &&
pluidLogonSessions)
{
//
// auto destructor for logon session
//
ON_BLOCK_EXIT ( pfnLsaFreeReturnBuffer, pluidLogonSessions ) ;
for(ULONG u = 0L;
u < ulLogonSessionCount && dwRet == ERROR_SUCCESS;
u++)
{
PSECURITY_LOGON_SESSION_DATA pSessionData = NULL;
dwRet = pfnGetLogonSessionData(
&pluidLogonSessions[u],
&pSessionData);
if(dwRet == ERROR_SUCCESS &&
pSessionData)
{
//
// smart session data
//
ON_BLOCK_EXIT ( pfnLsaFreeReturnBuffer, pSessionData ) ;
// See if we have the session already...
if(!IsSessionMapped(pSessionData->LogonId))
{
// and if not, add it to the map.
CSession sesNew(pSessionData->LogonId);
CUser cuTmp(pSessionData->Sid);
CHString chstrTmp;
if(cuTmp.IsValid())
{
cuTmp.GetSidString(chstrTmp);
m_usr2ses.insert(
USER_SESSION_MAP::value_type(
cuTmp,
sesNew));
}
else
{
LUID luidTmp = sesNew.GetLUID();
LogMessage3(
L"GetLogonSessionData returned logon data for session "
L"luid %d (highpart) %u (lowpart) containing an invalid SID",
luidTmp.HighPart,
luidTmp.LowPart);
}
}
// While we are here, add in various
// session properties lsa has been kind
// enough to provide for us.
USER_SESSION_ITERATOR usiter;
usiter = m_usr2ses.begin();
bool fFound = false;
while(usiter != m_usr2ses.end() &&
!fFound)
{
LUID luidTmp = pSessionData->LogonId;
__int64 i64Tmp = *((__int64*)(&luidTmp));
if((usiter->second).GetLUIDint64() ==
i64Tmp)
{
fFound = true;
}
else
{
usiter++;
}
}
if(fFound)
{
WCHAR wstrTmp[_MAX_PATH] = { '\0' };
if((pSessionData->AuthenticationPackage).Length < (_MAX_PATH - 1))
{
wcsncpy(
wstrTmp,
(pSessionData->AuthenticationPackage).Buffer,
(pSessionData->AuthenticationPackage).Length);
(usiter->second).m_chstrAuthPkg = wstrTmp;
}
(usiter->second).m_ulLogonType =
pSessionData->LogonType;
(usiter->second).i64LogonTime =
*((__int64*)(&(pSessionData->LogonTime)));
}
}
}
}
}
}
else
{
LogErrorMessage(L"Failed to load library SECUR32.dll");
}
return dwRet;
}
//*****************************************************************************
// CSession functions
//*****************************************************************************
CSession::CSession(
const LUID& luidSessionID)
{
m_luid.LowPart = luidSessionID.LowPart;
m_luid.HighPart = luidSessionID.HighPart;
m_ulLogonType = 0;
i64LogonTime = 0;
}
CSession::CSession(
const CSession& ses)
{
m_luid.LowPart = ses.m_luid.LowPart;
m_luid.HighPart = ses.m_luid.HighPart;
m_chstrAuthPkg = ses.m_chstrAuthPkg;
m_ulLogonType = ses.m_ulLogonType;
i64LogonTime = ses.i64LogonTime;
m_vecProcesses.clear();
for(long lPos = 0;
lPos < ses.m_vecProcesses.size();
lPos++)
{
m_vecProcesses.push_back(
ses.m_vecProcesses[lPos]);
}
}
LUID CSession::GetLUID() const
{
return m_luid;
}
__int64 CSession::GetLUIDint64() const
{
__int64 i64LuidSes = *((__int64*)(&m_luid));
return i64LuidSes;
}
CHString CSession::GetAuthenticationPkg() const
{
return m_chstrAuthPkg;
}
ULONG CSession::GetLogonType() const
{
return m_ulLogonType;
}
__int64 CSession::GetLogonTime() const
{
return i64LogonTime;
}
// Functions to support enumeration of
// processes associated with this session.
// Returns a newly allocated CProcess* that
// the caller must free.
CProcess* CSession::GetFirstProcess(
PROCESS_ITERATOR& pos)
{
CProcess* procRet = NULL;
if(!m_vecProcesses.empty())
{
pos = m_vecProcesses.begin();
procRet = new CProcess(*pos);
}
return procRet;
}
// Returns a newly allocated CProcess* that
// the caller must free.
CProcess* CSession::GetNextProcess(
PROCESS_ITERATOR& pos)
{
CProcess* procRet = NULL;
if(pos >= m_vecProcesses.begin() &&
pos < m_vecProcesses.end())
{
pos++;
if(pos != m_vecProcesses.end())
{
procRet = new CProcess(*pos);
}
}
return procRet;
}
void CSession::Copy(
CSession& sesCopy) const
{
sesCopy.m_luid.LowPart = m_luid.LowPart;
sesCopy.m_luid.HighPart = m_luid.HighPart;
sesCopy.m_chstrAuthPkg = m_chstrAuthPkg;
sesCopy.m_ulLogonType = m_ulLogonType;
sesCopy.i64LogonTime = i64LogonTime;
sesCopy.m_vecProcesses.clear();
for(long lPos = 0;
lPos < m_vecProcesses.size();
lPos++)
{
sesCopy.m_vecProcesses.push_back(
m_vecProcesses[lPos]);
}
}
// This function impersonates the
// explorer process in the session's
// process array, if it is present.
// (If it isn't, impersonates the
// first process in the process array.)
// Returns the handle of token of the
// thread we started from for easy
// reversion, orINVALID_HANDLE_VALUE if
// we couldn't impersonate. The caller
// must close that handle.
HANDLE CSession::Impersonate()
{
HANDLE hCurToken = INVALID_HANDLE_VALUE;
// Find the explorer process...
DWORD dwImpProcPID = GetImpProcPID();
if(dwImpProcPID != -1L)
{
//
// smart CloseHandle
//
ScopeGuard SmartCloseHandleFnc = MakeGuard ( CloseHandle, hCurToken ) ;
bool fOK = false;
if(::OpenThreadToken(
::GetCurrentThread(),
TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE ,
TRUE,
&hCurToken))
{
SmartCloseHandle hProcess;
hProcess = ::OpenProcess(
PROCESS_QUERY_INFORMATION,
FALSE,
dwImpProcPID);
if(hProcess)
{
// now open its token...
SmartCloseHandle hExplorerToken;
if(::OpenProcessToken(
hProcess,
TOKEN_READ | TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE,
&hExplorerToken))
{
CProcessToken cpt ( hExplorerToken );
if ( cpt.IsValidToken () )
{
TOKEN_TYPE type;
if ( cpt.GetTokenType ( type ) )
{
if ( TokenPrimary == type )
{
CToken ct;
if ( ct.Duplicate ( cpt, FALSE ) )
{
// Set the thread token...
if(::SetThreadToken(NULL, ct.GetTokenHandle ()))
{
fOK = true;
}
}
}
else
{
// Set the thread token...
if(::SetThreadToken(NULL, cpt.GetTokenHandle ()))
{
fOK = true;
}
}
}
}
}
}
}
SmartCloseHandleFnc.Dismiss () ;
if (!fOK)
{
if(hCurToken != INVALID_HANDLE_VALUE)
{
::CloseHandle(hCurToken);
hCurToken = INVALID_HANDLE_VALUE;
}
}
}
return hCurToken;
}
DWORD CSession::GetImpProcPID()
{
DWORD dwRet = -1L;
if(!m_vecProcesses.empty())
{
bool fFoundExplorerExe = false;
for(long m = 0;
m < m_vecProcesses.size() &&
!fFoundExplorerExe;)
{
if(m_vecProcesses[m].GetImageName().CompareNoCase(
L"explorer.exe") == 0)
{
fFoundExplorerExe = true;
break;
}
else
{
m++;
}
}
if(!fFoundExplorerExe)
{
m = 0;
}
dwRet = m_vecProcesses[m].GetPID();
}
return dwRet;
}
bool CSession::IsSessionIDValid(
LPCWSTR wstrSessionID)
{
bool fRet = true;
if(wstrSessionID != NULL &&
*wstrSessionID != L'\0')
{
for(const WCHAR* pwc = wstrSessionID;
*pwc != NULL && fRet;
pwc++)
{
fRet = iswdigit(*pwc);
}
}
else
{
fRet = false;
}
return fRet;
}
//*****************************************************************************
// CProcess functions
//*****************************************************************************
CProcess::CProcess()
: m_dwPID(0)
{
}
CProcess::CProcess(
DWORD dwPID,
LPCWSTR wstrImageName)
: m_dwPID(dwPID)
{
m_chstrImageName = wstrImageName;
}
CProcess::CProcess(
const CProcess& process)
{
m_dwPID = process.m_dwPID;
m_chstrImageName = process.m_chstrImageName;
}
CProcess::~CProcess()
{
}
DWORD CProcess::GetPID() const
{
return m_dwPID;
}
CHString CProcess::GetImageName() const
{
return m_chstrImageName;
}
void CProcess::Copy(
CProcess& out) const
{
out.m_dwPID = m_dwPID;
out.m_chstrImageName = m_chstrImageName;
}
//*****************************************************************************
// CUser functions
//*****************************************************************************
CUser::CUser(
PSID pSid)
: m_sidUser(NULL),
m_fValid(false)
{
if(::IsValidSid(pSid))
{
DWORD dwSize = ::GetLengthSid(pSid);
m_sidUser = NULL;
m_sidUser = malloc(dwSize);
if(m_sidUser == NULL)
{
throw CHeap_Exception(
CHeap_Exception::E_ALLOCATION_ERROR);
}
else
{
::CopySid(
dwSize,
m_sidUser,
pSid);
m_fValid = true;
}
}
}
CUser::CUser(
const CUser& user)
{
DWORD dwSize = ::GetLengthSid(user.m_sidUser);
m_sidUser = malloc(dwSize);
if(m_sidUser == NULL)
{
throw CHeap_Exception(
CHeap_Exception::E_ALLOCATION_ERROR);
}
::CopySid(
dwSize,
m_sidUser,
user.m_sidUser);
m_fValid = user.m_fValid;
}
CUser::~CUser()
{
if(m_sidUser)
{
free(m_sidUser);
m_sidUser = NULL;
}
}
bool CUser::IsValid()
{
return m_fValid;
}
void CUser::Copy(
CUser& out) const
{
if(out.m_sidUser)
{
free(out.m_sidUser);
out.m_sidUser = NULL;
}
DWORD dwSize = ::GetLengthSid(m_sidUser);
out.m_sidUser = malloc(dwSize);
if(out.m_sidUser == NULL)
{
throw CHeap_Exception(
CHeap_Exception::E_ALLOCATION_ERROR);
}
::CopySid(
dwSize,
out.m_sidUser,
m_sidUser);
out.m_fValid = m_fValid;
}
// Implementation lifted from sid.cpp.
void CUser::GetSidString(CHString& str) const
{
ASSERT_BREAK(m_fValid);
if(m_fValid)
{
// Initialize m_strSid - human readable form of our SID
SID_IDENTIFIER_AUTHORITY *psia = NULL;
psia = ::GetSidIdentifierAuthority( m_sidUser );
// We assume that only last byte is used (authorities between 0 and 15).
// Correct this if needed.
ASSERT_BREAK( psia->Value[0] == psia->Value[1] ==
psia->Value[2] == psia->Value[3] ==
psia->Value[4] == 0 );
DWORD dwTopAuthority = psia->Value[5];
str.Format( L"S-1-%u", dwTopAuthority );
CHString strSubAuthority;
int iSubAuthorityCount = *( GetSidSubAuthorityCount( m_sidUser ) );
for ( int i = 0; i < iSubAuthorityCount; i++ ) {
DWORD dwSubAuthority = *( GetSidSubAuthority( m_sidUser, i ) );
strSubAuthority.Format( L"%u", dwSubAuthority );
str += _T("-") + strSubAuthority;
}
}
} | 26.611371 | 99 | 0.48047 | npocmaka |
c9d45367809e61a9700e32cda325817e9055661f | 1,590 | cpp | C++ | src/RNN.cpp | Lehdari/EvolutionSimulator | 432da1c1f5bae389b6e785d1c7e47eca8dca9698 | [
"MIT"
] | 1 | 2018-03-22T07:52:03.000Z | 2018-03-22T07:52:03.000Z | src/RNN.cpp | Lehdari/EvolutionSimulator | 432da1c1f5bae389b6e785d1c7e47eca8dca9698 | [
"MIT"
] | null | null | null | src/RNN.cpp | Lehdari/EvolutionSimulator | 432da1c1f5bae389b6e785d1c7e47eca8dca9698 | [
"MIT"
] | null | null | null | #include "RNN.hpp"
#include <cstdio>
RNN::RNN(uint64_t nInputs, uint64_t nOutputs, const RNN::Genome& genome) :
_nInputs(nInputs), _nOutputs(nOutputs)
{
for (auto i=0llu; i<_nInputs; ++i)
_neurons.emplace_back();
for (auto i=0llu; i<_nOutputs; ++i)
_neurons.emplace_back();
for (auto& cg : genome) {
uint64_t maxId = std::max(cg.from, cg.to);
if (maxId >= _neurons.size())
_neurons.resize(maxId+1);
_neurons[cg.to].conns.emplace_back(cg.from, cg.weight);
}
}
void RNN::setInput(uint64_t inputId, float val)
{
if (inputId > _nInputs)
return;
_neurons[inputId].i = val;
}
float RNN::getOutput(uint64_t outputId) const
{
if (outputId > _nOutputs)
return 0.0f;
return _neurons[_nInputs+outputId].a;
}
uint64_t RNN::getNumInputs(void) const
{
return _nInputs;
}
uint64_t RNN::getNumOutputs(void) const
{
return _nOutputs;
}
const std::vector<RNN::Neuron>& RNN::getNeurons(void) const
{
return _neurons;
}
void RNN::tick(void)
{
for (auto& n : _neurons) {
for (auto& c : n.conns)
n.i += _neurons[c.from].a*c.w;
}
for (auto& n : _neurons) {
n.a = activationLogistic(n.i);
n.i = 0.0f;
}
}
void RNN::print(bool printConns) const
{
for (auto i=0u; i<_neurons.size(); ++i) {
auto& n = _neurons[i];
printf("Neuron %u\ti: %0.3f\ta: %0.3f\n", i, n.i, n.a);
if (printConns)
for (auto& c : n.conns)
printf(" Conn from neuron %llu\tw: %0.3f\n", c.from, c.w);
}
}
| 20.649351 | 75 | 0.579874 | Lehdari |
c9d46ea4afcdf5148a8dedae4db1fc7153030da7 | 17,019 | cxx | C++ | athena/Simulation/ISF/ISF_FastCaloSim/ISF_FastCaloSimParametrization/src/CaloGeometryLookup.cxx | atif4461/FCS-GPU | 181865f55d299287873f99c777aad2ef9404e961 | [
"Apache-2.0"
] | 2 | 2022-01-25T20:32:53.000Z | 2022-02-16T01:15:47.000Z | athena/Simulation/ISF/ISF_FastCaloSim/ISF_FastCaloSimParametrization/src/CaloGeometryLookup.cxx | atif4461/FCS-GPU | 181865f55d299287873f99c777aad2ef9404e961 | [
"Apache-2.0"
] | null | null | null | athena/Simulation/ISF/ISF_FastCaloSim/ISF_FastCaloSimParametrization/src/CaloGeometryLookup.cxx | atif4461/FCS-GPU | 181865f55d299287873f99c777aad2ef9404e961 | [
"Apache-2.0"
] | 1 | 2022-02-11T15:54:10.000Z | 2022-02-11T15:54:10.000Z | /*
Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
*/
#include "ISF_FastCaloSimParametrization/CaloGeometry.h"
#include "ISF_FastCaloSimParametrization/CaloGeometryLookup.h"
#include <TTree.h>
#include <TVector2.h>
#include <TCanvas.h>
#include <TH2D.h>
#include <TGraphErrors.h>
#include <TVector3.h>
#include <TLegend.h>
#include "CaloDetDescr/CaloDetDescrElement.h"
//#include "ISF_FastCaloSimParametrization/CaloDetDescrElement.h"
#include "CaloGeoHelpers/CaloSampling.h"
#include "ISF_FastCaloSimEvent/FastCaloSim_CaloCell_ID.h"
//#include "TMVA/Tools.h"
//#include "TMVA/Factory.h"
using namespace std;
CaloGeometryLookup::CaloGeometryLookup(int ind):m_xy_grid_adjustment_factor(0.75),m_index(ind)
{
m_mineta=+10000;
m_maxeta=-10000;
m_minphi=+10000;
m_maxphi=-10000;
m_mineta_raw=+10000;
m_maxeta_raw=-10000;
m_minphi_raw=+10000;
m_maxphi_raw=-10000;
m_mindeta=10000;
m_mindphi=10000;
m_mineta_correction=+10000;
m_maxeta_correction=-10000;
m_minphi_correction=+10000;
m_maxphi_correction=-10000;
m_cell_grid_eta=0.;
m_cell_grid_phi=0.;
m_deta_double =0.;
m_dphi_double =0.;
}
CaloGeometryLookup::~CaloGeometryLookup()
{
}
bool CaloGeometryLookup::has_overlap(CaloGeometryLookup* ref)
{
if(m_cells.size()==0) return false;
for(t_cellmap::iterator ic=m_cells.begin();ic!=m_cells.end();++ic) {
const CaloDetDescrElement* cell=ic->second;
if(ref->IsCompatible(cell)) return true;
}
return false;
}
void CaloGeometryLookup::merge_into_ref(CaloGeometryLookup* ref)
{
for(t_cellmap::iterator ic=m_cells.begin();ic!=m_cells.end();++ic) {
const CaloDetDescrElement* cell=ic->second;
ref->add(cell);
}
}
bool CaloGeometryLookup::IsCompatible(const CaloDetDescrElement* cell)
{
if(m_cells.size()==0) return true;
t_cellmap::iterator ic=m_cells.begin();
const CaloDetDescrElement* refcell=ic->second;
int sampling=refcell->getSampling();
if(cell->getSampling()!=sampling) return false;
if(cell->eta_raw()*refcell->eta_raw()<0) return false;
if(sampling<21) { // keep only cells reasonable close in eta to each other
if(TMath::Abs(cell->deta()-refcell->deta())>0.001) return false;
if(TMath::Abs(cell->dphi()-refcell->dphi())>0.001) return false;
if( cell->eta()<mineta()-2.1*cell->deta() ) return false;
if( cell->eta()>maxeta()+2.1*cell->deta() ) return false;
double delta_eta=(cell->eta_raw()-refcell->eta_raw())/cell->deta();
double delta_phi=(cell->phi_raw()-refcell->phi_raw())/cell->dphi();
if(TMath::Abs(delta_eta-TMath::Nint(delta_eta)) > 0.01) return false;
if(TMath::Abs(delta_phi-TMath::Nint(delta_phi)) > 0.01) return false;
/*
cout<<"Compatible: s="<<cell->getSampling()<<"~"<<refcell->getSampling()<<"; ";
cout<<"eta="<<cell->eta_raw()<<","<<refcell->eta_raw()<<"; ";
cout<<"phi="<<cell->phi_raw()<<","<<refcell->phi_raw()<<"; ";
cout<<"deta="<<cell->deta()<<"~"<<refcell->deta()<<"; ";
cout<<"dphi="<<cell->dphi()<<"~"<<refcell->dphi()<<";";
cout<<"mineta="<<mineta()<<", maxeta="<<maxeta()<<"; ";
cout<<endl;
*/
} else {
//FCal is not sufficiently regular to use submaps with regular mapping
return true;
/*
if(TMath::Abs(cell->dx()-refcell->dx())>0.001) return false;
if(TMath::Abs(cell->dy()-refcell->dy())>0.001) return false;
if( cell->x()<minx()-20*cell->dx() ) return false;
if( cell->x()>maxx()+20*cell->dx() ) return false;
if( cell->y()<miny()-20*cell->dy() ) return false;
if( cell->y()>maxy()+20*cell->dy() ) return false;
double delta_x=(cell->x_raw()-refcell->x_raw())/cell->dx();
double delta_y=(cell->y_raw()-refcell->y_raw())/cell->dy();
if(TMath::Abs(delta_x-TMath::Nint(delta_x)) > 0.01) return false;
if(TMath::Abs(delta_y-TMath::Nint(delta_y)) > 0.01) return false;
*/
}
return true;
}
void CaloGeometryLookup::add(const CaloDetDescrElement* cell)
{
if(cell->getSampling()<21) {
m_deta.add(cell->deta());
m_dphi.add(cell->dphi());
m_mindeta=TMath::Min(cell->deta(),m_mindeta);
m_mindphi=TMath::Min(cell->dphi(),m_mindphi);
m_eta_correction.add(cell->eta_raw()-cell->eta());
m_phi_correction.add(cell->phi_raw()-cell->phi());
m_mineta_correction=TMath::Min(cell->eta_raw()-cell->eta() , m_mineta_correction);
m_maxeta_correction=TMath::Max(cell->eta_raw()-cell->eta() , m_maxeta_correction);
m_minphi_correction=TMath::Min(cell->phi_raw()-cell->phi() , m_minphi_correction);
m_maxphi_correction=TMath::Max(cell->phi_raw()-cell->phi() , m_maxphi_correction);
m_mineta=TMath::Min(cell->eta()-cell->deta()/2,m_mineta);
m_maxeta=TMath::Max(cell->eta()+cell->deta()/2,m_maxeta);
m_minphi=TMath::Min(cell->phi()-cell->dphi()/2,m_minphi);
m_maxphi=TMath::Max(cell->phi()+cell->dphi()/2,m_maxphi);
m_mineta_raw=TMath::Min(cell->eta_raw()-cell->deta()/2,m_mineta_raw);
m_maxeta_raw=TMath::Max(cell->eta_raw()+cell->deta()/2,m_maxeta_raw);
m_minphi_raw=TMath::Min(cell->phi_raw()-cell->dphi()/2,m_minphi_raw);
m_maxphi_raw=TMath::Max(cell->phi_raw()+cell->dphi()/2,m_maxphi_raw);
} else {
m_deta.add(cell->dx());
m_dphi.add(cell->dy());
m_mindeta=TMath::Min(cell->dx(),m_mindeta);
m_mindphi=TMath::Min(cell->dy(),m_mindphi);
m_eta_correction.add(cell->x_raw()-cell->x());
m_phi_correction.add(cell->y_raw()-cell->y());
m_mineta_correction=TMath::Min(cell->x_raw()-cell->x() , m_mineta_correction);
m_maxeta_correction=TMath::Max(cell->x_raw()-cell->x() , m_maxeta_correction);
m_minphi_correction=TMath::Min(cell->y_raw()-cell->y() , m_minphi_correction);
m_maxphi_correction=TMath::Max(cell->y_raw()-cell->y() , m_maxphi_correction);
m_mineta=TMath::Min(cell->x()-cell->dx()/2,m_mineta);
m_maxeta=TMath::Max(cell->x()+cell->dx()/2,m_maxeta);
m_minphi=TMath::Min(cell->y()-cell->dy()/2,m_minphi);
m_maxphi=TMath::Max(cell->y()+cell->dy()/2,m_maxphi);
m_mineta_raw=TMath::Min(cell->x_raw()-cell->dx()/2,m_mineta_raw);
m_maxeta_raw=TMath::Max(cell->x_raw()+cell->dx()/2,m_maxeta_raw);
m_minphi_raw=TMath::Min(cell->y_raw()-cell->dy()/2,m_minphi_raw);
m_maxphi_raw=TMath::Max(cell->y_raw()+cell->dy()/2,m_maxphi_raw);
}
m_cells[cell->identify()]=cell;
}
bool CaloGeometryLookup::index_range_adjust(int& ieta,int& iphi)
{
while(iphi<0) {iphi+=m_cell_grid_phi;};
while(iphi>=m_cell_grid_phi) {iphi-=m_cell_grid_phi;};
if(ieta<0) {
ieta=0;
return false;
}
if(ieta>=m_cell_grid_eta) {
ieta=m_cell_grid_eta-1;
return false;
}
return true;
}
void CaloGeometryLookup::post_process()
{
if(size()==0) return;
t_cellmap::iterator ic=m_cells.begin();
const CaloDetDescrElement* refcell=ic->second;
int sampling=refcell->getSampling();
if(sampling<21) {
double rneta=neta_double()-neta();
double rnphi=nphi_double()-nphi();
if(TMath::Abs(rneta)>0.05 || TMath::Abs(rnphi)>0.05) {
cout<<"ERROR: can't map cells into a regular grid for sampling "<<sampling<<", map index "<<index()<<endl;
return;
}
m_cell_grid_eta=neta();
m_cell_grid_phi=nphi();
m_deta_double=deta();
m_dphi_double=dphi();
} else {
//double rnx=nx_double()-nx();
//double rny=ny_double()-ny();
//if(TMath::Abs(rnx)>0.05 || TMath::Abs(rny)>0.05) {
// cout<<"Grid: Sampling "<<sampling<<"_"<<index()<<": mapping cells into a regular grid, although cells don't fit well"<<endl;
//}
m_cell_grid_eta=TMath::Nint(TMath::Ceil(nx_double()/m_xy_grid_adjustment_factor));
m_cell_grid_phi=TMath::Nint(TMath::Ceil(ny_double()/m_xy_grid_adjustment_factor));
m_deta_double=mindx()*m_xy_grid_adjustment_factor;
m_dphi_double=mindy()*m_xy_grid_adjustment_factor;
}
m_cell_grid.resize(m_cell_grid_eta);
for(int ieta=0;ieta<m_cell_grid_eta;++ieta) {
m_cell_grid[ieta].resize(m_cell_grid_phi,0);
}
for(ic=m_cells.begin();ic!=m_cells.end();++ic) {
refcell=ic->second;
int ieta,iphi;
if(sampling<21) {
ieta=raw_eta_position_to_index(refcell->eta_raw());
iphi=raw_phi_position_to_index(refcell->phi_raw());
} else {
ieta=raw_eta_position_to_index(refcell->x_raw());
iphi=raw_phi_position_to_index(refcell->y_raw());
}
if(index_range_adjust(ieta,iphi)) {
if(m_cell_grid[ieta][iphi]) {
cout<<"Grid: Sampling "<<sampling<<"_"<<index()<<": Already cell found at pos ("<<ieta<<","<<iphi<<"): id="
<<m_cell_grid[ieta][iphi]->identify()<<"->"<<refcell->identify()<<endl;
cout<<" x="<<m_cells[m_cell_grid[ieta][iphi]->identify()]->x_raw()<<" -> "<<refcell->x_raw();
cout<<" , y="<<m_cells[m_cell_grid[ieta][iphi]->identify()]->y_raw()<<" -> "<<refcell->y_raw();
cout<<" mindx="<<m_deta_double<<" mindy="<<m_dphi_double<<endl;
cout<<endl;
}
m_cell_grid[ieta][iphi]=refcell;
} else {
cout<<"Grid: Sampling "<<sampling<<"_"<<index()<<": Cell at pos ("<<ieta<<","<<iphi<<"): id="
<<refcell->identify()<<" outside eta range"<<endl;
}
}
int ncells=0;
int nempty=0;
for(int ieta=0;ieta<m_cell_grid_eta;++ieta) {
for(int iphi=0;iphi<m_cell_grid_phi;++iphi) {
if(!m_cell_grid[ieta][iphi]) {
++nempty;
//cout<<"Sampling "<<sampling<<"_"<<index()<<": No cell at pos ("<<ieta<<","<<iphi<<")"<<endl;
} else {
++ncells;
}
}
}
// cout<<"Grid: Sampling "<<sampling<<"_"<<index()<<": "<<ncells<<"/"<<size()<<" cells filled, "<<nempty<<" empty grid positions deta="<<m_deta_double<<" dphi="<<m_dphi_double<<endl;
}
float CaloGeometryLookup::calculate_distance_eta_phi(const CaloDetDescrElement* DDE,float eta,float phi,float& dist_eta0,float& dist_phi0)
{
dist_eta0=(eta - DDE->eta())/m_deta_double;
dist_phi0=(TVector2::Phi_mpi_pi(phi - DDE->phi()))/m_dphi_double;
float abs_dist_eta0=TMath::Abs(dist_eta0);
float abs_dist_phi0=TMath::Abs(dist_phi0);
return TMath::Max(abs_dist_eta0,abs_dist_phi0)-0.5;
}
const CaloDetDescrElement* CaloGeometryLookup::getDDE(float eta,float phi,float* distance,int* steps)
{
float dist;
const CaloDetDescrElement* bestDDE=0;
if(!distance) distance=&dist;
*distance=+10000000;
int intsteps=0;
if(!steps) steps=&intsteps;
float best_eta_corr=m_eta_correction;
float best_phi_corr=m_phi_correction;
float raw_eta=eta+best_eta_corr;
float raw_phi=phi+best_phi_corr;
int ieta=raw_eta_position_to_index(raw_eta);
int iphi=raw_phi_position_to_index(raw_phi);
index_range_adjust(ieta,iphi);
const CaloDetDescrElement* newDDE=m_cell_grid[ieta][iphi];
float bestdist=+10000000;
++(*steps);
int nsearch=0;
while(newDDE && nsearch<3) {
float dist_eta0,dist_phi0;
*distance=calculate_distance_eta_phi(newDDE,eta,phi,dist_eta0,dist_phi0);
bestDDE=newDDE;
bestdist=*distance;
if(CaloGeometry::m_debug || CaloGeometry::m_debug_identify==newDDE->identify()) {
cout<<"CaloGeometryLookup::getDDE, search iteration "<<nsearch<<endl;
cout<<"cell id="<<newDDE->identify()<<" steps "<<*steps<<" steps, eta="<<eta<<" phi="<<phi<<" dist="<<*distance<<" cell_grid_eta="<<cell_grid_eta()<<" cell_grid_phi="<<cell_grid_phi()<<" m_deta_double="<<m_deta_double<<" m_dphi_double="<<m_dphi_double<<" 1st_eta_corr="<<best_eta_corr<<" 1st_phi_corr="<<best_phi_corr<<endl;
cout<<" input sampling="<<newDDE->getSampling()<<" eta="<<newDDE->eta()<<" eta_raw="<<newDDE->eta_raw()<<" deta="<<newDDE->deta()<<" ("<<(newDDE->eta_raw()-newDDE->eta())/newDDE->deta()<<") phi="<<newDDE->phi()<<" phi_raw="<<newDDE->phi_raw()<<" dphi="<<newDDE->dphi()<<" ("<<(newDDE->phi_raw()-newDDE->phi())/newDDE->dphi()<<")"<<endl;
cout<<" ieta="<<ieta<<" iphi="<<iphi<<endl;
cout<<" dist_eta0="<<dist_eta0<<" ,dist_phi0="<<dist_phi0<<endl;
}
if(*distance<0) return newDDE;
//correct ieta and iphi by the observed difference to the hit cell
ieta+=TMath::Nint(dist_eta0);
iphi+=TMath::Nint(dist_phi0);
index_range_adjust(ieta,iphi);
const CaloDetDescrElement* oldDDE=newDDE;
newDDE=m_cell_grid[ieta][iphi];
++(*steps);
++nsearch;
if(oldDDE==newDDE) break;
}
if(CaloGeometry::m_debug && !newDDE) {
cout<<"CaloGeometryLookup::getDDE, direct search ieta="<<ieta<<" iphi="<<iphi<<" is empty"<<endl;
}
float minieta=ieta+TMath::Nint(TMath::Floor(m_mineta_correction/cell_grid_eta()));
float maxieta=ieta+TMath::Nint(TMath::Ceil(m_maxeta_correction/cell_grid_eta()));
float miniphi=iphi+TMath::Nint(TMath::Floor(m_minphi_correction/cell_grid_phi()));
float maxiphi=iphi+TMath::Nint(TMath::Ceil(m_maxphi_correction/cell_grid_phi()));
if(minieta<0) minieta=0;
if(maxieta>=m_cell_grid_eta) maxieta=m_cell_grid_eta-1;
for(int iieta=minieta;iieta<=maxieta;++iieta) {
for(int iiphi=miniphi;iiphi<=maxiphi;++iiphi) {
ieta=iieta;
iphi=iiphi;
index_range_adjust(ieta,iphi);
newDDE=m_cell_grid[ieta][iphi];
++(*steps);
if(newDDE) {
float dist_eta0,dist_phi0;
*distance=calculate_distance_eta_phi(newDDE,eta,phi,dist_eta0,dist_phi0);
if(CaloGeometry::m_debug || CaloGeometry::m_debug_identify==newDDE->identify()) {
cout<<"CaloGeometryLookup::getDDE, windows search! minieta="<<m_mineta_correction/cell_grid_eta()<<" maxieta="<<m_maxeta_correction/cell_grid_eta()<<" miniphi="<<m_minphi_correction/cell_grid_phi()<<" maxiphi="<<m_maxphi_correction/cell_grid_phi()<<endl;
cout<<"cell id="<<newDDE->identify()<<" steps "<<*steps<<" steps, eta="<<eta<<" phi="<<phi<<" dist="<<*distance<<endl;
cout<<" input sampling="<<newDDE->getSampling()<<" eta="<<newDDE->eta()<<" eta_raw="<<newDDE->eta_raw()<<" deta="<<newDDE->deta()<<" ("<<(newDDE->eta_raw()-newDDE->eta())/newDDE->deta()<<") phi="<<newDDE->phi()<<" phi_raw="<<newDDE->phi_raw()<<" dphi="<<newDDE->dphi()<<" ("<<(newDDE->phi_raw()-newDDE->phi())/newDDE->dphi()<<")"<<endl;
cout<<" ieta="<<ieta<<" iphi="<<iphi<<endl;
cout<<" dist_eta0="<<dist_eta0<<" ,dist_phi0="<<dist_phi0<<endl;
}
if(*distance<0) return newDDE;
if(*distance<bestdist) {
bestDDE=newDDE;
bestdist=*distance;
}
} else if(CaloGeometry::m_debug) {
cout<<"CaloGeometryLookup::getDDE, windows search ieta="<<ieta<<" iphi="<<iphi<<" is empty"<<endl;
}
}
}
*distance=bestdist;
return bestDDE;
}
/*
void CaloGeometryLookup::CalculateTransformation()
{
gROOT->cd();
TTree* tmap = new TTree( "mapping" , "mapping" );
float eta,phi,Deta_raw,Dphi_raw;
tmap->Branch("eta", &eta,"eta/F");
tmap->Branch("phi", &phi,"phi/F");
tmap->Branch("Deta_raw", &Deta_raw,"Deta_raw/F");
tmap->Branch("Dphi_raw", &Dphi_raw,"Dphi_raw/F");
if(m_cells.size()==0) return;
int sampling=0;
for(t_cellmap::iterator ic=m_cells.begin();ic!=m_cells.end();++ic) {
CaloGeoDetDescrElement* refcell=ic->second;
sampling=refcell->getSampling();
if(sampling<21) {
eta=refcell->eta();
phi=refcell->phi();
Deta_raw=refcell->eta_raw()-eta;
Dphi_raw=refcell->phi_raw()-phi;
} else {
eta=refcell->x();
phi=refcell->y();
Deta_raw=refcell->x_raw()-eta;
Dphi_raw=refcell->y_raw()-phi;
}
tmap->Fill();
tmap->Fill(); //Fill twice to have all events and training and test tree
}
tmap->Print();
TString outfileName( Form("Mapping%d_%d.root",sampling,m_index) );
TFile* outputFile = new TFile( outfileName, "RECREATE" );
//TFile* outputFile = new TMemFile( outfileName, "RECREATE" );
TMVA::Factory *factory = new TMVA::Factory( Form("Mapping%d_%d.root",sampling,m_index) , outputFile, "!V:!Silent:Color:DrawProgressBar" );
factory->AddVariable( "eta", "calo eta", "1", 'F' );
factory->AddVariable( "phi", "calo phi", "1", 'F' );
factory->AddTarget( "Deta_raw" );
factory->AddTarget( "Dphi_raw" );
factory->AddRegressionTree( tmap );
//factory->PrepareTrainingAndTestTree( "" , Form("nTrain_Regression=%d:nTest_Regression=%d:SplitMode=Random:NormMode=NumEvents:!V",(int)m_cells.size(),(int)m_cells.size()) );
factory->PrepareTrainingAndTestTree( "" , "nTrain_Regression=0:nTest_Regression=0:SplitMode=Alternate:NormMode=NumEvents:!V" );
factory->BookMethod( TMVA::Types::kMLP, "MLP", "!H:!V:VarTransform=Norm:NeuronType=tanh:NCycles=20000:HiddenLayers=N+5:TestRate=6:TrainingMethod=BFGS:Sampling=0.3:SamplingEpoch=0.8:ConvergenceImprove=1e-6:ConvergenceTests=15:!UseRegulator" );
cout<<"=== Start trainging ==="<<endl;
// Train MVAs using the set of training events
factory->TrainAllMethods();
cout<<"=== Start testing ==="<<endl;
// ---- Evaluate all MVAs using the set of test events
factory->TestAllMethods();
cout<<"=== Start evaluation ==="<<endl;
// ----- Evaluate and compare performance of all configured MVAs
factory->EvaluateAllMethods();
outputFile->Close();
delete factory;
delete tmap;
}
*/
| 38.94508 | 347 | 0.660791 | atif4461 |
c9d843e9c2af6209232f2faab470f508eb00895f | 1,091 | cpp | C++ | test/std/utilities/optional/optional.nullopt/nullopt_t.pass.cpp | ontio/libcxx-mirror | 4b4f32ea383deb28911f5618126c6ea6c110b5e4 | [
"Apache-2.0"
] | null | null | null | test/std/utilities/optional/optional.nullopt/nullopt_t.pass.cpp | ontio/libcxx-mirror | 4b4f32ea383deb28911f5618126c6ea6c110b5e4 | [
"Apache-2.0"
] | 1 | 2019-04-21T16:53:33.000Z | 2019-04-21T17:15:25.000Z | test/std/utilities/optional/optional.nullopt/nullopt_t.pass.cpp | ontio/libcxx-mirror | 4b4f32ea383deb28911f5618126c6ea6c110b5e4 | [
"Apache-2.0"
] | 1 | 2020-09-09T07:40:32.000Z | 2020-09-09T07:40:32.000Z | //===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++98, c++03, c++11, c++14
// <optional>
// struct nullopt_t{see below};
// inline constexpr nullopt_t nullopt(unspecified);
// [optional.nullopt]/2:
// Type nullopt_t shall not have a default constructor or an initializer-list
// constructor, and shall not be an aggregate.
#include <optional>
#include <type_traits>
using std::nullopt_t;
using std::nullopt;
constexpr bool test()
{
nullopt_t foo{nullopt};
(void)foo;
return true;
}
int main(int, char**)
{
static_assert(std::is_empty_v<nullopt_t>);
static_assert(!std::is_default_constructible_v<nullopt_t>);
static_assert(std::is_same_v<const nullopt_t, decltype(nullopt)>);
static_assert(test());
return 0;
}
| 25.97619 | 80 | 0.60495 | ontio |
c9d8c29878fb20c2e5978416532d330c3f00f6f3 | 3,982 | cc | C++ | third_party/sfntly/src/cpp/src/sfntly/tag.cc | wenfeifei/miniblink49 | 2ed562ff70130485148d94b0e5f4c343da0c2ba4 | [
"Apache-2.0"
] | 5,964 | 2016-09-27T03:46:29.000Z | 2022-03-31T16:25:27.000Z | third_party/sfntly/src/cpp/src/sfntly/tag.cc | w4454962/miniblink49 | b294b6eacb3333659bf7b94d670d96edeeba14c0 | [
"Apache-2.0"
] | 459 | 2016-09-29T00:51:38.000Z | 2022-03-07T14:37:46.000Z | third_party/sfntly/src/cpp/src/sfntly/tag.cc | w4454962/miniblink49 | b294b6eacb3333659bf7b94d670d96edeeba14c0 | [
"Apache-2.0"
] | 1,006 | 2016-09-27T05:17:27.000Z | 2022-03-30T02:46:51.000Z | /*
* Copyright 2011 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "sfntly/tag.h"
#include "sfntly/port/endian.h"
// Use a macro instead of GenerateTag() because gcc 4.4.3 creates static
// initializers in that case.
#define TAG(a, b, c, d) ((a << 24) | (b << 16) | (c << 8) | d);
namespace sfntly {
const int32_t Tag::ttcf = TAG('t', 't', 'c', 'f');
const int32_t Tag::cmap = TAG('c', 'm', 'a', 'p');
const int32_t Tag::head = TAG('h', 'e', 'a', 'd');
const int32_t Tag::hhea = TAG('h', 'h', 'e', 'a');
const int32_t Tag::hmtx = TAG('h', 'm', 't', 'x');
const int32_t Tag::maxp = TAG('m', 'a', 'x', 'p');
const int32_t Tag::name = TAG('n', 'a', 'm', 'e');
const int32_t Tag::OS_2 = TAG('O', 'S', '/', '2');
const int32_t Tag::post = TAG('p', 'o', 's', 't');
const int32_t Tag::cvt = TAG('c', 'v', 't', ' ');
const int32_t Tag::fpgm = TAG('f', 'p', 'g', 'm');
const int32_t Tag::glyf = TAG('g', 'l', 'y', 'f');
const int32_t Tag::loca = TAG('l', 'o', 'c', 'a');
const int32_t Tag::prep = TAG('p', 'r', 'e', 'p');
const int32_t Tag::CFF = TAG('C', 'F', 'F', ' ');
const int32_t Tag::VORG = TAG('V', 'O', 'R', 'G');
const int32_t Tag::EBDT = TAG('E', 'B', 'D', 'T');
const int32_t Tag::EBLC = TAG('E', 'B', 'L', 'C');
const int32_t Tag::EBSC = TAG('E', 'B', 'S', 'C');
const int32_t Tag::BASE = TAG('B', 'A', 'S', 'E');
const int32_t Tag::GDEF = TAG('G', 'D', 'E', 'F');
const int32_t Tag::GPOS = TAG('G', 'P', 'O', 'S');
const int32_t Tag::GSUB = TAG('G', 'S', 'U', 'B');
const int32_t Tag::JSTF = TAG('J', 'S', 'T', 'F');
const int32_t Tag::DSIG = TAG('D', 'S', 'I', 'G');
const int32_t Tag::gasp = TAG('g', 'a', 's', 'p');
const int32_t Tag::hdmx = TAG('h', 'd', 'm', 'x');
const int32_t Tag::kern = TAG('k', 'e', 'r', 'n');
const int32_t Tag::LTSH = TAG('L', 'T', 'S', 'H');
const int32_t Tag::PCLT = TAG('P', 'C', 'L', 'T');
const int32_t Tag::VDMX = TAG('V', 'D', 'M', 'X');
const int32_t Tag::vhea = TAG('v', 'h', 'e', 'a');
const int32_t Tag::vmtx = TAG('v', 'm', 't', 'x');
const int32_t Tag::bsln = TAG('b', 's', 'l', 'n');
const int32_t Tag::feat = TAG('f', 'e', 'a', 't');
const int32_t Tag::lcar = TAG('l', 'c', 'a', 'r');
const int32_t Tag::morx = TAG('m', 'o', 'r', 'x');
const int32_t Tag::opbd = TAG('o', 'p', 'b', 'd');
const int32_t Tag::prop = TAG('p', 'r', 'o', 'p');
const int32_t Tag::Feat = TAG('F', 'e', 'a', 't');
const int32_t Tag::Glat = TAG('G', 'l', 'a', 't');
const int32_t Tag::Gloc = TAG('G', 'l', 'o', 'c');
const int32_t Tag::Sile = TAG('S', 'i', 'l', 'e');
const int32_t Tag::Silf = TAG('S', 'i', 'l', 'f');
const int32_t Tag::bhed = TAG('b', 'h', 'e', 'd');
const int32_t Tag::bdat = TAG('b', 'd', 'a', 't');
const int32_t Tag::bloc = TAG('b', 'l', 'o', 'c');
const int32_t CFF_TABLE_ORDERING[] = {
Tag::head,
Tag::hhea,
Tag::maxp,
Tag::OS_2,
Tag::name,
Tag::cmap,
Tag::post,
Tag::CFF };
const size_t CFF_TABLE_ORDERING_SIZE =
sizeof(CFF_TABLE_ORDERING) / sizeof(int32_t);
const int32_t TRUE_TYPE_TABLE_ORDERING[] = {
Tag::head,
Tag::hhea,
Tag::maxp,
Tag::OS_2,
Tag::hmtx,
Tag::LTSH,
Tag::VDMX,
Tag::hdmx,
Tag::cmap,
Tag::fpgm,
Tag::prep,
Tag::cvt,
Tag::loca,
Tag::glyf,
Tag::kern,
Tag::name,
Tag::post,
Tag::gasp,
Tag::PCLT,
Tag::DSIG };
const size_t TRUE_TYPE_TABLE_ORDERING_SIZE =
sizeof(TRUE_TYPE_TABLE_ORDERING) / sizeof(int32_t);
} // namespace sfntly
| 35.873874 | 75 | 0.566549 | wenfeifei |
c9d9649a41931432c8737a9bf9cdd88977d0893d | 8,608 | cpp | C++ | test/scenegraph/test_visualization3d.cpp | UCCS-Social-Robotics/libalmath | 608475eced68452eb19ef09c46e1916ac597ed88 | [
"BSD-3-Clause"
] | 4 | 2016-03-14T20:34:05.000Z | 2021-02-14T05:53:00.000Z | test/scenegraph/test_visualization3d.cpp | UCCS-Social-Robotics/libalmath | 608475eced68452eb19ef09c46e1916ac597ed88 | [
"BSD-3-Clause"
] | 1 | 2021-02-14T05:52:04.000Z | 2022-03-16T11:18:20.000Z | test/scenegraph/test_visualization3d.cpp | UCCS-Social-Robotics/libalmath | 608475eced68452eb19ef09c46e1916ac597ed88 | [
"BSD-3-Clause"
] | 9 | 2017-07-11T16:01:27.000Z | 2022-02-13T20:41:05.000Z | /*
* Copyright 2015 Aldebaran. All rights reserved.
*
*/
#include <almath/scenegraph/mesh.h>
#include <almath/scenegraph/scenebuilder.h>
#include <almath/scenegraph/meshfactory.h>
#include <almath/scenegraph/colladascenebuilder.h>
#include <almath/geometrics/shapes3d.h>
#include <gtest/gtest.h>
#include <almath/types/altransform.h>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/scoped_ptr.hpp>
using namespace AL;
boost::filesystem::path mktmpdir(const std::string &prefix) {
using namespace boost::filesystem;
path p = temp_directory_path() / unique_path(prefix + "%%%%-%%%%-%%%%-%%%%");
create_directory(p);
return p;
}
TEST(Mesh, init) {
Mesh m;
ASSERT_EQ(0u, m.polygonsNb());
ASSERT_EQ(0u, m.positionsNb());
ASSERT_EQ(0u, m.normalsNb());
ASSERT_EQ(0u, m.texCoordsNb());
}
TEST(Mesh, double_begin) {
Mesh m;
m.begin(Mesh::POLYGON);
// double begin
EXPECT_ANY_THROW(m.begin(Mesh::POLYGON));
}
TEST(Mesh, no_begin) {
Mesh m;
EXPECT_ANY_THROW(m.vertex(0.f, 0.f, 0.f));
ASSERT_EQ(0u, m.positionsNb());
EXPECT_ANY_THROW(m.end());
}
TEST(Mesh, no_normal) {
Mesh m;
m.begin(Mesh::POLYGON);
EXPECT_ANY_THROW(m.vertex(0.f, 0.f, 0.f));
m.end();
}
TEST(Mesh, no_texcoord_ok) {
Mesh m;
EXPECT_EQ(2u, m.verticesStride());
m.normal(0.f, 0.f, 1.f);
m.begin(Mesh::POLYGON);
m.vertex(0.f, 0.f, 0.f);
m.end();
}
TEST(Mesh, no_texcoord_ko) {
Mesh m(true);
EXPECT_EQ(3u, m.verticesStride());
m.normal(0.f, 0.f, 1.f);
m.begin(Mesh::POLYGON);
EXPECT_ANY_THROW(m.vertex(0.f, 0.f, 0.f));
m.end();
}
TEST(Mesh, accessors) {
Mesh m;
m.position(0.f, 1.f, 2.f);
m.position(3.f, 4.f, 5.f);
EXPECT_EQ(0.f, *m.positionPtrAt(0));
EXPECT_EQ(1.f, *(m.positionPtrAt(0) + 1));
EXPECT_EQ(2.f, *(m.positionPtrAt(0) + 2));
EXPECT_EQ(3.f, *m.positionPtrAt(1));
EXPECT_EQ(4.f, *(m.positionPtrAt(1) + 1));
EXPECT_EQ(5.f, *(m.positionPtrAt(1) + 2));
m.normal(0.f, 0.f, 1.f);
m.normal(0.f, 1.f, 0.f);
EXPECT_EQ(0.f, *m.normalPtrAt(0));
EXPECT_EQ(0.f, *(m.normalPtrAt(0) + 1));
EXPECT_EQ(1.f, *(m.normalPtrAt(0) + 2));
EXPECT_EQ(0.f, *m.normalPtrAt(1));
EXPECT_EQ(1.f, *(m.normalPtrAt(1) + 1));
EXPECT_EQ(0.f, *(m.normalPtrAt(1) + 2));
m.texCoord(0.f, 1.f);
m.texCoord(2.f, 3.f);
EXPECT_EQ(0.f, *m.texCoordPtrAt(0));
EXPECT_EQ(1.f, *(m.texCoordPtrAt(0) + 1));
EXPECT_EQ(2.f, *m.texCoordPtrAt(1));
EXPECT_EQ(3.f, *(m.texCoordPtrAt(1) + 1));
m.begin(Mesh::POLYGON);
m.vertex(0);
m.vertex(1);
m.vertex(0);
m.end();
m.begin(Mesh::POLYGON);
m.vertex(0);
m.vertex(1);
m.vertex(0);
m.vertex(1);
m.end();
EXPECT_EQ(0u, *m.vertexPtrAt(0));
EXPECT_EQ(1u, *(m.vertexPtrAt(0) + 1));
EXPECT_EQ(1u, *m.vertexPtrAt(1));
EXPECT_EQ(1u, *(m.vertexPtrAt(1) + 1));
EXPECT_EQ(0u, *m.vertexPtrAt(2));
EXPECT_EQ(1u, *(m.vertexPtrAt(2) + 1));
EXPECT_EQ(3, m.polygonVerticesCountAt(0));
EXPECT_EQ(4, m.polygonVerticesCountAt(1));
}
TEST(Mesh, vertex) {
Mesh m;
size_t n = m.polygonsNb();
size_t p = m.position(0.f, 0.f, 0.f);
ASSERT_EQ(0u, p);
ASSERT_EQ(1u, m.positionsNb());
m.normal(0.f, 0.f, 1.f);
m.texCoord(0.f, 0.f);
m.begin(Mesh::POLYGON);
m.end();
// empty polygon is a no-op
ASSERT_EQ(n, m.polygonsNb());
m.begin(Mesh::POLYGON);
m.vertex(p);
m.vertex(p);
m.vertex(p);
m.end();
ASSERT_EQ(n + 1u, m.polygonsNb());
ASSERT_EQ(3u, m.polygonVerticesCountAt(n));
m.begin(Mesh::POLYGON);
m.vertex(p);
m.vertex(p);
m.vertex(p);
m.vertex(p);
m.end();
ASSERT_EQ(n + 2u, m.polygonsNb());
ASSERT_EQ(4u, m.polygonVerticesCountAt(n + 1u));
m.begin(Mesh::TRIANGLES);
m.end();
// empty triangles set is a no-op
ASSERT_EQ(n + 2u, m.polygonsNb());
m.begin(Mesh::TRIANGLES);
m.vertex(p);
m.vertex(p);
m.vertex(p);
// the triangle is not added before the end() call
ASSERT_EQ(n + 2u, m.polygonsNb());
m.vertex(p);
m.vertex(p);
// unfinished triangle
EXPECT_ANY_THROW(m.end());
// the first triangle was not added before the failed end() call
ASSERT_EQ(n + 2u, m.polygonsNb());
m.vertex(p);
m.end();
ASSERT_EQ(n + 4u, m.polygonsNb());
ASSERT_EQ(3u, m.polygonVerticesCountAt(n + 2u));
ASSERT_EQ(3u, m.polygonVerticesCountAt(n + 3u));
m.begin(Mesh::QUADS);
m.end();
// empty quads set is a no-op
ASSERT_EQ(n + 4, m.polygonsNb());
m.begin(Mesh::QUADS);
m.vertex(p);
m.vertex(p);
m.vertex(p);
m.vertex(p);
ASSERT_EQ(n + 4u, m.polygonsNb());
m.vertex(p);
m.vertex(p);
m.vertex(p);
// unfinished quad
EXPECT_ANY_THROW(m.end());
// the first triangle was not added before the failed end() call
ASSERT_EQ(n + 4u, m.polygonsNb());
m.vertex(p);
m.end();
ASSERT_EQ(n + 6u, m.polygonsNb());
ASSERT_EQ(4u, m.polygonVerticesCountAt(n + 4u));
ASSERT_EQ(4u, m.polygonVerticesCountAt(n + 5u));
}
class ColladaSceneBuilderTest : public ::testing::Test {
public:
static boost::filesystem::path tmpdir;
static void SetUpTestCase() {
// tmpdir = "/tmp"; return;
tmpdir = mktmpdir("test_visualization3d");
}
static void writeScene(const ColladaSceneBuilder &scene,
const std::string &filename) {
boost::filesystem::path path = tmpdir / filename;
std::cout << "writing collada scene to: " << path << "\n";
boost::filesystem::ofstream os(path.c_str());
os << scene;
}
};
boost::filesystem::path ColladaSceneBuilderTest::tmpdir;
#define WRITE_SCENE(scene) writeScene(scene, #scene ".dae")
TEST_F(ColladaSceneBuilderTest, rule_of_three) {
SceneBuilder::Config config0, config1;
config1.color.r = 1.f - config0.color.r;
ColladaSceneBuilder sc0;
EXPECT_EQ(config0.color.r, sc0.getConfig().color.r);
ColladaSceneBuilder sc1(config1);
sc1.add(createBoxMesh(1.f, 1.f, 1.f), Math::Transform());
EXPECT_EQ(config1.color.r, sc1.getConfig().color.r);
ColladaSceneBuilder sc2(sc1);
sc2.add(createBoxMesh(.5f, .5f, .5f), Math::Transform(2.f, 0.f, 0.f));
EXPECT_EQ(config1.color.r, sc2.getConfig().color.r);
ColladaSceneBuilder sc3;
sc3 = sc1;
sc3.add(createBoxMesh(.5f, .5f, .5f), Math::Transform(2.f, 0.f, 0.f));
EXPECT_EQ(config1.color.r, sc0.getConfig().color.r);
WRITE_SCENE(sc0);
WRITE_SCENE(sc1);
WRITE_SCENE(sc2);
WRITE_SCENE(sc3);
}
TEST_F(ColladaSceneBuilderTest, shapes) {
ColladaSceneBuilder sc;
float d = 3.f;
float x = -d;
float y = 0.f;
float z = 0.f;
// add a box to m0
Mesh m0 = createBoxMesh(1.1f, 1.2f, 1.3f);
sc.add(m0, Eigen::Affine3f(Eigen::Translation3f(x += d, y, z)));
// add another box to m0
addBoxMesh(0.55f, 0.6f, 1.9f, m0);
sc.add(m0, Math::Transform(x += d, y, z));
x = -d;
y += 3.f;
sc.add(createRoundedBoxMesh(0.7f, 0.8f, 0.9f, 0.4f, 0),
Math::Transform(x += d, y, z));
sc.add(createRoundedBoxMesh(0.7f, 0.8f, 0.9f, 0.4f, 1),
Math::Transform(x += d, y, z));
sc.add(createRoundedBoxMesh(0.7f, 0.8f, 0.9f, 0.4f, 2),
Math::Transform(x += d, y, z));
sc.add(createRoundedBoxMesh(0.3f, 0.4f, 0.5f, 0.8f, 2),
Math::Transform(x += d, y, z));
sc.add(createRoundedBoxMesh(0.f, 0.8f, 0.9f, 0.4f, 2),
Math::Transform(x += d, y, z));
sc.add(createRoundedBoxMesh(0.7f, 0.f, 0.9f, 0.4f, 2),
Math::Transform(x += d, y, z));
sc.add(createRoundedBoxMesh(0.7f, 0.8f, 0.f, 0.4f, 2),
Math::Transform(x += d, y, z));
sc.add(createRoundedBoxMesh(0.f, 0.f, 0.9f, 0.4f, 2),
Math::Transform(x += d, y, z));
sc.add(createRoundedBoxMesh(0.f, 0.8f, 0.f, 0.4f, 2),
Math::Transform(x += d, y, z));
sc.add(createRoundedBoxMesh(0.7f, 0.f, 0.f, 0.4f, 2),
Math::Transform(x += d, y, z));
sc.add(createRoundedBoxMesh(0.f, 0.f, 0.f, 0.4f, 2),
Math::Transform(x += d, y, z));
sc.add(createRoundedBoxMesh(0.f, 0.f, 0.f, 0.4f, 11),
Math::Transform(x += d, y, z));
// fall back to a box
sc.add(createRoundedBoxMesh(1.1f, 1.2f, 1.3f, 0.f, 2),
Eigen::Affine3f(Eigen::Translation3f(x += d, y, z)));
x = -d;
y += 3.f;
// use a ptr to "forget" the concrete type of the shape and test the
// visitor
boost::scoped_ptr<Math::Shape3D> shape;
shape.reset(new Math::Sphere(1.f));
sc.add(*shape, Math::Transform(x += d, y, z));
shape.reset(new Math::RoundedRectangle(0.7f, 0.8f, 0.4f));
sc.add(*shape, Math::Transform(x += d, y, z));
shape.reset(new Math::Pill(0.9f, 0.4f));
sc.add(*shape, Math::Transform(x += d, y, z));
shape.reset(new Math::Plane);
EXPECT_ANY_THROW(sc.add(*shape, Math::Transform()));
WRITE_SCENE(sc);
}
| 27.414013 | 79 | 0.628369 | UCCS-Social-Robotics |
c9da357b490cb3140a8ed47c4083cc5336315b16 | 643 | hpp | C++ | libs/core/input/include/bksge/core/input/mouse_manager.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 4 | 2018-06-10T13:35:32.000Z | 2021-06-03T14:27:41.000Z | libs/core/input/include/bksge/core/input/mouse_manager.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 566 | 2017-01-31T05:36:09.000Z | 2022-02-09T05:04:37.000Z | libs/core/input/include/bksge/core/input/mouse_manager.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 1 | 2018-07-05T04:40:53.000Z | 2018-07-05T04:40:53.000Z | /**
* @file mouse_manager.hpp
*
* @brief MouseManager の定義
*
* @author myoukaku
*/
#ifndef BKSGE_CORE_INPUT_MOUSE_MANAGER_HPP
#define BKSGE_CORE_INPUT_MOUSE_MANAGER_HPP
#include <bksge/core/input/config.hpp>
#if defined(BKSGE_CORE_INPUT_MOUSE_MANAGER_HEADER)
# include BKSGE_CORE_INPUT_MOUSE_MANAGER_HEADER
#else
# if defined(BKSGE_PLATFORM_WIN32)
# include <bksge/core/input/win32/win32_mouse_manager.hpp>
# else
# include <bksge/core/input/null/null_mouse_manager.hpp>
# endif
#endif
namespace bksge
{
using input::MouseManager;
} // namespace bksge
#endif // BKSGE_CORE_INPUT_MOUSE_MANAGER_HPP
| 20.09375 | 60 | 0.752722 | myoukaku |
c9dd5ff102ed943e0434b9e6f4cd312f826df46d | 383 | cpp | C++ | chapter_07/Replace.cpp | Kevin-Oudai/my_cpp_solutions | a0f5f533ee4825f5b2d88cacc936d80276062ca4 | [
"MIT"
] | null | null | null | chapter_07/Replace.cpp | Kevin-Oudai/my_cpp_solutions | a0f5f533ee4825f5b2d88cacc936d80276062ca4 | [
"MIT"
] | 31 | 2021-05-14T03:37:24.000Z | 2022-03-13T17:38:32.000Z | chapter_07/Replace.cpp | Kevin-Oudai/my_cpp_solutions | a0f5f533ee4825f5b2d88cacc936d80276062ca4 | [
"MIT"
] | null | null | null | // Exercise 7.30 - Replace: space with underscore
#include <iostream>
#include <string>
int main()
{
std::string words;
std::cout << "Enter a string: ";
std::getline(std::cin, words);
for (int i = 0; i < words.length(); i++)
{
if (words[i] == ' ')
{
words[i] = '_';
}
}
std::cout << words << std::endl;
return 0;
} | 20.157895 | 49 | 0.490862 | Kevin-Oudai |
c9e0330c03136843f0894c5bc81325aa2c21db5a | 5,796 | cc | C++ | components/password_manager/core/browser/field_info_table.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | components/password_manager/core/browser/field_info_table.cc | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | components/password_manager/core/browser/field_info_table.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/password_manager/core/browser/field_info_table.h"
#include "build/build_config.h"
#include "components/autofill/core/common/signatures.h"
#include "components/password_manager/core/browser/sql_table_builder.h"
#include "sql/database.h"
#include "sql/statement.h"
namespace password_manager {
namespace {
constexpr char kFieldInfoTableName[] = "field_info";
#if !defined(OS_ANDROID)
// Represents columns of the FieldInfoTable. Used with SQL queries that use all
// the columns.
enum class FieldInfoTableColumn {
kFormSignature,
kFieldSignature,
kFieldType,
kCreateTime,
};
// Casts the field info table column enum to its integer value.
int GetColumnNumber(FieldInfoTableColumn column) {
return static_cast<int>(column);
}
// Teaches |builder| about the different DB schemes in different versions.
void InitializeFieldInfoBuilder(SQLTableBuilder* builder) {
// Version 0.
builder->AddColumnToUniqueKey("form_signature", "INTEGER NOT NULL");
builder->AddColumnToUniqueKey("field_signature", "INTEGER NOT NULL");
builder->AddColumn("field_type", "INTEGER NOT NULL");
builder->AddColumn("create_time", "INTEGER NOT NULL");
builder->AddIndex("field_info_index", {"form_signature", "field_signature"});
builder->SealVersion();
}
// Returns a FieldInfo vector from the SQL statement.
std::vector<FieldInfo> StatementToFieldInfo(sql::Statement* s) {
std::vector<FieldInfo> results;
while (s->Step()) {
results.emplace_back();
results.back().form_signature = autofill::FormSignature(
s->ColumnInt64(GetColumnNumber(FieldInfoTableColumn::kFormSignature)));
results.back().field_signature = autofill::FieldSignature(
s->ColumnInt(GetColumnNumber(FieldInfoTableColumn::kFieldSignature)));
results.back().field_type = static_cast<autofill::ServerFieldType>(
s->ColumnInt(GetColumnNumber(FieldInfoTableColumn::kFieldType)));
results.back().create_time = base::Time::FromDeltaSinceWindowsEpoch(
(base::TimeDelta::FromMicroseconds(s->ColumnInt64(
GetColumnNumber(FieldInfoTableColumn::kCreateTime)))));
}
return results;
}
#endif
} // namespace
bool operator==(const FieldInfo& lhs, const FieldInfo& rhs) {
return lhs.form_signature == rhs.form_signature &&
lhs.field_signature == rhs.field_signature &&
lhs.field_type == rhs.field_type && lhs.create_time == rhs.create_time;
}
void FieldInfoTable::Init(sql::Database* db) {
db_ = db;
#if defined(OS_ANDROID)
// Local predictions on Android are not reliable, so they are not used now.
// Remove the table which might have created in the old versions.
// TODO(https://crbug.com/1051914): remove this after M-83.
DropTableIfExists();
#endif // defined(OS_ANDROID)
}
bool FieldInfoTable::CreateTableIfNecessary() {
#if defined(OS_ANDROID)
return true;
#else
if (db_->DoesTableExist(kFieldInfoTableName))
return true;
SQLTableBuilder builder(kFieldInfoTableName);
InitializeFieldInfoBuilder(&builder);
return builder.CreateTable(db_);
#endif // defined(OS_ANDROID)
}
bool FieldInfoTable::DropTableIfExists() {
if (!db_->DoesTableExist(kFieldInfoTableName))
return false;
return db_->Execute("DROP TABLE field_info");
}
bool FieldInfoTable::AddRow(const FieldInfo& field) {
#if defined(OS_ANDROID)
return false;
#else
sql::Statement s(db_->GetCachedStatement(
SQL_FROM_HERE,
"INSERT OR IGNORE INTO field_info "
"(form_signature, field_signature, field_type, create_time) "
"VALUES (?, ?, ?, ?)"));
s.BindInt64(GetColumnNumber(FieldInfoTableColumn::kFormSignature),
field.form_signature.value());
s.BindInt64(GetColumnNumber(FieldInfoTableColumn::kFieldSignature),
field.field_signature.value());
s.BindInt(GetColumnNumber(FieldInfoTableColumn::kFieldType),
field.field_type);
s.BindInt64(GetColumnNumber(FieldInfoTableColumn::kCreateTime),
field.create_time.ToDeltaSinceWindowsEpoch().InMicroseconds());
return s.Run();
#endif // defined(OS_ANDROID)
}
bool FieldInfoTable::RemoveRowsByTime(base::Time remove_begin,
base::Time remove_end) {
#if defined(OS_ANDROID)
return false;
#else
sql::Statement s(
db_->GetCachedStatement(SQL_FROM_HERE,
"DELETE FROM field_info WHERE "
"create_time >= ? AND create_time < ?"));
s.BindInt64(0, remove_begin.ToDeltaSinceWindowsEpoch().InMicroseconds());
s.BindInt64(1, remove_end.ToDeltaSinceWindowsEpoch().InMicroseconds());
return s.Run();
#endif // defined(OS_ANDROID)
}
std::vector<FieldInfo> FieldInfoTable::GetAllRows() {
#if defined(OS_ANDROID)
return std::vector<FieldInfo>();
#else
sql::Statement s(db_->GetCachedStatement(
SQL_FROM_HERE,
"SELECT form_signature, field_signature, field_type, create_time FROM "
"field_info"));
return StatementToFieldInfo(&s);
#endif // defined(OS_ANDROID)
}
// Returns all FieldInfo from the database which have |form_signature|.
std::vector<FieldInfo> FieldInfoTable::GetAllRowsForFormSignature(
uint64_t form_signature) {
#if defined(OS_ANDROID)
return std::vector<FieldInfo>();
#else
sql::Statement s(
db_->GetCachedStatement(SQL_FROM_HERE,
"SELECT form_signature, field_signature, "
"field_type, create_time FROM field_info "
"WHERE form_signature = ?"));
s.BindInt64(0, form_signature);
return StatementToFieldInfo(&s);
#endif // defined(OS_ANDROID)
}
} // namespace password_manager
| 35.127273 | 80 | 0.717564 | mghgroup |
51859ece19ba8031ec7bea4cb8b4b23f38d3f48d | 828 | hpp | C++ | src/komuna/torent/TorentoTexta.hpp | cnsuhao/wortserchilo | 2788036dbcd754d68190514dd2df20d691309990 | [
"MIT"
] | 1 | 2021-05-12T16:41:47.000Z | 2021-05-12T16:41:47.000Z | src/komuna/torent/TorentoTexta.hpp | cnsuhao/wortserchilo | 2788036dbcd754d68190514dd2df20d691309990 | [
"MIT"
] | null | null | null | src/komuna/torent/TorentoTexta.hpp | cnsuhao/wortserchilo | 2788036dbcd754d68190514dd2df20d691309990 | [
"MIT"
] | null | null | null | #ifndef KOMUNA_TORENTOTEXTA_HPP
#define KOMUNA_TORENTOTEXTA_HPP
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream.hpp>
#include "../Texto.hpp"
#include "../trajtoj/specoj.hpp"
#include "../PropraAdres.hpp"
class AperatoTexta : public boost::iostreams::device<boost::iostreams::seekable, Texto::Ano>
{
using stream_offset = boost::iostreams::stream_offset;
public:
AperatoTexta(Texto* texto, ℕ unuaLoko = 0) : texto(texto), loko(unuaLoko) {};
std::streamsize read(char* celo, std::streamsize maximumaNombro);
std::streamsize write(const char* fonto, std::streamsize maximumaNombro);
stream_offset seek(stream_offset diferenco, std::ios::seekdir komenco);
Texto* texto;
ℕ loko;
};
using TorentoTexta = boost::iostreams::stream<AperatoTexta>;
#endif //KOMUNA_TORENTOTEXTA_HPP
| 33.12 | 92 | 0.747585 | cnsuhao |
51864f1c7716943607744f879263a31620698e3e | 4,131 | cpp | C++ | external/webkit/Source/WebKit/chromium/src/InspectorFrontendClientImpl.cpp | ghsecuritylab/android_platform_sony_nicki | 526381be7808e5202d7865aa10303cb5d249388a | [
"Apache-2.0"
] | 6 | 2017-05-31T01:46:45.000Z | 2018-06-12T10:53:30.000Z | Source/WebKit/chromium/src/InspectorFrontendClientImpl.cpp | FMSoftCN/mdolphin-core | 48ffdcf587a48a7bb4345ae469a45c5b64ffad0e | [
"Apache-2.0"
] | 2 | 2017-07-25T09:37:22.000Z | 2017-08-04T07:18:56.000Z | Source/WebKit/chromium/src/InspectorFrontendClientImpl.cpp | FMSoftCN/mdolphin-core | 48ffdcf587a48a7bb4345ae469a45c5b64ffad0e | [
"Apache-2.0"
] | 2 | 2017-08-09T09:03:23.000Z | 2020-05-26T09:14:49.000Z | /*
* Copyright (C) 2010 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.
*/
#include "config.h"
#include "InspectorFrontendClientImpl.h"
#include "Document.h"
#include "Frame.h"
#include "InspectorFrontendHost.h"
#include "Page.h"
#include "PlatformString.h"
#include "V8InspectorFrontendHost.h"
#include "V8Proxy.h"
#include "WebDevToolsFrontendClient.h"
#include "WebDevToolsFrontendImpl.h"
#include "WebString.h"
using namespace WebCore;
namespace WebKit {
InspectorFrontendClientImpl::InspectorFrontendClientImpl(Page* frontendPage, WebDevToolsFrontendClient* client, WebDevToolsFrontendImpl* frontend)
: m_frontendPage(frontendPage)
, m_client(client)
, m_frontend(frontend)
{
}
InspectorFrontendClientImpl::~InspectorFrontendClientImpl()
{
if (m_frontendHost)
m_frontendHost->disconnectClient();
m_client = 0;
}
void InspectorFrontendClientImpl::windowObjectCleared()
{
v8::HandleScope handleScope;
v8::Handle<v8::Context> frameContext = V8Proxy::context(m_frontendPage->mainFrame());
v8::Context::Scope contextScope(frameContext);
ASSERT(!m_frontendHost);
m_frontendHost = InspectorFrontendHost::create(this, m_frontendPage);
v8::Handle<v8::Value> frontendHostObj = toV8(m_frontendHost.get());
v8::Handle<v8::Object> global = frameContext->Global();
global->Set(v8::String::New("InspectorFrontendHost"), frontendHostObj);
}
void InspectorFrontendClientImpl::frontendLoaded()
{
m_frontend->frontendLoaded();
}
void InspectorFrontendClientImpl::moveWindowBy(float x, float y)
{
}
String InspectorFrontendClientImpl::localizedStringsURL()
{
return "";
}
String InspectorFrontendClientImpl::hiddenPanels()
{
if (m_client->shouldHideScriptsPanel())
return "scripts";
return "";
}
void InspectorFrontendClientImpl::bringToFront()
{
m_client->activateWindow();
}
void InspectorFrontendClientImpl::closeWindow()
{
m_client->closeWindow();
}
void InspectorFrontendClientImpl::disconnectFromBackend()
{
m_client->closeWindow();
}
void InspectorFrontendClientImpl::requestAttachWindow()
{
m_client->requestDockWindow();
}
void InspectorFrontendClientImpl::requestDetachWindow()
{
m_client->requestUndockWindow();
}
void InspectorFrontendClientImpl::changeAttachedWindowHeight(unsigned)
{
// Do nothing;
}
void InspectorFrontendClientImpl::inspectedURLChanged(const String& url)
{
m_frontendPage->mainFrame()->document()->setTitle("Developer Tools - " + url);
}
void InspectorFrontendClientImpl::sendMessageToBackend(const String& message)
{
m_client->sendMessageToBackend(message);
}
} // namespace WebKit
| 29.719424 | 146 | 0.761075 | ghsecuritylab |
51898833836d7ab71c1951140cfa005c8a858aeb | 4,330 | cpp | C++ | src/backend/gporca/libnaucrates/src/parser/CParseHandlerCTEConfig.cpp | zhongyibill/gpdb | 12cfded239d5da2ad102697c9d56efb5759807dd | [
"PostgreSQL",
"Apache-2.0"
] | 1 | 2021-01-03T17:55:43.000Z | 2021-01-03T17:55:43.000Z | src/backend/gporca/libnaucrates/src/parser/CParseHandlerCTEConfig.cpp | zhongyibill/gpdb | 12cfded239d5da2ad102697c9d56efb5759807dd | [
"PostgreSQL",
"Apache-2.0"
] | 16 | 2020-10-21T18:37:47.000Z | 2021-01-13T01:01:15.000Z | src/backend/gporca/libnaucrates/src/parser/CParseHandlerCTEConfig.cpp | zhongyibill/gpdb | 12cfded239d5da2ad102697c9d56efb5759807dd | [
"PostgreSQL",
"Apache-2.0"
] | 1 | 2020-03-26T02:47:22.000Z | 2020-03-26T02:47:22.000Z | //---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2013 EMC Corp.
//
// @filename:
// CParseHandlerCTEConfig.cpp
//
// @doc:
// Implementation of the SAX parse handler class for parsing CTE
// configuration
//---------------------------------------------------------------------------
#include "naucrates/dxl/parser/CParseHandlerManager.h"
#include "naucrates/dxl/parser/CParseHandlerFactory.h"
#include "naucrates/dxl/parser/CParseHandlerCTEConfig.h"
#include "naucrates/dxl/operators/CDXLOperatorFactory.h"
#include "naucrates/dxl/xml/dxltokens.h"
#include "gpopt/engine/CCTEConfig.h"
using namespace gpdxl;
using namespace gpopt;
XERCES_CPP_NAMESPACE_USE
//---------------------------------------------------------------------------
// @function:
// CParseHandlerCTEConfig::CParseHandlerCTEConfig
//
// @doc:
// Ctor
//
//---------------------------------------------------------------------------
CParseHandlerCTEConfig::CParseHandlerCTEConfig(
CMemoryPool *mp, CParseHandlerManager *parse_handler_mgr,
CParseHandlerBase *parse_handler_root)
: CParseHandlerBase(mp, parse_handler_mgr, parse_handler_root),
m_cte_conf(NULL)
{
}
//---------------------------------------------------------------------------
// @function:
// CParseHandlerCTEConfig::~CParseHandlerCTEConfig
//
// @doc:
// Dtor
//
//---------------------------------------------------------------------------
CParseHandlerCTEConfig::~CParseHandlerCTEConfig()
{
CRefCount::SafeRelease(m_cte_conf);
}
//---------------------------------------------------------------------------
// @function:
// CParseHandlerCTEConfig::StartElement
//
// @doc:
// Invoked by Xerces to process an opening tag
//
//---------------------------------------------------------------------------
void
CParseHandlerCTEConfig::StartElement(const XMLCh *const, //element_uri,
const XMLCh *const element_local_name,
const XMLCh *const, //element_qname,
const Attributes &attrs)
{
if (0 !=
XMLString::compareString(CDXLTokens::XmlstrToken(EdxltokenCTEConfig),
element_local_name))
{
CWStringDynamic *str = CDXLUtils::CreateDynamicStringFromXMLChArray(
m_parse_handler_mgr->GetDXLMemoryManager(), element_local_name);
GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiDXLUnexpectedTag,
str->GetBuffer());
}
// parse CTE configuration options
ULONG cte_inlining_cut_off =
CDXLOperatorFactory::ExtractConvertAttrValueToUlong(
m_parse_handler_mgr->GetDXLMemoryManager(), attrs,
EdxltokenCTEInliningCutoff, EdxltokenCTEConfig);
m_cte_conf = GPOS_NEW(m_mp) CCTEConfig(cte_inlining_cut_off);
}
//---------------------------------------------------------------------------
// @function:
// CParseHandlerCTEConfig::EndElement
//
// @doc:
// Invoked by Xerces to process a closing tag
//
//---------------------------------------------------------------------------
void
CParseHandlerCTEConfig::EndElement(const XMLCh *const, // element_uri,
const XMLCh *const element_local_name,
const XMLCh *const // element_qname
)
{
if (0 !=
XMLString::compareString(CDXLTokens::XmlstrToken(EdxltokenCTEConfig),
element_local_name))
{
CWStringDynamic *str = CDXLUtils::CreateDynamicStringFromXMLChArray(
m_parse_handler_mgr->GetDXLMemoryManager(), element_local_name);
GPOS_RAISE(gpdxl::ExmaDXL, gpdxl::ExmiDXLUnexpectedTag,
str->GetBuffer());
}
GPOS_ASSERT(NULL != m_cte_conf);
GPOS_ASSERT(0 == this->Length());
// deactivate handler
m_parse_handler_mgr->DeactivateHandler();
}
//---------------------------------------------------------------------------
// @function:
// CParseHandlerCTEConfig::GetParseHandlerType
//
// @doc:
// Return the type of the parse handler.
//
//---------------------------------------------------------------------------
EDxlParseHandlerType
CParseHandlerCTEConfig::GetParseHandlerType() const
{
return EdxlphCTEConfig;
}
//---------------------------------------------------------------------------
// @function:
// CParseHandlerCTEConfig::GetCteConf
//
// @doc:
// Returns the CTE configuration
//
//---------------------------------------------------------------------------
CCTEConfig *
CParseHandlerCTEConfig::GetCteConf() const
{
return m_cte_conf;
}
// EOF
| 28.866667 | 77 | 0.560046 | zhongyibill |
518b6befcd1cbcfa32f8b53241faebf1c19957cd | 14,567 | cpp | C++ | src/func-pilo/core/string/functional_test_module_class_fixed_wstring.cpp | picofox/pilo | 59e12c947307d664c4ca9dcc232b481d06be104a | [
"MIT"
] | 1 | 2019-07-31T06:44:46.000Z | 2019-07-31T06:44:46.000Z | src/func-pilo/core/string/functional_test_module_class_fixed_wstring.cpp | picofox/pilo | 59e12c947307d664c4ca9dcc232b481d06be104a | [
"MIT"
] | null | null | null | src/func-pilo/core/string/functional_test_module_class_fixed_wstring.cpp | picofox/pilo | 59e12c947307d664c4ca9dcc232b481d06be104a | [
"MIT"
] | null | null | null |
#include "core/string/string_util.hpp"
#include "core/string/fixed_wstring.hpp"
#include "core/io/format_output.hpp"
#include "functional_test_module_class_fixed_wstring.hpp"
#include <string>
#define MC_STR0_SIZE 8192
namespace pilo
{
namespace test
{
static pilo::i32_t functional_test_constructor_0_wchar(void* param);
static pilo::i32_t functional_test_constructor_1_wchar(void* param);
static pilo::i32_t functional_test_constructor_2_wchar(void* param);
static pilo::i32_t functional_test_constructor_3_wchar(void* param);
static pilo::i32_t functional_test_constructor_4_wchar(void* param);
static pilo::i32_t functional_test_constructor_5_wchar(void* param);
static pilo::i32_t functional_test_constructor_6_wchar(void* param);
static pilo::i32_t functional_test_copy_operator_0(void* param);
static pilo::i32_t functional_test_copy_operator_1(void* param);
static pilo::i32_t functional_test_copy_operator_2(void* param);
static pilo::i32_t functional_test_copy_operator_3(void* param);
static pilo::i32_t functional_test_copy_operator_4(void* param);
static pilo::i32_t functional_test_assign_0(void* param);
static pilo::i32_t functional_test_assign_1(void* param);
static pilo::i32_t functional_test_assign_2(void* param);
static pilo::i32_t functional_test_assign_3(void* param);
pilo::test::testing_case g_functional_cases_fixed_wstring[] =
{
/*---"---------------------------------------------"*/
{ 1, "fixed_wstring<wchar>() ", nullptr, functional_test_constructor_0_wchar, 0, -1, (pilo::u32_t) - 1 },
{ 2, "fixed_wstring<char>(const wchar_t*) ", nullptr, functional_test_constructor_1_wchar, 0, -1, (pilo::u32_t) - 1 },
{ 3, "fixed_wstring<wchar>(const whar_t*, size_t) ", nullptr, functional_test_constructor_2_wchar, 0, -1, (pilo::u32_t) - 1 },
{ 4, "fixed_wstring<wchar>(const fixed_wstring&) ", nullptr, functional_test_constructor_3_wchar, 0, -1, (pilo::u32_t) - 1 },
{ 4, "fixed_wstring<wchar>(const std::wstring &) ", nullptr, functional_test_constructor_4_wchar, 0, -1, (pilo::u32_t) - 1 },
{ 5, "fixed_wstring<wchar>(int) ", nullptr, functional_test_constructor_5_wchar, 0, -1, (pilo::u32_t) - 1 },
{ 6, "fixed_astring<char>(float) ", nullptr, functional_test_constructor_6_wchar, 0, -1, (pilo::u32_t) - 1 },
{ 7, "operator=<fixed_wstring>(fixed_wstring) ", nullptr, functional_test_copy_operator_0, 0, -1, (pilo::u32_t) - 1 },
{ 7, "operator=(std::wstring) ", nullptr, functional_test_copy_operator_1, 0, -1, (pilo::u32_t) - 1 },
{ 8, "operator=(const wchar_t* ", nullptr, functional_test_copy_operator_2, 0, -1, (pilo::u32_t) - 1 },
{ 9, "operator=(wchar_t) ", nullptr, functional_test_copy_operator_3, 0, -1, (pilo::u32_t) - 1 },
{10, "operator=<number>(wchar_t) ", nullptr, functional_test_copy_operator_4, 0, -1, (pilo::u32_t) - 1 },
{11, "assign(size_t, wchar_t) ", nullptr, functional_test_assign_0, 0, -1, (pilo::u32_t) - 1 },
{12, "assign(const std::string&) ", nullptr, functional_test_assign_1, 0, -1, (pilo::u32_t) - 1 },
{13, "assign(const wchar_t*) ", nullptr, functional_test_assign_2, 0, -1, (pilo::u32_t) - 1 },
{14, "assign(const fixed_string&) ", nullptr, functional_test_assign_3, 0, -1, (pilo::u32_t) - 1 },
{ -1, "end", nullptr, nullptr, 0, -1, 0 },
};
pilo::i32_t functional_test_constructor_0_wchar(void* param)
{
M_UNUSED(param);
pilo::core::string::fixed_wstring< MC_STR0_SIZE> str0;
if (str0.length() != 0)
{
return -1;
}
if (str0[0] != 0)
{
return -2;
}
if (str0.capacity() != MC_STR0_SIZE)
{
return -3;
}
if (!str0.empty())
{
return -4;
}
return 0;
}
pilo::i32_t functional_test_constructor_1_wchar(void* param)
{
M_UNUSED(param);
wchar_t str_buffer[MC_STR0_SIZE];
pilo::core::string::string_util::m_set(str_buffer, 0, MF_COUNT_OF(str_buffer));
pilo::core::string::string_util::m_set(str_buffer, 1, MF_COUNT_OF(str_buffer) - 1);
str_buffer[0] = '$';
str_buffer[MC_STR0_SIZE - 2] = '#';
pilo::core::string::fixed_wstring< MC_STR0_SIZE> str0(str_buffer);
if (str0.length() != 8191)
{
return -1;
}
if (str0.size() != 8191)
{
return -2;
}
if (str0.empty())
{
return -4;
}
if (str0.front() != '$')
{
return -5;
}
if (str0.back() != '#')
{
return -6;
}
if (::memcmp(str0.c_str(), str_buffer, MC_STR0_SIZE) != 0)
{
return -7;
}
return 0;
}
pilo::i32_t functional_test_constructor_2_wchar(void* param)
{
M_UNUSED(param);
wchar_t str_buffer[MC_STR0_SIZE + 1];
pilo::core::string::string_util::set(str_buffer, '1', MC_STR0_SIZE);
pilo::core::string::fixed_wstring< MC_STR0_SIZE + 1> str0(str_buffer, MC_STR0_SIZE);
if (str0.size() != MC_STR0_SIZE)
{
return -1;
}
if (::memcmp(str_buffer, str0.c_str(), sizeof(str_buffer) != 0))
{
return -2;
}
return 0;
}
pilo::i32_t functional_test_constructor_3_wchar(void* param)
{
M_UNUSED(param);
const wchar_t* str = L"1234567890";
size_t len = pilo::core::string::string_util::length(str);
pilo::core::string::fixed_wstring< 32> str0(str, len);
pilo::core::string::fixed_wstring< 64> str1(str0);
if (str0.size() != str1.length())
{
return -1;
}
if (::memcmp(str0.c_str(), str1.c_str(), (len + 1)*sizeof(wchar_t)) != 0)
{
return -2;
}
const wchar_t* cstr2 = L"012345678901234567890123456789";
len = pilo::core::string::string_util::length(cstr2);
pilo::core::string::fixed_wstring< 112> str2(cstr2);
pilo::core::string::fixed_wstring< 32> str3(str2);
if (str3.size() != len)
{
return -3;
}
if (::memcmp(str3.c_str(), str2.c_str(), (len + 1) * sizeof(wchar_t)) != 0)
{
return -4;
}
return 0;
}
pilo::i32_t functional_test_constructor_4_wchar(void* param)
{
M_UNUSED(param);
std::wstring stdstr0 = L"012345678901234567890123456789";
pilo::core::string::fixed_wstring<31> str0(stdstr0);
if (stdstr0.length() != stdstr0.length())
{
return -1;
}
if (::memcmp(stdstr0.c_str(), str0.c_str(), str0.size()*sizeof(wchar_t)) != 0)
{
return -2;
}
return 0;
}
pilo::i32_t functional_test_constructor_5_wchar(void* param)
{
M_UNUSED(param);
pilo::core::string::fixed_wstring< 10> str0(123456789);
if (str0.size() != 9)
{
return -1;
}
pilo::core::string::fixed_wstring< 10> str1 = 987654321;
if (str1.size() != 9)
{
return -3;
}
pilo::core::string::fixed_wstring<11> stri64(9876543210LL);
if (stri64.size() != 10)
{
return -1;
}
pilo::u64_t u64vv = 19876543210U;
pilo::core::string::fixed_wstring<12> stru64(u64vv);
if (stru64.size() != 11)
{
return -1;
}
return 0;
}
pilo::i32_t functional_test_constructor_6_wchar(void* param)
{
M_UNUSED(param);
float fv1 = -789.123f;
pilo::core::string::fixed_wstring<32> str0(fv1);
#ifdef WINDOWS
float fv2 = (float) ::_wtof(str0.c_str());
#else
float fv2 = (float) ::wcstof(str0, 0);
#endif
if (fv1 != fv2)
{
return -1;
}
double dv1 = -789.123456f;
pilo::core::string::fixed_wstring<32> str1(dv1);
#ifdef WINDOWS
double dv2 = (float) ::_wtof(str1.c_str());
#else
double dv2 = (float) ::wcstof(str1, 0);
#endif
if (dv1 != dv2)
{
return -1;
}
return 0;
}
pilo::i32_t functional_test_copy_operator_0(void* param)
{
M_UNUSED(param);
const wchar_t* cstr0 = L"012345678901234567890123456789";
pilo::core::string::fixed_wstring<64> tstr0 = cstr0;
pilo::core::string::fixed_wstring<32> tstr1;
tstr1 = tstr0;
if (tstr1.size() != 30)
{
return -1;
}
if (::memcmp(tstr1.c_str(), cstr0, (pilo::core::string::string_util::length(cstr0) + 1)*sizeof(wchar_t)) != 0)
{
return -2;
}
return 0;
}
pilo::i32_t functional_test_copy_operator_1(void* param)
{
M_UNUSED(param);
std::wstring stdstr0 = L"0123456789";
pilo::core::string::fixed_wstring<32> fastr;
fastr = stdstr0;
if (fastr.length() != stdstr0.length())
{
return -1;
}
return 0;
}
pilo::i32_t functional_test_copy_operator_2(void* param)
{
M_UNUSED(param);
pilo::core::string::fixed_wstring<32> fastr;
fastr = L"0123456789";
if (fastr.length() != 10)
{
return -1;
}
return 0;
}
pilo::i32_t functional_test_copy_operator_3(void* param)
{
M_UNUSED(param);
pilo::core::string::fixed_wstring<32> fastr;
fastr = 'x';
if (fastr.length() != 1)
{
return -1;
}
if (fastr[0] != 'x' || fastr[1] != 0)
{
return -2;
}
return 0;
}
pilo::i32_t functional_test_copy_operator_4(void* param)
{
M_UNUSED(param);
pilo::core::string::fixed_wstring<MC_STR0_SIZE> str0;
pilo::i32_t vi32 = -12345678;
str0 = vi32;
pilo::i64_t vi64 = -1234567890;
str0 = vi64;
pilo::u32_t vu32 = 82345678;
str0 = vu32;
pilo::u64_t vu64 = 11234567890;
str0 = vu64;
float fv = -235.238f;
str0 = fv;
#ifdef WINDOWS
float fv2 = (float) ::_wtof(str0.c_str());
#else
float fv2 = (float) ::wcstof(str0, 0);
#endif
if (fv != fv2)
{
return -5;
}
double dv = 123.683909;
str0 = dv;
#ifdef WINDOWS
double dv2 = ::_wtof(str0.c_str());
#else
double dv2 = (double) ::wcstof(str0, 0);
#endif
if (abs(dv - dv2) >= 0.000001)
{
pilo::core::io::console_format_output("dv=%f, dv2=%f diff=%f\n", dv, dv2, dv-dv2);
return -6;
}
return 0;
}
pilo::i32_t functional_test_assign_0(void* param)
{
M_UNUSED(param);
pilo::core::string::fixed_wstring<12> str0;
pilo::core::string::fixed_wstring<12> str1 = str0.assign(12, (wchar_t)'x');
if (str1.size() != 12)
{
return -1;
}
if (::memcmp(str1.c_str(), L"xxxxxxxxxxxx", 13) != 0)
{
return -2;
}
return 0;
}
pilo::i32_t functional_test_assign_1(void* param)
{
M_UNUSED(param);
std::wstring stdstr = L"xxxxxxxxxxxx";
pilo::core::string::fixed_wstring<12> str0;
pilo::core::string::fixed_wstring<12> str1 = str0.assign(stdstr);
if (str1.size() != 12)
{
return -1;
}
if (::memcmp(str1.c_str(), stdstr.c_str(), 13 * sizeof(wchar_t)) != 0)
{
return -2;
}
return 0;
}
pilo::i32_t functional_test_assign_2(void* param)
{
M_UNUSED(param);
const wchar_t* cstr = L"xxxxxxxxxxxx";
pilo::core::string::fixed_wstring<12> str0;
pilo::core::string::fixed_wstring<12> str1 = str0.assign(cstr);
if (str1.size() != 12)
{
return -1;
}
if (::memcmp(str1.c_str(), L"xxxxxxxxxxxx", 13 * sizeof(wchar_t)) != 0)
{
return -2;
}
return 0;
}
pilo::i32_t functional_test_assign_3(void* param)
{
M_UNUSED(param);
pilo::core::string::fixed_wstring<1024> fstr = L"xxxxxxxxxxxx";
pilo::core::string::fixed_wstring<12> str0;
pilo::core::string::fixed_wstring<12> str1 = str0.assign(fstr);
if (str1.size() != 12)
{
return -1;
}
if (::memcmp(str1.c_str(), fstr.c_str(), 13 * sizeof(wchar_t)) != 0)
{
return -2;
}
return 0;
}
}
} | 33.106818 | 151 | 0.483353 | picofox |
518b9a78c5ae45dcfc8ac2a695d551e72050bf8e | 338 | cpp | C++ | halfnetwork/HalfNetwork/ACE_wrappers/ace/Connection_Recycling_Strategy.cpp | cjwcjswo/com2us_cppNetStudy_work | 3aab26cfd2e9bf1544fa41a0f2694d81167b2584 | [
"MIT"
] | 25 | 2019-05-20T08:07:39.000Z | 2021-08-17T11:25:02.000Z | halfnetwork/HalfNetwork/ACE_wrappers/ace/Connection_Recycling_Strategy.cpp | cjwcjswo/com2us_cppNetStudy_work | 3aab26cfd2e9bf1544fa41a0f2694d81167b2584 | [
"MIT"
] | null | null | null | halfnetwork/HalfNetwork/ACE_wrappers/ace/Connection_Recycling_Strategy.cpp | cjwcjswo/com2us_cppNetStudy_work | 3aab26cfd2e9bf1544fa41a0f2694d81167b2584 | [
"MIT"
] | 17 | 2019-07-07T12:20:16.000Z | 2022-01-11T08:27:44.000Z | #include "ace/Connection_Recycling_Strategy.h"
ACE_RCSID(ace, Connection_Recycling_Strategy, "$Id: Connection_Recycling_Strategy.cpp 80826 2008-03-04 14:51:23Z wotte $")
ACE_BEGIN_VERSIONED_NAMESPACE_DECL
ACE_Connection_Recycling_Strategy::~ACE_Connection_Recycling_Strategy (void)
{
}
ACE_END_VERSIONED_NAMESPACE_DECL
| 24.142857 | 123 | 0.816568 | cjwcjswo |
518c8538c87fb9c19d1f0e319a6a030c3f1dd55f | 20,785 | cpp | C++ | src/MdCharm/baseeditor/baseeditor.cpp | MonkeyMo/MdCharm | 78799f0bd85603aae9361b4fca05384a69f690e6 | [
"BSD-3-Clause"
] | 387 | 2015-01-01T17:51:59.000Z | 2021-06-13T19:40:15.000Z | src/MdCharm/baseeditor/baseeditor.cpp | MonkeyMo/MdCharm | 78799f0bd85603aae9361b4fca05384a69f690e6 | [
"BSD-3-Clause"
] | 26 | 2015-01-09T08:36:26.000Z | 2020-04-02T12:51:01.000Z | src/MdCharm/baseeditor/baseeditor.cpp | heefan/MdCharm | 78799f0bd85603aae9361b4fca05384a69f690e6 | [
"BSD-3-Clause"
] | 145 | 2015-01-10T18:07:45.000Z | 2021-09-14T07:39:35.000Z | #include <QtGui>
#include <QtCore>
#ifdef QT_V5
#include <QtPrintSupport>
#endif
#include "baseeditor.h"
#include "util/spellcheck/spellchecker.h"
#include "configuration.h"
#include "utils.h"
BaseEditor::BaseEditor(QWidget *parent) :
QPlainTextEdit(parent)
{
conf = Configuration::getInstance();
mdCharmGlobal = MdCharmGlobal::getInstance();
lineNumberArea = new LineNumberArea(this);
displayLineNumber = false;
finded = false;
replacing = false;
if(conf->isCheckSpell())
spellCheckLanguage=conf->getSpellCheckLanguage();
connect(this, SIGNAL(textChanged()),
this, SLOT(ensureAtTheLast()));
}
BaseEditor::~BaseEditor(){}
void BaseEditor::initSpellCheckMatter()//triggered by setDocument()
{
if(!conf->isCheckSpell())
return;
connect(document(), SIGNAL(contentsChange(int,int,int)),
this, SLOT(spellCheck(int,int,int)));
checkWholeContent();
}
void BaseEditor::enableSpellCheck()
{
spellCheckErrorSelection.clear();
disconnect(document(), SIGNAL(contentsChange(int,int,int)),
this, SLOT(spellCheck(int,int,int)));
updateExtraSelection();
if(spellCheckLanguage.isEmpty())
spellCheckLanguage=conf->getSpellCheckLanguage();
if(mdCharmGlobal->getSpellChecker(spellCheckLanguage)==NULL){
Q_ASSERT(0 && "This should not be happen");
spellCheckLanguage.clear();
return;
}
connect(document(), SIGNAL(contentsChange(int,int,int)),
this, SLOT(spellCheck(int,int,int)));
checkWholeContent();
}
void BaseEditor::disableSpellCheck()
{
spellCheckErrorSelection.clear();
spellCheckLanguage.clear();
disconnect(document(), SIGNAL(contentsChange(int,int,int)),
this, SLOT(spellCheck(int,int,int)));
updateExtraSelection();;
}
void BaseEditor::setDocument(QTextDocument *doc)
{
QPlainTextEdit::setDocument(doc);
initSpellCheckMatter();
}
void BaseEditor::enableHighlightCurrentLine()
{
highlightCurrentLine();
connect(this, SIGNAL(cursorPositionChanged()),
this, SLOT(highlightCurrentLine()));
}
void BaseEditor::disableHighlightCurrentLine()
{
disconnect(this, SIGNAL(cursorPositionChanged()),
this, SLOT(highlightCurrentLine()));
currentLineSelection.clear();
updateExtraSelection();
}
void BaseEditor::enableDisplayLineNumber()
{
displayLineNumber = true;
connect(this, SIGNAL(blockCountChanged(int)),
this, SLOT(updateLineNumberAreaWidth(int)));
connect(this, SIGNAL(updateRequest(QRect,int)),
this, SLOT(updateLineNumberArea(QRect,int)));
updateLineNumberAreaWidth(0);
lineNumberArea->setVisible(true);
}
void BaseEditor::disableDisplayLineNumber()
{
displayLineNumber = false;
disconnect(this, SIGNAL(updateRequest(QRect,int)),
this, SLOT(updateLineNumberArea(QRect,int)));
disconnect(this, SIGNAL(blockCountChanged(int)),
this, SLOT(updateLineNumberAreaWidth(int)));
updateLineNumberAreaWidth(0);
lineNumberArea->setVisible(false);
}
int BaseEditor::lineNumberAreaWidth()
{
int digits = 1;
int max = qMax(1, blockCount());
while(max >= 10)
{
max /= 10;
++digits;
}
int space = 3 + QFontMetrics(document()->defaultFont()).width(QLatin1Char('9')) * digits;
return space;
}
int BaseEditor::firstVisibleLineNumber()
{
return firstVisibleBlock().blockNumber()+1;
}
void BaseEditor::findAndHighlightText(const QString &text, QTextDocument::FindFlags qff,
bool isRE, bool isSetTextCursor)
{
if(replacing)
return;
if(text.isEmpty())
{
findTextSelection.clear();
currentFindSelection.clear();
updateExtraSelection();
return;
}
if(findAllOccurrance(text, qff, isRE))
{
finded = true;
findFirstOccurrance(text, qff, isRE, true, isSetTextCursor);
}
}
bool BaseEditor::findAllOccurrance(const QString &text, QTextDocument::FindFlags qff, bool isRE)
{
QTextDocument *doc = document();
findTextSelection.clear();
bool finded=false;
if(text.isEmpty())
{
prevFindCursor = QTextCursor();
return finded;
} else {
QTextEdit::ExtraSelection es;
QTextCursor highlightCursor(doc);
QTextCharFormat plainFormat(highlightCursor.charFormat());
QTextCharFormat colorFormat = plainFormat;
colorFormat.setBackground(Qt::yellow);
es.format = colorFormat;
QRegExp re(text);
while(!highlightCursor.isNull() && !highlightCursor.atEnd())
{
highlightCursor = isRE ? doc->find(re, highlightCursor, qff) :
doc->find(text, highlightCursor, qff);
if(!highlightCursor.isNull())
{
finded = true;
es.cursor = highlightCursor;
findTextSelection.append(es);
}
}
if(!finded)
{
prevFindCursor = highlightCursor;
}
return finded;
}
}
void BaseEditor::findFirstOccurrance(const QString &text, QTextDocument::FindFlags qff,
bool isRE, bool init, bool isSetTextCusor)
{
if (!finded)
return;
QRegExp re(text);
QTextDocument *doc = document();
QTextCursor currentCursor = textCursor();
QTextCursor firstCursor;
QTextEdit::ExtraSelection es;
if(!init || prevFindCursor.isNull())
{
QTextCursor startCursor;
if(qff&QTextDocument::FindBackward && !prevFindCursor.isNull())
{
prevFindCursor.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor,
abs(prevFindCursor.selectionStart()-prevFindCursor.selectionEnd()));
}
if(prevFindCursor.isNull())
startCursor = currentCursor;
else
startCursor = prevFindCursor;
firstCursor = isRE ? doc->find(re, startCursor, qff):
doc->find(text, startCursor, qff);
} else {
firstCursor = isRE ? doc->find(re, prevFindCursor.selectionStart(), qff):
doc->find(text, prevFindCursor.selectionStart(), qff);
}
if(firstCursor.isNull())
{
QTextCursor wholeCursor(doc);
if(qff & QTextDocument::FindBackward)
wholeCursor.movePosition(QTextCursor::End);
firstCursor = isRE ? doc->find(re, wholeCursor, qff):
doc->find(text, wholeCursor, qff);
}
if(firstCursor.isNull())
{
prevFindCursor = firstCursor;
return;
}
es.cursor = firstCursor;
QTextCharFormat f;
f.setBackground(Qt::blue);
f.setForeground(Qt::white);
es.format = f;
currentFindSelection.clear();
currentFindSelection.append(es);
prevFindCursor = firstCursor;
firstCursor.clearSelection();
if(isSetTextCusor)
setTextCursor(firstCursor);
ensureCursorVisible();
updateExtraSelection();
}
void BaseEditor::updateLineNumberAreaWidth(int newBlockCount)
{
Q_UNUSED(newBlockCount)
setViewportMargins(displayLineNumber ? lineNumberAreaWidth() : 0, 0, 0, 0);
}
void BaseEditor::updateLineNumberArea(const QRect &rect, int dy)
{
if (dy)
lineNumberArea->scroll(0, dy);
else
lineNumberArea->update(0, rect.y(), lineNumberArea->width(), rect.height());
if (rect.contains(viewport()->rect()))
updateLineNumberAreaWidth(0);
}
void BaseEditor::resizeEvent(QResizeEvent *e)
{
QPlainTextEdit::resizeEvent(e);
if(!displayLineNumber)
return;
QRect cr = contentsRect();
lineNumberArea->setGeometry(QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height()));
}
void BaseEditor::keyPressEvent(QKeyEvent *e)
{
QPlainTextEdit::keyPressEvent(e);
if(!e->isAccepted()&&e->key()==Qt::Key_Insert)//FIXME: crashrpt 8135582f-6f1c-46db-b3be-85ee2702a88d
{
emit overWriteModeChanged();
}
}
void BaseEditor::focusInEvent(QFocusEvent *e)
{
emit focusInSignal();
QPlainTextEdit::focusInEvent(e);
}
static void fillBackground(QPainter *p, const QRectF &rect, QBrush brush, QRectF gradientRect = QRectF())//copy from QPlainTextEditor from 4.8.1
{
p->save();
if (brush.style() >= Qt::LinearGradientPattern && brush.style() <= Qt::ConicalGradientPattern) {
if (!gradientRect.isNull()) {
QTransform m = QTransform::fromTranslate(gradientRect.left(), gradientRect.top());
m.scale(gradientRect.width(), gradientRect.height());
brush.setTransform(m);
const_cast<QGradient *>(brush.gradient())->setCoordinateMode(QGradient::LogicalMode);
}
} else {
p->setBrushOrigin(rect.topLeft());
}
p->fillRect(rect, brush);
p->restore();
}
static QColor blendColors(const QColor &a, const QColor &b, int alpha)//copy from QPlainTextEditor from 4.8.1
{
return QColor((a.red() * (256 - alpha) + b.red() * alpha) / 256,
(a.green() * (256 - alpha) + b.green() * alpha) / 256,
(a.blue() * (256 - alpha) + b.blue() * alpha) / 256);
}
void BaseEditor::paintEvent(QPaintEvent *e)
{
//copy from QPlainTextEditor
QPainter painter(viewport());
Q_ASSERT(qobject_cast<QPlainTextDocumentLayout*>(document()->documentLayout()));
QPointF offset(contentOffset());
QRect er = e->rect();
QRect viewportRect = viewport()->rect();
bool editable = !isReadOnly();
QTextBlock block = firstVisibleBlock();
qreal maximumWidth = document()->documentLayout()->documentSize().width();
//margin
qreal lineX = 0;
if (conf->isDisplayRightColumnMargin()) {
// Don't use QFontMetricsF::averageCharWidth here, due to it returning
// a fractional size even when this is not supported by the platform.
lineX = QFontMetricsF(document()->defaultFont()).width(QLatin1Char('X')) * conf->getRightMarginColumn() + offset.x() + 4;
if (lineX < viewportRect.width()) {
const QBrush background = QBrush(QColor(239, 239, 239));
painter.fillRect(QRectF(lineX, er.top(), viewportRect.width() - lineX, er.height()),
background);
const QColor col = (palette().base().color().value() > 128) ? Qt::black : Qt::white;
const QPen pen = painter.pen();
painter.setPen(blendColors(background.isOpaque() ? background.color() : palette().base().color(),
col, 32));
painter.drawLine(QPointF(lineX, er.top()), QPointF(lineX, er.bottom()));
painter.setPen(pen);
}
}
// Set a brush origin so that the WaveUnderline knows where the wave started
painter.setBrushOrigin(offset);
// keep right margin clean from full-width selection
int maxX = offset.x() + qMax((qreal)viewportRect.width(), maximumWidth)
- document()->documentMargin();
er.setRight(qMin(er.right(), maxX));
painter.setClipRect(er);
QAbstractTextDocumentLayout::PaintContext context = getPaintContext();
while (block.isValid()) {
QRectF r = blockBoundingRect(block).translated(offset);
QTextLayout *layout = block.layout();
if (!block.isVisible()) {
offset.ry() += r.height();
block = block.next();
continue;
}
if (r.bottom() >= er.top() && r.top() <= er.bottom()) {
QTextBlockFormat blockFormat = block.blockFormat();
QBrush bg = blockFormat.background();
if (bg != Qt::NoBrush) {
QRectF contentsRect = r;
contentsRect.setWidth(qMax(r.width(), maximumWidth));
fillBackground(&painter, contentsRect, bg);
}
QVector<QTextLayout::FormatRange> selections;
int blpos = block.position();
int bllen = block.length();
for (int i = 0; i < context.selections.size(); ++i) {
const QAbstractTextDocumentLayout::Selection &range = context.selections.at(i);
const int selStart = range.cursor.selectionStart() - blpos;
const int selEnd = range.cursor.selectionEnd() - blpos;
if (selStart < bllen && selEnd > 0
&& selEnd > selStart) {
QTextLayout::FormatRange o;
o.start = selStart;
o.length = selEnd - selStart;
o.format = range.format;
selections.append(o);
} else if (!range.cursor.hasSelection() && range.format.hasProperty(QTextFormat::FullWidthSelection)
&& block.contains(range.cursor.position())) {
// for full width selections we don't require an actual selection, just
// a position to specify the line. that's more convenience in usage.
QTextLayout::FormatRange o;
QTextLine l = layout->lineForTextPosition(range.cursor.position() - blpos);
o.start = l.textStart();
o.length = l.textLength();
if (o.start + o.length == bllen - 1)
++o.length; // include newline
o.format = range.format;
selections.append(o);
}
}
bool drawCursor = ((editable || (textInteractionFlags() & Qt::TextSelectableByKeyboard))
&& context.cursorPosition >= blpos
&& context.cursorPosition < blpos + bllen);
bool drawCursorAsBlock = drawCursor && overwriteMode() ;
if (drawCursorAsBlock) {
if (context.cursorPosition == blpos + bllen - 1) {
drawCursorAsBlock = false;
} else {
QTextLayout::FormatRange o;
o.start = context.cursorPosition - blpos;
o.length = 1;
o.format.setForeground(palette().base());
o.format.setBackground(palette().text());
selections.append(o);
}
}
layout->draw(&painter, offset, selections, er);
if ((drawCursor && !drawCursorAsBlock)
|| (editable && context.cursorPosition < -1
&& !layout->preeditAreaText().isEmpty())) {
int cpos = context.cursorPosition;
if (cpos < -1)
cpos = layout->preeditAreaPosition() - (cpos + 2);
else
cpos -= blpos;
layout->drawCursor(&painter, offset, cpos, cursorWidth());
}
}
offset.ry() += r.height();
if (offset.y() > viewportRect.height())
break;
block = block.next();
}
if (backgroundVisible() && !block.isValid() && offset.y() <= er.bottom()
&& (centerOnScroll() || verticalScrollBar()->maximum() == verticalScrollBar()->minimum())) {
painter.fillRect(QRect(QPoint((int)er.left(), (int)offset.y()), er.bottomRight()), palette().background());
}
}
void BaseEditor::highlightCurrentLine()
{
currentLineSelection.clear();
if (!isReadOnly())
{
QTextEdit::ExtraSelection selection;
QColor lineColor = QColor::fromRgb(0xC6, 0xE2, 0xFF);
selection.format.setBackground(lineColor);
selection.format.setProperty(QTextFormat::FullWidthSelection, true);
selection.cursor = textCursor();
selection.cursor.clearSelection();;
currentLineSelection.append(selection);
}
updateExtraSelection();
}
void BaseEditor::lineNumberAreaPaintEvent(QPaintEvent *event)
{
QPainter painter(lineNumberArea);
painter.fillRect(event->rect(), QColor::fromRgb(0xEA,0xEA,0xEA));
painter.setFont(document()->defaultFont());
QTextBlock block = firstVisibleBlock();
int blockNumber = block.blockNumber();
int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top();
int bottom = top + (int) blockBoundingRect(block).height();
int height = QFontMetrics(document()->defaultFont()).height();
while(block.isValid() && top <= event->rect().bottom())
{
if (block.isVisible() && bottom >= event->rect().top())
{
QString number = QString::number(blockNumber+1);
painter.setPen(Qt::black);
painter.drawText(0, top, lineNumberArea->width(), height,
Qt::AlignRight, number);
}
block = block.next();
top = bottom;
bottom = top + (int) blockBoundingRect(block).height();
++blockNumber;
}
}
void BaseEditor::updateExtraSelection()
{
setExtraSelections(findTextSelection+currentLineSelection+currentFindSelection+spellCheckErrorSelection);
}
void BaseEditor::findFinished()
{
findTextSelection.clear();
currentFindSelection.clear();
updateExtraSelection();
prevFindCursor = QTextCursor();
finded = false;
}
void BaseEditor::replace(const QString &rt)
{
if(prevFindCursor.isNull())
return;
prevFindCursor.beginEditBlock();
prevFindCursor.insertText(rt);
prevFindCursor.endEditBlock();
}
void BaseEditor::replaceAll(const QString &ft, const QString &rt,
QTextDocument::FindFlags qff, bool isRE)
{
QTextDocument *doc = document();
QTextCursor tc(doc);
QRegExp re(ft);
replacing = true;
while(!tc.isNull() && !tc.atEnd())
{
tc = isRE ? doc->find(re, tc, qff) :
doc->find(ft, tc, qff);
if(!tc.isNull())
{
tc.beginEditBlock();
tc.insertText(rt);
tc.endEditBlock();
}
}
replacing = false;
findAndHighlightText(ft, qff, isRE);
}
void BaseEditor::ensureAtTheLast()
{
QTextCursor tc = textCursor();
if(tc.atEnd())
verticalScrollBar()->setValue(verticalScrollBar()->maximum());
}
void BaseEditor::spellCheck(int start, int unused, int length)
{
Q_UNUSED(unused)
if(length==0)
return;
// qDebug("start %d, length %d", start, length);;
int end = start+length;
bool isInSameBlock=false;
if(start==end)
isInSameBlock = true;
QTextBlock startBlock = document()->findBlock(start);
QTextBlock endBlock = document()->findBlock(end);
if(!endBlock.isValid())
endBlock = document()->lastBlock();
// qDebug("start block %d, end block %d", startBlock.blockNumber(), endBlock.blockNumber());
if(startBlock.blockNumber()==endBlock.blockNumber())
isInSameBlock = true;
spellCheckAux(startBlock);
if(!isInSameBlock){
for(int i=0; i<endBlock.blockNumber()-startBlock.blockNumber(); i++){
spellCheckAux(document()->findBlockByNumber(startBlock.blockNumber()+i+1));
}
}
updateExtraSelection();
}
void BaseEditor::spellCheckAux(const QTextBlock &block)
{
removeExtraSelectionInRange(spellCheckErrorSelection, block.position(), block.position()+block.length());
SpellChecker *spellChecker = mdCharmGlobal->getSpellChecker(spellCheckLanguage);
if(spellChecker==NULL)
return;
SpellCheckResultList resultList = spellChecker->checkString(block.text());
QTextCharFormat spellErrorCharFormat;
spellErrorCharFormat.setUnderlineStyle(QTextCharFormat::WaveUnderline);
spellErrorCharFormat.setUnderlineColor(Qt::darkRed);
for(int i=0; i<resultList.length(); i++){
SpellCheckResult result = resultList.at(i);
QTextCursor errorCursor(block);
errorCursor.setPosition(block.position()+result.start);
errorCursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, result.end-result.start);//select wrong words
QTextEdit::ExtraSelection es;
es.cursor = errorCursor;
es.format = spellErrorCharFormat;
spellCheckErrorSelection.append(es);
}
}
void BaseEditor::checkWholeContent()
{
for(int i=0; i<blockCount(); i++)
spellCheckAux(document()->findBlockByNumber(i));
updateExtraSelection();
}
void BaseEditor::removeExtraSelectionInRange(QList<QTextEdit::ExtraSelection> &extraList, int start, int end)
{
QStack<int> toRemove;
for(int i=0; i<extraList.length(); i++)
{
QTextEdit::ExtraSelection es = extraList.at(i);
QTextCursor tc= es.cursor;
if(tc.selectionStart()>=start && tc.selectionEnd()<=end)
toRemove.push(i);
}
//remove from end to begin
while(!toRemove.isEmpty())
extraList.removeAt(toRemove.pop());
}
| 33.470209 | 144 | 0.613279 | MonkeyMo |
518e20203bcc8f9d82cb17e797fc3152b00959f3 | 860 | cpp | C++ | PAT/A/1046.cpp | zhi2xin1/pat-ans | 740ee6b4d5a8c354bdff012750a615c738d5013e | [
"MIT"
] | null | null | null | PAT/A/1046.cpp | zhi2xin1/pat-ans | 740ee6b4d5a8c354bdff012750a615c738d5013e | [
"MIT"
] | null | null | null | PAT/A/1046.cpp | zhi2xin1/pat-ans | 740ee6b4d5a8c354bdff012750a615c738d5013e | [
"MIT"
] | null | null | null | //#include <iostream>
#include <cstdio>
void writex(int x)
{
if(x>9)
writex(x/10);
putchar(x%10+'0');
}
void readx(int &x)
{
x=0;
char s=getchar();
while(s<'0'||s>'9')
s=getchar();
while(s>='0'&&s<='9'){
x=x*10+s-'0';
s=getchar();
}
}
int main(){
int N,testN,dis[100000],ori,des;
int sum=0,sum_2=0,temp;
readx(N);
for(int i=0;i<N;++i){
readx(temp);
dis[i]=sum;
sum+=temp;
}
sum_2=sum/2;
readx(testN);
for(int i=0;i<testN;++i){
temp=0;
readx(ori);
readx(des);
--ori;
--des;
if(ori<des){
temp=dis[des]-dis[ori];
}
else{
temp=dis[ori]-dis[des];
}
if(temp>sum_2)
temp=sum-temp;
writex(temp);
putchar(10);
}
}
| 16.538462 | 36 | 0.426744 | zhi2xin1 |
518f2b8a9782e9625a56852e3082683a4abb6a53 | 1,811 | cpp | C++ | snowman.cpp | shaiBonfil/CPP-Ex1 | ec9a82b8de9b99e3dd4488781b363ec36c95509e | [
"MIT"
] | null | null | null | snowman.cpp | shaiBonfil/CPP-Ex1 | ec9a82b8de9b99e3dd4488781b363ec36c95509e | [
"MIT"
] | null | null | null | snowman.cpp | shaiBonfil/CPP-Ex1 | ec9a82b8de9b99e3dd4488781b363ec36c95509e | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <stdexcept>
#include <exception>
#include <array>
#include "snowman.hpp"
using namespace std;
using namespace ariel;
const int DEC = 10;
namespace ariel
{
int charToInt(char c) { return c - '0' -1;}
string snowman(long num)
{
// if the input number not equal to 8 digits, this is a invalid input
if (to_string(num).length() != VALID_LEN) { throw invalid_argument("error: invalid input!");}
// if the input is 8 digits, than we check it in the while loop
long tmp = num;
while (tmp != 0)
{
if ((tmp % DEC < 1) || (tmp % DEC > 4))
{
throw invalid_argument("error: invalid input!");
}
tmp /= DEC;
}
string ans;
array <string, VALID_LEN> res;
string str = to_string(num);
int j = 0;
for (int i = 0; i < VALID_LEN; i++)
{
j = charToInt(str.at(i));
res.at(i) = presets.at(i).at(j);
}
ans += res[HAT] + "\n"; // Hat
ans += res[LEFT_ARM].at(up); // Upper Left Arm
ans += "(" + res[LEFT_EYE] + res[NOSE] + res[RIGHT_EYE] + ")"; // Eyes and Nose
ans += res[RIGHT_ARM].at(up); // Upper Right Arm
ans += "\n";
ans += res[LEFT_ARM].at(down); // Lower Left Arm
ans += "(" + res[TORSO] + ")"; // Torso
ans += res[RIGHT_ARM].at(down); // Lower Right Arm
ans += "\n";
ans += space + "(" + res[BASE] + ")" + "\n"; // Base
return ans;
}
}
| 31.224138 | 101 | 0.437327 | shaiBonfil |
519182c69da169c4bf7c10e08b6ca8c09b4b2bf1 | 3,459 | cpp | C++ | code/libs/Object/Object.cpp | marwac-9/MyFramework | 2f8b44ad71fb64bba09b5a5d07822f260e78c39d | [
"Apache-2.0"
] | 3 | 2017-11-27T20:11:43.000Z | 2020-01-26T01:30:05.000Z | code/libs/Object/Object.cpp | marwac-9/MyFramework | 2f8b44ad71fb64bba09b5a5d07822f260e78c39d | [
"Apache-2.0"
] | null | null | null | code/libs/Object/Object.cpp | marwac-9/MyFramework | 2f8b44ad71fb64bba09b5a5d07822f260e78c39d | [
"Apache-2.0"
] | null | null | null | #include "Object.h"
#include "Node.h"
#include "Material.h"
#include <cmath>
#include <algorithm>
#include <math.h>
#include "Component.h"
#include "Bounds.h"
#include "Script.h"
Object::Object()
{
node = &localNode;
localNode.owner = this;
ID = currentID;
currentID++;
bounds = nullptr;
vao = nullptr;
}
Object::~Object()
{
for (auto& component : components)
{
delete component;
}
components.clear();
dynamicComponents.clear();
}
void Object::AssignMaterial(Material* mat, int slot)
{
if (materials.size() == 0) materials.push_back(mat);
else if (materials.size() > slot) materials[slot] = mat;
}
void Object::AddMaterial(Material * mat)
{
materials.push_back(mat);
}
void Object::RemoveMaterial(Material* mat)
{
int index = FindMaterialIndex(mat);
if (index != -1)
{
materials[index] = materials.back();
materials.pop_back();
}
}
std::string & Object::GetName()
{
return name;
}
Object * Object::GetParentObject()
{
return node->parent->owner;
}
Component * Object::GetComponent(const char * componentName)
{
auto component = componentsMap.find(componentName);
if (component != componentsMap.end()) return component->second;
return nullptr;
}
void Object::Update()
{
TopDownTransformF = node->TopDownTransform.toFloat();
}
void Object::UpdateComponents()
{
for (auto& component : dynamicComponents)
{
component->Update();
}
}
void Object::ResetIDs()
{
currentID = 0;
}
unsigned int Object::Count()
{
return currentID;
}
int Object::FindDynamicComponentIndex(Component * componentToFind)
{
for (size_t i = 0; i < dynamicComponents.size(); i++)
{
if (dynamicComponents[i] == componentToFind)
{
return i;
}
}
return -1;
}
int Object::FindComponentIndex(Component * componentToFind)
{
for (size_t i = 0; i < components.size(); i++)
{
if (components[i] == componentToFind)
{
return i;
}
}
return -1;
}
int Object::FindMaterialIndex(Material* materialToFind)
{
for (size_t i = 0; i < materials.size(); i++)
{
if (materials[i] == materialToFind)
{
return i;
}
}
return -1;
}
void Object::LoadLuaFile(const char * filename)
{
std::string directorywithfilename = "resources\\objects\\scripts";
directorywithfilename.append(filename);
directorywithfilename.append(".lua");
script->LoadLuaFile(directorywithfilename.c_str());
}
void Object::AddComponent(Component* newComponent, bool isDynamic)
{
components.push_back(newComponent);
if (isDynamic)
dynamicComponents.push_back(newComponent);
newComponent->Init(this);
}
void Object::SetComponentDynamicState(Component * component, bool isDynamic)
{
if (isDynamic)
{
dynamicComponents.push_back(component);
}
else
{
for (size_t i = 0; i < dynamicComponents.size(); i++)
{
if (component == dynamicComponents[i])
{
dynamicComponents[i] = dynamicComponents.back();
dynamicComponents.pop_back();
return;
}
}
}
}
void Object::RemoveComponent(Component * componentToRemove)
{
int index = FindDynamicComponentIndex(componentToRemove);
if (index != -1)
{
dynamicComponents[index] = dynamicComponents.back();
dynamicComponents.pop_back();
}
index = FindComponentIndex(componentToRemove);
if (index != -1)
{
components[index] = components.back();
components.pop_back();
}
for (auto& componentPair : componentsMap)
{
if (componentPair.second == componentToRemove)
{
componentsMap.erase(componentPair.first);
break;
}
}
}
unsigned int Object::currentID = 0; | 18.109948 | 76 | 0.696733 | marwac-9 |
5192a684fa45d00821c7d4d778a362747585ded9 | 2,376 | hpp | C++ | main/src/vtr_vision/include/vtr_vision/sensors/camera_model_interface.hpp | utiasASRL/vtr3 | b4edca56a19484666d3cdb25a032c424bdc6f19d | [
"Apache-2.0"
] | 32 | 2021-09-15T03:42:42.000Z | 2022-03-26T10:40:01.000Z | main/src/vtr_vision/include/vtr_vision/sensors/camera_model_interface.hpp | shimp-t/vtr3 | bdcad784ffe26fabfa737d0e195bcb3bacb930c3 | [
"Apache-2.0"
] | 7 | 2021-09-18T19:18:15.000Z | 2022-02-02T11:15:40.000Z | main/src/vtr_vision/include/vtr_vision/sensors/camera_model_interface.hpp | shimp-t/vtr3 | bdcad784ffe26fabfa737d0e195bcb3bacb930c3 | [
"Apache-2.0"
] | 7 | 2021-09-18T01:31:28.000Z | 2022-03-14T05:09:37.000Z | // Copyright 2021, Autonomous Space Robotics Lab (ASRL)
//
// 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.
/**
* \file camera_model_interface.hpp
* \brief Header file for the ASRL vision package
* \details
*
* \author Kirk MacTavish, Autonomous Space Robotics Lab (ASRL)
*/
#pragma once
#include <iostream>
#include <vtr_vision/sensors/sensor_model_types.hpp>
#include <vtr_vision/types.hpp>
namespace vtr {
namespace vision {
////////////////////////////////////////////////////////////////////
/// @brief This class provides the base interface for vision sensors
///
/// @details
////////////////////////////////////////////////////////////////////
template <typename M, typename C>
class CameraModelInterface {
public:
//
typedef std::shared_ptr<CameraModelInterface> Ptr;
////////////////////////////////////////////////////////////////////
/// @brief Verify the points that will be used for model evaluations
/// @param [in] matches The matches to verify
/// @return true if the matches are acceptable
////////////////////////////////////////////////////////////////////
virtual bool verifyMatches(const SimpleMatches& matches) const = 0;
////////////////////////////////////////////////////////////////////
/// @brief Set the points that will be used for model evaluations (owned by
/// user)
/// @param [in] pts_ref The points seen at the reference frame
/// @param [in] pts_query The points seen at the query frame
////////////////////////////////////////////////////////////////////
virtual void setPoints(const M* pts_ref, const C* pts_query) {
// Save to members
pts_ref_ = pts_ref;
pts_query_ = pts_query;
}
protected:
/// @brief The points from the reference frame
const M* pts_ref_;
/// @brief The points from frame b
const C* pts_query_;
};
} // namespace vision
} // namespace vtr
| 33 | 77 | 0.593855 | utiasASRL |
519a541e25f3b56b8474e43831e07c6e2093de86 | 6,635 | cpp | C++ | src/alns/SRP-Utils/ArgParser.cpp | alberto-santini/cvrp-decomposition | 854d2b5b7cdd51fe4ab46acac7d88dbc7e5bfb88 | [
"MIT"
] | null | null | null | src/alns/SRP-Utils/ArgParser.cpp | alberto-santini/cvrp-decomposition | 854d2b5b7cdd51fe4ab46acac7d88dbc7e5bfb88 | [
"MIT"
] | null | null | null | src/alns/SRP-Utils/ArgParser.cpp | alberto-santini/cvrp-decomposition | 854d2b5b7cdd51fe4ab46acac7d88dbc7e5bfb88 | [
"MIT"
] | null | null | null | // ***************************************************************************************
// * ArgParser.cpp
// *
// * Author: Stefan Ropke
// ***************************************************************************************
#include "ArgParser.h"
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
// ***************************************************************************************
// * void ArgParser::parseCmdLine(const string &strExpectedArgs, int argc, char *argv[ ])
// *
// * Parses the "command line" given as parameters <argc> and <argv> (it is expected that
// * <argc> and <argv> are the std. "main(...)" parameters), and stores the result internally
// * in the object.
// *
// * The method is inspired by the "getopts" method in Perl. The function parses
// * command lines like:
// * myprogram -f 10 -p5 -F -r help.txt
// *
// * --- input parameters ---
// * strExpectedArgs : A string that specifies the flags or switches to look for. In the example
// * <strExpectedArgs> could be "f:p:r:F" which is interpretted as:
// * look for "-f" followed by a parameter, look for "-p" followed by a parameter
// * look for "-r" followed by a parameter, look for "-F" _not_ followed by a parameter
// * (notice that there are no ":" after F in "f:p:r:F").
// * The method is quite stupid so you should probably be carefull with "-" characters
// * in the parameters following a switch.
// * If the method is called with <strExpectedArgs> = "f:p:r:F" and <argc> and <argv>
// * is defined by the example command line shown above then an internal map is built
// * that would contain the following bindings:
// *
// * 'f' -> "10"
// * 'p' -> "5"
// * 'F' -> ""
// * 'r' -> "help.txt"
// *
// * Notice that the switches must be single-characters.
// * --- return values ---
// ***************************************************************************************
void ArgParser::parseCmdLine(const string& strExpectedArgs, int argc, char* argv[]) {
mapArguments.clear();
int i = 0;
while(i < (int)strExpectedArgs.size()) {
bool bParameterExpected = false;
char cSwitch = strExpectedArgs[i];
i++;
if(i < (int)strExpectedArgs.size() && strExpectedArgs[i] == ':') {
bParameterExpected = true;
i++;
}
// search after the switch:
for(int j = 1; j < argc; j++) {
// Notice that we do not run into problems when argv[j] only contain one char (we might fear array-out-of-bound errors)
// The reason is that the argv[j] strings are zero terminated.
if((argv[j])[0] == '-' && (argv[j])[1] == cSwitch) {
string strPar = "";
// switch found:
if(bParameterExpected) {
if((argv[j])[2] != 0)
strPar = string(argv[j] + 2);
else {
if(j + 1 < argc)
strPar = string(argv[j + 1]);
}
}
mapArguments.insert(pair<char, string>(cSwitch, strPar));
}
}
}
}
void ArgParser::writeParams(ostream& os, int argc, char* argv[]) const {
for(int j = 1; j < argc; j++)
os << argv[j] << " ";
}
// ***************************************************************************************
// * bool ArgParser::getArg(char cArg, string &strValue) const
// *
// * gets a parameter from the parsed command line.
// *
// * --- input parameters ---
// * cArg : The switch we are looking for
// * --- output parameters ---
// * strValue : The parameter is returned through this parameter (nice sentence eh?).
// * --- return value: ---
// * true => the switch was found.
// * false => switch not found.
// ***************************************************************************************
bool ArgParser::getArg(char cArg, string& strValue) const {
map<char, string>::const_iterator itMap = mapArguments.find(cArg);
if(itMap != mapArguments.end()) {
strValue = itMap->second;
return true;
} else
return false;
}
// ***************************************************************************************
// * bool ArgParser::getArg(char cArg, int &iValue) const
// *
// * gets an integer parameter from the parsed command line.
// *
// * --- input parameters ---
// * cArg : The switch we are looking for
// * --- output parameters ---
// * iValue : The parameter is returned through this parameter (nice sentence eh?).
// * --- return value: ---
// * true => the parameter was found.
// * false => parameter not found.
// ***************************************************************************************
bool ArgParser::getIntArg(char cArg, int& iValue) const {
string str;
if(getArg(cArg, str)) {
iValue = atoi(str.c_str());
return true;
} else
return false;
}
// ***************************************************************************************
// * bool ArgParser::getArg(char cArg, double &dValue) const
// *
// * gets a double parameter from the parsed command line.
// *
// * --- input parameters ---
// * cArg : The switch we are looking for
// * --- output parameters ---
// * dValue : The parameter is returned through this parameter.
// * --- return value: ---
// * true => the parameter was found.
// * false => parameter not found.
// ***************************************************************************************
bool ArgParser::getDoubleArg(char cArg, double& dValue) const {
string str;
if(getArg(cArg, str)) {
dValue = atof(str.c_str());
return true;
} else
return false;
}
// ***************************************************************************************
// * bool ArgParser::hasArg(char cArg) const
// *
// * Checks if a specific argument was used on the command line.
// *
// * --- input parameters ---
// * cArg : The switch we are looking for
// * --- output parameters ---
// * --- return value: ---
// * true => the parameter was found.
// * false => parameter not found.
// ***************************************************************************************
bool ArgParser::hasArg(char cArg) const {
string str;
if(getArg(cArg, str))
return true;
else
return false;
}
| 38.575581 | 132 | 0.468124 | alberto-santini |
519c8414d40a3fa45c2df6ce968f3963980d1edd | 2,252 | cpp | C++ | Kernel/FileSystem/Custody.cpp | JamiKettunen/serenity | 232da5cc188496f570ef55276a897f1095509c87 | [
"BSD-2-Clause"
] | 3 | 2020-05-01T02:39:03.000Z | 2021-11-26T08:34:54.000Z | Kernel/FileSystem/Custody.cpp | JamiKettunen/serenity | 232da5cc188496f570ef55276a897f1095509c87 | [
"BSD-2-Clause"
] | 8 | 2019-08-25T12:52:40.000Z | 2019-09-08T14:46:11.000Z | Kernel/FileSystem/Custody.cpp | JamiKettunen/serenity | 232da5cc188496f570ef55276a897f1095509c87 | [
"BSD-2-Clause"
] | 1 | 2021-08-03T13:04:49.000Z | 2021-08-03T13:04:49.000Z | #include <AK/HashTable.h>
#include <AK/StringBuilder.h>
#include <Kernel/FileSystem/Custody.h>
#include <Kernel/FileSystem/Inode.h>
#include <Kernel/Lock.h>
static Lockable<InlineLinkedList<Custody>>& all_custodies()
{
static Lockable<InlineLinkedList<Custody>>* list;
if (!list)
list = new Lockable<InlineLinkedList<Custody>>;
return *list;
}
Custody* Custody::get_if_cached(Custody* parent, const StringView& name)
{
LOCKER(all_custodies().lock());
for (auto& custody : all_custodies().resource()) {
if (custody.is_deleted())
continue;
if (custody.is_mounted_on())
continue;
if (custody.parent() == parent && custody.name() == name)
return &custody;
}
return nullptr;
}
NonnullRefPtr<Custody> Custody::get_or_create(Custody* parent, const StringView& name, Inode& inode)
{
if (RefPtr<Custody> cached_custody = get_if_cached(parent, name)) {
if (&cached_custody->inode() != &inode) {
dbg() << "WTF! Cached custody for name '" << name << "' has inode=" << cached_custody->inode().identifier() << ", new inode=" << inode.identifier();
}
ASSERT(&cached_custody->inode() == &inode);
return *cached_custody;
}
return create(parent, name, inode);
}
Custody::Custody(Custody* parent, const StringView& name, Inode& inode)
: m_parent(parent)
, m_name(name)
, m_inode(inode)
{
LOCKER(all_custodies().lock());
all_custodies().resource().append(this);
}
Custody::~Custody()
{
LOCKER(all_custodies().lock());
all_custodies().resource().remove(this);
}
String Custody::absolute_path() const
{
Vector<const Custody*, 32> custody_chain;
for (auto* custody = this; custody; custody = custody->parent())
custody_chain.append(custody);
StringBuilder builder;
for (int i = custody_chain.size() - 2; i >= 0; --i) {
builder.append('/');
builder.append(custody_chain[i]->name().characters());
}
return builder.to_string();
}
void Custody::did_delete(Badge<VFS>)
{
m_deleted = true;
}
void Custody::did_mount_on(Badge<VFS>)
{
m_mounted_on = true;
}
void Custody::did_rename(Badge<VFS>, const String& name)
{
m_name = name;
}
| 27.13253 | 160 | 0.641208 | JamiKettunen |
51a11b456e88c5fe9d91740290cd4872e0c939a2 | 6,113 | cpp | C++ | CPP/Targets/SupportWFLib/symbian/MapLibSymbianUtil.cpp | wayfinder/Wayfinder-S60-Navigator | 14d1b729b2cea52f726874687e78f17492949585 | [
"BSD-3-Clause"
] | 6 | 2015-12-01T01:12:33.000Z | 2021-07-24T09:02:34.000Z | CPP/Targets/SupportWFLib/symbian/MapLibSymbianUtil.cpp | wayfinder/Wayfinder-S60-Navigator | 14d1b729b2cea52f726874687e78f17492949585 | [
"BSD-3-Clause"
] | null | null | null | CPP/Targets/SupportWFLib/symbian/MapLibSymbianUtil.cpp | wayfinder/Wayfinder-S60-Navigator | 14d1b729b2cea52f726874687e78f17492949585 | [
"BSD-3-Clause"
] | 2 | 2017-02-02T19:31:29.000Z | 2018-12-17T21:00:45.000Z | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
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 Vodafone Group Services Ltd 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.
*/
#include "MapLibSymbianUtil.h"
#include "DBufRequester.h"
#include "MapLib.h"
#include "SharedBuffer.h"
#include "SymbianMFDBufRequester.h"
#include "WFDRMUtil.h"
#include "WFTextUtil.h"
#include <f32file.h>
namespace {
_LIT(KPrecachedMapsWildcard, "wf-map-*");
_LIT(KPrecachedWarezMapsWildcard, "wf-wmap-*");
_LIT(KPrecachedMapsDir, "\\shared\\");
}
bool
MapLibSymbianUtil::insertPrecachedMapsL( RFs& serv,
MapLib& maplib,
const TDesC& userName,
int findWarez )
{
// Non-empty username needed if not warez to be found.
if ( userName.Length() == 0 && !findWarez ) {
return false;
}
// Copied from old func.
TBuf8<64> userNameAs8bit;
const char* uid = NULL;
// Use uid if not finding warez. NULL means warez to MapLib
if ( ! findWarez ) {
userNameAs8bit.Copy( userName );
uid = reinterpret_cast<const char*>(userNameAs8bit.PtrZ());
}
// Also copied
TFindFile finder(serv);
TInt retval;
CDir * file_list;
if ( findWarez ) {
retval = finder.FindWildByDir(KPrecachedWarezMapsWildcard,
KPrecachedMapsDir, file_list);
} else {
retval = finder.FindWildByDir(KPrecachedMapsWildcard,
KPrecachedMapsDir, file_list);
}
while (retval==KErrNone) {
for ( TInt i=0; i<file_list->Count(); ++i ) {
TParse fn;
fn.Set((*file_list)[i].iName, & (finder.File()), NULL);
// A new matching file name
char* utf8File = WFTextUtil::TDesCToUtf8LC( fn.FullName() );
maplib.addMultiFileCache( utf8File, uid );
// Delete
CleanupStack::PopAndDestroy( utf8File );
}
retval = finder.FindWild(file_list);
}
return true;
}
bool
MapLibSymbianUtil::insertPrecachedMapsAsParentsL( RFs& serv,
DBufRequester* topReq,
TDesC& userName,
int findWarez,
SharedBuffer** xorBuffer,
MemTracker* memTracker )
{
// Non-empty username needed.
if ( userName.Length() == 0 ) {
return false;
}
TBuf8<64> userNameAs8bit;
userNameAs8bit.Copy( userName );
TFindFile* finder = new (ELeave) TFindFile(serv);
TInt retval;
CDir * file_list;
if ( findWarez ) {
retval = finder->FindWildByDir(KPrecachedWarezMapsWildcard,
KPrecachedMapsDir, file_list);
} else {
retval = finder->FindWildByDir(KPrecachedMapsWildcard,
KPrecachedMapsDir, file_list);
}
//
// Create "encryption" buffer
if ( ! findWarez ) {
SharedBuffer tmpBuf( (byte*)(userNameAs8bit.Ptr()),
userNameAs8bit.Length());
if ( *xorBuffer == NULL ) {
*xorBuffer = WFDRMUtil::createXorKey( tmpBuf );
}
} else {
// Warez-buffer.
const char * tmpstr2 = "ueaag4ha58op0q4yX897t478ufjuf";
SharedBuffer tmpBuf2( (byte*)tmpstr2, strlen(tmpstr2));
if ( *xorBuffer == NULL ) {
*xorBuffer = WFDRMUtil::createXorKey( tmpBuf2 );
}
}
DBufRequester* curParent = topReq->getParent();
while (retval==KErrNone) {
for ( TInt i=0; i<file_list->Count(); ++i ) {
TParse fn;
fn.Set((*file_list)[i].iName, & (finder->File()), NULL);
// A new matching file name
SymbianMFDBufRequester * newReq =
new SymbianMFDBufRequester( curParent,
serv,
fn.FullName(),
memTracker,
0,
true);
// Set "encryption" buffer for the requester (owned by us)
newReq->setXorBuffer( *xorBuffer );
curParent = newReq;
}
retval = finder->FindWild(file_list);
}
topReq->setParent( curParent );
delete finder; // Wasn't done in VectorMapContainer. Hope it works.
return true;
}
| 37.048485 | 207 | 0.576967 | wayfinder |
51a770d702d9941335e5f76d102645410ce4252d | 2,863 | hpp | C++ | include/aw/graphics/core/pixelFormat.hpp | AlexAUT/rocketWar | edea1c703755e198b1ad8909c82e5d8d56c443ef | [
"MIT"
] | null | null | null | include/aw/graphics/core/pixelFormat.hpp | AlexAUT/rocketWar | edea1c703755e198b1ad8909c82e5d8d56c443ef | [
"MIT"
] | null | null | null | include/aw/graphics/core/pixelFormat.hpp | AlexAUT/rocketWar | edea1c703755e198b1ad8909c82e5d8d56c443ef | [
"MIT"
] | null | null | null | #pragma once
#include <cmath>
namespace aw
{
enum class PixelFormat
{
// uint8's
R8,
RG8,
RGB8,
RGBA8,
// Floats
RFloat,
RGFloat,
RGBFloat,
RGBAFloat,
// ETC2
RGB_ETC2,
RGBA1_ETC2,
RGBA_ETC2,
// Depth
Depth16,
Depth24,
DepthFloat,
// Depth/Stencil
Depth24Stencil8,
DepthFloatStencil8
};
inline constexpr unsigned pixelFormatToChannelCount(PixelFormat format);
inline constexpr unsigned pixelFormatToImageSize(PixelFormat format, int w, int h);
inline constexpr bool isPixelFormatCompressed(PixelFormat format);
inline constexpr unsigned pixelFormatToChannelCount(PixelFormat format)
{
switch (format)
{
// uint8's
case PixelFormat::R8:
return 1;
case PixelFormat::RG8:
return 2;
case PixelFormat::RGB8:
return 3;
case PixelFormat::RGBA8:
return 4;
// floats
case PixelFormat::RFloat:
return 1;
case PixelFormat::RGFloat:
return 2;
case PixelFormat::RGBFloat:
return 3;
case PixelFormat::RGBAFloat:
return 4;
// ETC2
case PixelFormat::RGB_ETC2:
return 3;
case PixelFormat::RGBA1_ETC2:
return 4;
case PixelFormat::RGBA_ETC2:
return 4;
// Depth
case PixelFormat::Depth16:
[[fallthrough]];
case PixelFormat::Depth24:
[[fallthrough]];
case PixelFormat::DepthFloat:
return 1;
// Depth Stencil
case PixelFormat::Depth24Stencil8:
[[fallthrough]];
case PixelFormat::DepthFloatStencil8:
return 2;
}
return 0;
}
inline constexpr unsigned pixelFormatToImageSize(PixelFormat format, int w, int h)
{
auto numChannels = pixelFormatToChannelCount(format);
switch (format)
{
// uint8's
case PixelFormat::R8:
case PixelFormat::RG8:
case PixelFormat::RGB8:
case PixelFormat::RGBA8:
return w * h * numChannels;
// floats
case PixelFormat::RFloat:
case PixelFormat::RGFloat:
case PixelFormat::RGBFloat:
case PixelFormat::RGBAFloat:
return w * h * numChannels * sizeof(float);
// ETC2
case PixelFormat::RGB_ETC2:
return std::ceil(w / 4) * std::ceil(h / 4) * 8;
case PixelFormat::RGBA_ETC2:
return std::ceil(w / 4) * std::ceil(h / 4) * 8;
case PixelFormat::RGBA1_ETC2:
return std::ceil(w / 4) * std::ceil(h / 4) * 16;
// Depth
case PixelFormat::Depth16:
return w * h * 2;
case PixelFormat::Depth24:
return w * h * 3;
case PixelFormat::DepthFloat:
return w * h * sizeof(float);
// Depth Stencil
case PixelFormat::Depth24Stencil8:
return w * h * 4;
case PixelFormat::DepthFloatStencil8:
return w * h * (sizeof(float) + 1);
}
return 0;
}
inline constexpr bool isPixelFormatCompressed(PixelFormat format)
{
switch (format)
{
case PixelFormat::RGB_ETC2:
[[fallthrough]];
case PixelFormat::RGBA_ETC2:
[[fallthrough]];
case PixelFormat::RGBA1_ETC2:
return true;
default:
return false;
}
}
} // namespace aw
| 20.746377 | 83 | 0.680405 | AlexAUT |
51a893e8356e179e9f3ec430ccbeb4428588cdca | 3,004 | cpp | C++ | test/ZDAMessageParse_Test.cpp | neuralsandwich/NMEAParser | 3bd29601b048b091745312f8a214ab454335c94c | [
"MIT"
] | 1 | 2020-07-19T15:25:57.000Z | 2020-07-19T15:25:57.000Z | test/ZDAMessageParse_Test.cpp | neuralsandwich/NMEAParser | 3bd29601b048b091745312f8a214ab454335c94c | [
"MIT"
] | null | null | null | test/ZDAMessageParse_Test.cpp | neuralsandwich/NMEAParser | 3bd29601b048b091745312f8a214ab454335c94c | [
"MIT"
] | 1 | 2020-07-19T15:33:28.000Z | 2020-07-19T15:33:28.000Z | //===-- ZDAMessageParse_Test.cpp --------------------------------*- C++ -*-===//
//
// This file is distributed uner the MIT license. See LICENSE.txt for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// Functional tests for Parsing ZDA Messages
///
//===----------------------------------------------------------------------===//
#include "NMEAParser.h"
#include "gtest/gtest.h"
namespace NMEA {
TEST(ZDAMessageParse, Valid_Message) {
const std::string RawMessage = "$GPZDA,082710.00,16,09,2002,00,00*64";
time_t ExpectedTimestamp = 0;
struct tm *TimeInfo;
std::time(&ExpectedTimestamp);
TimeInfo = gmtime(&ExpectedTimestamp);
TimeInfo->tm_hour = 8;
TimeInfo->tm_min = 27;
TimeInfo->tm_sec = 10;
TimeInfo->tm_mday = 16;
TimeInfo->tm_mon = 8;
TimeInfo->tm_year = 102;
ExpectedTimestamp = mktime(TimeInfo);
GPZDA Message = {
.TimeStamp = ExpectedTimestamp, .LocalHours = 0, .LocalMinutes = 0};
NMEAMessage Expected = {NMEA_TALKER_ID::GPS, NMEA_MESSAGE_TYPE::ZDA, 1,
.ZDA = &Message};
auto Parser = NMEAParser{};
auto Result = Parser.Parse(RawMessage);
// Compare Headers
EXPECT_EQ(Expected.ID, Result->ID) << "Talker ID is incorrect";
EXPECT_EQ(Expected.Type, Result->Type) << "Message type is incorrect";
EXPECT_EQ(Expected.Valid, Result->Valid)
<< "Message valid status is incorrect";
// Compate Messages
EXPECT_EQ(Expected.ZDA->TimeStamp, Result->ZDA->TimeStamp);
EXPECT_EQ(Expected.ZDA->LocalHours, Result->ZDA->LocalHours);
EXPECT_EQ(Expected.ZDA->LocalMinutes, Result->ZDA->LocalMinutes);
}
TEST(ZDAMessageParse, Invalid_Message) {
const std::string RawMessage =
"$GPZDA,082710.00,16,09,,12,4,123401924,00,00*64";
NMEAMessage Expected = {NMEA_TALKER_ID::UNKNOWN_TALKER_ID,
NMEA_MESSAGE_TYPE::UNKNOWN_MESSAGE,
0,
{}};
auto Parser = NMEAParser{};
auto Result = Parser.Parse(RawMessage);
// Compare Headers
EXPECT_EQ(Expected.ID, Result->ID) << "Talker ID is incorrect";
EXPECT_EQ(Expected.Type, Result->Type) << "Message type is incorrect";
EXPECT_EQ(Expected.Valid, Result->Valid)
<< "Message valid status is incorrect";
// Compare Message
EXPECT_EQ(Expected.ZDA, Result->ZDA);
}
TEST(ZDAMessageParse, Empty_Message) {
const std::string RawMessage = "";
NMEAMessage Expected = {NMEA_TALKER_ID::UNKNOWN_TALKER_ID,
NMEA_MESSAGE_TYPE::UNKNOWN_MESSAGE,
0,
{}};
auto Parser = NMEAParser{};
auto Result = Parser.Parse(RawMessage);
// Compare Headers
EXPECT_EQ(Expected.ID, Result->ID) << "Talker ID is incorrect";
EXPECT_EQ(Expected.Type, Result->Type) << "Message type is incorrect";
EXPECT_EQ(Expected.Valid, Result->Valid)
<< "Message valid status is incorrect";
// Compare Message
EXPECT_EQ(Expected.ZDA, Result->ZDA);
}
};
| 31.957447 | 80 | 0.616844 | neuralsandwich |
51a964727efe7d4f643c07a0e40b1e3f327b6152 | 4,518 | cc | C++ | course/test/src/isometry_TEST.cc | Lobotuerk/cppl1_q12020 | b93cf3adbd153fe6747a7bcf44dd8fea081ec26a | [
"Apache-2.0"
] | null | null | null | course/test/src/isometry_TEST.cc | Lobotuerk/cppl1_q12020 | b93cf3adbd153fe6747a7bcf44dd8fea081ec26a | [
"Apache-2.0"
] | 3 | 2020-03-12T12:58:58.000Z | 2020-04-27T01:56:30.000Z | course/test/src/isometry_TEST.cc | Lobotuerk/cppl1_q12020 | b93cf3adbd153fe6747a7bcf44dd8fea081ec26a | [
"Apache-2.0"
] | null | null | null | // This file describes a challenge of a C++ L1 Padawan. The goal
// of this unit test is to suggest an API and the abstractions
// needed to implement an isometry.
// Consider including other header files if needed.
// Copyright 2020 <Jose Tomas Lorente>
#include <cmath>
#include <sstream>
#include <string>
#include "gtest/gtest.h"
#include <isometry/isometry.hpp>
namespace ekumen {
namespace math {
namespace test {
namespace {
testing::AssertionResult areAlmostEqual(const Isometry & obj1,
const Isometry & obj2, const double tolerance) {
if (std::abs(obj1.translation()[0] - obj2.translation()[0]) > tolerance ||
std::abs(obj1.translation()[1] - obj2.translation()[1]) > tolerance ||
std::abs(obj1.translation()[2] - obj2.translation()[2]) > tolerance ||
std::abs(obj1.rotation()[0][0] - obj2.rotation()[0][0]) > tolerance ||
std::abs(obj1.rotation()[0][1] - obj2.rotation()[0][1]) > tolerance ||
std::abs(obj1.rotation()[0][2] - obj2.rotation()[0][2]) > tolerance ||
std::abs(obj1.rotation()[1][0] - obj2.rotation()[1][0]) > tolerance ||
std::abs(obj1.rotation()[1][1] - obj2.rotation()[1][1]) > tolerance ||
std::abs(obj1.rotation()[1][2] - obj2.rotation()[1][2]) > tolerance ||
std::abs(obj1.rotation()[2][0] - obj2.rotation()[2][0]) > tolerance ||
std::abs(obj1.rotation()[2][1] - obj2.rotation()[2][1]) > tolerance ||
std::abs(obj1.rotation()[2][2] - obj2.rotation()[2][2]) > tolerance) {
return testing::AssertionFailure() <<
"The isometrys are not almost equal";
}
return testing::AssertionSuccess();
}
testing::AssertionResult areAlmostEqual(const Matrix3 & obj1,
const Matrix3 & obj2, const double tolerance) {
if (std::abs(obj1[0][0] - obj2[0][0]) > tolerance ||
std::abs(obj1[0][1] - obj2[0][1]) > tolerance ||
std::abs(obj1[0][2] - obj2[0][2]) > tolerance ||
std::abs(obj1[1][0] - obj2[1][0]) > tolerance ||
std::abs(obj1[1][1] - obj2[1][1]) > tolerance ||
std::abs(obj1[1][2] - obj2[1][2]) > tolerance ||
std::abs(obj1[2][0] - obj2[2][0]) > tolerance ||
std::abs(obj1[2][1] - obj2[2][1]) > tolerance ||
std::abs(obj1[2][2] - obj2[2][2]) > tolerance) {
return testing::AssertionFailure() <<
"The isometrys are not almost equal";
}
return testing::AssertionSuccess();
}
GTEST_TEST(IsometryTest, IsometryFullTests) {
const double kTolerance{1e-12};
const Isometry t1 = Isometry::FromTranslation(Vector3{1., 2., 3.});
const Isometry t2{Vector3{1., 2., 3.}, Matrix3::kIdentity};
EXPECT_EQ(t1, t2);
// This is not mathematically correct but it could be a nice to have.
EXPECT_EQ(t1 * Vector3(1., 1., 1.), Vector3(2., 3., 4.));
EXPECT_EQ(t1.transform(Vector3(std::initializer_list<double>({1., 1., 1.}))),
Vector3(2., 3., 4.));
EXPECT_EQ(t1.inverse() * Vector3(2., 3., 4.), Vector3(1., 1., 1.));
EXPECT_EQ(t1 * t2 * Vector3(1., 1., 1.), Vector3(3., 5., 7.));
EXPECT_EQ(t1.compose(t2) * Vector3(1., 1., 1.), Vector3(3., 5., 7.));
// Composes rotations.
const Isometry t3{Isometry::RotateAround(Vector3::kUnitX, M_PI / 2.)};
const Isometry t4{Isometry::RotateAround(Vector3::kUnitY, M_PI / 4.)};
const Isometry t5{Isometry::RotateAround(Vector3::kUnitZ, M_PI / 8.)};
const Isometry t6{Isometry::FromEulerAngles(M_PI / 2., M_PI / 4., M_PI / 8.)};
EXPECT_TRUE(areAlmostEqual(t6, t3 * t4 * t5, kTolerance));
EXPECT_EQ(t3.translation(), Vector3::kZero);
const double pi_8{M_PI / 8.};
const double cpi_8{std::cos(pi_8)}; // 0.923879532
const double spi_8{std::sin(pi_8)}; // 0.382683432
EXPECT_TRUE(areAlmostEqual(t5.rotation(),
Matrix3{cpi_8, -spi_8, 0., spi_8, cpi_8, 0., 0., 0., 1.}, kTolerance));
std::stringstream ss;
ss << t5;
std::string answer = "[T: (x: 0, y: 0, z: 0), ";
answer += "R:[[0.923879533, -0.382683432, 0],";
answer += " [0.382683432, 0.923879533, 0], [0, 0, 1]]]";
EXPECT_EQ(ss.str(), answer);
Isometry t7;
EXPECT_EQ(t7.rotation()[2][2], 0);
EXPECT_EQ(t7.translation()[2], 0);
Isometry t8 = Isometry();
EXPECT_EQ(t8.rotation()[2][2], 0);
EXPECT_EQ(t8.translation()[2], 0);
Isometry t9 = Isometry::FromTranslation(Vector3{1., 2., 3.});
const Isometry t10{Vector3{2., 4., 6.}, Matrix3::kIdentity};
EXPECT_EQ(t9 *= t2, t10);
EXPECT_EQ(t9 * Vector3(1., 1., 1.), Vector3(3., 5., 7.));
}
} // namespace
} // namespace test
} // namespace math
} // namespace ekumen
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 38.615385 | 80 | 0.629925 | Lobotuerk |
51b0b992e3e5aca3632a14fef04fb59f1e78ab55 | 2,388 | hpp | C++ | WICWIU_src/Module/GRULayer.hpp | ChanhyoLee/TextDataset | 397571f476a89ad42ef3ed77b82c76fc19ac3e33 | [
"Apache-2.0"
] | null | null | null | WICWIU_src/Module/GRULayer.hpp | ChanhyoLee/TextDataset | 397571f476a89ad42ef3ed77b82c76fc19ac3e33 | [
"Apache-2.0"
] | null | null | null | WICWIU_src/Module/GRULayer.hpp | ChanhyoLee/TextDataset | 397571f476a89ad42ef3ed77b82c76fc19ac3e33 | [
"Apache-2.0"
] | null | null | null | #ifndef __GRU_LAYER__
#define __GRU_LAYER__ value
#include "../Module.hpp"
template<typename DTYPE> class GRULayer : public Module<DTYPE>{
private:
public:
GRULayer(Operator<DTYPE> *pInput, int inputsize, int hiddensize, int outputsize, int use_bias = TRUE, std::string pName = "No Name") : Module<DTYPE>(pName) {
Alloc(pInput, inputsize, hiddensize, outputsize, use_bias, pName);
}
virtual ~GRULayer() {}
int Alloc(Operator<DTYPE> *pInput, int inputsize, int hiddensize, int outputsize, int use_bias, std::string pName) {
this->SetInput(pInput);
Operator<DTYPE> *out = pInput;
//weight
Tensorholder<DTYPE> *pWeightIG = new Tensorholder<DTYPE>(Tensor<DTYPE>::Random_normal(1, 1, 1, 2*hiddensize, inputsize, 0.0, 0.01), "LSTMLayer_pWeight_IG_" + pName);
Tensorholder<DTYPE> *pWeightHG = new Tensorholder<DTYPE>(Tensor<DTYPE>::Random_normal(1, 1, 1, 2*hiddensize, hiddensize, 0.0, 0.01), "LSTMLayer_pWeight_HG_" + pName);
Tensorholder<DTYPE> *pWeightICH = new Tensorholder<DTYPE>(Tensor<DTYPE>::Random_normal(1, 1, 1, hiddensize, inputsize, 0.0, 0.01), "LSTMLayer_pWeight_HG_" + pName);
Tensorholder<DTYPE> *pWeightHCH = new Tensorholder<DTYPE>(Tensor<DTYPE>::Random_normal(1, 1, 1, hiddensize, hiddensize, 0.0, 0.01), "LSTMLayer_pWeight_HG_" + pName);
//Hidden to output weight
Tensorholder<DTYPE> *pWeight_h2o = new Tensorholder<DTYPE>(Tensor<DTYPE>::Random_normal(1, 1, 1, outputsize, hiddensize, 0.0, 0.01), "LSTMLayer_pWeight_HO_" + pName);
//bias
Tensorholder<DTYPE> *gBias = new Tensorholder<DTYPE>(Tensor<DTYPE>::Constants(1, 1, 1, 1, 2*hiddensize, 0.f), "RNN_Bias_f" + pName);
Tensorholder<DTYPE> *chBias = new Tensorholder<DTYPE>(Tensor<DTYPE>::Constants(1, 1, 1, 1, hiddensize, 0.f), "RNN_Bias_f" + pName);
out = new GRU<DTYPE>(out, pWeightIG, pWeightHG, pWeightICH, pWeightHCH, gBias, chBias);
out = new MatMul<DTYPE>(pWeight_h2o, out, "rnn_matmul_ho");
if (use_bias) {
Tensorholder<DTYPE> *pBias = new Tensorholder<DTYPE>(Tensor<DTYPE>::Constants(1, 1, 1, 1, outputsize, 0.f), "Add_Bias_" + pName);
out = new AddColWise<DTYPE>(out, pBias, "Layer_Add_" + pName);
}
this->AnalyzeGraph(out);
return TRUE;
}
};
#endif
| 47.76 | 175 | 0.657035 | ChanhyoLee |
51b4a7eacab4f9c03d9a1229d8b71afb3286bf5e | 4,280 | hh | C++ | Shared/BrainCloudCompletionBlocks.hh | davidstl/braincloud-objc | 42e9376cba1c3ef1231a5f74e1c5c66442a34779 | [
"Apache-2.0"
] | null | null | null | Shared/BrainCloudCompletionBlocks.hh | davidstl/braincloud-objc | 42e9376cba1c3ef1231a5f74e1c5c66442a34779 | [
"Apache-2.0"
] | 1 | 2019-11-30T17:08:15.000Z | 2019-11-30T17:08:15.000Z | Shared/BrainCloudCompletionBlocks.hh | OrbiLabs/braincloud-objc | b5b63f98e339582e7819e1b765abfb28bcaccbeb | [
"Apache-2.0"
] | null | null | null | //
// BrainCloudCompletionBlocks.h
// brainCloudClientObjc
//
// Created by Ryan Homer on 30/4/2015.
// Copyright (c) 2016 bitHeads. All rights reserved.
//
#ifndef brainCloudClientObjc_BrainCloudCompletionBlocks_h
#define brainCloudClientObjc_BrainCloudCompletionBlocks_h
#import <Foundation/Foundation.h>
typedef NSObject *BCCallbackObject;
/**
* Completion block called when an api completes successfully.
*
* @param serviceName The service name of the api call (see ServiceName.hh)
* @param serviceOperation The service operation of the api call (see ServiceOperation.hh)
* @param jsonData The returned JSON data from the api call.
* @param cbObject The passed in callback object. If nil is passed in to the api, nil will
* be returned in the completion block.
*/
typedef void (^BCCompletionBlock)(NSString *serviceName, NSString *serviceOperation,
NSString *jsonData, BCCallbackObject cbObject);
/**
* Completion block called when an api call returns an error.
*
* @param serviceName The service name of the api call.
* @param serviceOperation The service operation of the api call.
* @param statusCode The status code of the error (see StatusCodes.hh)
* @param reasonCode The reason code of the error (see ReasonCodes.hh)
* @param jsonError The returned JSON data from the api call.
* @param cbObject The passed in callback object. If nil is passed in to the api, nil will
* be returned in the completion block.
*/
typedef void (^BCErrorCompletionBlock)(NSString *serviceName, NSString *serviceOperation,
NSInteger statusCode, NSInteger reasonCode,
NSString *jsonError, BCCallbackObject cbObject);
/**
* Completion block called when an event is returned from brainCloud
*
* @param jsonData Returned data from the server
*/
typedef void (^BCEventCompletionBlock)(NSString *jsonData);
/**
* Completion block called whenever an api call returns rewards data.
*
* @param jsonData The rewards JSON data. The format is as follows:
* {
* "status": 200,
* "apiRewards": [
* {
* "service": "authenticationV2",
* "operation": "AUTHENTICATE",
* "rewards": {
* "rewardDetails": {
* // the reward depending on type (see docs)
* }
* }
* }
* ]
* }
*/
typedef void (^BCRewardCompletionBlock)(NSString *jsonData);
/**
* Completion block called when a file upload has completed.
*
* @param in_fileUploadId The file upload id
* @param in_jsonResponse The json response describing the file details similar to this
* {
* "status": 200,
* "data": {
* "fileList": [
* {
* "updatedAt": 1452603368201,
* "uploadedAt": null,
* "fileSize": 85470,
* "shareable": true,
* "createdAt": 1452603368201,
* "profileId": "bf8a1433-62d2-448e-b396-f3dbffff44",
* "gameId": "99999",
* "path": "test2",
* "filename": "testup.dat",
* "downloadUrl": "https://sharedprod.braincloudservers.com/s3/bc/g/99999/u/bf8a1433-62d2-448e-b396-f3dbffff44/f/test2/testup.dat"
* "cloudLocation": "bc/g/99999/u/bf8a1433-62d2-448e-b396-f3dbffff44/f/test2/testup.dat"
* }
* ]
* }
* }
*/
typedef void (^BCFileUploadCompletedCompletionBlock)(NSString *fileUploadId, NSString *json);
/**
* Completion block called when a file upload has failed.
*
* @param in_fileUploadId The file upload id
* @param in_statusCode The http status of the operation (see StatusCode.hh)
* @param in_reasonCode The reason code of the operation (see ReasonCodes.hh)
* @param in_jsonResponse The json response describing the failure. This uses the usual brainCloud error
* format similar to this:
* {
* "status": 403,
* "reason_code": 40300,
* "status_message": "Message describing failure",
* "severity": "ERROR"
* }
*/
typedef void (^BCFileUploadFailedCompletionBlock)(NSString *fileUploadId, NSInteger statusCode, NSInteger returnCode, NSString *json);
/**
* The networkError method is invoked whenever a network error is encountered
* communicating to the brainCloud server.
*
* Note this method is *not* invoked when FlushCachedMessages(true) is called.
*/
typedef void (^BCNetworkErrorCompletionBlock)();
#endif
| 34.24 | 134 | 0.692991 | davidstl |
51b5aab2205bc8294566036c8763a11dafd5717d | 3,405 | hh | C++ | boostrap/BTimesTable.hh | hanswenzel/opticks | b75b5929b6cf36a5eedeffb3031af2920f75f9f0 | [
"Apache-2.0"
] | 11 | 2020-07-05T02:39:32.000Z | 2022-03-20T18:52:44.000Z | boostrap/BTimesTable.hh | hanswenzel/opticks | b75b5929b6cf36a5eedeffb3031af2920f75f9f0 | [
"Apache-2.0"
] | null | null | null | boostrap/BTimesTable.hh | hanswenzel/opticks | b75b5929b6cf36a5eedeffb3031af2920f75f9f0 | [
"Apache-2.0"
] | 4 | 2020-09-03T20:36:32.000Z | 2022-01-19T07:42:21.000Z | /*
* Copyright (c) 2019 Opticks Team. All Rights Reserved.
*
* This file is part of Opticks
* (see https://bitbucket.org/simoncblyth/opticks).
*
* 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.
*/
#pragma once
#include <vector>
#include <string>
#include "plog/Severity.h"
class BTimes ;
#include "BRAP_API_EXPORT.hh"
#include "BRAP_HEAD.hh"
/**
BTimesTable
===========
A vector of labelled "columns" each of which holds a *BTimes* instance.
The table can be saved/loaded to/from a directory where it is stored
as individual ".ini" files named after the column labels.
*BTimeKeeper* is the canonical user of *BTimesTable*
::
simon:1 blyth$ BTimesTableTest
2016-09-15 11:11:08.829 INFO [342255] [BTimesTable::dump@43] BTimesTable::dump
t_absolute t_delta
5.944 5.944 : _seqhisMakeLookup
5.951 0.007 : seqhisMakeLookup
5.951 0.000 : seqhisApplyLookup
5.951 0.000 : _seqmatMakeLookup
5.956 0.005 : seqmatMakeLookup
5.956 0.000 : seqmatApplyLookup
5.986 0.030 : indexSequenceInterop
6.025 0.039 : indexBoundaries
6.028 0.003 : indexPresentationPrep
6.137 0.110 : _save
6.333 0.196 : save
**/
class BRAP_API BTimesTable {
public:
static const plog::Severity LEVEL ;
static const unsigned WIDTH ;
static const unsigned PRIME ;
public:
BTimesTable(const char* columns, const char* delim=",");
BTimesTable(const std::vector<std::string>& columns);
void dump(const char* msg="BTimesTable::dump", const char* startswith=NULL, const char* spacewith=NULL, double tcut=-1.0 );
unsigned getNumColumns();
BTimes* getColumn(unsigned int j);
template <typename T> void add( T row, double x, double y, double z, double w, int count=-1 );
template <typename T> const char* makeLabel( T row_, int count=-1 );
std::vector<std::string>& getLines();
public:
void save(const char* dir);
void load(const char* dir);
const char* getLabel();
private:
void makeLines();
void init(const std::vector<std::string>& columns);
void setLabel(const char* label);
unsigned getNumRows() const ;
const char* getColumnLabel(unsigned j) const ;
std::string getColumnLabels() const ;
private:
BTimes* m_tx ;
BTimes* m_ty ;
BTimes* m_tz ;
BTimes* m_tw ;
const char* m_label ;
std::vector<BTimes*> m_table ;
std::vector<std::string> m_lines ;
std::vector<std::string> m_names ;
std::vector<double> m_first ;
};
#include "BRAP_TAIL.hh"
| 30.675676 | 131 | 0.609692 | hanswenzel |
51b81d57427905c7f7afda489f398593374c12bb | 25,712 | hpp | C++ | src/include/polo/utility/blas.hpp | aytekinar/polo | da682618e98755738905fd19e55e5271af937661 | [
"MIT"
] | 8 | 2018-10-12T09:54:25.000Z | 2020-06-18T12:04:44.000Z | src/include/polo/utility/blas.hpp | aytekinar/polo | da682618e98755738905fd19e55e5271af937661 | [
"MIT"
] | 10 | 2018-10-10T10:28:23.000Z | 2019-03-14T11:36:03.000Z | src/include/polo/utility/blas.hpp | aytekinar/polo | da682618e98755738905fd19e55e5271af937661 | [
"MIT"
] | null | null | null | #ifndef POLO_UTILITY_BLAS_HPP_
#define POLO_UTILITY_BLAS_HPP_
extern "C" {
// Single-precision, L1
void srotg_(const float *, const float *, float *, float *);
void srotmg_(float *, float *, float *, const float *, float *);
void srot_(const int *, float *, const int *, float *, const int *,
const float *, const float *);
void srotm_(const int *, float *, const int *, float *, const int *,
const int *);
void sswap_(const int *, float *, const int *, float *, const int *);
void sscal_(const int *, const float *, float *, const int *);
void scopy_(const int *, const float *, const int *, float *, const int *);
void saxpy_(const int *, const float *, const float *, const int *, float *,
const int *);
float sdot_(const int *, const float *, const int *, const float *,
const int *);
float sdsdot_(const int *, const float *, const float *, const int *,
const float *, const int *);
float snrm2_(const int *, const float *, const int *);
float sasum_(const int *, const float *, const int *);
int isamax_(const int *, const float *, const int *);
// Single-precision, L2
void sgemv_(const char *, const int *, const int *, const float *,
const float *, const int *, const float *, const int *,
const float *, float *, const int *);
void sgbmv_(const char *, const int *, const int *, const int *, const int *,
const float *, const float *, const int *, const float *,
const int *, const float *, float *, const int *);
void ssymv_(const char *, const int *, const float *, const float *,
const int *, const float *, const int *, const float *, float *,
const int *);
void ssbmv_(const char *, const int *, const int *, const float *,
const float *, const int *, const int *, const int *, const float *,
float *, const int *);
void sspmv_(const char *, const int *, const float *, const float *,
const float *, const int *, const float *, float *, const int *);
void strmv_(const char *, const char *, const char *, const int *,
const float *, const int *, float *, const int *);
void stbmv_(const char *, const char *, const char *, const int *, const int *,
const float *, const int *, float *, const int *);
void stpmv_(const char *, const char *, const char *, const int *,
const float *, float *, const int *);
void strsv_(const char *, const char *, const char *, const int *,
const float *, const int *, float *, const int *);
void stbsv_(const char *, const char *, const char *, const int *, const int *,
const float *, const int *, float *, const int *);
void stpsv_(const char *, const char *, const char *, const int *,
const float *, float *, const int *);
void sger_(const int *, const int *, const float *, const float *, const int *,
const float *, const int *, float *, const int *);
void ssyr_(const char *, const int *, const float *, const float *, const int *,
float *, const int *);
void sspr_(const char *, const int *, const float *, const float *, const int *,
float *);
void ssyr2_(const char *, const int *, const float *, const float *,
const int *, const float *, const int *, float *, const int *);
void sspr2_(const char *, const int *, const float *, const float *,
const int *, const float *, const int *, float *);
// Single-precision, L3
void sgemm_(const char *, const char *, const int *, const int *, const int *,
const float *, const float *, const int *, const float *,
const int *, const float *, float *, const int *);
void ssymm_(const char *, const char *, const int *, const int *, const float *,
const float *, const int *, const float *, const int *,
const float *, float *, const int *);
void ssyrk_(const char *, const char *, const int *, const int *, const float *,
const float *, const int *, const float *, float *, const int *);
void ssyr2k_(const char *, const char *, const int *, const int *,
const float *, const float *, const int *, const float *,
const int *, const float *, float *, const int *);
void strmm_(const char *, const char *, const char *, const char *, const int *,
const int *, const float *, const float *, const int *, float *,
const int *);
void strsm_(const char *, const char *, const char *, const char *, const int *,
const int *, const float *, const float *, const int *, float *,
const int *);
// Double-precision, L1
void drotg_(const double *, const double *, double *, double *);
void drotmg_(double *, double *, double *, const double *, double *);
void drot_(const int *, double *, const int *, double *, const int *,
const double *, const double *);
void drotm_(const int *, double *, const int *, double *, const int *,
const int *);
void dswap_(const int *, double *, const int *, double *, const int *);
void dscal_(const int *, const double *, double *, const int *);
void dcopy_(const int *, const double *, const int *, double *, const int *);
void daxpy_(const int *, const double *, const double *, const int *, double *,
const int *);
double ddot_(const int *, const double *, const int *, const double *,
const int *);
double dsdot_(const int *, const double *, const double *, const int *,
const double *, const int *);
double dnrm2_(const int *, const double *, const int *);
double dasum_(const int *, const double *, const int *);
int idamax_(const int *, const double *, const int *);
// Double-precision, L2
void dgemv_(const char *, const int *, const int *, const double *,
const double *, const int *, const double *, const int *,
const double *, double *, const int *);
void dgbmv_(const char *, const int *, const int *, const int *, const int *,
const double *, const double *, const int *, const double *,
const int *, const double *, double *, const int *);
void dsymv_(const char *, const int *, const double *, const double *,
const int *, const double *, const int *, const double *, double *,
const int *);
void dsbmv_(const char *, const int *, const int *, const double *,
const double *, const int *, const int *, const int *,
const double *, double *, const int *);
void dspmv_(const char *, const int *, const double *, const double *,
const double *, const int *, const double *, double *, const int *);
void dtrmv_(const char *, const char *, const char *, const int *,
const double *, const int *, double *, const int *);
void dtbmv_(const char *, const char *, const char *, const int *, const int *,
const double *, const int *, double *, const int *);
void dtpmv_(const char *, const char *, const char *, const int *,
const double *, double *, const int *);
void dtrsv_(const char *, const char *, const char *, const int *,
const double *, const int *, double *, const int *);
void dtbsv_(const char *, const char *, const char *, const int *, const int *,
const double *, const int *, double *, const int *);
void dtpsv_(const char *, const char *, const char *, const int *,
const double *, double *, const int *);
void dger_(const int *, const int *, const double *, const double *,
const int *, const double *, const int *, double *, const int *);
void dsyr_(const char *, const int *, const double *, const double *,
const int *, double *, const int *);
void dspr_(const char *, const int *, const double *, const double *,
const int *, double *);
void dsyr2_(const char *, const int *, const double *, const double *,
const int *, const double *, const int *, double *, const int *);
void dspr2_(const char *, const int *, const double *, const double *,
const int *, const double *, const int *, double *);
// Double-precision, L3
void dgemm_(const char *, const char *, const int *, const int *, const int *,
const double *, const double *, const int *, const double *,
const int *, const double *, double *, const int *);
void dsymm_(const char *, const char *, const int *, const int *,
const double *, const double *, const int *, const double *,
const int *, const double *, double *, const int *);
void dsyrk_(const char *, const char *, const int *, const int *,
const double *, const double *, const int *, const double *,
double *, const int *);
void dsyr2k_(const char *, const char *, const int *, const int *,
const double *, const double *, const int *, const double *,
const int *, const double *, double *, const int *);
void dtrmm_(const char *, const char *, const char *, const char *, const int *,
const int *, const double *, const double *, const int *, double *,
const int *);
void dtrsm_(const char *, const char *, const char *, const char *, const int *,
const int *, const double *, const double *, const int *, double *,
const int *);
}
namespace polo {
namespace utility {
namespace matrix {
template <class value_t> struct blas;
template <> struct blas<float> {
// Level 1
static void rotg(const float sa, const float sb, float &c, float &s) {
srotg_(&sa, &sb, &c, &s);
}
static void rotmg(float &sd1, float &sd2, float &sx1, const float sy1,
float *sparam) {
srotmg_(&sd1, &sd2, &sx1, &sy1, sparam);
}
static void rot(const int n, float *sx, const int incx, float *sy,
const int incy, const float c, const float s) {
srot_(&n, sx, &incx, sy, &incy, &c, &s);
}
static void rotm(const int n, float *sx, const int incx, float *sy,
const int incy, const int *sparam) {
srotm_(&n, sx, &incx, sy, &incy, sparam);
}
static void swap(const int n, float *sx, const int incx, float *sy,
const int incy) {
sswap_(&n, sx, &incx, sy, &incy);
}
static void scal(const int n, const float sa, float *sx, const int incx) {
sscal_(&n, &sa, sx, &incx);
}
static void copy(const int n, const float *sx, const int incx, float *sy,
const int incy) {
scopy_(&n, sx, &incx, sy, &incy);
}
static void axpy(const int n, const float sa, const float *sx, const int incx,
float *sy, const int incy) {
saxpy_(&n, &sa, sx, &incx, sy, &incy);
}
static float dot(const int n, const float *sx, const int incx,
const float *sy, const int incy) {
return sdot_(&n, sx, &incx, sy, &incy);
}
static float dsdot(const int n, const float sb, const float *sx,
const int incx, const float *sy, const int incy) {
return sdsdot_(&n, &sb, sx, &incx, sy, &incy);
}
static float nrm2(const int n, const float *x, const int incx) {
return snrm2_(&n, x, &incx);
}
static float asum(const int n, const float *sx, const int incx) {
return sasum_(&n, sx, &incx);
}
static int iamax(const int n, const float *sx, const int incx) {
return isamax_(&n, sx, &incx);
}
// Level 2
static void gemv(const char trans, const int m, const int n,
const float alpha, const float *a, const int lda,
const float *x, const int incx, const float beta, float *y,
const int incy) {
sgemv_(&trans, &m, &n, &alpha, a, &lda, x, &incx, &beta, y, &incy);
}
static void gbmv(const char trans, const int m, const int n, const int kl,
const int ku, const float alpha, const float *a,
const int lda, const float *x, const int incx,
const float beta, float *y, const int incy) {
sgbmv_(&trans, &m, &n, &kl, &ku, &alpha, a, &lda, x, &incx, &beta, y,
&incy);
}
static void symv(const char uplo, const int n, const float alpha,
const float *a, const int lda, const float *x,
const int incx, const float beta, float *y, const int incy) {
ssymv_(&uplo, &n, &alpha, a, &lda, x, &incx, &beta, y, &incy);
}
static void sbmv(const char uplo, const int n, const int k, const float alpha,
const float *a, const int lda, const int *x, const int incx,
const float beta, float *y, const int incy) {
ssbmv_(&uplo, &n, &k, &alpha, a, &lda, x, &incx, &beta, y, &incy);
}
static void spmv(const char uplo, const int n, const float alpha,
const float *a, const float *x, const int incx,
const float beta, float *y, const int incy) {
sspmv_(&uplo, &n, &alpha, a, x, &incx, &beta, y, &incy);
}
static void trmv(const char uplo, const char trans, const char diag,
const int n, const float *a, const int lda, float *x,
const int incx) {
strmv_(&uplo, &trans, &diag, &n, a, &lda, x, &incx);
}
static void tbmv(const char uplo, const char trans, const char diag,
const int n, const int k, const float *a, const int lda,
float *x, const int incx) {
stbmv_(&uplo, &trans, &diag, &n, &k, a, &lda, x, &incx);
}
static void tpmv(const char uplo, const char trans, const char diag,
const int n, const float *ap, float *x, const int incx) {
stpmv_(&uplo, &trans, &diag, &n, ap, x, &incx);
}
static void trsv(const char uplo, const char trans, const char diag,
const int n, const float *a, const int lda, float *x,
const int incx) {
strsv_(&uplo, &trans, &diag, &n, a, &lda, x, &incx);
}
static void tbsv(const char uplo, const char trans, const char diag,
const int n, const int k, const float *a, const int lda,
float *x, const int incx) {
stbsv_(&uplo, &trans, &diag, &n, &k, a, &lda, x, &incx);
}
static void tpsv(const char uplo, const char trans, const char diag,
const int n, const float *ap, float *x, const int incx) {
stpsv_(&uplo, &trans, &diag, &n, ap, x, &incx);
}
static void ger(const int m, const int n, const float alpha, const float *x,
const int incx, const float *y, const int incy, float *a,
const int lda) {
sger_(&m, &n, &alpha, x, &incx, y, &incy, a, &lda);
}
static void syr(const char uplo, const int n, const float alpha,
const float *x, const int incx, float *a, const int lda) {
ssyr_(&uplo, &n, &alpha, x, &incx, a, &lda);
}
static void spr(const char uplo, const int n, const float alpha,
const float *x, const int incx, float *ap) {
sspr_(&uplo, &n, &alpha, x, &incx, ap);
}
static void syr2(const char uplo, const int n, const float alpha,
const float *x, const int incx, const float *y,
const int incy, float *a, const int lda) {
ssyr2_(&uplo, &n, &alpha, x, &incx, y, &incy, a, &lda);
}
static void spr2(const char uplo, const int n, const float alpha,
const float *x, const int incx, const float *y,
const int incy, float *ap) {
sspr2_(&uplo, &n, &alpha, x, &incx, y, &incy, ap);
}
// Level 3
static void gemm(const char transa, const char transb, const int m,
const int n, const int k, const float alpha, const float *a,
const int lda, const float *b, const int ldb,
const float beta, float *c, const int ldc) {
sgemm_(&transa, &transb, &m, &n, &k, &alpha, a, &lda, b, &ldb, &beta, c,
&ldc);
}
static void symm(const char side, const char uplo, const int m, const int n,
const float alpha, const float *a, const int lda,
const float *b, const int ldb, const float beta, float *c,
const int ldc) {
ssymm_(&side, &uplo, &m, &n, &alpha, a, &lda, b, &ldb, &beta, c, &ldc);
}
static void syrk(const char uplo, const char trans, const int n, const int k,
const float alpha, const float *a, const int lda,
const float beta, float *c, const int ldc) {
ssyrk_(&uplo, &trans, &n, &k, &alpha, a, &lda, &beta, c, &ldc);
}
static void syr2k(const char uplo, const char trans, const int n, const int k,
const float alpha, const float *a, const int lda,
const float *b, const int ldb, const float beta, float *c,
const int ldc) {
ssyr2k_(&uplo, &trans, &n, &k, &alpha, a, &lda, b, &ldb, &beta, c, &ldc);
}
static void trmm(const char side, const char uplo, const char transa,
const char diag, const int m, const int n, const float alpha,
const float *a, const int lda, float *b, const int ldb) {
strmm_(&side, &uplo, &transa, &diag, &m, &n, &alpha, a, &lda, b, &ldb);
}
static void trsm(const char side, const char uplo, const char transa,
const char diag, const int m, const int n, const float alpha,
const float *a, const int lda, float *b, const int ldb) {
strsm_(&side, &uplo, &transa, &diag, &m, &n, &alpha, a, &lda, b, &ldb);
}
};
template <> struct blas<double> {
// Level 1
static void rotg(const double sa, const double sb, double &c, double &s) {
drotg_(&sa, &sb, &c, &s);
}
static void rotmg(double &sd1, double &sd2, double &sx1, const double sy1,
double *sparam) {
drotmg_(&sd1, &sd2, &sx1, &sy1, sparam);
}
static void rot(const int n, double *sx, const int incx, double *sy,
const int incy, const double c, const double s) {
drot_(&n, sx, &incx, sy, &incy, &c, &s);
}
static void rotm(const int n, double *sx, const int incx, double *sy,
const int incy, const int *sparam) {
drotm_(&n, sx, &incx, sy, &incy, sparam);
}
static void swap(const int n, double *sx, const int incx, double *sy,
const int incy) {
dswap_(&n, sx, &incx, sy, &incy);
}
static void scal(const int n, const double sa, double *sx, const int incx) {
dscal_(&n, &sa, sx, &incx);
}
static void copy(const int n, const double *sx, const int incx, double *sy,
const int incy) {
dcopy_(&n, sx, &incx, sy, &incy);
}
static void axpy(const int n, const double sa, const double *sx,
const int incx, double *sy, const int incy) {
daxpy_(&n, &sa, sx, &incx, sy, &incy);
}
static double dot(const int n, const double *sx, const int incx,
const double *sy, const int incy) {
return ddot_(&n, sx, &incx, sy, &incy);
}
static double dsdot(const int n, const double sb, const double *sx,
const int incx, const double *sy, const int incy) {
return dsdot_(&n, &sb, sx, &incx, sy, &incy);
}
static double nrm2(const int n, const double *x, const int incx) {
return dnrm2_(&n, x, &incx);
}
static double asum(const int n, const double *sx, const int incx) {
return dasum_(&n, sx, &incx);
}
static int iamax(const int n, const double *sx, const int incx) {
return idamax_(&n, sx, &incx);
}
// Level 2
static void gemv(const char trans, const int m, const int n,
const double alpha, const double *a, const int lda,
const double *x, const int incx, const double beta,
double *y, const int incy) {
dgemv_(&trans, &m, &n, &alpha, a, &lda, x, &incx, &beta, y, &incy);
}
static void gbmv(const char trans, const int m, const int n, const int kl,
const int ku, const double alpha, const double *a,
const int lda, const double *x, const int incx,
const double beta, double *y, const int incy) {
dgbmv_(&trans, &m, &n, &kl, &ku, &alpha, a, &lda, x, &incx, &beta, y,
&incy);
}
static void symv(const char uplo, const int n, const double alpha,
const double *a, const int lda, const double *x,
const int incx, const double beta, double *y,
const int incy) {
dsymv_(&uplo, &n, &alpha, a, &lda, x, &incx, &beta, y, &incy);
}
static void sbmv(const char uplo, const int n, const int k,
const double alpha, const double *a, const int lda,
const int *x, const int incx, const double beta, double *y,
const int incy) {
dsbmv_(&uplo, &n, &k, &alpha, a, &lda, x, &incx, &beta, y, &incy);
}
static void spmv(const char uplo, const int n, const double alpha,
const double *a, const double *x, const int incx,
const double beta, double *y, const int incy) {
dspmv_(&uplo, &n, &alpha, a, x, &incx, &beta, y, &incy);
}
static void trmv(const char uplo, const char trans, const char diag,
const int n, const double *a, const int lda, double *x,
const int incx) {
dtrmv_(&uplo, &trans, &diag, &n, a, &lda, x, &incx);
}
static void tbmv(const char uplo, const char trans, const char diag,
const int n, const int k, const double *a, const int lda,
double *x, const int incx) {
dtbmv_(&uplo, &trans, &diag, &n, &k, a, &lda, x, &incx);
}
static void tpmv(const char uplo, const char trans, const char diag,
const int n, const double *ap, double *x, const int incx) {
dtpmv_(&uplo, &trans, &diag, &n, ap, x, &incx);
}
static void trsv(const char uplo, const char trans, const char diag,
const int n, const double *a, const int lda, double *x,
const int incx) {
dtrsv_(&uplo, &trans, &diag, &n, a, &lda, x, &incx);
}
static void tbsv(const char uplo, const char trans, const char diag,
const int n, const int k, const double *a, const int lda,
double *x, const int incx) {
dtbsv_(&uplo, &trans, &diag, &n, &k, a, &lda, x, &incx);
}
static void tpsv(const char uplo, const char trans, const char diag,
const int n, const double *ap, double *x, const int incx) {
dtpsv_(&uplo, &trans, &diag, &n, ap, x, &incx);
}
static void ger(const int m, const int n, const double alpha, const double *x,
const int incx, const double *y, const int incy, double *a,
const int lda) {
dger_(&m, &n, &alpha, x, &incx, y, &incy, a, &lda);
}
static void syr(const char uplo, const int n, const double alpha,
const double *x, const int incx, double *a, const int lda) {
dsyr_(&uplo, &n, &alpha, x, &incx, a, &lda);
}
static void spr(const char uplo, const int n, const double alpha,
const double *x, const int incx, double *ap) {
dspr_(&uplo, &n, &alpha, x, &incx, ap);
}
static void syr2(const char uplo, const int n, const double alpha,
const double *x, const int incx, const double *y,
const int incy, double *a, const int lda) {
dsyr2_(&uplo, &n, &alpha, x, &incx, y, &incy, a, &lda);
}
static void spr2(const char uplo, const int n, const double alpha,
const double *x, const int incx, const double *y,
const int incy, double *ap) {
dspr2_(&uplo, &n, &alpha, x, &incx, y, &incy, ap);
}
// Level 3
static void gemm(const char transa, const char transb, const int m,
const int n, const int k, const double alpha,
const double *a, const int lda, const double *b,
const int ldb, const double beta, double *c, const int ldc) {
dgemm_(&transa, &transb, &m, &n, &k, &alpha, a, &lda, b, &ldb, &beta, c,
&ldc);
}
static void symm(const char side, const char uplo, const int m, const int n,
const double alpha, const double *a, const int lda,
const double *b, const int ldb, const double beta, double *c,
const int ldc) {
dsymm_(&side, &uplo, &m, &n, &alpha, a, &lda, b, &ldb, &beta, c, &ldc);
}
static void syrk(const char uplo, const char trans, const int n, const int k,
const double alpha, const double *a, const int lda,
const double beta, double *c, const int ldc) {
dsyrk_(&uplo, &trans, &n, &k, &alpha, a, &lda, &beta, c, &ldc);
}
static void syr2k(const char uplo, const char trans, const int n, const int k,
const double alpha, const double *a, const int lda,
const double *b, const int ldb, const double beta,
double *c, const int ldc) {
dsyr2k_(&uplo, &trans, &n, &k, &alpha, a, &lda, b, &ldb, &beta, c, &ldc);
}
static void trmm(const char side, const char uplo, const char transa,
const char diag, const int m, const int n,
const double alpha, const double *a, const int lda,
double *b, const int ldb) {
dtrmm_(&side, &uplo, &transa, &diag, &m, &n, &alpha, a, &lda, b, &ldb);
}
static void trsm(const char side, const char uplo, const char transa,
const char diag, const int m, const int n,
const double alpha, const double *a, const int lda,
double *b, const int ldb) {
dtrsm_(&side, &uplo, &transa, &diag, &m, &n, &alpha, a, &lda, b, &ldb);
}
};
} // namespace matrix
} // namespace utility
} // namespace polo
#endif
| 51.321357 | 80 | 0.57269 | aytekinar |
51b8890f8099cf19145dff92f04e4146ee4a2744 | 3,072 | cpp | C++ | cplusplus/common/atlasutil/src/atlas_thread_mgr.cpp | Dedederek/samples | 31d99de20af2f7046556e0f48c4b789b99e422f8 | [
"Apache-2.0"
] | 5 | 2021-02-26T17:58:12.000Z | 2022-03-15T06:21:28.000Z | cplusplus/common/atlasutil/src/atlas_thread_mgr.cpp | Dedederek/samples | 31d99de20af2f7046556e0f48c4b789b99e422f8 | [
"Apache-2.0"
] | null | null | null | cplusplus/common/atlasutil/src/atlas_thread_mgr.cpp | Dedederek/samples | 31d99de20af2f7046556e0f48c4b789b99e422f8 | [
"Apache-2.0"
] | 5 | 2021-03-22T21:13:11.000Z | 2021-09-24T06:52:33.000Z | #include "atlas_thread_mgr.h"
#include "atlas_utils.h"
namespace {
const uint32_t kMsgQueueSize = 256;
const uint32_t kWait10Milliseconds = 10000;
const uint32_t kWaitThreadStart = 1000;
}
AtlasThreadMgr::AtlasThreadMgr(AtlasThread* userThreadInstance, const string& threadName)
:name_(threadName),
userInstance_(userThreadInstance),
isExit_(false),
status_(THREAD_READY),
msgQueue_(kMsgQueueSize) {
}
AtlasThreadMgr::~AtlasThreadMgr() {
userInstance_ = nullptr;
while(!msgQueue_.Empty()) {
msgQueue_.Pop();
}
}
void AtlasThreadMgr::CreateThread() {
thread engine(&AtlasThreadMgr::ThreadEntry, (void *)this);
engine.detach();
}
void AtlasThreadMgr::ThreadEntry(void* arg){
AtlasThreadMgr* thMgr = (AtlasThreadMgr*)arg;
AtlasThread* userInstance = thMgr->GetUserInstance();
if (userInstance == nullptr) {
ATLAS_LOG_ERROR("Atlas thread exit for user thread instance is null");
return;
}
string& instName = userInstance->SelfInstanceName();
aclrtContext context = userInstance->GetContext();
aclError aclRet = aclrtSetCurrentContext(context);
if (aclRet != ACL_ERROR_NONE) {
ATLAS_LOG_ERROR("Thread %s set context failed, error: %d",
instName.c_str(), aclRet);
return;
}
int ret = userInstance->Init();
if (ret) {
ATLAS_LOG_ERROR("Thread %s init error %d, thread exit",
instName.c_str(), ret);
thMgr->SetStatus(THREAD_ERROR);
return;
}
thMgr->SetStatus(THREAD_RUNNING);
while(THREAD_RUNNING == thMgr->GetStatus()) {
// 从队列中取数据
shared_ptr<AtlasMessage> msg = thMgr->PopMsgFromQueue();
if(msg == nullptr) {
usleep(kWait10Milliseconds);
continue;
}
// 线程消息处理函数
ret = userInstance->Process(msg->msgId, msg->data);
msg->data = nullptr;
if (ret) {
ATLAS_LOG_ERROR("Thread %s process function return "
"error %d, thread exit", instName.c_str(), ret);
thMgr->SetStatus(THREAD_ERROR);
return;
}
usleep(0);
}
thMgr->SetStatus(THREAD_EXITED);
return;
}
AtlasError AtlasThreadMgr::WaitThreadInitEnd() {
while(true) {
if (status_ == THREAD_RUNNING) {
break;
} else if (status_ > THREAD_RUNNING) {
string& instName = userInstance_->SelfInstanceName();
ATLAS_LOG_ERROR("Thread instance %s status change to %d, "
"app start failed", instName.c_str(), status_);
return ATLAS_ERROR_START_THREAD;
} else {
usleep(kWaitThreadStart);
}
}
return ATLAS_OK;
}
AtlasError AtlasThreadMgr::PushMsgToQueue(shared_ptr<AtlasMessage>& pMessage) {
if (status_ != THREAD_RUNNING) {
ATLAS_LOG_ERROR("Thread instance %s status(%d) is invalid, "
"can not reveive message", name_.c_str(), status_);
return ATLAS_ERROR_THREAD_ABNORMAL;
}
return msgQueue_.Push(pMessage)? ATLAS_OK : ATLAS_ERROR_ENQUEUE;
}
| 28.444444 | 89 | 0.636068 | Dedederek |
51b8be0f99da81e3bf496150b2c4ea4ad3c719f4 | 15,390 | cpp | C++ | mapleall/maple_me/src/me_placement_opt.cpp | lvyitian/mapleall | 1112501c1bcbff5d9388bf46f195d56560c5863a | [
"MulanPSL-1.0"
] | null | null | null | mapleall/maple_me/src/me_placement_opt.cpp | lvyitian/mapleall | 1112501c1bcbff5d9388bf46f195d56560c5863a | [
"MulanPSL-1.0"
] | null | null | null | mapleall/maple_me/src/me_placement_opt.cpp | lvyitian/mapleall | 1112501c1bcbff5d9388bf46f195d56560c5863a | [
"MulanPSL-1.0"
] | null | null | null | /*
* Copyright (c) [2020] Huawei Technologies Co., Ltd. All rights reserved.
*
* OpenArkCompiler is licensed under the Mulan Permissive Software License v2.
* You can use this software according to the terms and conditions of the MulanPSL - 2.0.
* You may obtain a copy of MulanPSL - 2.0 at:
*
* https://opensource.org/licenses/MulanPSL-2.0
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR
* FIT FOR A PARTICULAR PURPOSE.
* See the MulanPSL - 2.0 for more details.
*/
#include "me_dominance.h"
#include "me_placement_opt.h"
// This phase is invoked by the analyzerc phase. When localrefvars become dead
// before function exit, they need to be cleaned up by performing a decref.
// If these decref's are inserted before all return statements in the function,
// some of them can be redundant for a given function invocation because a given
// localref may not have been active within the paths of execution leading to
// a return statement. The purpose of this phase is to determine mroe optimal
// placements for these decref's, thus elimination partial redundancy in the
// inserted decref's. The decref placement optimization can be viewed as
// either moving (if not deleting) the decref's from the return statement
// backwards so they would not be uselessly executed on paths leading to the
// return statement where the localrefvar has not been active. The effect is
// to insert the decrefs as early as possible while still covering all the last
// uses of the localrefvar.
//
// For each invocation of this phase, one localrefvar is processed.
// The entry point to this phase is ComputePlacement(MapleSet<BBId> *occurbbs)
// where occurbbs gives the set of BBs where the current localrefvar is active.
// The output of this phase is represented by inserted_bbs and lastuse_bbs.
// inserted_bbs give the set of BBs where decref should be inserted at BB entry.
// lastuse_bbs give the set of BBs where decref should be inserted at BB exit,
// because there is a last use of the localref within those BBs.
//
// The algorithm is the dual of the SSAPRE algorithm, where lambdas are isnerted
// at control flow split points according to post-dominance frontiers of BBs in
// occurbbs. The control flow graph is viewed upside down. The data flow
// analysis computes upsafe followed by canbeant.
// accumulate the BBs that are in the iterated postdominance frontiers of bb in
// the set dfset, visiting each BB only once
namespace maple {
void PlacementOpt::FormLambdas() {
lambda_dfns.clear();
for (uint32 dfn : occur_dfns) {
BBId bbid = dominance->pdtPreOrder[dfn];
BB *bb = func->theCFG->bbVec[bbid.idx];
GetIterPdomFrontier(bb, &lambda_dfns);
}
}
void PlacementOpt::FormLambdaRes() {
lambdares_dfns.clear();
for (uint32 dfn : lambda_dfns) {
BBId bbid = dominance->pdtPreOrder[dfn];
BB *bb = func->theCFG->bbVec[bbid.idx];
for (BB *succ : bb->succ) {
lambdares_dfns.insert(dominance->pdtDfn[succ->id.idx]);
}
}
}
// create ordered_occs consisting of all 4 kinds of BBOcc nodes, sorted
// according to pdtPreOrder; also create lambda_occs for only the lambda occs
// sorted in pdtPreOrder
void PlacementOpt::CreateSortedOccs() {
std::unordered_map<BBId, BBLambdaresOcc *> bb2lambdaresMap;
ordered_occs.clear();
lambda_occs.clear();
MapleSet<uint32>::iterator lambdadfnIt = lambda_dfns.begin();
MapleSet<uint32>::iterator realdfnIt = occur_dfns.begin();
MapleSet<uint32>::iterator lambdaresdfnIt = lambdares_dfns.begin();
MapleSet<uint32>::iterator entrydfnIt = entry_dfns.begin();
BBLambdaOcc *nextLambdaocc = nullptr;
if (lambdadfnIt != lambda_dfns.end())
nextLambdaocc = percand_mp->New<BBLambdaOcc>(dominance->pdtPreOrder[*lambdadfnIt], &percand_allocator);
BBOcc *nextRealocc = nullptr;
if (realdfnIt != occur_dfns.end())
nextRealocc = percand_mp->New<BBOcc>(kBBOccReal, dominance->pdtPreOrder[*realdfnIt]);
BBOcc *nextEntryocc = nullptr;
if (entrydfnIt != entry_dfns.end())
nextEntryocc = percand_mp->New<BBOcc>(kBBOccEntry, dominance->pdtPreOrder[*entrydfnIt]);
BBLambdaresOcc *nextLambdaresocc = nullptr;
if (lambdaresdfnIt != lambdares_dfns.end()) {
CHECK(*lambdaresdfnIt < dominance->pdtPreOrder.size(), "index out of range in PlacementOpt::CreateSortedOccs");
nextLambdaresocc = percand_mp->New<BBLambdaresOcc>(dominance->pdtPreOrder[*lambdaresdfnIt]);
bb2lambdaresMap[nextLambdaresocc->bbid] = nextLambdaresocc;
}
BBOcc *pickedocc;
do {
pickedocc = nullptr;
// the 4 kinds of occ must be checked in this order, so it will be right
// if more than 1 has the same dfn
if (nextLambdaocc) {
pickedocc = nextLambdaocc;
}
if (nextRealocc && (pickedocc == nullptr || *realdfnIt < dominance->pdtDfn[pickedocc->bbid.idx])) {
pickedocc = nextRealocc;
}
if (nextLambdaresocc && (pickedocc == nullptr || *lambdaresdfnIt < dominance->pdtDfn[pickedocc->bbid.idx])) {
pickedocc = nextLambdaresocc;
}
if (nextEntryocc && (pickedocc == nullptr || *entrydfnIt < dominance->pdtDfn[pickedocc->bbid.idx])) {
pickedocc = nextEntryocc;
}
if (pickedocc != nullptr) {
ordered_occs.push_back(pickedocc);
switch (pickedocc->occty) {
case kBBOccLambda:
lambda_occs.push_back(static_cast<BBLambdaOcc *>(pickedocc));
lambdadfnIt++;
if (lambdadfnIt != lambda_dfns.end())
nextLambdaocc = percand_mp->New<BBLambdaOcc>(dominance->pdtPreOrder[*lambdadfnIt], &percand_allocator);
else {
nextLambdaocc = nullptr;
}
break;
case kBBOccReal:
realdfnIt++;
if (realdfnIt != occur_dfns.end())
nextRealocc = percand_mp->New<BBOcc>(kBBOccReal, dominance->pdtPreOrder[*realdfnIt]);
else {
nextRealocc = nullptr;
}
break;
case kBBOccEntry:
entrydfnIt++;
if (entrydfnIt != entry_dfns.end())
nextEntryocc = percand_mp->New<BBOcc>(kBBOccEntry, dominance->pdtPreOrder[*entrydfnIt]);
else {
nextEntryocc = nullptr;
}
break;
case kBBOccLambdares:
lambdaresdfnIt++;
if (lambdaresdfnIt != lambdares_dfns.end()) {
nextLambdaresocc = percand_mp->New<BBLambdaresOcc>(dominance->pdtPreOrder[*lambdaresdfnIt]);
bb2lambdaresMap[nextLambdaresocc->bbid] = nextLambdaresocc;
} else {
nextLambdaresocc = nullptr;
}
break;
default:
ASSERT(false, "CreateSortedOccs: unexpected occty");
}
}
} while (pickedocc != nullptr);
// initialize lambdaRes vector in each BBLambdaOcc node
for (BBLambdaOcc *lambdaOcc : lambda_occs) {
BB *bb = func->theCFG->bbVec[lambdaOcc->bbid.idx];
for (BB *succbb : bb->succ) {
lambdaOcc->lambdaRes.push_back(bb2lambdaresMap[succbb->id]);
}
}
}
void PlacementOpt::RenameOccs() {
MapleStack<BBOcc *> occStack(percand_allocator.Adapter());
for (BBOcc *occ : ordered_occs) {
while (!occStack.empty() &&
!dominance->Postdominate(func->theCFG->bbVec[occStack.top()->bbid.idx], func->theCFG->bbVec[occ->bbid.idx])) {
occStack.pop();
}
switch (occ->occty) {
case kBBOccReal:
if (occStack.empty()) {
occ->classid = classcount++;
occStack.push(occ);
} else {
occ->classid = occStack.top()->classid;
if (occStack.top()->occty == kBBOccLambda) {
occStack.push(occ);
}
}
break;
case kBBOccLambda:
occ->classid = classcount++;
occStack.push(occ);
break;
case kBBOccLambdares:
if (occStack.empty()) {
// keep classid as -1 and def as nullptr
} else {
BBLambdaresOcc *lmbdaresocc = static_cast<BBLambdaresOcc *>(occ);
lmbdaresocc->def = occStack.top();
lmbdaresocc->classid = occStack.top()->classid;
if (occStack.top()->occty == kBBOccReal) {
lmbdaresocc->has_real_use = true;
// if the real occ is defined by lambda, make def point to the lambda
if (occStack.size() > 1) {
BBOcc *savedTos = occStack.top();
occStack.pop();
if (occStack.top()->occty == kBBOccLambda && occStack.top()->classid == lmbdaresocc->classid) {
lmbdaresocc->def = occStack.top();
}
occStack.push(savedTos);
}
}
}
break;
case kBBOccEntry:
if (occStack.empty()) {
break;
}
if (occStack.top()->occty == kBBOccLambda) {
BBLambdaOcc *lambdaOcc = static_cast<BBLambdaOcc *>(occStack.top());
lambdaOcc->is_upsafe = false;
}
break;
default:
ASSERT(false, "RenameOccs: unexpected occty");
}
}
}
// propagate not-is_upsafe
void PlacementOpt::ResetUpsafe(BBLambdaresOcc *lmbdares) {
if (lmbdares->def == nullptr) {
return;
}
if (lmbdares->def->occty != kBBOccLambda) {
return;
}
BBLambdaOcc *lambda = static_cast<BBLambdaOcc *>(lmbdares->def);
if (!lambda->is_upsafe) {
return;
}
lambda->is_upsafe = false;
for (BBLambdaresOcc *lmbdares0 : lambda->lambdaRes)
if (!lmbdares0->has_real_use) {
ResetUpsafe(lmbdares0);
}
}
void PlacementOpt::ComputeUpsafe() {
for (BBLambdaOcc *lambdaOcc : lambda_occs) {
if (!lambdaOcc->is_upsafe) {
for (BBLambdaresOcc *lmbdares0 : lambdaOcc->lambdaRes)
if (!lmbdares0->has_real_use) {
ResetUpsafe(lmbdares0);
}
}
}
}
// propagate not-canbeant
void PlacementOpt::ResetCanbeant(BBLambdaOcc *lmbdaocc) {
lmbdaocc->canbeant = false;
// loop thru all occ's to find lmbdaocc's result opnds and reset
for (BBLambdaOcc *lambdaOcc : lambda_occs) {
for (BBLambdaresOcc *lmbdares0 : lambdaOcc->lambdaRes)
if (lmbdares0->def && lmbdares0->def == lmbdaocc) {
if (!lmbdares0->has_real_use && lambdaOcc->canbeant && !lambdaOcc->is_upsafe) {
ResetCanbeant(lambdaOcc);
}
}
}
}
void PlacementOpt::ComputeCanbeant() {
for (BBLambdaOcc *lambdaOcc : lambda_occs) {
if (!lambdaOcc->canbeant || lambdaOcc->is_upsafe) {
continue;
}
for (BBLambdaresOcc *lmbdares0 : lambdaOcc->lambdaRes)
if (lmbdares0->def == nullptr) {
ResetCanbeant(lambdaOcc);
break;
}
}
// go thru again to check insertion at critical edge and fix up canbeant
bool has_crit_edge;
do {
has_crit_edge = false;
for (BBLambdaOcc *lambdaOcc : lambda_occs) {
if (!lambdaOcc->canbeant) {
continue;
}
for (BBLambdaresOcc *lmbdares0 : lambdaOcc->lambdaRes) {
if (lmbdares0->has_real_use) {
continue;
}
if (lmbdares0->def == nullptr)
;
else if (lmbdares0->def->occty != kBBOccLambda) {
continue;
} else {
BBLambdaOcc *lambda = static_cast<BBLambdaOcc *>(lmbdares0->def);
if (lambda->canbeant) {
continue;
}
}
// check for critical edge
BB *insertbb = func->theCFG->bbVec[lmbdares0->bbid.idx];
if (insertbb->pred.size() > 1) {
ResetCanbeant(lambdaOcc);
has_crit_edge = true;
break;
}
}
}
} while (has_crit_edge);
}
void PlacementOpt::ComputePlacement(MapleSet<BBId> *occurbbs) {
classcount = 0;
// initialize occur_dfns
MapleSet<BBId>::iterator occurbbidIt = occurbbs->begin();
occur_dfns.clear();
for (; occurbbidIt != occurbbs->end(); occurbbidIt++) {
occur_dfns.insert(dominance->pdtDfn[occurbbidIt->idx]);
}
FormLambdas(); // result put in the set lambda_bbs
FormLambdaRes(); // result put in the set lambdares_bbs
CreateSortedOccs();
RenameOccs();
ComputeUpsafe();
ComputeCanbeant();
if (placementoptdebug) {
LogInfo::MapleLogger() << "--- occur at bbs:";
for (BBId bbid : *occurbbs) {
LogInfo::MapleLogger() << " " << bbid.idx;
}
LogInfo::MapleLogger() << std::endl;
LogInfo::MapleLogger() << "--- lambdas at bbs:";
for (BBLambdaOcc *lambdaOcc : lambda_occs) {
LogInfo::MapleLogger() << " " << lambdaOcc->bbid.idx;
if (lambdaOcc->is_upsafe) {
LogInfo::MapleLogger() << " upsafe";
}
if (lambdaOcc->canbeant) {
LogInfo::MapleLogger() << " canbeant";
}
}
LogInfo::MapleLogger() << std::endl;
LogInfo::MapleLogger() << "--- full occ list:";
for (BBOcc *occ : ordered_occs) {
LogInfo::MapleLogger() << " " << occ->bbid.idx;
if (occ->occty == kBBOccReal) {
LogInfo::MapleLogger() << "(real " << occ->classid << ")";
} else if (occ->occty == kBBOccLambda) {
LogInfo::MapleLogger() << "(lambda " << occ->classid << ")";
} else if (occ->occty == kBBOccLambdares) {
LogInfo::MapleLogger() << "(lmbdares " << occ->classid << ")";
} else if (occ->occty == kBBOccEntry) {
LogInfo::MapleLogger() << "(entry)";
}
}
LogInfo::MapleLogger() << std::endl;
}
// determine inserted_bbs
inserted_bbs.clear();
for (BBLambdaOcc *lambdaOcc : lambda_occs) {
if (!lambdaOcc->canbeant) {
continue;
}
MapleVector<BBLambdaresOcc *>::iterator lambdaresIt = lambdaOcc->lambdaRes.begin();
for (; lambdaresIt != lambdaOcc->lambdaRes.end(); lambdaresIt++) {
BBLambdaresOcc *lambdares0 = *lambdaresIt;
if (lambdares0->has_real_use) {
continue;
}
if (lambdares0->def == nullptr)
;
else if (lambdares0->def->occty != kBBOccLambda) {
continue;
} else {
BBLambdaOcc *lambda = static_cast<BBLambdaOcc *>(lambdares0->def);
if (lambda->canbeant) {
continue;
}
}
BB *insertbb = func->theCFG->bbVec[lambdares0->bbid.idx];
CHECK_FATAL(insertbb->pred.size() == 1, "ComputePlacement: cannot insert at critical edge");
inserted_bbs.insert(lambdares0->bbid);
}
}
if (placementoptdebug) {
LogInfo::MapleLogger() << "--- inserted decrefs at entries of bbs:";
for (BBId bbid : inserted_bbs) {
LogInfo::MapleLogger() << " " << bbid.idx;
}
LogInfo::MapleLogger() << std::endl;
}
// determine lastuse_bbs by pre-order traversal of post-dominator tree
lastuse_bbs.clear();
std::vector<bool> classidVisited(classcount, false); // index is classid
for (BBOcc *occ : ordered_occs) {
switch (occ->occty) {
case kBBOccReal:
if (!classidVisited[occ->classid]) {
classidVisited[occ->classid] = true;
lastuse_bbs.insert(occ->bbid);
}
break;
case kBBOccLambda: {
BBLambdaOcc *lambdaOcc = static_cast<BBLambdaOcc *>(occ);
if (lambdaOcc->canbeant) {
classidVisited[occ->classid] = true;
}
break;
}
default:;
}
}
if (placementoptdebug) {
LogInfo::MapleLogger() << "--- lastuse decrefs at exits of bbs:";
for (BBId bbid : lastuse_bbs) {
LogInfo::MapleLogger() << " " << bbid.idx;
}
LogInfo::MapleLogger() << std::endl;
}
}
} // namespace maple
| 35.625 | 121 | 0.635413 | lvyitian |
51ba7f4f6ecb18e636c21d6b5ec58d4e2cd860f0 | 3,547 | cpp | C++ | src/server/backends/MemoryBackendCache.cpp | svalat/iocatcher | 4845e20d938c816f6ca5ee8d3308aa9a0e0abaff | [
"Apache-2.0"
] | 2 | 2022-01-28T16:03:14.000Z | 2022-02-18T07:35:22.000Z | src/server/backends/MemoryBackendCache.cpp | svalat/iocatcher | 4845e20d938c816f6ca5ee8d3308aa9a0e0abaff | [
"Apache-2.0"
] | 2 | 2022-02-10T10:22:02.000Z | 2022-02-11T18:00:47.000Z | src/server/backends/MemoryBackendCache.cpp | svalat/iocatcher | 4845e20d938c816f6ca5ee8d3308aa9a0e0abaff | [
"Apache-2.0"
] | 1 | 2022-01-31T21:09:15.000Z | 2022-01-31T21:09:15.000Z | /*****************************************************
* PROJECT : IO Catcher *
* LICENSE : Apache 2.0 *
* COPYRIGHT: 2020-2022 Bull SAS All rights reserved *
*****************************************************/
/****************************************************/
//std
#include <cstdlib>
#include <cstring>
#include <string>
#include <map>
#include <cassert>
//unix
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
//internal
#include "base/common/Debug.hpp"
#include "MemoryBackendCache.hpp"
/****************************************************/
using namespace IOC;
/****************************************************/
/**
* Constructor of the cached memory backend.
* @param backend Pointer to the sub backend to
* use to allocate and free memory.
**/
MemoryBackendCache::MemoryBackendCache(MemoryBackend * backend)
:MemoryBackend(NULL)
{
//check
assert(backend != NULL);
//setup
this->backend = backend;
}
/****************************************************/
/**
* Destructor of the memory backend, it free all the allocated memory.
* memory.
**/
MemoryBackendCache::~MemoryBackendCache(void)
{
//check that all lists are free
size_t cnt = 0;
for (auto & it : this->freeLists)
cnt += it.second.size();
if (cnt != this->rangesTracker.size())
IOC_WARNING_ARG("Missing elements in free list, might not have free all: %1 != %2")
.arg(cnt)
.arg(this->rangesTracker.size())
.end();
assert(cnt == this->rangesTracker.size());
//remove ranges
for (auto & it : this->rangesTracker) {
this->backend->deallocate(it.first, it.second);
}
//clear
this->rangesTracker.clear();
this->freeLists.clear();
//delete backend
delete this->backend;
}
/****************************************************/
/**
* Check if chunks are available in the cache and return it,
* if not found allocate new memory to the sub backend.
* @param size Size of the desired memory.
**/
void * MemoryBackendCache::allocate(size_t size)
{
//check
assert(size > 0);
//search in preexisting
auto & freeList = this->freeLists[size];
//check if empty
void * ptr = NULL;
if (freeList.empty()) {
//get from backend
ptr = this->backend->allocate(size);
//register to range tracker
this->rangesTracker[ptr] = size;
} else {
//extract first from list
ptr = freeList.front();
freeList.pop_front();
}
//return
return ptr;
}
/****************************************************/
/**
* Return the given chunk to the cache and register it
* for latter use. Notice, we currently free the memory
* only at exit.
* @param addr Address of the memory to return.
* @param size Size of the memory to return.
**/
void MemoryBackendCache::deallocate(void * addr, size_t size)
{
//check
assert(addr != NULL);
assert(size > 0);
//check
assert(isLocalMemory(addr, size));
//register to free list
this->freeLists[size].push_front(addr);
}
/****************************************************/
/**
* For debugging check if the given pointer belongs to the cache.
* @param ptr Address of the memory to return.
* @param size Size of the memory to return.
**/
bool MemoryBackendCache::isLocalMemory(void * ptr, size_t size)
{
//check
assert(ptr != NULL);
assert(size > 0);
assert(size % 4096 == 0);
//search
auto it = this->rangesTracker.find(ptr);
//return
if (it == this->rangesTracker.end()) {
return false;
} else {
assert(it->second == size);
return true;
}
}
| 23.490066 | 85 | 0.576262 | svalat |
51bc4e001b165451ed5d356f30f6b1d24c029ba8 | 563 | cpp | C++ | programmers/hash1.cpp | rune2002/coding-study | 94ae7f4d4f5ea21f68538462cff56cc12f0e0718 | [
"MIT"
] | null | null | null | programmers/hash1.cpp | rune2002/coding-study | 94ae7f4d4f5ea21f68538462cff56cc12f0e0718 | [
"MIT"
] | null | null | null | programmers/hash1.cpp | rune2002/coding-study | 94ae7f4d4f5ea21f68538462cff56cc12f0e0718 | [
"MIT"
] | null | null | null | #include <string>
#include <vector>
#include <algorithm>
using namespace std;
string solution(vector<string> participant, vector<string> completion) {
sort(participant.begin(), participant.end());
sort(completion.begin(), completion.end());
string answer;
for (int i = 0; i < completion.size(); i++)
{
if (participant[i].compare(completion[i]) != 0)
{
answer = participant[i];
break;
}
if (i == completion.size() - 1)
answer = participant[i+1];
}
return answer;
}
| 24.478261 | 72 | 0.577265 | rune2002 |
51bd7a66f51e0b4efff85820169c5feffb791ae4 | 262 | cpp | C++ | src/batteries/suppress_test.cpp | tonyastolfi/batteries | 67349930e54785f44eab84f1e56da6c78c66a5f9 | [
"Apache-2.0"
] | 1 | 2022-01-04T20:28:17.000Z | 2022-01-04T20:28:17.000Z | src/batteries/suppress_test.cpp | mihir-thakkar/batteries | 67349930e54785f44eab84f1e56da6c78c66a5f9 | [
"Apache-2.0"
] | 2 | 2020-06-04T14:02:24.000Z | 2020-06-04T14:03:18.000Z | src/batteries/suppress_test.cpp | mihir-thakkar/batteries | 67349930e54785f44eab84f1e56da6c78c66a5f9 | [
"Apache-2.0"
] | 1 | 2022-01-03T20:24:31.000Z | 2022-01-03T20:24:31.000Z | // Copyright 2021 Anthony Paul Astolfi
//
#include <batteries/suppress.hpp>
//
#include <batteries/suppress.hpp>
namespace {
BATT_SUPPRESS("-Wreturn-type")
BATT_SUPPRESS("-Wunused-function")
int foo()
{
}
BATT_UNSUPPRESS()
BATT_UNSUPPRESS()
} // namespace
| 13.1 | 38 | 0.729008 | tonyastolfi |
51bf698e4fbace8bd5e5a1d8f11bbb91abbe18ac | 2,818 | cc | C++ | stapl_release/benchmarks/runtime/synthetic/sqrt_asyncs.cc | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | stapl_release/benchmarks/runtime/synthetic/sqrt_asyncs.cc | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | stapl_release/benchmarks/runtime/synthetic/sqrt_asyncs.cc | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | /*
// Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a
// component of the Texas A&M University System.
// All rights reserved.
// The information and source code contained herein is the exclusive
// property of TEES and may not be disclosed, examined or reproduced
// in whole or in part without explicit written authorization from TEES.
*/
//////////////////////////////////////////////////////////////////////
/// @file
/// Benchmark where each location communicates with sqrt(N) locations, where N
/// is the total number of locations.
//////////////////////////////////////////////////////////////////////
#include "../benchmark.h"
#include <algorithm>
#include <cmath>
#include <numeric>
#include <random>
#include <vector>
class A
: public stapl::p_object
{
private:
std::vector<unsigned int> m_locs;
unsigned int m_num;
std::mt19937 m_rng;
struct randomizer
{
std::mt19937& m_rng;
explicit randomizer(std::mt19937& rng)
: m_rng(rng)
{ }
unsigned int operator()(unsigned int i)
{
return std::uniform_int_distribution<unsigned int>(0, i)(m_rng);
}
};
public:
A(void)
: m_locs(this->get_num_locations(), 0),
m_num(int(std::sqrt(double(m_locs.size()))))
{
if (m_locs.size()>1) {
std::fill(m_locs.begin() + 1, m_locs.end(), 1);
std::partial_sum(m_locs.begin(), m_locs.end(), m_locs.begin());
}
this->advance_epoch();
}
void pong(void)
{ }
void ping(unsigned int l)
{
stapl::async_rmi(l, this->get_rmi_handle(), &A::pong);
}
void call_pong(void)
{
randomizer r(m_rng);
std::random_shuffle(m_locs.begin(), m_locs.end(), r);
for (unsigned int i=0; i<m_num; ++i)
stapl::async_rmi(m_locs[i], this->get_rmi_handle(), &A::pong);
}
void call_ping_pong(void)
{
unsigned int myid = get_location_id();
randomizer r(m_rng);
std::random_shuffle(m_locs.begin(), m_locs.end(), r);
for (unsigned int i=0; i<m_num; ++i)
stapl::async_rmi(m_locs[i], this->get_rmi_handle(), &A::ping, myid);
}
};
// Kernel that does asyncs to random sqrt(p) locations
struct pong_wf
{
typedef void result_type;
static std::string name(void)
{ return std::string("multipong"); }
A obj;
void operator()(void)
{ obj.call_pong(); }
};
// Kernel that does asyncs to random sqrt(p) locations, followed by a reply
struct ping_pong_wf
{
typedef void result_type;
static std::string name(void)
{ return std::string("multipingpong"); }
A obj;
void operator()(void)
{ obj.call_ping_pong(); }
};
stapl::exit_code stapl_main(int argc, char* argv[])
{
stapl::runtime_profiler<> p(argc, argv);
{
pong_wf wf;
p.benchmark(wf);
}
{
ping_pong_wf wf;
p.benchmark(wf);
}
return EXIT_SUCCESS;
}
| 21.18797 | 78 | 0.61462 | parasol-ppl |
51c0068121fe645432d8c07de6d95e472cb9df6f | 700 | cpp | C++ | editor/model/serialize/ControlSurfaceSerializer.cpp | remaininlight/axiom | abd3d9232ffe89dff84b0ef56ab4a1ba9e58d7ce | [
"MIT"
] | 642 | 2017-12-10T14:22:04.000Z | 2022-03-03T15:23:23.000Z | editor/model/serialize/ControlSurfaceSerializer.cpp | remaininlight/axiom | abd3d9232ffe89dff84b0ef56ab4a1ba9e58d7ce | [
"MIT"
] | 151 | 2017-12-21T02:08:45.000Z | 2020-07-03T14:18:51.000Z | editor/model/serialize/ControlSurfaceSerializer.cpp | remaininlight/axiom | abd3d9232ffe89dff84b0ef56ab4a1ba9e58d7ce | [
"MIT"
] | 30 | 2018-09-11T14:06:31.000Z | 2021-11-09T04:19:00.000Z | #include "ControlSurfaceSerializer.h"
#include "../objects/ControlSurface.h"
using namespace AxiomModel;
void ControlSurfaceSerializer::serialize(AxiomModel::ControlSurface *surface, QDataStream &stream) {}
std::unique_ptr<ControlSurface> ControlSurfaceSerializer::deserialize(QDataStream &stream, uint32_t version,
const QUuid &uuid, const QUuid &parentUuid,
AxiomModel::ReferenceMapper *ref,
AxiomModel::ModelRoot *root) {
return ControlSurface::create(uuid, parentUuid, root);
}
| 46.666667 | 113 | 0.561429 | remaininlight |
51c1339d1ad811b34fd2ecc986a842594b4578fa | 4,866 | cpp | C++ | code/Arduino/src/main.cpp | ClassicDIY/SkyeTracker | e6b44344a66ef8cc7e6a64ea05dfc864eeb46d3a | [
"Apache-2.0"
] | 17 | 2020-04-08T15:51:58.000Z | 2022-03-23T12:20:48.000Z | code/Arduino/src/main.cpp | Scientist265/SkyeTracker | 78e929bba7dcabbc8ecd23b9e70426eafd0386df | [
"Apache-2.0"
] | 16 | 2016-11-15T17:03:02.000Z | 2020-03-30T18:15:21.000Z | code/Arduino/src/main.cpp | Scientist265/SkyeTracker | 78e929bba7dcabbc8ecd23b9e70426eafd0386df | [
"Apache-2.0"
] | 9 | 2020-04-02T12:39:21.000Z | 2021-12-30T22:13:34.000Z |
#include <ArduinoJson.h>
#include <ThreadController.h>
#include <Thread.h>
#include <SoftwareSerial.h>
#include <Wire.h>
#include <RTClib.h>
#include "sun.h"
#include "Configuration.h"
#include "Tracker.h"
#include "Trace.h"
#include "Anemometer.h"
using namespace SkyeTracker;
#define RECEIVE_BUFFER 200
RTC_DS1307 _rtc;
Configuration _config(&_rtc);
ThreadController _controller = ThreadController();
Tracker _tracker(&_config, &_rtc);
Anemometer _anemometer(A3);
Thread* _workerThread = new Thread();
SoftwareSerial _swSer(8, 9, false);
char* _receiveBuffer;
int _receiveIndex = 0;
int _protectCountdown = 0;
float _recordedWindSpeedAtLastEvent = 0;
uint32_t _lastWindEvent;
int freeRam()
{
extern int __heap_start, *__brkval;
int v;
return (int)&v - (__brkval == 0 ? (int)&__heap_start : (int)__brkval);
}
void runWorker()
{
//freeMem("Run");
//trace(&_swSer, F("RAM in Run: "));
//traceln(&_swSer, String(freeRam(), DEC));
bool broadcasting = _tracker.BroadcastPosition();
if (_config.hasAnemometer())
{
float windSpeed = _anemometer.WindSpeed();
if (_recordedWindSpeedAtLastEvent < windSpeed)
{
_lastWindEvent = _rtc.now().unixtime();
_recordedWindSpeedAtLastEvent = windSpeed;
}
if (_tracker.getState() == TrackerState_Tracking)
{
if (windSpeed > (AnemometerWindSpeedProtection / 3.6)) // wind speed greater than 28.8 km/hour? (8 M/S *3600 S)
{
_lastWindEvent = _rtc.now().unixtime();
_recordedWindSpeedAtLastEvent = windSpeed;
_tracker.Park(true);
_protectCountdown = 300; // 10 minute countdown to resume tracking
}
else if (--_protectCountdown <= 0)
{
_protectCountdown = 0;
_tracker.Resume();
}
}
if (broadcasting)
{
Serial.print("Wind|{");
Serial.print("\"sT\":"); // seconds in unixtime
Serial.print(_lastWindEvent);
Serial.print(",\"sC\":"); // current wind speed
Serial.print(windSpeed);
Serial.print(",\"sH\":"); // last high wind speed
Serial.print(_recordedWindSpeedAtLastEvent);
Serial.println("}");
};
}
}
void serialEvent() {
while (Serial.available()) {
char inChar = (char)Serial.read();
_receiveBuffer[_receiveIndex++] = inChar;
if (_receiveIndex >= RECEIVE_BUFFER)
{
Serial.print(F("receive buffer overflow!: "));
_receiveIndex = 0;
}
else if (inChar == '\r') {
//printHexString(_receiveBuffer);
_receiveBuffer[_receiveIndex] = 0;
_tracker.ProcessCommand(_receiveBuffer);
_receiveIndex = 0;
}
}
}
void setup()
{
Serial.begin(9600); // HC-06 default baud rate
while (!Serial) {
; // wait for serial port to connect.
}
_swSer.begin(115200);
//freeMem("At start of setup");
trace(&_swSer, F("RAM At start of setup: "));
traceln(&_swSer, String(freeRam(), DEC));
Wire.begin();
_rtc.begin();
if (!_rtc.isrunning()) {
traceln(&_swSer, F("RTC not running!"));
_rtc.adjust(DateTime(2015, 6, 21, 12, 00, 0));
_tracker._errorState = TrackerError_FailedToAccessRTC;
}
_lastWindEvent = 0;
String d = "";
DateTime now = _rtc.now();
d = d + now.year() + "/" + now.month() + "/" + now.day() + " " + now.hour() + ":" + now.minute() + ":" + now.second() + " ";
traceln(&_swSer, d);
traceln(&_swSer, F("Loading configuration"));
_config.Load();
// Configure main worker thread
_workerThread->onRun(runWorker);
_workerThread->setInterval(2000);
_controller.add(_workerThread);
traceln(&_swSer, F("Initializing tracker"));
_tracker.Initialize(&_controller);
_tracker.Track();
_receiveBuffer = (char*)malloc(RECEIVE_BUFFER);
//freeMem("At end of setup");
traceln(&_swSer, F("RAM Completing setup: ") );
traceln(&_swSer, String(freeRam(), DEC));
}
void loop()
{
_controller.run();
if (_tracker.getState() == TrackerState_Standby)
{
_tracker.Track();
}
serialEvent();
}
// Debug helper functions
//
//void printHexString(String txt)
//{
// for (int i = 0; i < txt.length(); i++)
// {
// trace(&_swSer, txt[i], HEX);
// }
// traceln(&_swSer, "");
//}
//Code to print out the free memory
//struct __freelist {
// size_t sz;
// struct __freelist *nx;
//};
//
//extern char * const __brkval;
//extern struct __freelist *__flp;
//
//uint16_t freeMem(uint16_t *biggest)
//{
// char *brkval;
// char *cp;
// unsigned freeSpace;
// struct __freelist *fp1, *fp2;
//
// brkval = __brkval;
// if (brkval == 0) {
// brkval = __malloc_heap_start;
// }
// cp = __malloc_heap_end;
// if (cp == 0) {
// cp = ((char *)AVR_STACK_POINTER_REG) - __malloc_margin;
// }
// if (cp <= brkval) return 0;
//
// freeSpace = cp - brkval;
//
// for (*biggest = 0, fp1 = __flp, fp2 = 0;
// fp1;
// fp2 = fp1, fp1 = fp1->nx) {
// if (fp1->sz > *biggest) *biggest = fp1->sz;
// freeSpace += fp1->sz;
// }
//
// return freeSpace;
//}
//
//uint16_t biggest;
//
//void freeMem(char* message) {
// trace(&_swSer, message);
// trace(&_swSer, ":\t");
// traceln(&_swSer, freeMem(&biggest));
//}
| 23.394231 | 128 | 0.655569 | ClassicDIY |
51c4a6bb6749515743378b5a027d76c56509cd44 | 7,431 | cpp | C++ | src/shapefunction/spline.cpp | ellery85/sparselizard | 7d09e97e9443a436d74cbd241b8466527edb9e2f | [
"MIT"
] | null | null | null | src/shapefunction/spline.cpp | ellery85/sparselizard | 7d09e97e9443a436d74cbd241b8466527edb9e2f | [
"MIT"
] | null | null | null | src/shapefunction/spline.cpp | ellery85/sparselizard | 7d09e97e9443a436d74cbd241b8466527edb9e2f | [
"MIT"
] | null | null | null | #include "spline.h"
#include "mathop.h"
#include "mat.h"
#include "vec.h"
#include "myalgorithm.h"
spline::spline(std::string filename, char delimiter)
{
std::vector<double> data = mathop::loadvector(filename, delimiter, false);
if (data.size()%2 != 0)
{
std::cout << "Error in 'spline' object: expected a vector length multiple of 2 in '" << filename << "' (format {x1,y1,x2,y2,...})" << std::endl;
abort();
}
std::vector<double> xin(data.size()/2);
std::vector<double> yin(data.size()/2);
for (int i = 0; i < data.size()/2; i++)
{
xin[i] = data[2*i+0];
yin[i] = data[2*i+1];
}
set(xin,yin);
}
spline::spline(std::vector<double> xin, std::vector<double> yin)
{
set(xin,yin);
}
void spline::set(std::vector<double>& xin, std::vector<double>& yin)
{
if (xin.size() != yin.size())
{
std::cout << "Error in 'spline' object: x and y dataset sizes do not match" << std::endl;
abort();
}
int len = xin.size();
if (len < 2)
{
std::cout << "Error in 'spline' object: expected at least two data points" << std::endl;
abort();
}
myx = densematrix(len,1);
myy = densematrix(len,1);
double* xvals = myx.getvalues();
double* yvals = myy.getvalues();
// First sort ascendingly according to x:
std::vector<int> reorderingvector;
myalgorithm::stablesort(0, xin, reorderingvector);
for (int i = 0; i < len; i++)
{
xvals[i] = xin[reorderingvector[i]];
yvals[i] = yin[reorderingvector[i]];
}
xmin = xvals[0]; xmax = xvals[len-1];
double absnoise = noisethreshold*std::abs(xmax-xmin);
for (int i = 1; i < len; i++)
{
if (xvals[i]-xvals[i-1] < absnoise)
{
std::cout << "Error in 'spline' object: distance between two samples is " << (xvals[i]-xvals[i-1]) << " (below noise level " << absnoise << ")" << std::endl;
abort();
}
}
// Create the A matrix and b rhs:
intdensematrix Arows(3*len-2,1), Acols(3*len-2,1);
int* Arowvals = Arows.getvalues();
int* Acolvals = Acols.getvalues();
densematrix Av(3*len-2,1);
double* Avals = Av.getvalues();
densematrix bv(len,1);
double* bvals = bv.getvalues();
// First row has no left neighbour:
Arowvals[0] = 0; Arowvals[1] = 0; Acolvals[0] = 0; Acolvals[1] = 1;
Avals[0] = 2.0/(xvals[1]-xvals[0]); Avals[1] = 1.0/(xvals[1]-xvals[0]);
bvals[0] = 3.0*(yvals[1]-yvals[0])*Avals[1]*Avals[1];
// Rows with two neighbours:
double b1 = bvals[0]; int ind = 2;
for (int i = 1; i < len-1; i++)
{
Arowvals[ind+0] = i; Arowvals[ind+1] = i; Arowvals[ind+2] = i;
Acolvals[ind+0] = i-1; Acolvals[ind+1] = i; Acolvals[ind+2] = i+1;
Avals[ind+0] = Avals[ind-1]; Avals[ind+2] = 1.0/(xvals[i+1]-xvals[i]); Avals[ind+1] = 2.0*(Avals[ind+0]+Avals[ind+2]);
double b2 = 3.0*(yvals[i+1]-yvals[i])*Avals[ind+2]*Avals[ind+2];
bvals[i] = b1+b2;
b1 = b2;
ind += 3;
}
// Last row has no right neighbour:
Arowvals[ind+0] = len-1; Arowvals[ind+1] = len-1; Acolvals[ind+0] = len-2; Acolvals[ind+1] = len-1;
Avals[ind+0] = 1.0/(xvals[len-1]-xvals[len-2]); Avals[ind+1] = 2.0/(xvals[len-1]-xvals[len-2]);
bvals[len-1] = 3.0*(yvals[len-1]-yvals[len-2])*Avals[ind+0]*Avals[ind+0];
// Solve problem Ak = b:
mat A(len, Arows, Acols, Av);
vec b(len, intdensematrix(len,1,0,1), bv);
vec k = mathop::solve(A,b);
densematrix kv = k.getvalues(intdensematrix(len,1,0,1));
double* kvals = kv.getvalues();
// Compute the spline parameters a and b:
mya = densematrix(len,1);
myb = densematrix(len,1);
double* aparamvals = mya.getvalues();
double* bparamvals = myb.getvalues();
for (int i = 1; i < len; i++)
{
aparamvals[i] = kvals[i-1]*(xvals[i]-xvals[i-1])-(yvals[i]-yvals[i-1]);
bparamvals[i] = -kvals[i]*(xvals[i]-xvals[i-1])+(yvals[i]-yvals[i-1]);
}
}
double spline::evalat(double input)
{
std::vector<double> invec = {input};
return evalat(invec)[0];
}
std::vector<double> spline::evalat(std::vector<double> input)
{
densematrix indm(input.size(),1, input);
densematrix outdm = evalat(indm);
std::vector<double> output;
outdm.getvalues(output);
return output;
}
densematrix spline::evalat(densematrix input)
{
int numin = input.count();
double* inputvals = input.getvalues();
std::vector<double> invals;
input.getvalues(invals);
// Sort the input data ascendingly:
std::vector<int> reorderingvector;
myalgorithm::stablesort(0, invals, reorderingvector);
for (int i = 0; i < numin; i++)
inputvals[i] = invals[reorderingvector[i]];
double inmin = inputvals[0]; double inmax = inputvals[numin-1];
// Error if request is out of range:
double absnoise = noisethreshold*std::abs(xmax-xmin);
if (inmin < xmin-absnoise || inmax > xmax+absnoise)
{
std::cout << "Error in 'spline' object: data requested in interval (" << inmin << "," << inmax << ") is out of the provided data range (" << xmin << "," << xmax << ")" << std::endl;
abort();
}
std::vector<double> outvec(numin);
// Get the corresponding data via spline interpolation.
double* xvals = myx.getvalues(); double* yvals = myy.getvalues();
double* avals = mya.getvalues(); double* bvals = myb.getvalues();
// First find the corresponding spline:
int curspline = 1;
for (int i = 0; i < numin; i++)
{
double cur = inputvals[i];
// Find the spline:
while (xvals[curspline] < cur-absnoise)
curspline++;
// Interpolate on the spline:
double tx = (cur-xvals[curspline-1])/(xvals[curspline]-xvals[curspline-1]);
outvec[i] = (1.0-tx)*yvals[curspline-1] + tx*yvals[curspline] + tx*(1.0-tx)*((1.0-tx)*avals[curspline]+tx*bvals[curspline]);
}
// Unsort the data:
densematrix output(input.countrows(),input.countcolumns());
double* outputvals = output.getvalues();
for (int i = 0; i < numin; i++)
outputvals[reorderingvector[i]] = outvec[i];
return output;
}
void spline::write(std::string filename, int numsplits, char delimiter)
{
if (numsplits < 0)
{
std::cout << "Error in 'spline' object: cannot write with " << numsplits << " splits" << std::endl;
abort();
}
// Get the x positions:
double* xvalues = myx.getvalues();
densematrix xsplit(1+(myx.count()-1)*(numsplits+1),1);
double* xsplitvals = xsplit.getvalues();
double step = 1.0/(numsplits+1.0);
xsplitvals[0] = xvalues[0];
int index = 1;
for (int i = 0; i < myx.count()-1; i++)
{
for (int j = 0; j < numsplits+1; j++)
{
xsplitvals[index] = xvalues[i]+(j+1.0)*step*(xvalues[i+1]-xvalues[i]);
index++;
}
}
densematrix evaled = evalat(xsplit);
double* evaledvals = evaled.getvalues();
// Write to file:
std::vector<double> data(2*xsplit.count());
for (int i = 0; i < xsplit.count(); i++)
{
data[2*i+0] = xsplitvals[i];
data[2*i+1] = evaledvals[i];
}
mathop::writevector(filename, data, delimiter, false);
}
| 30.9625 | 189 | 0.56668 | ellery85 |
51c96f6d013ecc6f84edbadd1476d86a9c1cee6e | 54,305 | cpp | C++ | src/lms7002m/LMS7002M_RxTxCalibrations.cpp | bastille-attic/LimeSuite | 761805c75b1ae1e0ec9b8c6c182ebd058a088ab8 | [
"Apache-2.0"
] | null | null | null | src/lms7002m/LMS7002M_RxTxCalibrations.cpp | bastille-attic/LimeSuite | 761805c75b1ae1e0ec9b8c6c182ebd058a088ab8 | [
"Apache-2.0"
] | null | null | null | src/lms7002m/LMS7002M_RxTxCalibrations.cpp | bastille-attic/LimeSuite | 761805c75b1ae1e0ec9b8c6c182ebd058a088ab8 | [
"Apache-2.0"
] | null | null | null | #include "LMS7002M.h"
#include "CalibrationCache.h"
#include "ErrorReporting.h"
#include <assert.h>
#include "MCU_BD.h"
#include "IConnection.h"
#include "mcu_programs.h"
#include "LMS64CProtocol.h"
#include <vector>
#include <ciso646>
#define LMS_VERBOSE_OUTPUT
///define for parameter enumeration if prefix might be needed
#define LMS7param(id) id
using namespace lime;
float_type calibUserBwDivider = 5;
const static uint16_t MCU_PARAMETER_ADDRESS = 0x002D; //register used to pass parameter values to MCU
#define MCU_ID_DC_IQ_CALIBRATIONS 0x01
#define MCU_FUNCTION_CALIBRATE_TX 1
#define MCU_FUNCTION_CALIBRATE_RX 2
#define MCU_FUNCTION_READ_RSSI 3
#define MCU_FUNCTION_UPDATE_REF_CLK 4
#ifdef ENABLE_CALIBRATION_USING_FFT
#include "kiss_fft.h"
int fftBin = 0; //which bin to use when calibration using FFT
bool rssiFromFFT = false;
#endif // ENABLE_CALIBRATION_USING_FFT
const float calibrationSXOffset_Hz = 4e6;
const int16_t firCoefs[] =
{
8,
4,
0,
-6,
-11,
-16,
-20,
-22,
-22,
-20,
-14,
-5,
6,
20,
34,
46,
56,
61,
58,
48,
29,
3,
-29,
-63,
-96,
-123,
-140,
-142,
-128,
-94,
-44,
20,
93,
167,
232,
280,
302,
291,
244,
159,
41,
-102,
-258,
-409,
-539,
-628,
-658,
-614,
-486,
-269,
34,
413,
852,
1328,
1814,
2280,
2697,
3038,
3277,
3401,
3401,
3277,
3038,
2697,
2280,
1814,
1328,
852,
413,
34,
-269,
-486,
-614,
-658,
-628,
-539,
-409,
-258,
-102,
41,
159,
244,
291,
302,
280,
232,
167,
93,
20,
-44,
-94,
-128,
-142,
-140,
-123,
-96,
-63,
-29,
3,
29,
48,
58,
61,
56,
46,
34,
20,
6,
-5,
-14,
-20,
-22,
-22,
-20,
-16,
-11,
-6,
0,
4,
8
};
const uint16_t backupAddrs[] = {
0x0020, 0x0082, 0x0084, 0x0085, 0x0086, 0x0087, 0x0088,
0x0089, 0x008A, 0x008B, 0x008C, 0x0100, 0x0101, 0x0102, 0x0103,
0x0104, 0x0105, 0x0106, 0x0107, 0x0108, 0x0109, 0x010A, 0x010C,
0x010D, 0x010E, 0x010F, 0x0110, 0x0111, 0x0112, 0x0113, 0x0114,
0x0115, 0x0116, 0x0117, 0x0118, 0x0119, 0x011A, 0x0200, 0x0201,
0x0202, 0x0203, 0x0204, 0x0205, 0x0206, 0x0207, 0x0208, 0x0240,
0x0241, 0x0242, 0x0243, 0x0244, 0x0245, 0x0246, 0x0247, 0x0248,
0x0249, 0x024A, 0x024B, 0x024C, 0x024D, 0x024E, 0x024F, 0x0250,
0x0251, 0x0252, 0x0253, 0x0254, 0x0255, 0x0256, 0x0257, 0x0258,
0x0259, 0x025A, 0x025B, 0x025C, 0x025D, 0x025E, 0x025F, 0x0260,
0x0261, 0x0400, 0x0401, 0x0402, 0x0403, 0x0404, 0x0405, 0x0406,
0x0407, 0x0408, 0x0409, 0x040A, 0x040C, 0x040D, 0x0440, 0x0441,
0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447, 0x0448, 0x0449,
0x044A, 0x044B, 0x044C, 0x044D, 0x044E, 0x044F, 0x0450, 0x0451,
0x0452, 0x0453, 0x0454, 0x0455, 0x0456, 0x0457, 0x0458, 0x0459,
0x045A, 0x045B, 0x045C, 0x045D, 0x045E, 0x045F, 0x0460, 0x0461
};
uint16_t backupRegs[sizeof(backupAddrs) / sizeof(int16_t)];
const uint16_t backupSXAddr[] = { 0x011C, 0x011D, 0x011E, 0x011F, 0x0120, 0x0121, 0x0122, 0x0123, 0x0124 };
uint16_t backupRegsSXR[sizeof(backupSXAddr) / sizeof(int16_t)];
uint16_t backupRegsSXT[sizeof(backupSXAddr) / sizeof(int16_t)];
int16_t rxGFIR3_backup[sizeof(firCoefs) / sizeof(int16_t)];
uint16_t backup0x010D;
uint16_t backup0x0100;
inline uint16_t pow2(const uint8_t power)
{
assert(power >= 0 && power < 16);
return 1 << power;
}
bool sign(const int number)
{
return number < 0;
}
/** @brief Parameters setup instructions for Tx calibration
@return 0-success, other-failure
*/
int LMS7002M::CalibrateTxSetup(float_type bandwidth_Hz, const bool useExtLoopback)
{
//Stage 2
uint8_t ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC));
uint8_t sel_band1_trf = (uint8_t)Get_SPI_Reg_bits(LMS7param(SEL_BAND1_TRF));
uint8_t sel_band2_trf = (uint8_t)Get_SPI_Reg_bits(LMS7param(SEL_BAND2_TRF));
//rfe
//reset RFE to defaults
SetDefaults(RFE);
if(useExtLoopback)
{
int LNAselection = 1;
Modify_SPI_Reg_bits(LMS7param(SEL_PATH_RFE), LNAselection); //SEL_PATH_RFE 3
Modify_SPI_Reg_bits(LMS7param(G_LNA_RFE), 1);
Modify_SPI_Reg_bits(0x010C, 4, 3, 0); //PD_MXLOBUF_RFE 0, PD_QGEN_RFE 0
Modify_SPI_Reg_bits(LMS7param(CCOMP_TIA_RFE), 4);
Modify_SPI_Reg_bits(LMS7param(CFB_TIA_RFE), 50);
Modify_SPI_Reg_bits(LMS7param(ICT_LODC_RFE), 31); //ICT_LODC_RFE 31
if(LNAselection == 2)
{
Modify_SPI_Reg_bits(LMS7param(EN_INSHSW_L_RFE), 0);
Modify_SPI_Reg_bits(LMS7param(EN_INSHSW_W_RFE), 1);
}
else if(LNAselection == 3)
{
Modify_SPI_Reg_bits(LMS7param(EN_INSHSW_L_RFE), 1);
Modify_SPI_Reg_bits(LMS7param(EN_INSHSW_W_RFE), 0);
}
else
{
Modify_SPI_Reg_bits(LMS7param(EN_INSHSW_L_RFE), 1);
Modify_SPI_Reg_bits(LMS7param(EN_INSHSW_W_RFE), 1);
}
Modify_SPI_Reg_bits(LMS7param(PD_LNA_RFE), 0);
Modify_SPI_Reg_bits(LMS7param(EN_DCOFF_RXFE_RFE), 1);
Modify_SPI_Reg_bits(LMS7param(G_TIA_RFE), 1);
}
else
{
if(sel_band1_trf == 1)
Modify_SPI_Reg_bits(LMS7param(SEL_PATH_RFE), 3); //SEL_PATH_RFE 3
else if(sel_band2_trf == 1)
Modify_SPI_Reg_bits(LMS7param(SEL_PATH_RFE), 2);
else
return ReportError(EINVAL, "Tx Calibration: band not selected");
Modify_SPI_Reg_bits(LMS7param(G_RXLOOPB_RFE), 7);
Modify_SPI_Reg_bits(0x010C, 4, 3, 0); //PD_MXLOBUF_RFE 0, PD_QGEN_RFE 0
Modify_SPI_Reg_bits(LMS7param(CCOMP_TIA_RFE), 4);
Modify_SPI_Reg_bits(LMS7param(CFB_TIA_RFE), 50);
Modify_SPI_Reg_bits(LMS7param(ICT_LODC_RFE), 31); //ICT_LODC_RFE 31
if(sel_band1_trf)
{
Modify_SPI_Reg_bits(LMS7param(PD_RLOOPB_1_RFE), 0);
Modify_SPI_Reg_bits(LMS7param(PD_RLOOPB_2_RFE), 1);
Modify_SPI_Reg_bits(LMS7param(EN_INSHSW_LB1_RFE), 0);
Modify_SPI_Reg_bits(LMS7param(EN_INSHSW_LB2_RFE), 1);
}
else
{
Modify_SPI_Reg_bits(LMS7param(PD_RLOOPB_1_RFE), 1);
Modify_SPI_Reg_bits(LMS7param(PD_RLOOPB_2_RFE), 0);
Modify_SPI_Reg_bits(LMS7param(EN_INSHSW_LB1_RFE), 1);
Modify_SPI_Reg_bits(LMS7param(EN_INSHSW_LB2_RFE), 0);
}
Modify_SPI_Reg_bits(LMS7param(EN_DCOFF_RXFE_RFE), 1);
}
//RBB
//reset RBB to defaults
SetDefaults(RBB);
Modify_SPI_Reg_bits(LMS7param(PD_LPFL_RBB), 1);
Modify_SPI_Reg_bits(LMS7param(G_PGA_RBB), 0);
Modify_SPI_Reg_bits(LMS7param(INPUT_CTL_PGA_RBB), 2);
Modify_SPI_Reg_bits(LMS7param(ICT_PGA_OUT_RBB), 12);
Modify_SPI_Reg_bits(LMS7param(ICT_PGA_IN_RBB), 12);
//TRF
Modify_SPI_Reg_bits(LMS7param(L_LOOPB_TXPAD_TRF), 0); //L_LOOPB_TXPAD_TRF 0
if(useExtLoopback)
{
Modify_SPI_Reg_bits(LMS7param(EN_LOOPB_TXPAD_TRF), 0); //EN_LOOPB_TXPAD_TRF 1
Modify_SPI_Reg_bits(LMS7param(EN_G_TRF), 1);
}
else
Modify_SPI_Reg_bits(LMS7param(EN_LOOPB_TXPAD_TRF), 1); //EN_LOOPB_TXPAD_TRF 1
//AFE
Modify_SPI_Reg_bits(LMS7param(PD_RX_AFE1), 0); //PD_RX_AFE1 0
Modify_SPI_Reg_bits(LMS7param(PD_RX_AFE2), 0); //PD_RX_AFE2 0
//BIAS
uint16_t backup = Get_SPI_Reg_bits(LMS7param(RP_CALIB_BIAS));
SetDefaults(BIAS);
Modify_SPI_Reg_bits(LMS7param(RP_CALIB_BIAS), backup); //RP_CALIB_BIAS
//XBUF
Modify_SPI_Reg_bits(0x0085, 2, 0, 1); //PD_XBUF_RX 0, PD_XBUF_TX 0, EN_G_XBUF 1
//CGEN
//reset CGEN to defaults
const float_type cgenFreq = GetFrequencyCGEN();
int cgenMultiplier = int((cgenFreq / 46.08e6) + 0.5);
if(cgenMultiplier < 2)
cgenMultiplier = 2;
if(cgenMultiplier > 9 && cgenMultiplier < 12)
cgenMultiplier = 12;
if(cgenMultiplier > 13)
cgenMultiplier = 13;
//power up VCO
Modify_SPI_Reg_bits(0x0086, 2, 2, 0);
int status = SetFrequencyCGEN(46.08e6 * cgenMultiplier);
if(status != 0)
return status;
//SXR
Modify_SPI_Reg_bits(LMS7param(MAC), 1);
SetDefaults(SX);
Modify_SPI_Reg_bits(LMS7param(PD_VCO), 0);
Modify_SPI_Reg_bits(LMS7param(ICT_VCO), 200);
{
float_type SXTfreq = GetFrequencySX(Tx);
float_type SXRfreq = SXTfreq - bandwidth_Hz / calibUserBwDivider - calibrationSXOffset_Hz;
status = SetFrequencySX(Rx, SXRfreq);
if(status != 0)
return status;
status = TuneVCO(VCO_SXR);
if(status != 0)
return status;
}
//SXT
Modify_SPI_Reg_bits(LMS7param(MAC), 2);
Modify_SPI_Reg_bits(PD_LOCH_T2RBUF, 1);
Modify_SPI_Reg_bits(LMS7param(MAC), ch);
//TXTSP
Modify_SPI_Reg_bits(LMS7param(TSGMODE_TXTSP), 1);
Modify_SPI_Reg_bits(LMS7param(INSEL_TXTSP), 1);
if(useExtLoopback)
Modify_SPI_Reg_bits(LMS7param(CMIX_BYP_TXTSP), 1);
else
Modify_SPI_Reg_bits(LMS7param(CMIX_BYP_TXTSP), 0);
Modify_SPI_Reg_bits(DC_BYP_TXTSP, 0);
Modify_SPI_Reg_bits(GC_BYP_TXTSP, 0);
Modify_SPI_Reg_bits(PH_BYP_TXTSP, 0);
Modify_SPI_Reg_bits(GCORRI_TXTSP, 2047);
Modify_SPI_Reg_bits(GCORRQ_TXTSP, 2047);
Modify_SPI_Reg_bits(CMIX_SC_TXTSP, 0);
LoadDC_REG_IQ(Tx, (int16_t)0x7FFF, (int16_t)0x8000);
SetNCOFrequency(Tx, 0, bandwidth_Hz / calibUserBwDivider);
//RXTSP
SetDefaults(RxTSP);
SetDefaults(RxNCO);
Modify_SPI_Reg_bits(LMS7param(GFIR2_BYP_RXTSP), 1);
Modify_SPI_Reg_bits(LMS7param(GFIR1_BYP_RXTSP), 1);
Modify_SPI_Reg_bits(LMS7param(HBD_OVR_RXTSP), 4); //Decimation HBD ratio
if(useExtLoopback)
{
Modify_SPI_Reg_bits(LMS7param(GFIR3_BYP_RXTSP), 1);
Modify_SPI_Reg_bits(LMS7param(AGC_BYP_RXTSP), 1);
}
else
{
Modify_SPI_Reg_bits(LMS7param(AGC_MODE_RXTSP), 1);
Modify_SPI_Reg_bits(LMS7param(CMIX_BYP_RXTSP), 1);
Modify_SPI_Reg_bits(LMS7param(AGC_AVG_RXTSP), 0x1);
Modify_SPI_Reg_bits(LMS7param(GFIR3_L_RXTSP), 7);
if(Get_SPI_Reg_bits(EN_ADCCLKH_CLKGN) == 1)
{
int clkh_ov = Get_SPI_Reg_bits(CLKH_OV_CLKL_CGEN);
Modify_SPI_Reg_bits(LMS7param(GFIR3_N_RXTSP), 4 * cgenMultiplier/pow2(clkh_ov) - 1);
}
else
Modify_SPI_Reg_bits(LMS7param(GFIR3_N_RXTSP), 4 * cgenMultiplier - 1);
SetGFIRCoefficients(Rx, 2, firCoefs, sizeof(firCoefs) / sizeof(int16_t));
}
if(ch == 2)
{
Modify_SPI_Reg_bits(MAC, 1);
Modify_SPI_Reg_bits(LMS7param(PD_TX_AFE2), 0);
Modify_SPI_Reg_bits(LMS7param(EN_NEXTRX_RFE), 1); // EN_NEXTTX_RFE 1
Modify_SPI_Reg_bits(LMS7param(EN_NEXTTX_TRF), 1); //EN_NEXTTX_TRF 1
Modify_SPI_Reg_bits(MAC, ch);
}
return 0;
}
/** @brief Flips the CAPTURE bit and returns digital RSSI value
*/
uint32_t LMS7002M::GetRSSI()
{
#ifdef ENABLE_CALIBRATION_USING_FFT
if(!rssiFromFFT)
{
const int fftSize = 16384;
StreamConfig config;
config.isTx = false;
config.channels.push_back(0);
config.channels.push_back(1);
config.format = StreamConfig::STREAM_12_BIT_IN_16;
config.bufferLength = fftSize;
size_t streamID(~0);
controlPort->SetHardwareTimestamp(0);
const auto errorMsg = controlPort->SetupStream(streamID, config);
float avgRSSI = 0;
const int channelsCount = 1;
kiss_fft_cfg m_fftCalcPlan = kiss_fft_alloc(fftSize, 0, 0, 0);
kiss_fft_cpx* m_fftCalcIn = new kiss_fft_cpx[fftSize];
kiss_fft_cpx* m_fftCalcOut = new kiss_fft_cpx[fftSize];
int16_t **buffs = new int16_t*[channelsCount];
for(int i=0; i<channelsCount; ++i)
buffs[i] = new int16_t[fftSize];
//TODO setup streaming
StreamMetadata metadata;
auto ret = controlPort->ReadStream(streamID, (void* const*)buffs, fftSize, 1000, metadata);
long samplesCollected = 0;
int16_t sample = 0;
const int stepSize = 4;
/*for (uint16_t b = 0; b < bytesReceived; b += stepSize)
{
//I sample
sample = (buffer[b] & 0xFF);
sample |= (buffer[b + 1] & 0x0F) << 8;
sample = sample << 4;
sample = sample >> 4;
m_fftCalcIn[samplesCollected].r = sample;
//Q sample
sample = (buffer[b + 2] & 0xFF);
sample |= (buffer[b + 3] & 0x0F) << 8;
sample = sample << 4;
sample = sample >> 4;
m_fftCalcIn[samplesCollected].i = sample;
++samplesCollected;
if (samplesCollected >= fftSize)
break;
}*/
kiss_fft(m_fftCalcPlan, m_fftCalcIn, m_fftCalcOut);
for (int i = 0; i < fftSize; ++i)
{
// normalize FFT results
m_fftCalcOut[i].r /= fftSize;
m_fftCalcOut[i].i /= fftSize;
}
std::vector<float> fftBins_dbFS;
fftBins_dbFS.resize(fftSize, 0);
int output_index = 0;
for (int i = 0; i < fftSize; ++i)
{
fftBins_dbFS[output_index++] = sqrt(m_fftCalcOut[i].r * m_fftCalcOut[i].r + m_fftCalcOut[i].i * m_fftCalcOut[i].i);
}
for (int s = 0; s < fftSize; ++s)
fftBins_dbFS[s] = (fftBins_dbFS[s] != 0 ? (20 * log10(fftBins_dbFS[s])) - 69.2369 : -300);
int binToGet = fftBin;
float rssiToReturn = m_fftCalcOut[binToGet].r * m_fftCalcOut[binToGet].r + m_fftCalcOut[binToGet].i * m_fftCalcOut[binToGet].i;
avgRSSI = fftBins_dbFS[binToGet];
kiss_fft_free(m_fftCalcPlan);
for(int i=0; i<channelsCount; ++i)
delete buffs[i];
delete[]buffs;
printf("FFT RSSI = %f \n", avgRSSI);
controlPort->CloseStream(streamID);
return avgRSSI;
}
#endif
Modify_SPI_Reg_bits(LMS7param(CAPTURE), 0);
Modify_SPI_Reg_bits(LMS7param(CAPTURE), 1);
return (Get_SPI_Reg_bits(0x040F, 15, 0, true) << 2) | Get_SPI_Reg_bits(0x040E, 1, 0, true);
}
/** @brief Calibrates Transmitter. DC correction, IQ gains, IQ phase correction
@return 0-success, other-failure
*/
int LMS7002M::CalibrateTx(float_type bandwidth_Hz, const bool useExtLoopback)
{
if(useExtLoopback)
return ReportError(EPERM, "Calibration with external loopback not yet implemented");
int status;
if(mCalibrationByMCU)
{
uint8_t mcuID = mcuControl->ReadMCUProgramID();
if(mcuID != MCU_ID_DC_IQ_CALIBRATIONS)
{
status = mcuControl->Program_MCU(mcu_program_lms7_dc_iq_calibration_bin, MCU_BD::SRAM);
if(status != 0)
return status;
}
}
Channel ch = this->GetActiveChannel();
uint8_t sel_band1_trf = (uint8_t)Get_SPI_Reg_bits(LMS7param(SEL_BAND1_TRF));
uint8_t sel_band2_trf = (uint8_t)Get_SPI_Reg_bits(LMS7param(SEL_BAND2_TRF));
uint32_t boardId = controlPort->GetDeviceInfo().boardSerialNumber;
double txFreq = GetFrequencySX(Tx);
uint8_t channel = ch == 1 ? 0 : 1;
bool foundInCache = false;
int band = sel_band1_trf ? 0 : 1;
uint16_t gainAddr;
uint16_t gcorri;
uint16_t gcorrq;
uint16_t dccorri;
uint16_t dccorrq;
int16_t phaseOffset;
int16_t gain = 1983;
const uint16_t gainMSB = 10;
const uint16_t gainLSB = 0;
if(useCache)
{
int dcI, dcQ, gainI, gainQ, phOffset;
foundInCache = (mValueCache->GetDC_IQ(boardId, txFreq*1e6, channel, true, band, &dcI, &dcQ, &gainI, &gainQ, &phOffset) == 0);
if(foundInCache)
{
printf("Tx calibration: using cached values\n");
dccorri = dcI;
dccorrq = dcQ;
gcorri = gainI;
gcorrq = gainQ;
phaseOffset = phOffset;
Modify_SPI_Reg_bits(LMS7param(DCCORRI_TXTSP), dcI);
Modify_SPI_Reg_bits(LMS7param(DCCORRQ_TXTSP), dcQ);
Modify_SPI_Reg_bits(LMS7param(GCORRI_TXTSP), gainI);
Modify_SPI_Reg_bits(LMS7param(GCORRQ_TXTSP), gainQ);
Modify_SPI_Reg_bits(LMS7param(IQCORR_TXTSP), phaseOffset);
Modify_SPI_Reg_bits(LMS7param(DC_BYP_TXTSP), 0); //DC_BYP
Modify_SPI_Reg_bits(0x0208, 1, 0, 0); //GC_BYP PH_BYP
return 0;
}
}
LMS7002M_SelfCalState state(this);
Log("Tx calibration started", LOG_INFO);
BackupAllRegisters();
Log("Setup stage", LOG_INFO);
status = CalibrateTxSetup(bandwidth_Hz, useExtLoopback);
if(status != 0)
goto TxCalibrationEnd; //go to ending stage to restore registers
if(mCalibrationByMCU)
{
//set reference clock parameter inside MCU
long refClk = GetReferenceClk_SX(false);
uint16_t refClkToMCU = (int(refClk / 1000000) << 9) | ((refClk % 1000000) / 10000);
SPI_write(MCU_PARAMETER_ADDRESS, refClkToMCU);
mcuControl->CallMCU(MCU_FUNCTION_UPDATE_REF_CLK);
auto statusMcu = mcuControl->WaitForMCU(100);
//set bandwidth for MCU to read from register, value is integer stored in MHz
SPI_write(MCU_PARAMETER_ADDRESS, (uint16_t)(bandwidth_Hz / 1e6));
mcuControl->CallMCU(MCU_FUNCTION_CALIBRATE_TX);
statusMcu = mcuControl->WaitForMCU(30000);
if(statusMcu == 0)
{
printf("MCU working too long %i\n", statusMcu);
}
}
else
{
CheckSaturationTxRx(bandwidth_Hz, useExtLoopback);
Modify_SPI_Reg_bits(EN_G_TRF, 0);
if(!useExtLoopback)
CalibrateRxDC_RSSI();
CalibrateTxDC_RSSI(bandwidth_Hz);
//TXIQ
Modify_SPI_Reg_bits(EN_G_TRF, 1);
Modify_SPI_Reg_bits(CMIX_BYP_TXTSP, 0);
SetNCOFrequency(LMS7002M::Rx, 0, calibrationSXOffset_Hz - 0.1e6);
//coarse gain
uint32_t rssiIgain;
uint32_t rssiQgain;
Modify_SPI_Reg_bits(GCORRI_TXTSP, 2047 - 64);
Modify_SPI_Reg_bits(GCORRQ_TXTSP, 2047);
rssiIgain = GetRSSI();
Modify_SPI_Reg_bits(GCORRI_TXTSP, 2047);
Modify_SPI_Reg_bits(GCORRQ_TXTSP, 2047 - 64);
rssiQgain = GetRSSI();
Modify_SPI_Reg_bits(GCORRI_TXTSP, 2047);
Modify_SPI_Reg_bits(GCORRQ_TXTSP, 2047);
if(rssiIgain < rssiQgain)
gainAddr = GCORRI_TXTSP.address;
else
gainAddr = GCORRQ_TXTSP.address;
CoarseSearch(gainAddr, gainMSB, gainLSB, gain, 7);
#ifdef LMS_VERBOSE_OUTPUT
printf("Coarse search Tx GAIN_%s: %i\n", gainAddr == GCORRI_TXTSP.address ? "I" : "Q", gain);
#endif
//coarse phase offset
uint32_t rssiUp;
uint32_t rssiDown;
Modify_SPI_Reg_bits(IQCORR_TXTSP, 15);
rssiUp = GetRSSI();
Modify_SPI_Reg_bits(IQCORR_TXTSP, -15);
rssiDown = GetRSSI();
if(rssiUp > rssiDown)
phaseOffset = -64;
else if(rssiUp < rssiDown)
phaseOffset = 192;
else
phaseOffset = 64;
Modify_SPI_Reg_bits(IQCORR_TXTSP, phaseOffset);
CoarseSearch(IQCORR_TXTSP.address, IQCORR_TXTSP.msb, IQCORR_TXTSP.lsb, phaseOffset, 7);
#ifdef LMS_VERBOSE_OUTPUT
printf("Coarse search Tx IQCORR: %i\n", phaseOffset);
#endif
CoarseSearch(gainAddr, gainMSB, gainLSB, gain, 4);
#ifdef LMS_VERBOSE_OUTPUT
printf("Coarse search Tx GAIN_%s: %i\n", gainAddr == GCORRI_TXTSP.address ? "I" : "Q", gain);
printf("Fine search Tx GAIN_%s/IQCORR...\n", gainAddr == GCORRI_TXTSP.address ? "I" : "Q");
#endif
FineSearch(gainAddr, gainMSB, gainLSB, gain, IQCORR_TXTSP.address, IQCORR_TXTSP.msb, IQCORR_TXTSP.lsb, phaseOffset, 7);
#ifdef LMS_VERBOSE_OUTPUT
printf("Fine search Tx GAIN_%s: %i, IQCORR: %i\n", gainAddr == GCORRI_TXTSP.address ? "I" : "Q", gain, phaseOffset);
#endif
Modify_SPI_Reg_bits(gainAddr, gainMSB, gainLSB, gain);
Modify_SPI_Reg_bits(IQCORR_TXTSP.address, IQCORR_TXTSP.msb, IQCORR_TXTSP.lsb, phaseOffset);
}
dccorri = Get_SPI_Reg_bits(LMS7param(DCCORRI_TXTSP), true);
dccorrq = Get_SPI_Reg_bits(LMS7param(DCCORRQ_TXTSP), true);
gcorri = Get_SPI_Reg_bits(LMS7param(GCORRI_TXTSP), true);
gcorrq = Get_SPI_Reg_bits(LMS7param(GCORRQ_TXTSP), true);
phaseOffset = Get_SPI_Reg_bits(LMS7param(IQCORR_TXTSP), true);
TxCalibrationEnd:
Log("Restoring registers state", LOG_INFO);
Modify_SPI_Reg_bits(LMS7param(MAC), ch);
RestoreAllRegisters();
if(status != 0)
{
Log("Tx calibration failed", LOG_WARNING);
return status;
}
if(useCache)
mValueCache->InsertDC_IQ(boardId, txFreq*1e6, channel, true, band, dccorri, dccorrq, gcorri, gcorrq, phaseOffset);
Modify_SPI_Reg_bits(LMS7param(MAC), ch);
Modify_SPI_Reg_bits(LMS7param(DCCORRI_TXTSP), dccorri);
Modify_SPI_Reg_bits(LMS7param(DCCORRQ_TXTSP), dccorrq);
Modify_SPI_Reg_bits(LMS7param(GCORRI_TXTSP), gcorri);
Modify_SPI_Reg_bits(LMS7param(GCORRQ_TXTSP), gcorrq);
Modify_SPI_Reg_bits(LMS7param(IQCORR_TXTSP), phaseOffset);
Modify_SPI_Reg_bits(LMS7param(DC_BYP_TXTSP), 0); //DC_BYP
Modify_SPI_Reg_bits(0x0208, 1, 0, 0); //GC_BYP PH_BYP
LoadDC_REG_IQ(Tx, (int16_t)0x7FFF, (int16_t)0x8000);
Log("Tx calibration finished", LOG_INFO);
return 0;
}
/** @brief Performs Rx DC offsets calibration
*/
void LMS7002M::CalibrateRxDC_RSSI()
{
#ifdef ENABLE_CALIBRATION_USING_FFT
fftBin = 0;
#endif
int16_t offsetI = 32;
int16_t offsetQ = 32;
Modify_SPI_Reg_bits(DC_BYP_RXTSP, 1);
Modify_SPI_Reg_bits(CAPSEL, 0);
SetRxDCOFF(offsetI, offsetQ);
//find I
CoarseSearch(DCOFFI_RFE.address, DCOFFI_RFE.msb, DCOFFI_RFE.lsb, offsetI, 6);
//find Q
CoarseSearch(DCOFFQ_RFE.address, DCOFFQ_RFE.msb, DCOFFQ_RFE.lsb, offsetQ, 6);
CoarseSearch(DCOFFI_RFE.address, DCOFFI_RFE.msb, DCOFFI_RFE.lsb, offsetI, 3);
CoarseSearch(DCOFFQ_RFE.address, DCOFFQ_RFE.msb, DCOFFQ_RFE.lsb, offsetQ, 3);
#ifdef LMS_VERBOSE_OUTPUT
printf("Fine search Rx DCOFFI/DCOFFQ\n");
#endif
FineSearch(DCOFFI_RFE.address, DCOFFI_RFE.msb, DCOFFI_RFE.lsb, offsetI, DCOFFQ_RFE.address, DCOFFQ_RFE.msb, DCOFFQ_RFE.lsb, offsetQ, 5);
#ifdef LMS_VERBOSE_OUTPUT
printf("Fine search Rx DCOFFI: %i, DCOFFQ: %i\n", offsetI, offsetQ);
#endif
SetRxDCOFF(offsetI, offsetQ);
Modify_SPI_Reg_bits(DC_BYP_RXTSP, 0); // DC_BYP 0
#ifdef ENABLE_CALIBRATION_USING_FFT
fftBin = 569; //fft bin 100 kHz
#endif
}
/** @brief Parameters setup instructions for Rx calibration
@param bandwidth_Hz filter bandwidth in Hz
@return 0-success, other-failure
*/
int LMS7002M::CalibrateRxSetup(float_type bandwidth_Hz, const bool useExtLoopback)
{
uint8_t ch = (uint8_t)Get_SPI_Reg_bits(LMS7param(MAC));
//rfe
Modify_SPI_Reg_bits(LMS7param(EN_DCOFF_RXFE_RFE), 1);
if(not useExtLoopback)
Modify_SPI_Reg_bits(LMS7param(G_RXLOOPB_RFE), 3);
Modify_SPI_Reg_bits(0x010C, 4, 3, 0); //PD_MXLOBUF_RFE 0, PD_QGEN_RFE 0
Modify_SPI_Reg_bits(0x010C, 1, 1, 0); //PD_TIA 0
Modify_SPI_Reg_bits(0x0110, 4, 0, 31); //ICT_LO_RFE 31
//RBB
Modify_SPI_Reg_bits(0x0115, 15, 14, 0); //Loopback switches disable
Modify_SPI_Reg_bits(0x0119, 15, 15, 0); //OSW_PGA 0
//TRF
//reset TRF to defaults
SetDefaults(TRF);
if(not useExtLoopback)
{
Modify_SPI_Reg_bits(L_LOOPB_TXPAD_TRF, 0);
Modify_SPI_Reg_bits(EN_LOOPB_TXPAD_TRF, 1);
}
else
Modify_SPI_Reg_bits(LOSS_MAIN_TXPAD_TRF, 10);
Modify_SPI_Reg_bits(EN_G_TRF, 0);
{
uint8_t selPath;
if(useExtLoopback) //use PA1
selPath = 3;
else
selPath = Get_SPI_Reg_bits(SEL_PATH_RFE);
if (selPath == 2)
{
Modify_SPI_Reg_bits(SEL_BAND2_TRF, 1);
Modify_SPI_Reg_bits(SEL_BAND1_TRF, 0);
}
else if (selPath == 3)
{
Modify_SPI_Reg_bits(SEL_BAND2_TRF, 0);
Modify_SPI_Reg_bits(SEL_BAND1_TRF, 1);
}
else
return ReportError("CalibrateRxSetup() - SEL_PATH_RFE must be LNAL or LNAW"); //todo restore settings
}
//TBB
//reset TBB to defaults
SetDefaults(TBB);
Modify_SPI_Reg_bits(LMS7param(CG_IAMP_TBB), 1);
Modify_SPI_Reg_bits(LMS7param(ICT_IAMP_FRP_TBB), 1); //ICT_IAMP_FRP_TBB 1
Modify_SPI_Reg_bits(LMS7param(ICT_IAMP_GG_FRP_TBB), 6); //ICT_IAMP_GG_FRP_TBB 6
//AFE
Modify_SPI_Reg_bits(LMS7param(PD_RX_AFE2), 0); //PD_RX_AFE2
//BIAS
{
uint16_t rp_calib_bias = Get_SPI_Reg_bits(0x0084, 10, 6);
SetDefaults(BIAS);
Modify_SPI_Reg_bits(0x0084, 10, 6, rp_calib_bias); //RP_CALIB_BIAS
}
//XBUF
Modify_SPI_Reg_bits(0x0085, 2, 0, 1); //PD_XBUF_RX 0, PD_XBUF_TX 0, EN_G_XBUF 1
//CGEN
//reset CGEN to defaults
const float_type cgenFreq = GetFrequencyCGEN();
SetDefaults(CGEN);
int cgenMultiplier = int(cgenFreq / 46.08e6 + 0.5);
if(cgenMultiplier < 2)
cgenMultiplier = 2;
if(cgenMultiplier > 9 && cgenMultiplier < 12)
cgenMultiplier = 12;
if(cgenMultiplier > 13)
cgenMultiplier = 13;
//power up VCO
Modify_SPI_Reg_bits(0x0086, 2, 2, 0);
int status = SetFrequencyCGEN(46.08e6 * cgenMultiplier);
if(status != 0)
return status;
Modify_SPI_Reg_bits(MAC, 2);
bool isTDD = Get_SPI_Reg_bits(PD_LOCH_T2RBUF, true) == 0;
if(isTDD)
{
//in TDD do nothing
Modify_SPI_Reg_bits(MAC, 1);
SetDefaults(SX);
SetFrequencySX(false, GetFrequencySX(true) - bandwidth_Hz / calibUserBwDivider - 9e6);
Modify_SPI_Reg_bits(PD_VCO, 1);
}
else
{
//SXR
Modify_SPI_Reg_bits(LMS7param(MAC), 1);
float_type SXRfreqHz = GetFrequencySX(Rx);
//SXT
Modify_SPI_Reg_bits(LMS7param(MAC), 2);
SetDefaults(SX);
Modify_SPI_Reg_bits(LMS7param(PD_VCO), 0);
status = SetFrequencySX(Tx, SXRfreqHz + bandwidth_Hz / calibUserBwDivider + 9e6);
if(status != 0) return status;
}
Modify_SPI_Reg_bits(LMS7param(MAC), ch);
//TXTSP
SetDefaults(TxTSP);
SetDefaults(TxNCO);
Modify_SPI_Reg_bits(LMS7param(TSGFCW_TXTSP), 1);
Modify_SPI_Reg_bits(TSGMODE_TXTSP, 0x1); //TSGMODE 1
Modify_SPI_Reg_bits(INSEL_TXTSP, 1);
Modify_SPI_Reg_bits(0x0208, 6, 4, 0x7); //GFIR3_BYP 1, GFIR2_BYP 1, GFIR1_BYP 1
Modify_SPI_Reg_bits(CMIX_GAIN_TXTSP, 0);
Modify_SPI_Reg_bits(CMIX_SC_TXTSP, 1);
LoadDC_REG_IQ(Tx, (int16_t)0x7FFF, (int16_t)0x8000);
SetNCOFrequency(Tx, 0, 9e6);
//RXTSP
SetDefaults(RxTSP);
SetDefaults(RxNCO);
Modify_SPI_Reg_bits(0x040C, 4, 4, 1); //
Modify_SPI_Reg_bits(0x040C, 3, 3, 1); //
Modify_SPI_Reg_bits(LMS7param(HBD_OVR_RXTSP), 4);
if(not useExtLoopback)
{
Modify_SPI_Reg_bits(LMS7param(AGC_MODE_RXTSP), 1); //AGC_MODE 1
Modify_SPI_Reg_bits(0x040C, 7, 7, 0x1); //CMIX_BYP 1
Modify_SPI_Reg_bits(LMS7param(CAPSEL), 0);
Modify_SPI_Reg_bits(LMS7param(AGC_AVG_RXTSP), 1); //agc_avg iq corr
Modify_SPI_Reg_bits(LMS7param(CMIX_GAIN_RXTSP), 0);
Modify_SPI_Reg_bits(LMS7param(GFIR3_L_RXTSP), 7);
Modify_SPI_Reg_bits(LMS7param(GFIR3_N_RXTSP), 4*cgenMultiplier - 1);
SetGFIRCoefficients(Rx, 2, firCoefs, sizeof(firCoefs) / sizeof(int16_t));
}
else
{
Modify_SPI_Reg_bits(0x040C, 5, 5, 1); // GFIR3_BYP
Modify_SPI_Reg_bits(AGC_BYP_RXTSP, 1);
Modify_SPI_Reg_bits(CMIX_BYP_RXTSP, 1);
}
SetNCOFrequency(Rx, 0, bandwidth_Hz/calibUserBwDivider - 0.1e6);
if(useExtLoopback)
{
//limelight
Modify_SPI_Reg_bits(LML1_FIDM, 1);
Modify_SPI_Reg_bits(LML2_FIDM, 1);
Modify_SPI_Reg_bits(LML1_MODE, 0);
Modify_SPI_Reg_bits(LML2_MODE, 0);
}
//modifications when calibrating channel B
if(ch == 2)
{
Modify_SPI_Reg_bits(MAC, 1);
Modify_SPI_Reg_bits(LMS7param(EN_NEXTRX_RFE), 1);
Modify_SPI_Reg_bits(EN_NEXTTX_TRF, 1);
Modify_SPI_Reg_bits(LMS7param(PD_TX_AFE2), 0);
Modify_SPI_Reg_bits(MAC, ch);
}
return 0;
}
/** @brief Calibrates Receiver. DC offset, IQ gains, IQ phase correction
@return 0-success, other-failure
*/
int LMS7002M::CalibrateRx(float_type bandwidth_Hz, const bool useExtLoopback)
{
if(useExtLoopback)
return ReportError(EPERM, "Calibration with external loopback not yet implemented");
int status;
if(mCalibrationByMCU)
{
uint8_t mcuID = mcuControl->ReadMCUProgramID();
if(mcuID != MCU_ID_DC_IQ_CALIBRATIONS)
{
status = mcuControl->Program_MCU(mcu_program_lms7_dc_iq_calibration_bin, MCU_BD::SRAM);
if( status != 0)
return status;
}
}
Channel ch = this->GetActiveChannel();
uint32_t boardId = controlPort->GetDeviceInfo().boardSerialNumber;
uint8_t channel = ch == 1 ? 0 : 1;
uint8_t sel_path_rfe = (uint8_t)Get_SPI_Reg_bits(LMS7param(SEL_PATH_RFE));
int lna = sel_path_rfe;
int16_t iqcorr_rx = 0;
int16_t dcoffi;
int16_t dcoffq;
int16_t gain;
uint16_t gainAddr = 0;
const uint8_t gainMSB = 10;
const uint8_t gainLSB = 0;
uint16_t mingcorri;
uint16_t mingcorrq;
int16_t phaseOffset;
double rxFreq = GetFrequencySX(Rx);
bool foundInCache = false;
if(useCache)
{
int dcI, dcQ, gainI, gainQ, phOffset;
foundInCache = (mValueCache->GetDC_IQ(boardId, rxFreq, channel, false, lna, &dcI, &dcQ, &gainI, &gainQ, &phOffset) == 0);
dcoffi = dcI;
dcoffq = dcQ;
mingcorri = gainI;
mingcorrq = gainQ;
phaseOffset = phOffset;
if(foundInCache)
{
printf("Rx calibration: using cached values\n");
SetRxDCOFF(dcoffi, dcoffq);
Modify_SPI_Reg_bits(LMS7param(EN_DCOFF_RXFE_RFE), 1);
Modify_SPI_Reg_bits(LMS7param(GCORRI_RXTSP), gainI);
Modify_SPI_Reg_bits(LMS7param(GCORRQ_RXTSP), gainQ);
Modify_SPI_Reg_bits(LMS7param(IQCORR_RXTSP), phaseOffset);
Modify_SPI_Reg_bits(0x040C, 2, 0, 0); //DC_BYP 0, GC_BYP 0, PH_BYP 0
Modify_SPI_Reg_bits(0x0110, 4, 0, 31); //ICT_LO_RFE 31
return 0;
}
}
LMS7002M_SelfCalState state(this);
Log("Rx calibration started", LOG_INFO);
Log("Saving registers state", LOG_INFO);
BackupAllRegisters();
if(sel_path_rfe == 1 || sel_path_rfe == 0)
return ReportError(EINVAL, "Rx Calibration: bad SEL_PATH");
Log("Setup stage", LOG_INFO);
status = CalibrateRxSetup(bandwidth_Hz, useExtLoopback);
if(status != 0)
goto RxCalibrationEndStage;
if(mCalibrationByMCU)
{
//set reference clock parameter inside MCU
long refClk = GetReferenceClk_SX(false);
uint16_t refClkToMCU = (int(refClk / 1000000) << 9) | ((refClk % 1000000) / 10000);
SPI_write(MCU_PARAMETER_ADDRESS, refClkToMCU);
mcuControl->CallMCU(MCU_FUNCTION_UPDATE_REF_CLK);
auto statusMcu = mcuControl->WaitForMCU(100);
//set bandwidth for MCU to read from register, value is integer stored in MHz
SPI_write(MCU_PARAMETER_ADDRESS, (uint16_t)(bandwidth_Hz / 1e6));
mcuControl->CallMCU(MCU_FUNCTION_CALIBRATE_RX);
statusMcu = mcuControl->WaitForMCU(30000);
if(statusMcu == 0)
{
printf("MCU working too long %i\n", statusMcu);
}
}
else
{
Log("Rx DC calibration", LOG_INFO);
CalibrateRxDC_RSSI();
// RXIQ calibration
Modify_SPI_Reg_bits(LMS7param(EN_G_TRF), 1);
if(not useExtLoopback)
{
if (sel_path_rfe == 2)
{
Modify_SPI_Reg_bits(LMS7param(PD_RLOOPB_2_RFE), 0);
Modify_SPI_Reg_bits(LMS7param(EN_INSHSW_LB2_RFE), 0);
}
if (sel_path_rfe == 3)
{
Modify_SPI_Reg_bits(LMS7param(PD_RLOOPB_1_RFE), 0);
Modify_SPI_Reg_bits(LMS7param(EN_INSHSW_LB1_RFE), 0);
}
Modify_SPI_Reg_bits(DC_BYP_RXTSP, 0); //DC_BYP 0
}
Modify_SPI_Reg_bits(MAC, 2);
if (Get_SPI_Reg_bits(PD_LOCH_T2RBUF) == false)
{
Modify_SPI_Reg_bits(PD_LOCH_T2RBUF, 1);
//TDD MODE
Modify_SPI_Reg_bits(MAC, 1);
Modify_SPI_Reg_bits(PD_VCO, 0);
}
Modify_SPI_Reg_bits(MAC, ch);
CheckSaturationRx(bandwidth_Hz, useExtLoopback);
Modify_SPI_Reg_bits(CMIX_SC_RXTSP, 1);
Modify_SPI_Reg_bits(CMIX_BYP_RXTSP, 0);
SetNCOFrequency(LMS7002M::Rx, 0, bandwidth_Hz/calibUserBwDivider + 0.1e6);
Modify_SPI_Reg_bits(IQCORR_RXTSP, 0);
Modify_SPI_Reg_bits(GCORRI_RXTSP, 2047);
Modify_SPI_Reg_bits(GCORRQ_RXTSP, 2047);
//coarse gain
{
Modify_SPI_Reg_bits(GCORRI_RXTSP, 2047 - 64);
Modify_SPI_Reg_bits(GCORRQ_RXTSP, 2047);
uint32_t rssiIgain = GetRSSI();
Modify_SPI_Reg_bits(GCORRI_RXTSP, 2047);
Modify_SPI_Reg_bits(GCORRQ_RXTSP, 2047 - 64);
uint32_t rssiQgain = GetRSSI();
Modify_SPI_Reg_bits(GCORRI_RXTSP, 2047);
Modify_SPI_Reg_bits(GCORRQ_RXTSP, 2047);
gain = 1983;
if(rssiIgain < rssiQgain)
{
gainAddr = 0x0402;
Modify_SPI_Reg_bits(GCORRI_RXTSP, gain);
}
else
{
gainAddr = 0x0401;
Modify_SPI_Reg_bits(GCORRQ_RXTSP, gain);
}
}
CoarseSearch(gainAddr, gainMSB, gainLSB, gain, 7);
#ifdef LMS_VERBOSE_OUTPUT
printf("Coarse search Rx GAIN_%s: %i\n", gainAddr == GCORRI_RXTSP.address ? "I" : "Q", gain);
#endif
//find phase offset
uint32_t rssiUp;
uint32_t rssiDown;
Modify_SPI_Reg_bits(IQCORR_RXTSP, 15);
rssiUp = GetRSSI();
Modify_SPI_Reg_bits(IQCORR_RXTSP, -15);
rssiDown = GetRSSI();
if(rssiUp > rssiDown)
phaseOffset = -64;
else if(rssiUp < rssiDown)
phaseOffset = 192;
else
phaseOffset = 64;
Modify_SPI_Reg_bits(IQCORR_RXTSP, phaseOffset);
CoarseSearch(IQCORR_RXTSP.address, IQCORR_RXTSP.msb, IQCORR_RXTSP.lsb, phaseOffset, 7);
#ifdef LMS_VERBOSE_OUTPUT
printf("Coarse search Rx IQCORR: %i\n", phaseOffset);
#endif
CoarseSearch(gainAddr, gainMSB, gainLSB, gain, 4);
#ifdef LMS_VERBOSE_OUTPUT
printf("Coarse search Rx GAIN_%s: %i\n", gainAddr == GCORRI_RXTSP.address ? "I" : "Q", gain);
#endif
CoarseSearch(IQCORR_RXTSP.address, IQCORR_RXTSP.msb, IQCORR_RXTSP.lsb, phaseOffset, 4);
#ifdef LMS_VERBOSE_OUTPUT
printf("Coarse search Rx IQCORR: %i\n", phaseOffset);
#endif
#ifdef LMS_VERBOSE_OUTPUT
printf("Fine search Rx GAIN_%s/IQCORR\n", gainAddr == GCORRI_RXTSP.address ? "I" : "Q");
#endif
FineSearch(gainAddr, gainMSB, gainLSB, gain, IQCORR_RXTSP.address, IQCORR_RXTSP.msb, IQCORR_RXTSP.lsb, phaseOffset, 7);
Modify_SPI_Reg_bits(gainAddr, gainMSB, gainLSB, gain);
Modify_SPI_Reg_bits(IQCORR_RXTSP.address, IQCORR_RXTSP.msb, IQCORR_RXTSP.lsb, phaseOffset);
#ifdef LMS_VERBOSE_OUTPUT
printf("Fine search Rx GAIN_%s: %i, IQCORR: %i\n", gainAddr == GCORRI_RXTSP.address ? "I" : "Q", gain, phaseOffset);
#endif
}
mingcorri = Get_SPI_Reg_bits(GCORRI_RXTSP, true);
mingcorrq = Get_SPI_Reg_bits(GCORRQ_RXTSP, true);
dcoffi = Get_SPI_Reg_bits(DCOFFI_RFE, true);
dcoffq = Get_SPI_Reg_bits(DCOFFQ_RFE, true);
phaseOffset = Get_SPI_Reg_bits(IQCORR_RXTSP, true);
RxCalibrationEndStage:
Log("Restoring registers state", LOG_INFO);
RestoreAllRegisters();
if (status != 0)
{
Log("Rx calibration failed", LOG_WARNING);
return status;
}
if(useCache)
mValueCache->InsertDC_IQ(boardId, rxFreq*1e6, channel, false, lna, dcoffi, dcoffq, mingcorri, mingcorrq, phaseOffset);
Modify_SPI_Reg_bits(LMS7param(MAC), ch);
SetRxDCOFF((int8_t)dcoffi, (int8_t)dcoffq);
Modify_SPI_Reg_bits(LMS7param(EN_DCOFF_RXFE_RFE), 1);
Modify_SPI_Reg_bits(LMS7param(GCORRI_RXTSP), mingcorri);
Modify_SPI_Reg_bits(LMS7param(GCORRQ_RXTSP), mingcorrq);
Modify_SPI_Reg_bits(LMS7param(IQCORR_RXTSP), phaseOffset);
Modify_SPI_Reg_bits(0x040C, 2, 0, 0); //DC_BYP 0, GC_BYP 0, PH_BYP 0
Modify_SPI_Reg_bits(0x0110, 4, 0, 31); //ICT_LO_RFE 31
Log("Rx calibration finished", LOG_INFO);
return 0;
}
/** @brief Stores chip current registers state into memory for later restoration
*/
void LMS7002M::BackupAllRegisters()
{
Channel ch = this->GetActiveChannel();
SPI_read_batch(backupAddrs, backupRegs, sizeof(backupAddrs) / sizeof(uint16_t));
this->SetActiveChannel(ChA); // channel A
SPI_read_batch(backupSXAddr, backupRegsSXR, sizeof(backupRegsSXR) / sizeof(uint16_t));
//backup GFIR3 coefficients
GetGFIRCoefficients(LMS7002M::Rx, 2, rxGFIR3_backup, sizeof(rxGFIR3_backup)/sizeof(int16_t));
//EN_NEXTRX_RFE could be modified in channel A
backup0x010D = SPI_read(0x010D);
//EN_NEXTTX_TRF could be modified in channel A
backup0x0100 = SPI_read(0x0100);
this->SetActiveChannel(ChB); // channel B
SPI_read_batch(backupSXAddr, backupRegsSXT, sizeof(backupRegsSXR) / sizeof(uint16_t));
this->SetActiveChannel(ch);
}
/** @brief Sets chip registers to state that was stored in memory using BackupAllRegisters()
*/
void LMS7002M::RestoreAllRegisters()
{
Channel ch = this->GetActiveChannel();
SPI_write_batch(backupAddrs, backupRegs, sizeof(backupAddrs) / sizeof(uint16_t));
//restore GFIR3
SetGFIRCoefficients(LMS7002M::Rx, 2, rxGFIR3_backup, sizeof(rxGFIR3_backup)/sizeof(int16_t));
this->SetActiveChannel(ChA); // channel A
SPI_write(0x010D, backup0x010D); //restore EN_NEXTRX_RFE
SPI_write(0x0100, backup0x0100); //restore EN_NEXTTX_TRF
SPI_write_batch(backupSXAddr, backupRegsSXR, sizeof(backupRegsSXR) / sizeof(uint16_t));
this->SetActiveChannel(ChB); // channel B
SPI_write_batch(backupSXAddr, backupRegsSXT, sizeof(backupRegsSXR) / sizeof(uint16_t));
this->SetActiveChannel(ch);
//reset Tx logic registers, fixes interpolator
uint16_t x0020val = SPI_read(0x0020);
SPI_write(0x0020, x0020val & ~0xA000);
SPI_write(0x0020, x0020val);
}
int LMS7002M::CheckSaturationRx(const float_type bandwidth_Hz, const bool useExtLoopback)
{
Modify_SPI_Reg_bits(CMIX_SC_RXTSP, 0);
Modify_SPI_Reg_bits(CMIX_BYP_RXTSP, 0);
SetNCOFrequency(LMS7002M::Rx, 0, bandwidth_Hz / calibUserBwDivider - 0.1e6);
uint32_t rssi = GetRSSI();
#ifdef ENABLE_CALIBRATION_USING_FFT
//use FFT bin 100 kHz for RSSI
fftBin = 569;
//0x0B000 = -3 dBFS
if(useExtLoopback)
{
const float_type target_dBFS = -14;
int loss_main_txpad = Get_SPI_Reg_bits(LOSS_MAIN_TXPAD_TRF);
while (rssi < target_dBFS && loss_main_txpad > 0)
{
rssi = GetRSSI();
if (rssi < target_dBFS)
loss_main_txpad -= 1;
if (rssi > target_dBFS)
break;
Modify_SPI_Reg_bits(G_RXLOOPB_RFE, loss_main_txpad);
}
int cg_iamp = Get_SPI_Reg_bits(CG_IAMP_TBB);
while (rssi < target_dBFS && cg_iamp < 39)
{
rssi = GetRSSI();
if (rssi < target_dBFS)
cg_iamp += 2;
if (rssi > target_dBFS)
break;
Modify_SPI_Reg_bits(CG_IAMP_TBB, cg_iamp);
}
return 0;
}
#endif
int g_rxloopb_rfe = Get_SPI_Reg_bits(G_RXLOOPB_RFE);
while (rssi < 0x0B000 && g_rxloopb_rfe < 15)
{
rssi = GetRSSI();
if (rssi < 0x0B000)
g_rxloopb_rfe += 2;
if (rssi > 0x0B000)
break;
Modify_SPI_Reg_bits(G_RXLOOPB_RFE, g_rxloopb_rfe);
}
int cg_iamp = Get_SPI_Reg_bits(CG_IAMP_TBB);
while (rssi < 0x01000 && cg_iamp < 63-6)
{
rssi = GetRSSI();
if (rssi < 0x01000)
cg_iamp += 4;
if (rssi > 0x01000)
break;
Modify_SPI_Reg_bits(CG_IAMP_TBB, cg_iamp);
}
while (rssi < 0x0B000 && cg_iamp < 62)
{
rssi = GetRSSI();
if (rssi < 0x0B000)
cg_iamp += 2;
Modify_SPI_Reg_bits(CG_IAMP_TBB, cg_iamp);
}
return 0;
}
static uint16_t toDCOffset(int16_t offset)
{
uint16_t valToSend = 0;
if (offset < 0)
valToSend |= 0x40;
valToSend |= labs(offset);
return valToSend;
}
void LMS7002M::CoarseSearch(const uint16_t addr, const uint8_t msb, const uint8_t lsb, int16_t &value, const uint8_t maxIterations)
{
const uint16_t DCOFFaddr = 0x010E;
uint8_t rssi_counter = 0;
uint32_t rssiUp;
uint32_t rssiDown;
int16_t upval;
int16_t downval;
upval = value;
for(rssi_counter = 0; rssi_counter < maxIterations - 1; ++rssi_counter)
{
rssiUp = GetRSSI();
value -= pow2(maxIterations - rssi_counter);
Modify_SPI_Reg_bits(addr, msb, lsb, addr != DCOFFaddr ? value : toDCOffset(value));
downval = value;
rssiDown = GetRSSI();
if(rssiUp >= rssiDown)
value += pow2(maxIterations - 2 - rssi_counter);
else
value = value + pow2(maxIterations - rssi_counter) + pow2(maxIterations - 1 - rssi_counter) - pow2(maxIterations - 2 - rssi_counter);
Modify_SPI_Reg_bits(addr, msb, lsb, addr != DCOFFaddr ? value : toDCOffset(value));
upval = value;
}
value -= pow2(maxIterations - rssi_counter);
rssiUp = GetRSSI();
if(addr != DCOFFaddr)
Modify_SPI_Reg_bits(addr, msb, lsb, value - pow2(maxIterations - rssi_counter));
else
Modify_SPI_Reg_bits(addr, msb, lsb, toDCOffset(value - pow2(maxIterations - rssi_counter)));
rssiDown = GetRSSI();
if(rssiUp < rssiDown)
value += 1;
Modify_SPI_Reg_bits(addr, msb, lsb, addr != DCOFFaddr ? value : toDCOffset(value));
rssiDown = GetRSSI();
if(rssiUp < rssiDown)
{
value += 1;
Modify_SPI_Reg_bits(addr, msb, lsb, addr != DCOFFaddr ? value : toDCOffset(value));
}
}
int LMS7002M::CheckSaturationTxRx(const float_type bandwidth_Hz, const bool useExtLoopback)
{
if(useExtLoopback)
{
SetNCOFrequency(LMS7002M::Rx, 0, calibrationSXOffset_Hz - 0.1e6 + bandwidth_Hz / calibUserBwDivider);
const float target_dBFS = -10;
int g_tia = Get_SPI_Reg_bits(G_TIA_RFE);
int g_lna = Get_SPI_Reg_bits(G_LNA_RFE);
int g_pga = Get_SPI_Reg_bits(G_PGA_RBB);
while(GetRSSI() < target_dBFS && g_lna <= 15)
{
g_lna += 1;
Modify_SPI_Reg_bits(LMS7param(G_LNA_RFE), g_lna);
}
if(g_lna > 15)
g_lna = 15;
Modify_SPI_Reg_bits(LMS7param(G_LNA_RFE), g_lna);
if(GetRSSI() >= target_dBFS)
goto rxGainFound;
while(GetRSSI() < target_dBFS && g_tia <= 3)
{
g_tia += 1;
Modify_SPI_Reg_bits(LMS7param(G_TIA_RFE), g_tia);
}
if(g_tia > 3)
g_tia = 3;
Modify_SPI_Reg_bits(LMS7param(G_TIA_RFE), g_tia);
if(GetRSSI() >= target_dBFS)
goto rxGainFound;
while(GetRSSI() < target_dBFS && g_pga < 18)
{
g_pga += 2;
Modify_SPI_Reg_bits(LMS7param(G_PGA_RBB), g_pga);
}
Modify_SPI_Reg_bits(LMS7param(G_PGA_RBB), g_pga);
rxGainFound:
Modify_SPI_Reg_bits(LMS7param(EN_G_TRF), 0);
Modify_SPI_Reg_bits(LMS7param(CMIX_BYP_RXTSP), 1);
CalibrateRxDC_RSSI();
Modify_SPI_Reg_bits(LMS7param(CMIX_BYP_RXTSP), 0);
Modify_SPI_Reg_bits(LMS7param(EN_G_TRF), 1);
SetNCOFrequency(LMS7002M::Rx, 0, calibrationSXOffset_Hz + 0.1e6 + bandwidth_Hz / calibUserBwDivider);
Modify_SPI_Reg_bits(LMS7param(CMIX_SC_RXTSP), 1);
//---------IQ calibration-----------------
int16_t iqcorr_rx = 0;
int16_t gain;
uint16_t gainAddr = 0;
const uint8_t gainMSB = 10;
const uint8_t gainLSB = 0;
int16_t phaseOffset;
Modify_SPI_Reg_bits(IQCORR_RXTSP, 0);
Modify_SPI_Reg_bits(GCORRI_RXTSP, 2047);
Modify_SPI_Reg_bits(GCORRQ_RXTSP, 2047);
//coarse gain
Modify_SPI_Reg_bits(GCORRI_RXTSP, 2047 - 64);
Modify_SPI_Reg_bits(GCORRQ_RXTSP, 2047);
uint32_t rssiIgain = GetRSSI();
Modify_SPI_Reg_bits(GCORRI_RXTSP, 2047);
Modify_SPI_Reg_bits(GCORRQ_RXTSP, 2047 - 64);
uint32_t rssiQgain = GetRSSI();
Modify_SPI_Reg_bits(GCORRI_RXTSP, 2047);
Modify_SPI_Reg_bits(GCORRQ_RXTSP, 2047);
gain = 1983;
if(rssiIgain < rssiQgain)
{
gainAddr = 0x0402;
Modify_SPI_Reg_bits(GCORRI_RXTSP, gain);
}
else
{
gainAddr = 0x0401;
Modify_SPI_Reg_bits(GCORRQ_RXTSP, gain);
}
CoarseSearch(gainAddr, gainMSB, gainLSB, gain, 7);
//find phase offset
{
uint32_t rssiUp;
uint32_t rssiDown;
Modify_SPI_Reg_bits(IQCORR_RXTSP, 15);
rssiUp = GetRSSI();
Modify_SPI_Reg_bits(IQCORR_RXTSP, -15);
rssiDown = GetRSSI();
if(rssiUp > rssiDown)
phaseOffset = -64;
else if(rssiUp < rssiDown)
phaseOffset = 192;
else
phaseOffset = 64;
Modify_SPI_Reg_bits(IQCORR_RXTSP, phaseOffset);
}
CoarseSearch(IQCORR_RXTSP.address, IQCORR_RXTSP.msb, IQCORR_RXTSP.lsb, phaseOffset, 7);
CoarseSearch(gainAddr, gainMSB, gainLSB, gain, 4);
CoarseSearch(IQCORR_RXTSP.address, IQCORR_RXTSP.msb, IQCORR_RXTSP.lsb, phaseOffset, 4);
FineSearch(gainAddr, gainMSB, gainLSB, gain, IQCORR_RXTSP.address, IQCORR_RXTSP.msb, IQCORR_RXTSP.lsb, phaseOffset, 7);
Modify_SPI_Reg_bits(gainAddr, gainMSB, gainLSB, gain);
Modify_SPI_Reg_bits(IQCORR_RXTSP.address, IQCORR_RXTSP.msb, IQCORR_RXTSP.lsb, phaseOffset);
Modify_SPI_Reg_bits(LMS7param(CMIX_SC_RXTSP), 0);
return 0;
}
//----------------------------------------
Modify_SPI_Reg_bits(LMS7param(DC_BYP_RXTSP), 0);
Modify_SPI_Reg_bits(LMS7param(CMIX_BYP_RXTSP), 0);
SetNCOFrequency(LMS7002M::Rx, 0, calibrationSXOffset_Hz - 0.1e6 + (bandwidth_Hz / calibUserBwDivider) * 2);
uint32_t rssi = GetRSSI();
int g_pga = Get_SPI_Reg_bits(G_PGA_RBB);
int g_rxlooop = Get_SPI_Reg_bits(G_RXLOOPB_RFE);
const int saturationLevel = 0x0B000;
while(rssi < saturationLevel && g_rxlooop < 15)
{
rssi = GetRSSI();
if(rssi < saturationLevel)
{
g_rxlooop += 1;
Modify_SPI_Reg_bits(G_RXLOOPB_RFE, g_rxlooop);
}
else
break;
}
rssi = GetRSSI();
while(g_pga < 18 && g_rxlooop == 15 && rssi < saturationLevel)
{
g_pga += 1;
Modify_SPI_Reg_bits(G_PGA_RBB, g_pga);
rssi = GetRSSI();
}
Modify_SPI_Reg_bits(CMIX_BYP_RXTSP, 1);
Modify_SPI_Reg_bits(DC_BYP_RXTSP, 1);
return 0;
}
void LMS7002M::CalibrateTxDC_RSSI(const float_type bandwidth)
{
Modify_SPI_Reg_bits(EN_G_TRF, 1);
Modify_SPI_Reg_bits(CMIX_BYP_TXTSP, 0);
Modify_SPI_Reg_bits(CMIX_BYP_RXTSP, 0);
SetNCOFrequency(LMS7002M::Rx, 0, calibrationSXOffset_Hz - 0.1e6 + (bandwidth / calibUserBwDivider));
int16_t corrI = 64;
int16_t corrQ = 64;
Modify_SPI_Reg_bits(DCCORRI_TXTSP, 64);
Modify_SPI_Reg_bits(DCCORRQ_TXTSP, 0);
CoarseSearch(DCCORRI_TXTSP.address, DCCORRI_TXTSP.msb, DCCORRI_TXTSP.lsb, corrI, 7);
Modify_SPI_Reg_bits(DCCORRI_TXTSP, corrI);
Modify_SPI_Reg_bits(DCCORRQ_TXTSP, 64);
CoarseSearch(DCCORRQ_TXTSP.address, DCCORRQ_TXTSP.msb, DCCORRQ_TXTSP.lsb, corrQ, 7);
Modify_SPI_Reg_bits(DCCORRQ_TXTSP, corrQ);
CoarseSearch(DCCORRI_TXTSP.address, DCCORRI_TXTSP.msb, DCCORRI_TXTSP.lsb, corrI, 4);
Modify_SPI_Reg_bits(DCCORRI_TXTSP, corrI);
CoarseSearch(DCCORRQ_TXTSP.address, DCCORRQ_TXTSP.msb, DCCORRQ_TXTSP.lsb, corrQ, 4);
Modify_SPI_Reg_bits(DCCORRQ_TXTSP, corrQ);
#ifdef LMS_VERBOSE_OUTPUT
printf("Fine search Tx DCCORRI/DCCORRQ\n");
#endif
FineSearch(DCCORRI_TXTSP.address, DCCORRI_TXTSP.msb, DCCORRI_TXTSP.lsb, corrI, DCCORRQ_TXTSP.address, DCCORRQ_TXTSP.msb, DCCORRQ_TXTSP.lsb, corrQ, 7);
#ifdef LMS_VERBOSE_OUTPUT
printf("Fine search Tx DCCORRI: %i, DCCORRQ: %i\n", corrI, corrQ);
#endif
Modify_SPI_Reg_bits(DCCORRI_TXTSP, corrI);
Modify_SPI_Reg_bits(DCCORRQ_TXTSP, corrQ);
}
void LMS7002M::FineSearch(const uint16_t addrI, const uint8_t msbI, const uint8_t lsbI, int16_t &valueI, const uint16_t addrQ, const uint8_t msbQ, const uint8_t lsbQ, int16_t &valueQ, const uint8_t fieldSize)
{
const uint16_t DCOFFaddr = 0x010E;
uint32_t **rssiField = new uint32_t*[fieldSize];
for (int i = 0; i < fieldSize; ++i)
{
rssiField[i] = new uint32_t[fieldSize];
for (int q = 0; q < fieldSize; ++q)
rssiField[i][q] = ~0;
}
uint32_t minRSSI = ~0;
int16_t minI = 0;
int16_t minQ = 0;
for (int i = 0; i < fieldSize; ++i)
{
for (int q = 0; q < fieldSize; ++q)
{
int16_t ival = valueI + (i - fieldSize / 2);
int16_t qval = valueQ + (q - fieldSize / 2);
Modify_SPI_Reg_bits(addrI, msbI, lsbI, addrI != DCOFFaddr ? ival : toDCOffset(ival), true);
Modify_SPI_Reg_bits(addrQ, msbQ, lsbQ, addrQ != DCOFFaddr ? qval : toDCOffset(qval), true);
rssiField[i][q] = GetRSSI();
if (rssiField[i][q] < minRSSI)
{
minI = ival;
minQ = qval;
minRSSI = rssiField[i][q];
}
}
}
#ifdef LMS_VERBOSE_OUTPUT
printf(" |");
for (int i = 0; i < fieldSize; ++i)
printf("%6i|", valueQ - fieldSize / 2 + i);
printf("\n");
for (int i = 0; i < fieldSize + 1; ++i)
printf("------+");
printf("\n");
for (int i = 0; i < fieldSize; ++i)
{
printf("%5i |", valueI + (i - fieldSize / 2));
for (int q = 0; q < fieldSize; ++q)
printf("%6i.2|", rssiField[i][q]);
printf("\n");
}
#endif
valueI = minI;
valueQ = minQ;
for (int i = 0; i < fieldSize; ++i)
delete rssiField[i];
delete rssiField;
}
/** @brief Loads given DC_REG values into registers
@param tx TxTSP or RxTSP selection
@param I DC_REG I value
@param Q DC_REG Q value
*/
int LMS7002M::LoadDC_REG_IQ(bool tx, int16_t I, int16_t Q)
{
if(tx)
{
Modify_SPI_Reg_bits(LMS7param(DC_REG_TXTSP), I);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDI_TXTSP), 0);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDI_TXTSP), 1);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDI_TXTSP), 0);
Modify_SPI_Reg_bits(LMS7param(DC_REG_TXTSP), Q);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDQ_TXTSP), 0);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDQ_TXTSP), 1);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDQ_TXTSP), 0);
}
else
{
Modify_SPI_Reg_bits(LMS7param(DC_REG_RXTSP), I);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDI_RXTSP), 0);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDI_RXTSP), 1);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDI_RXTSP), 0);
Modify_SPI_Reg_bits(LMS7param(DC_REG_TXTSP), Q);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDQ_RXTSP), 0);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDQ_RXTSP), 1);
Modify_SPI_Reg_bits(LMS7param(TSGDCLDQ_RXTSP), 0);
}
return 0;
}
int LMS7002M::StoreDigitalCorrections(const bool isTx)
{
const int idx = this->GetActiveChannelIndex();
const uint32_t boardId = controlPort->GetDeviceInfo().boardSerialNumber;
const double freq = this->GetFrequencySX(isTx);
int band = 0; //TODO
int dccorri, dccorrq, gcorri, gcorrq, phaseOffset;
if (isTx)
{
dccorri = int8_t(Get_SPI_Reg_bits(LMS7param(DCCORRI_TXTSP))); //signed 8-bit
dccorrq = int8_t(Get_SPI_Reg_bits(LMS7param(DCCORRQ_TXTSP))); //signed 8-bit
gcorri = int16_t(Get_SPI_Reg_bits(LMS7param(GCORRI_TXTSP))); //unsigned 11-bit
gcorrq = int16_t(Get_SPI_Reg_bits(LMS7param(GCORRQ_TXTSP))); //unsigned 11-bit
phaseOffset = int16_t(Get_SPI_Reg_bits(LMS7param(IQCORR_TXTSP)) << 4) >> 4; //sign extend 12-bit
}
else
{
dccorri = 0;
dccorrq = 0;
gcorri = int16_t(Get_SPI_Reg_bits(LMS7param(GCORRI_RXTSP)) << 4) >> 4;
gcorrq = int16_t(Get_SPI_Reg_bits(LMS7param(GCORRQ_RXTSP)) << 4) >> 4;
phaseOffset = int16_t(Get_SPI_Reg_bits(LMS7param(IQCORR_RXTSP)) << 4) >> 4;
}
return mValueCache->InsertDC_IQ(boardId, freq, idx, isTx, band, dccorri, dccorrq, gcorri, gcorrq, phaseOffset);
}
int LMS7002M::ApplyDigitalCorrections(const bool isTx)
{
const int idx = this->GetActiveChannelIndex();
const uint32_t boardId = controlPort->GetDeviceInfo().boardSerialNumber;
const double freq = this->GetFrequencySX(isTx);
int band = 0; //TODO
int dccorri, dccorrq, gcorri, gcorrq, phaseOffset;
int rc = mValueCache->GetDC_IQ_Interp(boardId, freq, idx, isTx, band, &dccorri, &dccorrq, &gcorri, &gcorrq, &phaseOffset);
if (rc != 0) return rc;
if (isTx)
{
Modify_SPI_Reg_bits(DCCORRI_TXTSP, dccorri);
Modify_SPI_Reg_bits(DCCORRQ_TXTSP, dccorrq);
Modify_SPI_Reg_bits(GCORRI_TXTSP, gcorri);
Modify_SPI_Reg_bits(GCORRQ_TXTSP, gcorrq);
Modify_SPI_Reg_bits(IQCORR_TXTSP, phaseOffset);
Modify_SPI_Reg_bits(DC_BYP_TXTSP, 0);
Modify_SPI_Reg_bits(PH_BYP_TXTSP, 0);
Modify_SPI_Reg_bits(GC_BYP_TXTSP, 0);
}
else
{
Modify_SPI_Reg_bits(GCORRI_RXTSP, gcorri);
Modify_SPI_Reg_bits(GCORRQ_RXTSP, gcorrq);
Modify_SPI_Reg_bits(IQCORR_RXTSP, phaseOffset);
Modify_SPI_Reg_bits(PH_BYP_RXTSP, 0);
Modify_SPI_Reg_bits(GC_BYP_RXTSP, 0);
}
return 0;
}
| 33.604579 | 208 | 0.646405 | bastille-attic |
51c9c21d1b4092479f18df349118a72c0f23ce99 | 520 | cc | C++ | src/fe-readatarist.cc | hpingel/fluxengine | d4db131d3c8541fa0d35bac8591e6dea192e8fd6 | [
"MIT"
] | null | null | null | src/fe-readatarist.cc | hpingel/fluxengine | d4db131d3c8541fa0d35bac8591e6dea192e8fd6 | [
"MIT"
] | null | null | null | src/fe-readatarist.cc | hpingel/fluxengine | d4db131d3c8541fa0d35bac8591e6dea192e8fd6 | [
"MIT"
] | null | null | null | #include "globals.h"
#include "flags.h"
#include "reader.h"
#include "fluxmap.h"
#include "decoders/decoders.h"
#include "sector.h"
#include "sectorset.h"
#include "record.h"
#include "dataspec.h"
#include "ibm/ibm.h"
#include "fmt/format.h"
static FlagGroup flags { &readerFlags };
int mainReadAtariST(int argc, const char* argv[])
{
setReaderDefaultSource(":t=0-79:s=0-1");
setReaderDefaultOutput("atarist.st");
flags.parseFlags(argc, argv);
IbmDecoder decoder(1);
readDiskCommand(decoder);
return 0;
}
| 20.8 | 49 | 0.715385 | hpingel |
51d0df018658860ac68fe792ad64e4345f056757 | 753 | hpp | C++ | simulator/include/marlin/simulator/core/Event.hpp | marlinprotocol/OpenWeaver | 7a8c668cccc933d652fabe8a141e702b8a0fd066 | [
"MIT"
] | 60 | 2020-07-01T17:37:34.000Z | 2022-02-16T03:56:55.000Z | simulator/include/marlin/simulator/core/Event.hpp | marlinpro/openweaver | 0aca30fbda3121a8e507f48a52b718b5664a5bbc | [
"MIT"
] | 5 | 2020-10-12T05:17:49.000Z | 2021-05-25T15:47:01.000Z | simulator/include/marlin/simulator/core/Event.hpp | marlinpro/openweaver | 0aca30fbda3121a8e507f48a52b718b5664a5bbc | [
"MIT"
] | 18 | 2020-07-01T17:43:18.000Z | 2022-01-09T14:29:08.000Z | #ifndef MARLIN_SIMULATOR_CORE_EVENT_HPP
#define MARLIN_SIMULATOR_CORE_EVENT_HPP
#include <cstdint>
namespace marlin {
namespace simulator {
template<typename EventManager>
class Event {
private:
static uint64_t id_seq;
protected:
uint64_t id;
uint64_t tick;
public:
Event(uint64_t tick);
inline uint64_t get_tick() {
return tick;
}
inline uint64_t get_id() {
return id;
}
virtual void run(EventManager&) = 0;
virtual ~Event() = default;
};
// Impl
template<typename EventManager>
uint64_t Event<EventManager>::id_seq = 0;
template<typename EventManager>
Event<EventManager>::Event(uint64_t tick) {
id = id_seq++;
this->tick = tick;
}
} // namespace simulator
} // namespace marlin
#endif // MARLIN_SIMULATOR_CORE_EVENT_HPP
| 15.367347 | 43 | 0.74502 | marlinprotocol |
51d79b198e4fbaa925d325a02ccf495b91093d73 | 1,036 | hpp | C++ | src/color/yiq/akin/lab.hpp | 3l0w/color | e42d0933b6b88564807bcd5f49e9c7f66e24990a | [
"Apache-2.0"
] | null | null | null | src/color/yiq/akin/lab.hpp | 3l0w/color | e42d0933b6b88564807bcd5f49e9c7f66e24990a | [
"Apache-2.0"
] | null | null | null | src/color/yiq/akin/lab.hpp | 3l0w/color | e42d0933b6b88564807bcd5f49e9c7f66e24990a | [
"Apache-2.0"
] | 1 | 2022-03-03T07:55:24.000Z | 2022-03-03T07:55:24.000Z | #ifndef color_yiq_akin_lab
#define color_yiq_akin_lab
#include "../../generic/akin/yiq.hpp"
#include "../category.hpp"
#include "../../lab/category.hpp"
namespace color
{
namespace akin
{
template< >struct yiq< ::color::category::lab_uint8 >{ typedef ::color::category::yiq_uint8 akin_type; };
template< >struct yiq< ::color::category::lab_uint16 >{ typedef ::color::category::yiq_uint16 akin_type; };
template< >struct yiq< ::color::category::lab_uint32 >{ typedef ::color::category::yiq_uint32 akin_type; };
template< >struct yiq< ::color::category::lab_uint64 >{ typedef ::color::category::yiq_uint64 akin_type; };
template< >struct yiq< ::color::category::lab_float >{ typedef ::color::category::yiq_float akin_type; };
template< >struct yiq< ::color::category::lab_double >{ typedef ::color::category::yiq_double akin_type; };
template< >struct yiq< ::color::category::lab_ldouble >{ typedef ::color::category::yiq_ldouble akin_type; };
}
}
#endif
| 41.44 | 114 | 0.669884 | 3l0w |
51d81593a82dfd12f724018e95fd99ffeccd43d9 | 7,172 | cpp | C++ | CH19/FEM/channel.cpp | acastellanos95/AppCompPhys | 920a7ba707e92f1ef92fba9d97323863994f0b1a | [
"MIT"
] | null | null | null | CH19/FEM/channel.cpp | acastellanos95/AppCompPhys | 920a7ba707e92f1ef92fba9d97323863994f0b1a | [
"MIT"
] | null | null | null | CH19/FEM/channel.cpp | acastellanos95/AppCompPhys | 920a7ba707e92f1ef92fba9d97323863994f0b1a | [
"MIT"
] | null | null | null | /*
channel.cpp
solve for flow rates in a rectangular channel
Nx/Ny = number of nodes along a side
g++ -I/usr/local/include/eigen3 ...
*/
#include <iostream>
#include <fstream>
#include <cmath>
#include <random>
#include <vector>
#include <Eigen/Dense>
using namespace std;
using namespace Eigen;
class TwoVect {
public:
double x;
double y;
TwoVect () {
x=0.0; y=0.0;
};
TwoVect (double x0, double y0) {
x=x0; y=y0;
};
void setV(double x0, double y0) {
x=x0; y=y0;
}
double mag() {
return sqrt(x*x + y*y);
}
double operator*(const TwoVect & other);
TwoVect operator+(const TwoVect & other);
TwoVect operator-(const TwoVect & other);
friend std::ostream &operator<<(std::ostream &out, TwoVect v0) {
out << v0.x << " " << v0.y;
return out;
}
}; // end of class TwoVect
TwoVect TwoVect::operator-(const TwoVect & other) {
return TwoVect(x-other.x,y-other.y);
}
TwoVect TwoVect::operator+(const TwoVect & other) {
return TwoVect(x+other.x,y+other.y);
}
double TwoVect::operator*(const TwoVect & other) {
// dot product
return x*other.x + y*other.y;
}
TwoVect operator*(const double & lhs, const TwoVect & rhs) {
TwoVect v0 = TwoVect(lhs*rhs.x,lhs*rhs.y);
return v0;
}
TwoVect operator*(const TwoVect & lhs, const double & rhs) {
TwoVect v0 = TwoVect(rhs*lhs.x,rhs*lhs.y);
return v0;
}
TwoVect operator/(const TwoVect & lhs, const double & rhs) {
TwoVect v0 = TwoVect(lhs.x/rhs,lhs.y/rhs);
return v0;
}
// --------------------------------------------------------------------
typedef int node;
typedef int element;
TwoVect *rNode = NULL; // vector of node coordinates
typedef Matrix<int,Dynamic,3> eMat; // custom Eigen matrix type
eMat nL; // track nodes associated with element 0,1,2 = CCW nodes
double area(element e) {
double a3 = rNode[nL(e,1)].x - rNode[nL(e,0)].x;
double a2 = rNode[nL(e,0)].x - rNode[nL(e,2)].x;
double b3 = rNode[nL(e,0)].y - rNode[nL(e,1)].y;
double b2 = rNode[nL(e,2)].y - rNode[nL(e,0)].y;
return 0.5*(a3*b2 - a2*b3);
}
TwoVect cm(element e) {
// center of mass of element e
return (rNode[nL(e,0)] + rNode[nL(e,1)] + rNode[nL(e,2)])/3.0;
}
int main(void) {
int verbose=0;
int Nx,Ny;
double hw,Pz,Vz;
ofstream ofs,ofs2,ofs3,ofs4;
ofs.open("channel.dat");
ofs2.open("c2.dat");
ofs3.open("c3.dat");
ofs4.open("c4.dat");
cout << " input Nx, Ny, H/W [0.5], Pz/mu [-6], Vz [0] " << endl;
cin >> Nx >> Ny >> hw >> Pz >> Vz;
cout << " enter 1 for verbose mode " << endl;
cin >> verbose;
int Nnodes = Nx*Ny;
int Nelements = (Nx-1)*(Ny-1)*2;
cout << " number of nodes: " << Nnodes << endl;
cout << " number of elements: " << Nelements << endl;
VectorXd f(Nnodes),w(Nnodes);
MatrixXd K(Nnodes,Nnodes);
nL = eMat(Nelements,3);
// define rectangle nodes
rNode = new TwoVect[Nnodes];
node nodeNumber = 0;
for (int iy=0;iy<Ny;iy++) {
for (int ix=0;ix<Nx;ix++) {
double x = (double) ix/(Nx-1);
double y = (double) iy/(Ny-1);
y *= hw; // scale to desired proportions
rNode[nodeNumber].setV(x,y);
nodeNumber++;
}}
//label elements and specify their nodes
if (verbose) cout << endl << " element and associated nodes: " << endl << endl;
for (int iy=0;iy<Ny-1;iy++) {
for (int ix=0;ix<Nx-1;ix++) {
node i = iy*(Nx-1)+ix;
element eNumber = 2*i;
node j = ix + Nx*iy;
nL(eNumber,0) = j;
nL(eNumber,1) = j+Nx+1;
nL(eNumber,2) = j+Nx;
if (verbose) cout << eNumber << " " << nL(eNumber,0) << " " << nL(eNumber,1) << " " <<
nL(eNumber,2) << endl;
eNumber++;
nL(eNumber,0) = j;
nL(eNumber,1) = j+1;
nL(eNumber,2) = j+1+Nx;
if (verbose) cout << eNumber << " " << nL(eNumber,0) << " " << nL(eNumber,1) << " " <<
nL(eNumber,2) << endl;
}}
if (verbose) {
cout << " ----------- " << endl;
// print mesh
for (element e=0;e<Nelements;e++) {
ofs << rNode[nL(e,0)] << " " << rNode[nL(e,1)] << endl;
ofs << rNode[nL(e,1)] << " " << rNode[nL(e,2)] << endl;
ofs << rNode[nL(e,2)] << " " << rNode[nL(e,0)] << endl;
ofs2 << e << " " << cm(e) << " " << area(e) << endl;
}
}
// assemble FEM stiffness matrix, K
for (element e=0;e<Nelements;e++) {
double beta[3],gamma[3];
for (int i=0;i<3;i++) {
int j = (i+1)%3;
int k = (i+2)%3;
beta[i] = rNode[nL(e,j)].y - rNode[nL(e,k)].y;
gamma[i] = rNode[nL(e,k)].x - rNode[nL(e,j)].x;
if (verbose) cout << e << " " << i << " " << beta[i] << " " << gamma[i] << endl;
}
for (int i=0;i<3;i++) {
for (int j=0;j<3;j++) {
node I = nL(e,i);
node J = nL(e,j);
K(I,J) += (beta[i]*beta[j] + gamma[i]*gamma[j])/(4.0*area(e));
}}
}
if (verbose) {
cout << " ----------- " << endl;
cout << "K " << endl;
cout << "det(K) = " << K.determinant() << endl;
for (node i=0;i<Nnodes;i++) {
for (node j=0;j<Nnodes;j++) {
cout << i << " " << j << " " << K(i,j) << endl;
}}
cout << " ----------- " << endl;
}
// assemble force vector [pressure gradient/viscosity = dp/dz / mu == Pz]
for (element e=0;e<Nelements;e++) {
double ff = -Pz*area(e)/3.0;
f(nL(e,0)) += ff; // sum force contribution to nodes
f(nL(e,1)) += ff;
f(nL(e,2)) += ff;
}
if (verbose) {
cout << " f " << endl;
for (node i=0;i<Nnodes;i++) cout << i << " " << f(i) << endl;
cout << " ----------- " << endl;
}
// boundary conditions [trick to force w(...) = f(...) = 0]
// we need to identify the nodes on the boundary !
for (node n=0;n<Nx;n++) {
if (verbose) cout << " boundary nodes: " << n << " " << n + Nx*(Ny-1) << endl;
K(n,n) *= 1e12;
K(n+Nx*(Ny-1),n+Nx*(Ny-1)) *= 1e12;
f(n) = 0.0*K(n,n); // bottom
f(n+Nx*(Ny-1)) = Vz*K(n+Nx*(Ny-1),n+Nx*(Ny-1)); // top
}
for (node n=1;n<Ny-1;n++) {
if (verbose) cout << " boundary nodes: " << n*Nx << " " << n*Nx + Nx - 1 << endl;
K(n*Nx,n*Nx) *= 1e12;
K(n*Nx+Nx-1,n*Nx+Nx-1) *= 1e12;
f(n*Nx) = 0.0*K(n*Nx,n*Nx); // left
f(n*Nx+Nx-1) = 0.0; // right
}
int num=0;
for (node n=0;n<Nnodes;n++) {
for (node m=0;m<Nnodes;m++) {
if (K(n,m) != 0.0) num++;
}}
cout << --num << " nonzero elements in K " << endl;
// obtain solution
w = K.inverse()*f;
// store solution
int nx = 1;
for (node n=0;n<Nnodes;n++) {
ofs4 << rNode[n] << " " << w(n) << endl;
nx++;
if (nx > Nx) {
ofs4 << " " << endl;
nx=1;
}
}
// integrate to obtain flow rate [= int dx dy w(x,y)]
double in = 0.0;
for (element e=0;e<Nelements;e++) {
in +=area(e)*(w(nL(e,0)) + w(nL(e,1)) + w(nL(e,2)));
}
in /= 3.0;
cout << " flow rate = " << in << endl;
delete [] rNode;
ofs.close();
ofs2.close();
ofs3.close();
ofs4.close();
cout << " mesh coords in channel.dat " << endl;
cout << " e cm(e) area(e) in c2.dat " << endl;
cout << " r_node w(r_node) in c4.dat" << endl;
return 0;
}
| 26.08 | 93 | 0.506274 | acastellanos95 |
51daf32dcb3c3ca753d62d048d76611712f3cb6e | 641 | hpp | C++ | SDK/ARKSurvivalEvolved_E_StegoBackplateMode_structs.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 10 | 2020-02-17T19:08:46.000Z | 2021-07-31T11:07:19.000Z | SDK/ARKSurvivalEvolved_E_StegoBackplateMode_structs.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 9 | 2020-02-17T18:15:41.000Z | 2021-06-06T19:17:34.000Z | SDK/ARKSurvivalEvolved_E_StegoBackplateMode_structs.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 3 | 2020-07-22T17:42:07.000Z | 2021-06-19T17:16:13.000Z | #pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_Basic.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Enums
//---------------------------------------------------------------------------
// UserDefinedEnum E_StegoBackplateMode.E_StegoBackplateMode
enum class E_StegoBackplateMode : uint8_t
{
E_StegoBackplateMode__NewEnumerator0 = 0,
E_StegoBackplateMode__NewEnumerator1 = 1,
E_StegoBackplateMode__NewEnumerator2 = 2,
E_StegoBackplateMode__E_MAX = 3
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 19.424242 | 77 | 0.595944 | 2bite |