text string | size int64 | token_count int64 |
|---|---|---|
#include "stdafx.h"
#include "RenderTask.h"
// DX12 Specifics
#include "../CommandInterface.h"
#include "../GPUMemory/GPUMemory.h"
#include "../PipelineState/GraphicsState.h"
#include "../RootSignature.h"
#include "../SwapChain.h"
RenderTask::RenderTask(
ID3D12Device5* device,
RootSignature* rootSignature,
const std::wstring& VSName, const std::wstring& PSName,
std::vector<D3D12_GRAPHICS_PIPELINE_STATE_DESC*>* gpsds,
const std::wstring& psoName)
:DX12Task(device, COMMAND_INTERFACE_TYPE::DIRECT_TYPE)
{
if (gpsds != nullptr)
{
for (auto gpsd : *gpsds)
{
m_PipelineStates.push_back(new GraphicsState(device, rootSignature, VSName, PSName, gpsd, psoName));
}
}
m_pRootSig = rootSignature->GetRootSig();
}
RenderTask::~RenderTask()
{
for (auto pipelineState : m_PipelineStates)
delete pipelineState;
}
PipelineState* RenderTask::GetPipelineState(unsigned int index)
{
return m_PipelineStates[index];
}
void RenderTask::AddRenderTargetView(std::string name, const RenderTargetView* renderTargetView)
{
m_RenderTargetViews[name] = renderTargetView;
}
void RenderTask::AddShaderResourceView(std::string name, const ShaderResourceView* shaderResourceView)
{
m_ShaderResourceViews[name] = shaderResourceView;
}
void RenderTask::SetRenderComponents(std::vector<RenderComponent*> *renderComponents)
{
m_RenderComponents = renderComponents;
}
void RenderTask::SetMainDepthStencil(DepthStencil* depthStencil)
{
m_pDepthStencil = depthStencil;
}
void RenderTask::SetCamera(BaseCamera* camera)
{
m_pCamera = camera;
}
void RenderTask::SetSwapChain(SwapChain* swapChain)
{
m_pSwapChain = swapChain;
}
| 1,634 | 623 |
#include <iostream>
#include <string>
using namespace std;
typedef long long ll;
int main()
{
// HACKERMAN
ios::sync_with_stdio(false);
cin.tie(0);
//Read inputs
int value;
cin >> value;
string res = "NO SOLUTION";
if (value > 3) {
res = "";
for (int i = 2; i <= value; i += 2) {
res += to_string(i) + " ";
}
for (int i = 1; i <= value; i += 2) {
res += to_string(i) + " ";
}
}
else if (value == 1) {
res = "1";
}
cout << res << endl;
}
| 568 | 217 |
#pragma once
#include "nlohmann/json.hpp"
namespace expert_system::utility {
/**
* @brief A managed confidence factor.
* Ensures that the confidence factor does not exceed the range of 0.0f and 1.0f.
*/
class Confidence {
public:
/**
* @brief Default constructor.
* Initial confidence factor value of 0.0f.
*/
Confidence();
/**
* @brief Parameterized constructor.
* @param [in] value The confidence factor value to assign.
* @note This will be replaced by the closest range bounds if outside them.
*/
explicit Confidence(float value);
/**
* @brief Attempts to assign a confidence factor value.
* @param [in] value The confidence factor value to assign.
* @note This will be replaced by the closest range bounds if outside them.
*/
void Set(float value);
/**
* @brief Provides a read-only access to the private confidence factor value.
* @return A copy of the stored confidence factor value.
*/
float Get() const;
/**
* @brief Creates a new confidence factor from combining this value with another.
* @param [in] value The confidence factor value to assign.
* @return A new Confidence, generated from multiplying the provided value with the stored value.
*/
[[nodiscard]] Confidence Combine(const Confidence& value) const;
/**
* @brief 'More than' relational operator overload.
* @param target A reference to a Confidence factor.
* @return True if the target Confidence factor value is more than this.
*/
bool operator<(const Confidence& target);
/**
* @brief 'Less than' relational operator overload.
* @param target A reference to a Confidence factor.
* @return True if the target Confidence factor value is less than this.
*/
bool operator>(const Confidence& target);
/**
* @brief 'Equal to' relational operator overload.
* @param target A reference to a Confidence factor.
* @return True if the target Confidence factor value is equal to this.
*/
bool operator==(const Confidence& target);
private:
/// The protected confidence factor value.
float confidence_factor_;
/// Enables JSON serializer access to private contents
friend void to_json(nlohmann::json& json_sys, const Confidence& target);
/// Enables JSON serializer access to private contents
friend void from_json(const nlohmann::json& json_sys, Confidence& target);
};
/**
* @brief Confidence serialization to JSON format.
* @param [in,out] json_sys A reference to a JSON object.
* @param [in] target A reference to the Confidence to export.
*/
void to_json(nlohmann::json& json_sys, const Confidence& target);
/**
* @brief Confidence serialization from JSON format.
* @param [in] json_sys A reference to a JSON object.
* @param [in,out] target A reference to the Confidence to import.
*/
void from_json(const nlohmann::json& json_sys, Confidence& target);
} // namespace expert_system::utility
| 3,531 | 854 |
#include "Lighting.h"
#include "LightCalculator/LightCommon.h"
#include "LightCalculator/BFSLightCalculator.h"
#include "LightCalculator/DirectionalLightCalculator.h"
#include <TRGame/TRGame.hpp>
#include <TRGame/Player/Player.h>
#include <TRGame/Worlds/GameWorld.h>
#include <TRGame/Worlds/WorldResources.h>
#include <TRGame/Worlds/Tile.h>
#include <TRGame/Worlds/TileSection.h>
#include <TREngine/Core/Render/SpriteRenderer.h>
#include <TREngine/Core/Utils/Utils.h>
#include <TREngine/Core/Assets/assets.h>
#include <TREngine/Core/Render/render.h>
#include <TREngine/Engine.h>
#include <set>
using namespace trv2;
Lighting::Lighting()
{
_lightCommonData = std::make_unique<LightCommon>();
_bfsCalculator = std::make_unique<BFSLightCalculator>(trv2::ptr(_lightCommonData));
_directionCalculator = std::make_unique<DirectionalLightCalculator>(trv2::ptr(_lightCommonData));
}
Lighting::~Lighting()
{}
static glm::vec3 Gamma(const glm::vec3 color)
{
return glm::pow(color, glm::vec3(2.2));
}
static glm::vec3 InvGamma(const glm::vec3 color)
{
return glm::pow(color, glm::vec3(1 / 2.2));
}
void Lighting::ClearLights()
{
_bfsCalculator->ClearLights();
_directionCalculator->ClearLights();
}
void Lighting::AddNormalLight(const Light& light)
{
_bfsCalculator->AddLight(light);
}
void Lighting::AddDirectionalLight(const Light& light)
{
_directionCalculator->AddLight(light);
}
void Lighting::CalculateLight(const trv2::RectI& tileRectCalc, const trv2::RectI& tileRectScreen)
{
_lightCommonData->TileRectScreen = tileRectScreen;
auto sectionRect = GameWorld::GetTileSectionRect(tileRectCalc);
_lightCommonData->SectionRect = sectionRect;
_lightCommonData->TileRectWorld = trv2::RectI(sectionRect.Position * GameWorld::TILE_SECTION_SIZE,
sectionRect.Size * GameWorld::TILE_SECTION_SIZE);
auto gameWorld = TRGame::GetInstance()->GetGameWorld();
_lightCommonData->GameWorld = gameWorld;
auto common = _lightCommonData.get();
const int totalBlocks = common->TileRectWorld.Size.x * common->TileRectWorld.Size.y;
common->SectionRect.ForEach([this, common](glm::ivec2 sectionCoord) {
const TileSection* section = common->GameWorld->GetSection(sectionCoord);
section->ForEachTile([this, common](glm::ivec2 coord, const Tile& tile) {
int id = common->GetBlockId(coord - common->TileRectWorld.Position);
common->CachedTile[id].Type = tile.Type;
});
});
_bfsCalculator->Calculate();
_directionCalculator->Calculate();
_directionCalculator->RasterizeLightTriangles();
}
void Lighting::DrawLightMap(trv2::SpriteRenderer* renderer, const glm::mat4& projection)
{
trv2::BatchSettings setting{};
renderer->Begin(projection, setting);
{
_lightCommonData->TileRectScreen.ForEach([this, renderer](glm::ivec2 coord) -> void {
auto& common = _lightCommonData;
int id = common->GetBlockId(coord - common->TileRectWorld.Position);
auto color = glm::vec3(common->TileColors[0][id],
common->TileColors[1][id],
common->TileColors[2][id]);
if (color == glm::vec3(0)) return;
renderer->Draw(coord, glm::vec2(1), glm::vec2(0),
0.f, glm::vec4(color, 1.f));
});
}
renderer->End();
}
void Lighting::DrawDirectionalTriangles(const glm::mat4& worldProjection)
{
_directionCalculator->DrawTriangles(worldProjection);
}
float Lighting::GetLight(glm::ivec2 coord)
{
return 0.f;
}
| 3,347 | 1,268 |
// This file is part of snark, a generic and flexible library for robotics research
// Copyright (c) 2011 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.
#ifdef WIN32
#include <fcntl.h>
#include <io.h>
#endif
#include "thin_reader.h"
namespace snark {
snark::thin_reader::thin_reader() : is_new_scan_( true )
{
#ifdef WIN32
_setmode( _fileno( stdin ), _O_BINARY );
#endif
}
const char* thin_reader::read()
{
if( !std::cin.good() || std::cin.eof() ) { return NULL; }
comma::uint16 size;
std::cin.read( reinterpret_cast< char* >( &size ), 2 );
if( std::cin.gcount() < 2 ) { return NULL; }
std::cin.read( m_buf, size );
if( std::cin.gcount() < size ) { return NULL; }
comma::int64 seconds;
comma::int32 nanoseconds;
::memcpy( &seconds, m_buf, sizeof( comma::int64 ) );
::memcpy( &nanoseconds, m_buf + sizeof( comma::int64 ), sizeof( comma::int32 ) );
m_timestamp = boost::posix_time::ptime( snark::timing::epoch, boost::posix_time::seconds( static_cast< long >( seconds ) ) + boost::posix_time::microseconds( nanoseconds / 1000 ) );
comma::uint32 scan = velodyne::thin::deserialize( m_packet, m_buf + timeSize );
is_new_scan_ = is_new_scan_ || !last_scan_ || *last_scan_ != scan; // quick and dirty; keep it set until we clear it in is_new_scan()
last_scan_ = scan;
return reinterpret_cast< char* >( &m_packet );
}
void thin_reader::close() {}
boost::posix_time::ptime thin_reader::timestamp() const { return m_timestamp; }
bool thin_reader::is_new_scan()
{
bool r = is_new_scan_;
is_new_scan_ = false;
return r;
}
} // namespace snark {
| 3,237 | 1,170 |
/* This software and supporting documentation are distributed by
* Institut Federatif de Recherche 49
* CEA/NeuroSpin, Batiment 145,
* 91191 Gif-sur-Yvette cedex
* France
*
* This software is governed by the CeCILL-B license under
* French law and abiding by the rules of distribution of free software.
* You can use, modify and/or redistribute the software under the
* terms of the CeCILL-B license as circulated by CEA, CNRS
* and INRIA at the following URL "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL-B license and that you accept its terms.
*/
// activate deprecation warning
#ifdef AIMSDATA_CLASS_NO_DEPREC_WARNING
#undef AIMSDATA_CLASS_NO_DEPREC_WARNING
#endif
#include <aims/io/imasparseheader.h>
#include <aims/def/general.h>
#include <aims/io/defaultItemR.h>
#include <cartobase/exception/ioexcept.h>
#include <cartobase/stream/fileutil.h>
#include <soma-io/utilities/asciidatasourcetraits.h>
#include <fstream>
using namespace aims;
using namespace carto;
using namespace std;
ImasHeader::ImasHeader( const string & filename ) :
PythonHeader(),
_filename( filename )
{
}
ImasHeader::~ImasHeader()
{
}
namespace
{
bool testBinFormat( const string & fname, uint32_t & lines, uint32_t & cols,
uint32_t & count )
{
ifstream is( fname.c_str(), ios::in | ios::binary );
if( !is )
io_error::launchErrnoExcept( fname );
is.unsetf( ios::skipws );
static DefaultItemReader<uint32_t> itemR1;
uint32_t size1 = 0U;
uint32_t size2 = 0U;
uint32_t nonZeroElementCount = 0U;
itemR1.read( is, size1 );
if( !is )
return false;
itemR1.read( is, size2 );
if( !is )
return false;
itemR1.read( is, nonZeroElementCount );
if( !is )
return false;
streampos p = is.tellg(), e;
is.seekg( 0, ios_base::end );
e = is.tellg();
is.seekg( p, ios_base::beg );
if( nonZeroElementCount > size1 * size2
|| nonZeroElementCount * 16 != e - p )
return false;
lines = size1;
cols = size2;
count = nonZeroElementCount;
return true;
}
bool testBswapFormat( const string & fname, uint32_t & lines,
uint32_t & cols, uint32_t & count )
{
ifstream is( fname.c_str(), ios::in | ios::binary );
if( !is )
io_error::launchErrnoExcept( fname );
is.unsetf( ios::skipws );
static DefaultBSwapItemReader<uint32_t> itemR1;
uint32_t size1 = 0U;
uint32_t size2 = 0U;
uint32_t nonZeroElementCount = 0U;
itemR1.read( is, size1 );
if( !is )
return false;
itemR1.read( is, size2 );
if( !is )
return false;
itemR1.read( is, nonZeroElementCount );
if( !is )
return false;
streampos p = is.tellg(), e;
is.seekg( 0, ios_base::end );
e = is.tellg();
is.seekg( p, ios_base::beg );
if( nonZeroElementCount > size1 * size2
|| nonZeroElementCount * 16 != e - p )
return false;
lines = size1;
cols = size2;
count = nonZeroElementCount;
return true;
}
bool testAsciiFormat( const string & fname, uint32_t & lines,
uint32_t & cols, uint32_t & count )
{
ifstream is( fname.c_str(), ios::in | ios::binary );
if( !is )
io_error::launchErrnoExcept( fname );
is.unsetf( ios::skipws );
static DefaultAsciiItemReader<uint32_t> itemR1;
uint32_t size1 = 0U;
uint32_t size2 = 0U;
uint32_t nonZeroElementCount = 0U;
itemR1.read( is, size1 );
if( !is )
return false;
itemR1.read( is, size2 );
if( !is )
return false;
itemR1.read( is, nonZeroElementCount );
if( !is )
return false;
streampos p = is.tellg(), e;
is.seekg( 0, ios_base::end );
e = is.tellg();
is.seekg( p, ios_base::beg );
if( nonZeroElementCount > size1 * size2
|| nonZeroElementCount * 16 != e - p )
return false;
lines = size1;
cols = size2;
count = nonZeroElementCount;
return true;
}
}
bool ImasHeader::read( uint32_t* )
{
string fname = filename();
if( FileUtil::fileStat( fname ).find( '+' ) == string::npos )
throw file_not_found_error( fname );
bool ascii = false;
bool bswap = false;
uint32_t lines = 0, cols = 0, count = 0;
if( testBinFormat( fname, lines, cols, count ) )
{
ascii = false;
bswap = false;
}
else if( testBswapFormat( fname, lines, cols, count ) )
{
ascii = false;
bswap = true;
}
else if( testAsciiFormat( fname, lines, cols, count ) )
{
ascii = true;
bswap = false;
}
else
throw wrong_format_error( "Wrong format or corrupted .imas format",
"<?>" );
setProperty( "file_type", string( "IMASPARSE" ) );
setProperty( "object_type", "SparseMatrix" );
setProperty( "data_type", "DOUBLE" );
setProperty( "ascii", (int) ascii );
if( !ascii )
setProperty( "byte_swapping", (int) bswap );
vector<int> dims(2);
dims[0] = (int) lines;
dims[1] = (int) cols;
setProperty( "dimensions", dims );
setProperty( "non_zero_elements", (int) count );
// add meta-info to header
readMinf( removeExtension( fname ) + extension() + ".minf" );
return true;
}
string ImasHeader::openMode() const
{
int om = 0;
getProperty( "ascii", om );
if ( om )
return string("ascii");
return string("binar");
}
bool ImasHeader::byteSwapping() const
{
int bswap = 0;
getProperty( "byte_swapping", bswap );
return bswap ? true : false;
}
string ImasHeader::filename() const
{
if( _filename.length() > 5
&& _filename.substr( _filename.length()-5, 5 ) == ".imas" )
return _filename;
else
{
if( FileUtil::fileStat( _filename ).find( 'r' ) != string::npos )
return _filename;
return _filename + ".imas";
}
}
set<string> ImasHeader::extensions() const
{
set<string> exts;
exts.insert( ".imas" );
return exts;
}
| 6,993 | 2,492 |
// Copyright (C) 2018-2019 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include <vector>
/**
* @brief Class for action info
*/
using Action = int;
/**
* @brief Class for events on a single frame with action info
*/
struct FrameEvent {
/** @brief Frame index */
int frame_id;
/** @brief Action label */
Action action;
/**
* @brief Constructor
*/
FrameEvent(int frame_id, Action action)
: frame_id(frame_id), action(action) {}
};
using FrameEventsTrack = std::vector<FrameEvent>;
/**
* @brief Class for range of the same event with action info
*/
struct RangeEvent {
/** @brief Start frame index */
int begin_frame_id;
/** @brief Next after the last valid frame index */
int end_frame_id;
/** @brief Action label */
Action action;
/**
* @brief Constructor
*/
RangeEvent(int begin_frame_id, int end_frame_id, Action action)
: begin_frame_id(begin_frame_id), end_frame_id(end_frame_id), action(action) {}
};
using RangeEventsTrack = std::vector<RangeEvent>;
enum ActionsType { STUDENT, TEACHER };
| 1,112 | 367 |
#include "soundmanager.hpp"
void SoundManager::lowerMusicVolume(bool lower) {
if (lower) {
sounds.at(MENU).setVolume(50);
sounds.at(LEVEL).setVolume(50);
} else {
sounds.at(MENU).setVolume(100);
sounds.at(LEVEL).setVolume(100);
}
}
SoundManager::SoundManager()
{
menuSB.loadFromFile(SOUNDS_DIR + "menu.ogg");
levelSB.loadFromFile(SOUNDS_DIR + "level.ogg");
levelCompletedSB.loadFromFile(SOUNDS_DIR + "level_completed.ogg");
gameOverSB.loadFromFile(SOUNDS_DIR + "game_over.ogg");
sounds.at(MENU).setLoop(true);
sounds.at(LEVEL).setLoop(true);
}
SoundManager* SoundManager::instance = 0;
SoundManager& SoundManager::getInstance() {
if (!instance) {
instance = new SoundManager();
}
return *instance;
}
void SoundManager::destroyInstance() {
if (instance) {
delete instance;
instance = 0;
}
}
void SoundManager::changeMusic(Sound music) {
if (musicPlaying == music) {
return;
}
switch (music) {
case NONE:
sounds.at(musicPlaying).stop();
break;
case MENU:
case LEVEL:
if (musicPlaying != NONE) {
sounds.at(musicPlaying).stop();
}
sounds.at(music).play();
musicPlaying = music;
break;
default:
break;
}
}
void SoundManager::playEffect(Sound effect) {
switch (effect) {
case LEVEL_COMPLETED:
case GAME_OVER:
lowerMusicVolume(true);
sounds.at(effect).play();
effectPlaying = effect;
break;
default:
break;
}
}
void SoundManager::update() {
if (effectPlaying != NONE && sounds.at(effectPlaying).getStatus() == sf::SoundSource::Stopped) {
lowerMusicVolume(false);
effectPlaying = NONE;
}
}
| 1,807 | 612 |
/*
* Copyright (c) 2017 James Jackson, BYU MAGICC Lab.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 <rosflight_utils/turbomath.h>
#include <cstdint>
static const int16_t atan_lookup_table[250] = {
0, 40, 80, 120, 160, 200, 240, 280, 320, 360, 400, 440, 480, 520, 559, 599, 639, 679,
719, 759, 798, 838, 878, 917, 957, 997, 1036, 1076, 1115, 1155, 1194, 1234, 1273, 1312, 1352, 1391,
1430, 1469, 1508, 1548, 1587, 1626, 1664, 1703, 1742, 1781, 1820, 1858, 1897, 1935, 1974, 2012, 2051, 2089,
2127, 2166, 2204, 2242, 2280, 2318, 2355, 2393, 2431, 2469, 2506, 2544, 2581, 2618, 2656, 2693, 2730, 2767,
2804, 2841, 2878, 2915, 2951, 2988, 3024, 3061, 3097, 3133, 3169, 3206, 3241, 3277, 3313, 3349, 3385, 3420,
3456, 3491, 3526, 3561, 3596, 3631, 3666, 3701, 3736, 3771, 3805, 3839, 3874, 3908, 3942, 3976, 4010, 4044,
4078, 4112, 4145, 4179, 4212, 4245, 4278, 4311, 4344, 4377, 4410, 4443, 4475, 4508, 4540, 4572, 4604, 4636,
4668, 4700, 4732, 4764, 4795, 4827, 4858, 4889, 4920, 4951, 4982, 5013, 5044, 5074, 5105, 5135, 5166, 5196,
5226, 5256, 5286, 5315, 5345, 5375, 5404, 5434, 5463, 5492, 5521, 5550, 5579, 5608, 5636, 5665, 5693, 5721,
5750, 5778, 5806, 5834, 5862, 5889, 5917, 5944, 5972, 5999, 6026, 6053, 6080, 6107, 6134, 6161, 6187, 6214,
6240, 6267, 6293, 6319, 6345, 6371, 6397, 6422, 6448, 6473, 6499, 6524, 6549, 6574, 6599, 6624, 6649, 6674,
6698, 6723, 6747, 6772, 6796, 6820, 6844, 6868, 6892, 6916, 6940, 6963, 6987, 7010, 7033, 7057, 7080, 7103,
7126, 7149, 7171, 7194, 7217, 7239, 7261, 7284, 7306, 7328, 7350, 7372, 7394, 7416, 7438, 7459, 7481, 7502,
7524, 7545, 7566, 7587, 7608, 7629, 7650, 7671, 7691, 7712, 7733, 7753, 7773, 7794, 7814, 7834};
static const int16_t asin_lookup_table[250] = {
0, 40, 80, 120, 160, 200, 240, 280, 320, 360, 400, 440, 480, 520, 560, 600,
640, 681, 721, 761, 801, 841, 881, 921, 961, 1002, 1042, 1082, 1122, 1163, 1203, 1243,
1284, 1324, 1364, 1405, 1445, 1485, 1526, 1566, 1607, 1647, 1688, 1729, 1769, 1810, 1851, 1891,
1932, 1973, 2014, 2054, 2095, 2136, 2177, 2218, 2259, 2300, 2341, 2382, 2424, 2465, 2506, 2547,
2589, 2630, 2672, 2713, 2755, 2796, 2838, 2880, 2921, 2963, 3005, 3047, 3089, 3131, 3173, 3215,
3257, 3300, 3342, 3384, 3427, 3469, 3512, 3554, 3597, 3640, 3683, 3726, 3769, 3812, 3855, 3898,
3941, 3985, 4028, 4072, 4115, 4159, 4203, 4246, 4290, 4334, 4379, 4423, 4467, 4511, 4556, 4601,
4645, 4690, 4735, 4780, 4825, 4870, 4916, 4961, 5007, 5052, 5098, 5144, 5190, 5236, 5282, 5329,
5375, 5422, 5469, 5515, 5562, 5610, 5657, 5704, 5752, 5800, 5848, 5896, 5944, 5992, 6041, 6089,
6138, 6187, 6236, 6286, 6335, 6385, 6435, 6485, 6535, 6586, 6637, 6687, 6739, 6790, 6841, 6893,
6945, 6997, 7050, 7102, 7155, 7208, 7262, 7315, 7369, 7423, 7478, 7532, 7587, 7643, 7698, 7754,
7810, 7867, 7923, 7981, 8038, 8096, 8154, 8213, 8271, 8331, 8390, 8450, 8511, 8572, 8633, 8695,
8757, 8820, 8883, 8947, 9011, 9076, 9141, 9207, 9273, 9340, 9407, 9476, 9545, 9614, 9684, 9755,
9827, 9900, 9973, 10047, 10122, 10198, 10275, 10353, 10432, 10512, 10593, 10675, 10759, 10844, 10930, 11018,
11107, 11198, 11290, 11385, 11481, 11580, 11681, 11784, 11890, 11999, 12111, 12226, 12346, 12469, 12597, 12730,
12870, 13017, 13171, 13336, 13513, 13705, 13917, 14157, 14442, 14813};
static const int16_t sin_lookup_table[250] = {
0, 63, 126, 188, 251, 314, 377, 440, 502, 565, 628, 691, 753, 816, 879, 941, 1004, 1066,
1129, 1191, 1253, 1316, 1378, 1440, 1502, 1564, 1626, 1688, 1750, 1812, 1874, 1935, 1997, 2059, 2120, 2181,
2243, 2304, 2365, 2426, 2487, 2548, 2608, 2669, 2730, 2790, 2850, 2910, 2970, 3030, 3090, 3150, 3209, 3269,
3328, 3387, 3446, 3505, 3564, 3623, 3681, 3740, 3798, 3856, 3914, 3971, 4029, 4086, 4144, 4201, 4258, 4315,
4371, 4428, 4484, 4540, 4596, 4652, 4707, 4762, 4818, 4873, 4927, 4982, 5036, 5090, 5144, 5198, 5252, 5305,
5358, 5411, 5464, 5516, 5569, 5621, 5673, 5724, 5776, 5827, 5878, 5929, 5979, 6029, 6079, 6129, 6179, 6228,
6277, 6326, 6374, 6423, 6471, 6518, 6566, 6613, 6660, 6707, 6753, 6800, 6845, 6891, 6937, 6982, 7026, 7071,
7115, 7159, 7203, 7247, 7290, 7333, 7375, 7417, 7459, 7501, 7543, 7584, 7624, 7665, 7705, 7745, 7785, 7824,
7863, 7902, 7940, 7978, 8016, 8053, 8090, 8127, 8163, 8200, 8235, 8271, 8306, 8341, 8375, 8409, 8443, 8477,
8510, 8543, 8575, 8607, 8639, 8671, 8702, 8733, 8763, 8793, 8823, 8852, 8881, 8910, 8938, 8966, 8994, 9021,
9048, 9075, 9101, 9127, 9152, 9178, 9202, 9227, 9251, 9274, 9298, 9321, 9343, 9365, 9387, 9409, 9430, 9451,
9471, 9491, 9511, 9530, 9549, 9567, 9585, 9603, 9620, 9637, 9654, 9670, 9686, 9701, 9716, 9731, 9745, 9759,
9773, 9786, 9799, 9811, 9823, 9834, 9846, 9856, 9867, 9877, 9887, 9896, 9905, 9913, 9921, 9929, 9936, 9943,
9950, 9956, 9961, 9967, 9972, 9976, 9980, 9984, 9987, 9990, 9993, 9995, 9997, 9998, 9999, 10000};
float sign(float y)
{
return (0 < y) - (y < 0);
}
float asin_lookup(float x)
{
static const float max = 1.0;
static const float min = 0.0;
static const int16_t num_entries = 250;
static float dx = 0.0;
static const float scale = 10000.0;
float t = (x - min) / (max - min) * num_entries;
uint8_t index = (uint8_t)t;
dx = t - (float)index;
if (index >= num_entries)
{
return max;
}
else if (index < num_entries - 1)
{
return (float)asin_lookup_table[index] / scale
+ dx * (float)(asin_lookup_table[index + 1] - asin_lookup_table[index]) / scale;
}
else
{
return (float)asin_lookup_table[index] / scale
+ dx * (float)(asin_lookup_table[index] - asin_lookup_table[index - 1]) / scale;
}
}
float turboacos(float x)
{
if (x < 0)
return M_PI + asin_lookup(-x);
else
return M_PI - asin_lookup(x);
}
float turboasin(float x)
{
if (x < 0)
return -asin_lookup(-x);
else
return asin_lookup(x);
}
float sin_lookup(float x)
{
static const float max = 1.0;
static const float min = 0.0;
static const int16_t num_entries = 250;
static float dx = 0.0;
static const float scale = 10000.0;
float t = (x - min) / (max - min) * num_entries;
uint8_t index = (uint8_t)t;
dx = t - (float)index;
if (index >= num_entries)
return max;
else if (index < num_entries - 1)
return (float)sin_lookup_table[index] / scale
+ dx * (float)(sin_lookup_table[index + 1] - sin_lookup_table[index]) / scale;
else
return (float)sin_lookup_table[index] / scale
+ dx * (float)(sin_lookup_table[index] - sin_lookup_table[index - 1]) / scale;
}
float turbosin(float x)
{
while (x > M_PI) x -= 2.0 * M_PI;
while (x <= -M_PI) x += 2.0 * M_PI;
if (0 <= x && x <= M_PI / 2.0)
return sin_lookup(x);
else if (-M_PI / 2.0 <= x && x < 0)
return -sin_lookup(-x);
else if (M_PI / 2.0 < x)
return sin_lookup(M_PI - x);
else
return -sin_lookup(x + M_PI);
}
float turbocos(float x)
{
return turbosin(x + M_PI);
}
float atan_lookup(float x)
{
if (x < 0)
return -1 * atan_lookup(-1 * x);
if (x > 1.0)
return M_PI - atan_lookup(1.0 / x);
static const float max = 1.0;
static const float min = 0.0;
static const int16_t num_entries = 250;
static float dx = 0.0;
static const float scale = 10000.0;
float t = (x - min) / (max - min) * num_entries;
uint8_t index = (uint8_t)t;
dx = t - (float)index;
if (index >= num_entries)
return max;
else if (index < num_entries - 1)
return (float)atan_lookup_table[index] / scale
+ dx * (float)(atan_lookup_table[index + 1] - atan_lookup_table[index]) / scale;
else
return (float)atan_lookup_table[index] / scale
+ dx * (float)(atan_lookup_table[index] - atan_lookup_table[index - 1]) / scale;
}
float turboatan2(float y, float x)
{
if (y == 0)
{
if (x < 0)
return M_PI;
else
return 0;
}
else if (x == 0)
{
return M_PI / 2.0 * sign(y);
}
else
{
float arctan = atan_lookup(x / y);
if (y > 0)
return M_PI / 2.0 - arctan;
else if (y < 0)
return -M_PI / 2.0 - arctan;
else if (x < 0)
return arctan + M_PI;
else
return arctan;
}
}
double turbopow(double a, double b)
{
union
{
double d;
int x[2];
} u = {a};
u.x[1] = (int)(b * (u.x[1] - 1072632447) + 1072632447);
u.x[0] = 0;
return u.d;
}
float turboInvSqrt(float x)
{
long i;
float x2, y;
const float threehalfs = 1.5F;
x2 = x * 0.5F;
y = x;
i = *(long*)&y; // evil floating point bit level hacking
i = 0x5f3759df - (i >> 1);
y = *(float*)&i;
y = y * (threehalfs - (x2 * y * y)); // 1st iteration
// y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed
return y;
}
| 10,530 | 6,810 |
#include "dma.hpp"
#include "events.hpp"
#include "usart.hpp"
static USART_TypeDef *usart_base(int iusart);
static DMA_Stream_TypeDef *usart_dma_stream(int iusart);
static IRQn_Type usart_irqn(int iusart);
// Set up USART for interrupt-driven RX, DMA-driven TX.
void USART::init(void) {
volatile uint32_t &apbenr_reg = RCC->APB1ENR;
const uint32_t apbenr_bit = RCC_APB1ENR_USART3EN;
volatile uint32_t &ahbenr_dma_reg = RCC->AHB1ENR;
const uint32_t ahbenr_dma_bit = RCC_AHB1ENR_DMA1EN + _dma_chan.dma - 1;
// Disable USART.
CLEAR_BIT(_usart->CR1, USART_CR1_UE);
// Enable USART APB clock.
SET_BIT(apbenr_reg, apbenr_bit);
(void)READ_BIT(apbenr_reg, apbenr_bit);
// Select system clock (216 MHz) as clock source for USART.
const uint32_t dckcfgr2_pos = 2 * (_iusart - 1);
const uint32_t dckcfgr2_mask = 0x03 << dckcfgr2_pos;
MODIFY_REG(RCC->DCKCFGR2, dckcfgr2_mask, 0x01 << dckcfgr2_pos);
// Set word length (M1 = 0, M0 = 0 => 1 start bit, 8 data bits, n
// stop bits).
CLEAR_BIT(_usart->CR1, USART_CR1_M0);
CLEAR_BIT(_usart->CR1, USART_CR1_M1);
// Disable parity.
CLEAR_BIT(_usart->CR1, USART_CR1_PCE);
// Disable auto baudrate detection.
CLEAR_BIT(_usart->CR2, USART_CR2_ABREN);
// Send/receive LSB first.
CLEAR_BIT(_usart->CR2, USART_CR2_MSBFIRST);
// Set oversampling rate to 16 and select baud rate 115200 based on
// USART clock running at 216 MHz (value taken from Table 220 in
// STM32F767ZI reference manual). (216000000 / 115200 = 0x0753)
CLEAR_BIT(_usart->CR1, USART_CR1_OVER8);
_usart->BRR = 0x0753;
// One stop bit (USART.CR2.STOP[1:0] = 0 => 1 stop bit).
MODIFY_REG(_usart->CR2, USART_CR2_STOP_Msk, 0);
// Enable USART, receiver and transmitter.
SET_BIT(_usart->CR1, USART_CR1_UE);
SET_BIT(_usart->CR1, USART_CR1_RE);
SET_BIT(_usart->CR1, USART_CR1_TE);
// Pin configuration: set TX to output (PP, pull-up), RX to input,
// set both to the appropriate alternate function.
_tx.output(GPIO_SPEED_VERY_HIGH, GPIO_TYPE_PUSH_PULL, GPIO_PUPD_PULL_UP);
_rx.input(GPIO_SPEED_VERY_HIGH);
_tx.alternate(_tx_af);
_rx.alternate(_rx_af);
// Receive interrupt setup: enable USART interrupts in NVIC and
// enable RX interrupt (also handles overrun errors).
NVIC_EnableIRQ(usart_irqn(_iusart));
SET_BIT(_usart->CR1, USART_CR1_RXNEIE);
// Transmit DMA setup. (Following procedure in Section 8.3.18 of
// reference manual.)
// TODO: SOME OF THIS IS STILL SPECIFIC TO USART3, I THINK.
// Enable DMA transmitter for UART.
SET_BIT(_usart->CR3, USART_CR3_DMAT);
// Enable clock for DMA1.
SET_BIT(ahbenr_dma_reg, ahbenr_dma_bit);
// 2. Set the peripheral port register address in the DMA_SxPAR
// register.
_dma->PAR = (uintptr_t)&_usart->TDR;
// 5. Select the DMA channel (request) using CHSEL[3:0] in the
// DMA_SxCR register.
MODIFY_REG(_dma->CR, DMA_SxCR_CHSEL_Msk,
_dma_chan.channel << DMA_SxCR_CHSEL_Pos);
// DMA is flow controller.
CLEAR_BIT(_dma->CR, DMA_SxCR_PFCTRL);
// 7. Configure the stream priority using the PL[1:0] bits in the
// DMA_SxCR register.
// Medium priority.
MODIFY_REG(_dma->CR, DMA_SxCR_PL_Msk, 0x02 << DMA_SxCR_PL_Pos);
// 8. Configure the FIFO usage (enable or disable, threshold in
// transmission and reception).
CLEAR_BIT(_dma->FCR, DMA_SxFCR_DMDIS); // No FIFO: direct mode.
// 9. Configure the data transfer direction, peripheral and memory
// incremented/fixed mode, single or burst transactions,
// peripheral and memory data widths, circular mode,
// double-buffer mode and interrupts after half and/or full
// transfer, and/or errors in the DMA_SxCR register.
// Memory-to-peripheral.
MODIFY_REG(_dma->CR, DMA_SxCR_DIR_Msk, 0x01 << DMA_SxCR_DIR_Pos);
// Increment memory, no increment peripheral.
SET_BIT(_dma->CR, DMA_SxCR_MINC);
CLEAR_BIT(_dma->CR, DMA_SxCR_PINC);
// No burst at either end.
MODIFY_REG(_dma->CR, DMA_SxCR_MBURST_Msk, 0x00 << DMA_SxCR_MBURST_Pos);
MODIFY_REG(_dma->CR, DMA_SxCR_PBURST_Msk, 0x00 << DMA_SxCR_PBURST_Pos);
// Byte size at both ends.
MODIFY_REG(_dma->CR, DMA_SxCR_MSIZE_Msk, 0x00 << DMA_SxCR_MSIZE_Pos);
MODIFY_REG(_dma->CR, DMA_SxCR_PSIZE_Msk, 0x00 << DMA_SxCR_PSIZE_Pos);
// No circular mode, no double buffering.
CLEAR_BIT(_dma->CR, DMA_SxCR_CIRC);
CLEAR_BIT(_dma->CR, DMA_SxCR_DBM);
// Transfer complete interrupt, no half-transfer interrupt, transfer
// error interrupt and direct mode error interrupt.
SET_BIT(_dma->CR, DMA_SxCR_TCIE);
CLEAR_BIT(_dma->CR, DMA_SxCR_HTIE);
SET_BIT(_dma->CR, DMA_SxCR_TEIE);
SET_BIT(_dma->CR, DMA_SxCR_DMEIE);
// Transmit DMA interrupt setup: enable DMA interrupts for DMA
// channel attached to USART.
NVIC_EnableIRQ(dma_irqn(_dma_chan));
}
// Buffer a single character for transmission.
void USART::tx(char c) {
// Buffer overflow: clear buffer, post error.
if (_tx_size >= USART_TX_BUFSIZE) {
_tx_size = 0;
if (mgr) mgr->post(Events::USART_TX_OVERFLOW);
return;
}
// Buffer character.
_tx_buff[_tx_size++] = c;
}
// Event handler: this checks whether we need to fire off a DMA TX on
// every SysTick. To force a flush, we just call the `flush` method,
// which sets the `need_flush` flag, and a DMA TX is started at the
// next SysTick.
void USART::dispatch(const Events::Event &e) {
switch (e.tag) {
case Events::EVENT_LOOP_STARTED:
init();
mgr->post(Events::USART_INIT, _iusart);
break;
case Events::SYSTICK:
// Skip conditions that don't require us to start a DMA TX.
if (_need_flush && _tx_size != 0 && !_tx_sending)
start_tx_dma();
break;
default:
break;
}
}
// Start a DMA transmission.
void USART::start_tx_dma(void) {
// Set DMA request to send _tx_size bytes starting at _tx_buff.
// (Following procedure in Section 8.3.18 of reference manual.)
// 1. If the stream is enabled, disable it by resetting the EN bit
// in the DMA_SxCR register, then read this bit in order to
// confirm that there is no ongoing stream operation.
CLEAR_BIT(_dma->CR, DMA_SxCR_EN);
while (READ_BIT(_dma->CR, DMA_SxCR_EN)) { __asm("nop"); }
// 3. Set the memory address in the DMA_SxMA0R register.
_dma->M0AR = (uintptr_t)_tx_buff;
// 4. Configure the total number of data items to be transferred in
// the DMA_SxNDTR register.
_dma->NDTR = _tx_size;
// Clear all interrupt pending flags.
SET_BIT(DMA1->LIFCR, DMA_LIFCR_CTCIF3);
SET_BIT(DMA1->LIFCR, DMA_LIFCR_CHTIF3);
SET_BIT(DMA1->LIFCR, DMA_LIFCR_CTEIF3);
SET_BIT(DMA1->LIFCR, DMA_LIFCR_CDMEIF3);
// Ensure all relevant interrupts are enabled.
SET_BIT(_dma->CR, DMA_SxCR_TCIE);
// 10. Activate the stream by setting the EN bit in the DMA_SxCR
// register.
SET_BIT(_dma->CR, DMA_SxCR_EN);
// TODO: SOME OF THIS SHOULD BE DONE *BEFORE* ENABLING THE DMA!
// Swap DMA buffers for writing and mark that a DMA is in progress.
_tx_buff_idx = 1 - _tx_buff_idx;
_tx_buff = _tx_buffs[_tx_buff_idx];
_tx_size = 0;
_tx_sending = true;
_need_flush = false;
}
// USART RX interrupt handler.
void USART::rx_irq(void) {
// Overrun: clear buffer, return error.
if (_usart->ISR & USART_ISR_ORE) {
SET_BIT(_usart->ICR, USART_ICR_ORECF);
if (mgr) mgr->post(Events::USART_RX_OVERRUN);
return;
}
// Byte received.
if (_usart->ISR & USART_ISR_RXNE) {
char c = _usart->RDR;
if (mgr) mgr->post(Events::USART_RX_CHAR, c);
}
}
// DMA stream interrupt handler.
void USART::tx_dma_irq(void) {
// Permit another flush.
_tx_sending = false;
// Errors.
if (DMA1->LISR & DMA_LISR_TEIF3) {
_tx_error = true;
SET_BIT(DMA1->LIFCR, DMA_LIFCR_CTEIF3);
}
if (DMA1->LISR & DMA_LISR_DMEIF3) {
_tx_error = true;
SET_BIT(DMA1->LIFCR, DMA_LIFCR_CDMEIF3);
}
// Transfer complete.
if (DMA1->LISR & DMA_LISR_TCIF3) {
SET_BIT(DMA1->LIFCR, DMA_LIFCR_CTCIF3);
}
if (_tx_error) {
if (mgr) mgr->post(Events::USART_TX_ERROR);
}
}
// The addresses for these aren't assigned systematically, hence the
// need for a switch statement here.
USART_TypeDef *USART::usart_base(int iusart) {
switch (iusart) {
case 1: return USART1;
case 2: return USART2;
case 3: return USART3;
case 4: return UART4;
case 5: return UART5;
case 6: return USART6;
default: return nullptr;
}
}
// TODO: DO THIS BETTER -- THERE ARE MULTIPLE POSSIBLE DMA STREAMS FOR
// MOST PERIPHERALS. FOR EXAMPLE, USART3_TX IS ON DMA1_Stream3,
// CHANNEL 4 AND ON DMA1_Stream4, CHANNEL 7.
DMA_Stream_TypeDef *USART::usart_dma_stream(int iusart) {
switch (iusart) {
case 1: return DMA2_Stream7;
case 2: return DMA1_Stream6;
case 3: return DMA1_Stream3;
case 4: return DMA1_Stream4;
case 5: return DMA1_Stream7;
case 6: return DMA2_Stream6;
default: return nullptr;
}
}
static IRQn_Type usart_irqn(int iusart) {
switch (iusart) {
case 1: return USART1_IRQn;
case 2: return USART2_IRQn;
case 3: return USART3_IRQn;
case 4: return UART4_IRQn;
case 5: return UART5_IRQn;
case 6: return USART6_IRQn;
default: return NonMaskableInt_IRQn;
}
}
//----------------------------------------------------------------------
//
// TESTS
//
#ifdef TEST
#include "doctest.h"
#include "doctest/trompeloeil.hpp"
#include "events_mock.hpp"
TEST_CASE("USART") {
using trompeloeil::_;
MockEventWaiter waiter;
Events::Manager ev(MockEventWaiter::wait_for_event);
USART usart(3, PD8, GPIO_AF_7, PD9, GPIO_AF_7, DMAChannel { 1, 3, 4 });
ev += usart;
MockEventConsumer consumer;
ev += consumer;
SUBCASE("RX ISR enqueues correct event") {
ALLOW_CALL(consumer, dispatch(_));
ev.drain();
USART3->RDR = 'x';
SET_BIT(USART3->ISR, USART_ISR_RXNE);
usart.rx_irq();
REQUIRE_CALL(consumer, dispatch(_))
.WITH(_1.tag == Events::USART_RX_CHAR && _1.param1 == 'x');
ev.drain();
CHECK(ev.pending_count() == 0);
}
SUBCASE("RX overrun enqueues correct event") {
ALLOW_CALL(consumer, dispatch(_));
ev.drain();
SET_BIT(USART3->ISR, USART_ISR_ORE);
usart.rx_irq();
REQUIRE_CALL(consumer, dispatch(_))
.WITH(_1.tag == Events::USART_RX_OVERRUN);
ev.drain();
CHECK(ev.pending_count() == 0);
}
SUBCASE("SysTick triggers TX DMA") {
ALLOW_CALL(consumer, dispatch(_));
ev.drain();
memset(DMA1_Stream3, 0, sizeof(DMA_Stream_TypeDef));
for (auto c : "abcdef") {
usart.tx(c);
}
usart.flush();
ev.post(Events::SYSTICK);
ev.drain();
CHECK(READ_BIT(DMA1_Stream3->CR, DMA_SxCR_EN) != 0);
}
}
#endif
| 10,608 | 4,688 |
// Copyright 2014 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 "mojo/examples/apptest/example_client_application.h"
#include "mojo/examples/apptest/example_client_impl.h"
#include "mojo/examples/apptest/example_service.mojom.h"
#include "mojo/public/c/system/main.h"
#include "mojo/public/cpp/application/application_delegate.h"
#include "mojo/public/cpp/application/application_impl.h"
#include "mojo/public/cpp/bindings/callback.h"
#include "mojo/public/cpp/environment/environment.h"
#include "mojo/public/cpp/system/macros.h"
#include "mojo/public/cpp/utility/run_loop.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
// TODO(msw): Remove this once we can get ApplicationImpl from TLS.
mojo::ApplicationImpl* g_application_impl_hack = NULL;
} // namespace
namespace mojo {
namespace {
class ExampleServiceTest : public testing::Test {
public:
ExampleServiceTest() {
g_application_impl_hack->ConnectToService("mojo:mojo_example_service",
&example_service_);
example_service_.set_client(&example_client_);
}
virtual ~ExampleServiceTest() MOJO_OVERRIDE {}
protected:
ExampleServicePtr example_service_;
ExampleClientImpl example_client_;
private:
MOJO_DISALLOW_COPY_AND_ASSIGN(ExampleServiceTest);
};
TEST_F(ExampleServiceTest, Ping) {
EXPECT_EQ(0, example_client_.last_pong_value());
example_service_->Ping(1);
RunLoop::current()->Run();
EXPECT_EQ(1, example_client_.last_pong_value());
}
template <typename T>
struct SetAndQuit : public Callback<void()>::Runnable {
SetAndQuit(T* val, T result) : val_(val), result_(result) {}
virtual ~SetAndQuit() {}
virtual void Run() const MOJO_OVERRIDE{
*val_ = result_;
RunLoop::current()->Quit();
}
T* val_;
T result_;
};
TEST_F(ExampleServiceTest, RunCallback) {
bool was_run = false;
example_service_->RunCallback(SetAndQuit<bool>(&was_run, true));
RunLoop::current()->Run();
EXPECT_TRUE(was_run);
}
} // namespace
} // namespace mojo
MojoResult MojoMain(MojoHandle shell_handle) {
mojo::Environment env;
mojo::RunLoop loop;
// TODO(tim): Perhaps the delegate should be the thing that provides
// the ExampleServiceTest with the ApplicationImpl somehow.
mojo::ApplicationDelegate* delegate = new mojo::ExampleClientApplication();
mojo::ApplicationImpl app(delegate, shell_handle);
g_application_impl_hack = &app;
// TODO(msw): Get actual commandline arguments.
int argc = 0;
char** argv = NULL;
testing::InitGoogleTest(&argc, argv);
mojo_ignore_result(RUN_ALL_TESTS());
delete delegate;
return MOJO_RESULT_OK;
}
| 2,736 | 928 |
#include "CardAreaDetection.h"
#include <opencv2/videostab/ring_buffer.hpp>
// defines includes
#include <opencv2\imgcodecs\imgcodecs_c.h>
#include <opencv2\imgproc\types_c.h>
using namespace cv;
IDAP::CardAreaDetection::CardAreaDetection(int _id, int _playerID, int _sizeID, int _xPos, int _yPos, int _width, int _height, int imageWidth, int imageHeight, float mmInPixel, bool turn)
{
id = _id;
playerID = _playerID;
sizeID = _sizeID;
posX = _xPos;
posY = _yPos;
turned = turn;
// to over come the inaccuracy of calibration, the roi is 40 % bigger
const float bigger = 0.4;
const float deltaWidth = (_width / mmInPixel) * bigger;
const float deltaHeight = (_height / mmInPixel) * bigger;
const float newPosX = (posX * (imageWidth / 100.f)) - deltaWidth / 2.f;
const float newPosY = (posY * (imageHeight / 100.f)) - deltaHeight / 2.f;
if (!turned)
{
roi = cv::Rect(newPosX, newPosY, (_width / mmInPixel) + deltaWidth, (_height / mmInPixel) + deltaHeight);
const float ratio = static_cast<float>(roi.height) / static_cast<float>(roi.width);
sizeTM = cv::Size(CARD_MATCHING_WIDTH*(1.f + bigger), CARD_MATCHING_WIDTH*(1.f + bigger)*ratio);
}
else
{
roi = cv::Rect(newPosX, newPosY, (_height / mmInPixel) + deltaHeight, (_width / mmInPixel) + deltaWidth);
const float ratio = static_cast<float>(roi.width) / static_cast<float>(roi.height);
sizeTM = cv::Size(CARD_MATCHING_WIDTH*(1.f + bigger)*ratio, CARD_MATCHING_WIDTH*(1.f + bigger));
}
initState = true;
results = new TopThree();
}
IDAP::CardAreaDetection::~CardAreaDetection()
{
delete(results);
}
void IDAP::CardAreaDetection::isCardChanged(uint16_t& errorCode, cv::Mat currentFrame, std::vector<std::pair<int, cv::Mat>>& cardDataReference, std::vector<std::pair<int, cv::Mat>>& cardDataGradientReference, cv::Mat meanCardGrad, uint16_t& cardType) const
{
// cut roi from frame, settle up card in it, set the right direction and perform template matching
const cv::Mat area = currentFrame(roi);
// grayscale
cv::Mat gray;
cv::cvtColor(area, gray, cv::COLOR_RGB2GRAY);
// resize area
cv::Mat areaTM;
cv::resize(gray, areaTM, sizeTM);
// turn area if needed
if(turned)
{
cv::rotate(areaTM, areaTM, ROTATE_90_COUNTERCLOCKWISE);
}
// create gradient version
const int scale = 1;
const int delta = 0;
const int ddepth = CV_16S;
cv::Mat grad_x, grad_y;
cv::Mat abs_grad_x, abs_grad_y;
cv::Mat grad;
// Gradient X
Sobel(areaTM, grad_x, ddepth, 1, 0, 3, scale, delta, cv::BORDER_DEFAULT);
convertScaleAbs(grad_x, abs_grad_x);
// Gradient Y
Sobel(areaTM, grad_y, ddepth, 0, 1, 3, scale, delta, cv::BORDER_DEFAULT);
convertScaleAbs(grad_y, abs_grad_y);
// approximate total gradient calculation
cv::addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0, grad);
cv::Mat img_display, result;
area.copyTo(img_display);
const int result_cols = areaTM.cols - meanCardGrad.cols + 1;
const int result_rows = areaTM.rows - meanCardGrad.rows + 1;
//cv::imshow("img", grad);
//cv::imshow("templ", meanCardGrad);
result.create(result_rows, result_cols, CV_32FC1);
cv::matchTemplate(grad, meanCardGrad, result, CV_TM_CCORR_NORMED);
double minVal; double maxVal;
cv::Point minLoc;
cv::Point maxLoc;
minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc, cv::Mat());
const float meanValue = cv::mean(grad)[0];
if(meanValue >= MIN_MEAN_VALUE && maxVal >= TEMPLATE_MATCH_SCORE_MIN)
{
// perform SURF on imput image
// Detect and describe interest points using SURF Detector and Descriptor.
const int minHessian = 500; // min Hessian was experimentaly set, to obtain at least 8 matches on correct card class
Ptr<cv::xfeatures2d::SURF> detector = cv::xfeatures2d::SURF::create();
detector->setHessianThreshold(minHessian);
std::vector<KeyPoint> interestPointsArea;
Mat interestPointsAreaDesc;
detector->detectAndCompute(area, Mat(), interestPointsArea, interestPointsAreaDesc);
// classify using SURF and FLANN
results->SetMin(true);
for (std::vector<std::pair<int, cv::Mat>>::iterator it = cardDataReference.begin(); it != cardDataReference.end(); ++it)
{
// ----------------------------------- FLANN -------------------------------------
const uint16_t templCardType = static_cast<uint16_t>(it->first);
std::vector<KeyPoint> interestPointTempl;
Mat interestPointTemplDesc;
detector->detectAndCompute(it->second, Mat(), interestPointTempl, interestPointTemplDesc);
// Matching descriptor vectors using FLANN matcher - searching for nearest neighbors
FlannBasedMatcher matcher;
std::vector< DMatch > matches;
matcher.match(interestPointsAreaDesc, interestPointTemplDesc, matches);
double maxDist = 0; double minDist = 100;
//-- Quick calculation of max and min distances between keypoints
for (int i = 0; i < interestPointsAreaDesc.rows; i++)
{
const double dist = matches[i].distance;
if (dist < minDist) minDist = dist;
if (dist > maxDist) maxDist = dist;
}
std::map<float, int> goodMatchesDistance;
// filter only good matches - the ones which are at worst two times minimal distance
std::vector< DMatch > good_matches;
for (int i = 0; i < interestPointsAreaDesc.rows; i++)
{
if (matches[i].distance <= max(2 * minDist, 0.02))
{
good_matches.push_back(matches[i]);
goodMatchesDistance.insert(std::make_pair(matches[i].distance, i));
}
}
// if at least 8 good matches were found, compare the sum of distance of these good matches with the previously classes
// if it is better, put this class to TopThree result
// the TopThree classes are then sorted by the best match -> this was experimentaly tested and lead to better result than using all 8 best matches
if (goodMatchesDistance.size() >= 8)
{
float bestEightSum = 0.f;
int count = 0;
for (std::map<float, int>::iterator it = goodMatchesDistance.begin(); it != goodMatchesDistance.end(); ++it)
{
if (++count > 8)
break;
bestEightSum += it->first;
}
if (results->isBetter(bestEightSum))
{
results->TryAddNew(templCardType, bestEightSum);
}
}
}
// return the class the card fit the best
cardType = results->GetFirst();
results->Init();
}
else
{
// return no card, if no card is detected
cardType = IDAP::BangCardTypes::NONE;
}
}
void IDAP::CardAreaDetection::CardDetectionTester(std::vector<std::pair<int, cv::Mat>> cardDataReference)
{
std::map<int, int> classifications;
for(int i = 1; i < 32; ++i)
{
classifications.insert(std::make_pair(i, 0));
}
const bool templateMethod = false;
const std::string path = "CardDetectionData/BANG_A";
const auto match_method = CV_TM_CCORR_NORMED;
if (templateMethod)
results->SetMin(false);
else
results->SetMin(true);
// variable settings for gradient
const int scale = 1;
const int delta = 0;
const int ddepth = CV_16S;
// list all files in given folder and load them to memory and provide them to card area detection for template matching
for (auto &file : std::experimental::filesystem::directory_iterator(path))
{
cv::Mat img = cv::imread(file.path().string().c_str(), CV_LOAD_IMAGE_COLOR);
std::cout << file.path().string().c_str() << std::endl;
if (file.path().string().find("Bang_06.png") == std::string::npos)
continue;
// variables
cv::Mat rotImg, templ, imgGray, templGray, imgGrayDenoise;
cv::Mat gradTempl, gradImage;
cv::Mat imgGradFinal;
// perform classification
if(templateMethod)
{
//----------------------------- TEMPLATE MATCHING -------------------------------
// hought transform to turn right -------------------------------------------------
cv::Mat edges, gray, dil, ero, dst, cdst;
cv::cvtColor(img, gray, CV_BGR2GRAY);
cv::Canny(gray, edges, 85, 255);
cv::cvtColor(edges, cdst, COLOR_GRAY2BGR);
cv::Mat cdstP = cdst.clone();
std::vector<Vec2f> lines; // will hold the results of the detection
// Probabilistic Line Transform
std::vector<Vec4i> linesP; // will hold the results of the detection
HoughLinesP(edges, linesP, 1, CV_PI / 180, 50, 50, 10); // runs the actual detection
// Draw the lines
float angleFin = 0.f;
float linesUsed = 0;
for (size_t i = 0; i < linesP.size(); i++)
{
Vec4i l = linesP[i];
line(cdstP, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, LINE_AA);
Point p1, p2;
p1 = Point(l[0], l[1]);
p2 = Point(l[2], l[3]);
// calculate angle in radian, to degrees: angle * 180 / PI
float angle = atan2(p1.y - p2.y, p1.x - p2.x) * 180 / CV_PI;
if (angle > 0)
angle -= 90;
else
angle += 90;
// limit the lines which will be used, to limit errors
if ((angle < MAX_LINE_ANGLE_FOR_HOUGH && angle > 0) ||
(angle > -MAX_LINE_ANGLE_FOR_HOUGH && angle < 0))
{
angleFin += angle;
++linesUsed;
}
}
if(linesUsed > 0)
angleFin /= linesUsed;
// rotate img
const cv::Mat rot = getRotationMatrix2D(Point2f(img.cols / 2, img.rows / 2), angleFin, 1);
cv::warpAffine(img, rotImg, rot, Size(img.cols, img.rows));
cv::cvtColor(rotImg, imgGray, CV_BGR2GRAY);
// gradient of input image
cv::Mat imgGradX, imgGradY;
cv::Mat absGradX, absGradY;
/// Gradient X
Sobel(imgGray, imgGradX, ddepth, 1, 0, 3, scale, delta, cv::BORDER_DEFAULT);
convertScaleAbs(imgGradX, absGradX);
/// Gradient Y
//Scharr( src_gray, grad_y, ddepth, 0, 1, scale, delta, BORDER_DEFAULT );
Sobel(imgGray, imgGradY, ddepth, 0, 1, 3, scale, delta, cv::BORDER_DEFAULT);
convertScaleAbs(imgGradY, absGradY);
// combine gradient
cv::addWeighted(absGradX, 0.5, absGradY, 0.5, 0, imgGradFinal);
}
for (std::vector<std::pair<int, cv::Mat>>::iterator it = cardDataReference.begin(); it != cardDataReference.end(); ++it)
{
uint16_t templCardType = static_cast<uint16_t>(it->first);
cv::Mat rawtempl = it->second;
cv::Mat mask;
// ----------------------------------- FLANN -------------------------------------
if (!templateMethod)
{
cv::Mat img_1, img_2;
img.copyTo(img_1);
rawtempl.copyTo(img_2);
const int minHessian = 500;
Ptr<cv::xfeatures2d::SURF> detector = cv::xfeatures2d::SURF::create();
detector->setHessianThreshold(minHessian);
std::vector<KeyPoint> keypoints_1, keypoints_2;
Mat descriptors_1, descriptors_2;
detector->detectAndCompute(img_1, Mat(), keypoints_1, descriptors_1);
detector->detectAndCompute(img_2, Mat(), keypoints_2, descriptors_2);
FlannBasedMatcher matcher;
std::vector< DMatch > matches;
matcher.match(descriptors_1, descriptors_2, matches);
double max_dist = 0; double min_dist = 100;
for (int i = 0; i < descriptors_1.rows; i++)
{
const double dist = matches[i].distance;
if (dist < min_dist) min_dist = dist;
if (dist > max_dist) max_dist = dist;
}
//printf("-- Max dist : %f \n", max_dist);
//printf("-- Min dist : %f \n", min_dist);
std::map<float, int> goodMatchesDistance;
std::vector< DMatch > good_matches;
for (int i = 0; i < descriptors_1.rows; i++)
{
if (matches[i].distance <= max(2 * min_dist, 0.02))
{
good_matches.push_back(matches[i]);
goodMatchesDistance.insert(std::make_pair(matches[i].distance, i));
}
}
double evalNew = static_cast<double>(good_matches.size()) / static_cast<double>(matches.size());
//printf("EVAL: %d | %d : %f\n", static_cast<int>(good_matches.size()), static_cast<int>(matches.size()), eval);
if (goodMatchesDistance.size() >= 8)
{
float bestFive = 0.f;
int count = 0;
for (std::map<float, int>::iterator it2 = goodMatchesDistance.begin(); it2 != goodMatchesDistance.end(); ++it2)
{
if (++count > 8)
break;
bestFive += it2->first;
}
//std::cout << "Chesking add: " << templCardType << ", " << bestFive << std::endl;
if (results->isBetter(bestFive))
{
results->TryAddNew(templCardType, bestFive);
}
}
//-- Draw only "good" matches
Mat img_matches;
drawMatches(img_1, keypoints_1, img_2, keypoints_2,
good_matches, img_matches, Scalar::all(-1), Scalar::all(-1),
std::vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS);
//-- Show detected matches
//imshow("Good Matches", img_matches);
//imwrite("goodMatches.png", img_matches);
for (int i = 0; i < (int)good_matches.size(); i++)
{
//printf("-- Good Match [%d] Keypoint 1: %d -- Keypoint 2: %d \n", i, good_matches[i].queryIdx, good_matches[i].trainIdx);
}
//cv::waitKey(0);
}
else
{
cv::cvtColor(rawtempl, templGray, CV_BGR2GRAY);
// gradient of input image
cv::Mat templGradX, templGradY;
cv::Mat absGradXTempl, absGradYTempl;
cv::Mat templGradFinal;
/// Gradient X
Sobel(templGray, templGradX, ddepth, 1, 0, 3, scale, delta, cv::BORDER_DEFAULT);
convertScaleAbs(templGradX, absGradXTempl);
/// Gradient Y
//Scharr( src_gray, grad_y, ddepth, 0, 1, scale, delta, BORDER_DEFAULT );
Sobel(templGray, templGradY, ddepth, 0, 1, 3, scale, delta, cv::BORDER_DEFAULT);
convertScaleAbs(templGradY, absGradYTempl);
// combine gradient
cv::addWeighted(absGradXTempl, 0.5, absGradYTempl, 0.5, 0, templGradFinal);
cv::Point matchLoc;
/*for (float i = 1; i > 0.5; i -= 0.1)
{
// scale template
cv::Size newSize(rawtempl.cols*i, rawtempl.rows*i);
cv::resize(templGradFinal, templGradFinal, newSize);*/
cv::Mat img_display, result;
gradImage.copyTo(img_display);
int result_cols = imgGradFinal.cols - templGradFinal.cols + 1;
int result_rows = imgGradFinal.rows - templGradFinal.rows + 1;
result.create(result_rows, result_cols, CV_32FC1);
matchTemplate(imgGradFinal, templGradFinal, result, match_method);
double minVal; double maxVal; cv::Point minLoc; cv::Point maxLoc;
cv::minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc);
matchLoc = maxLoc;
results->TryAddNew(templCardType, maxVal);
cv::Mat locationMatch;
imgGradFinal.copyTo(locationMatch);
const cv::Rect rect(matchLoc.x, matchLoc.y, templGradFinal.size().width, templGradFinal.size().height);
cv::rectangle(locationMatch, rect, Scalar(255,0,0));
//}
}
}
//std::cout << "result for " << file.path().string() << ": " << results->GetFirst() << ", " << results->GetSecond() << ", " << results->GetThird() << std::endl;
//printf("eval: %f, %f, %f\n", results->firstEval, results->secondEval, results->thirdEval);
classifications.at(results->GetFirst()) += 1;
results->Init();
//cv::waitKey(0);
}
for(int i = 1; i < 32; ++i)
{
if(classifications.at(i) > 0)
std::cout << "template ID:" << i << " -> " << classifications.at(i) << std::endl;
}
//cv::waitKey(0);
}
void IDAP::TopThree::Init()
{
first = 0;
second = 0;
third = 0;
bestPoints = std::numeric_limits<double>::max();
if (min)
{
firstEval = std::numeric_limits<double>::max();
secondEval = std::numeric_limits<double>::max();
thirdEval = std::numeric_limits<double>::max();
}
else
{
firstEval = std::numeric_limits<double>::min();
secondEval = std::numeric_limits<double>::min();
thirdEval = std::numeric_limits<double>::min();
}
}
void IDAP::TopThree::TryAddNew(uint16_t cardType, float eval)
{
if (min)
{
if (eval < thirdEval)
{
// new top three
third = cardType;
thirdEval = eval;
SortTopThree();
}
}
else
{
if (eval > thirdEval)
{
// new top three
third = cardType;
thirdEval = eval;
SortTopThree();
}
}
}
bool IDAP::TopThree::isBetter(float val)
{
double curVal = static_cast<double>(val);
if (curVal < bestPoints)
{
bestPoints = curVal;
return true;
}
return false;
}
void IDAP::TopThree::SortTopThree()
{
if (min)
{
if (thirdEval < secondEval)
{
std::swap(third, second);
std::swap(thirdEval, secondEval);
}
if(secondEval < firstEval)
{
std::swap(first, second);
std::swap(firstEval, secondEval);
}
}
else
{
if (thirdEval > secondEval)
{
std::swap(third, second);
std::swap(thirdEval, secondEval);
}
if (secondEval > firstEval)
{
std::swap(first, second);
std::swap(firstEval, secondEval);
}
}
}
| 19,733 | 6,329 |
/* Copyright (c) MediaArea.net SARL & AV Preservation by reto.ch.
*
* Use of this source code is governed by a BSD-style license that can
* be found in the License.html file in the root of the source tree.
*/
//---------------------------------------------------------------------------
#include "CLI/Global.h"
#include "CLI/Help.h"
#include <iostream>
#include <cstring>
#include <iomanip>
#include <thread>
#if defined(_WIN32) || defined(_WINDOWS)
#include <direct.h>
#define getcwd _getcwd
#else
#include <unistd.h>
#endif
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// Glue
void global_ProgressIndicator_Show(global* G)
{
G->ProgressIndicator_Show();
}
//---------------------------------------------------------------------------
int global::SetOutputFileName(const char* FileName)
{
OutputFileName = FileName;
OutputFileName_IsProvided = true;
return 0;
}
//---------------------------------------------------------------------------
int global::SetBinName(const char* FileName)
{
BinName = FileName;
return 0;
}
//---------------------------------------------------------------------------
int global::SetLicenseKey(const char* Key, bool StoreIt)
{
LicenseKey = Key;
StoreLicenseKey = StoreIt;
return 0;
}
//---------------------------------------------------------------------------
int global::SetSubLicenseId(uint64_t Id)
{
if (!Id || Id >= 127)
{
cerr << "Error: sub-licensee ID must be between 1 and 126.\n";
return 1;
}
SubLicenseId = Id;
return 0;
}
//---------------------------------------------------------------------------
int global::SetSubLicenseDur(uint64_t Dur)
{
if (Dur > 12)
{
cerr << "Error: sub-licensee duration must be between 0 and 12.\n";
return 1;
}
SubLicenseDur = Dur;
return 0;
}
//---------------------------------------------------------------------------
int global::SetDisplayCommand()
{
DisplayCommand = true;
return 0;
}
//---------------------------------------------------------------------------
int global::SetAcceptFiles()
{
AcceptFiles = true;
return 0;
}
//---------------------------------------------------------------------------
int global::SetCheck(bool Value)
{
Actions.set(Action_Check, Value);
Actions.set(Action_CheckOptionIsSet);
if (Value)
return SetDecode(false);
return 0;
}
//---------------------------------------------------------------------------
int global::SetQuickCheck()
{
Actions.set(Action_Check, false);
Actions.set(Action_CheckOptionIsSet, false);
return 0;
}
//---------------------------------------------------------------------------
int global::SetCheck(const char* Value, int& i)
{
if (Value && (strcmp(Value, "0") == 0 || strcmp(Value, "partial") == 0))
{
SetCheckPadding(false);
++i; // Next argument is used
cerr << "Warning: \" --check " << Value << "\" is deprecated, use \" --no-check-padding\" instead.\n" << endl;
return 0;
}
if (Value && (strcmp(Value, "1") == 0 || strcmp(Value, "full") == 0))
{
SetCheckPadding(true);
++i; // Next argument is used
cerr << "Warning: \" --check " << Value << "\" is deprecated, use \" --check-padding\" instead.\n" << endl;
return 0;
}
SetCheck(true);
return 0;
}
//---------------------------------------------------------------------------
int global::SetCheckPadding(bool Value)
{
Actions.set(Action_CheckPadding, Value);
Actions.set(Action_CheckPaddingOptionIsSet);
return 0;
}
//---------------------------------------------------------------------------
int global::SetQuickCheckPadding()
{
Actions.set(Action_CheckPadding, false);
Actions.set(Action_CheckPaddingOptionIsSet, false);
return 0;
}
//---------------------------------------------------------------------------
int global::SetAcceptGaps(bool Value)
{
Actions.set(Action_AcceptGaps, Value);
return 0;
}
//---------------------------------------------------------------------------
int global::SetCoherency(bool Value)
{
Actions.set(Action_Coherency, Value);
return 0;
}
//---------------------------------------------------------------------------
int global::SetConch(bool Value)
{
Actions.set(Action_Conch, Value);
if (Value)
{
SetDecode(false);
SetEncode(false);
}
return 0;
}
//---------------------------------------------------------------------------
int global::SetDecode(bool Value)
{
Actions.set(Action_Decode, Value);
return 0;
}
//---------------------------------------------------------------------------
int global::SetEncode(bool Value)
{
Actions.set(Action_Encode, Value);
return 0;
}
//---------------------------------------------------------------------------
int global::SetInfo(bool Value)
{
Actions.set(Action_Info, Value);
if (Value)
{
SetDecode(false);
SetEncode(false);
}
return 0;
}
//---------------------------------------------------------------------------
int global::SetFrameMd5(bool Value)
{
Actions.set(Action_FrameMd5, Value);
return 0;
}
//---------------------------------------------------------------------------
int global::SetFrameMd5FileName(const char* FileName)
{
FrameMd5FileName = FileName;
return 0;
}
//---------------------------------------------------------------------------
int global::SetHash(bool Value)
{
Actions.set(Action_Hash, Value);
return 0;
}
//---------------------------------------------------------------------------
int global::SetAll(bool Value)
{
if (int ReturnValue = SetInfo(Value))
return ReturnValue;
if (int ReturnValue = SetConch(Value))
return ReturnValue;
if (int ReturnValue = (Value?SetCheck(true):SetQuickCheck())) // Never implicitely set no check
return ReturnValue;
if (int ReturnValue = (Value && SetCheckPadding(Value))) // Never implicitely set no check padding
return ReturnValue;
if (int ReturnValue = SetAcceptGaps(Value))
return ReturnValue;
if (int ReturnValue = SetCoherency(Value))
return ReturnValue;
if (int ReturnValue = SetDecode(Value))
return ReturnValue;
if (int ReturnValue = SetEncode(Value))
return ReturnValue;
if (int ReturnValue = SetHash(Value))
return ReturnValue;
return 0;
}
//---------------------------------------------------------------------------
int Error_NotTested(const char* Option1, const char* Option2 = NULL)
{
cerr << "Error: option " << Option1;
if (Option2)
cerr << ' ' << Option2;
cerr << " not yet tested.\nPlease contact info@mediaarea.net if you want support of such option." << endl;
return 1;
}
//---------------------------------------------------------------------------
int Error_Missing(const char* Option1)
{
cerr << "Error: missing argument for option '" << Option1 << "'." << endl;
return 1;
}
//---------------------------------------------------------------------------
int global::SetOption(const char* argv[], int& i, int argc)
{
if (strcmp(argv[i], "-c:a") == 0)
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
if (strcmp(argv[i], "copy") == 0)
{
OutputOptions["c:a"] = argv[i];
License.Encoder(encoder::PCM);
return 0;
}
if (strcmp(argv[i], "flac") == 0)
{
OutputOptions["c:a"] = argv[i];
License.Encoder(encoder::FLAC);
return 0;
}
return Error_NotTested(argv[i - 1], argv[i]);
}
if (!strcmp(argv[i], "-c:v"))
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
if (!strcmp(argv[i], "ffv1"))
{
OutputOptions["c:v"] = argv[i];
License.Encoder(encoder::FFV1);
return 0;
}
return Error_NotTested(argv[i - 1], argv[i]);
}
if (!strcmp(argv[i], "-coder"))
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
if (!strcmp(argv[i], "0")
|| !strcmp(argv[i], "1")
|| !strcmp(argv[i], "2"))
{
OutputOptions["coder"] = argv[i];
License.Feature(feature::EncodingOptions);
return 0;
}
return Error_NotTested(argv[i - 1], argv[i]);
}
if (!strcmp(argv[i], "-context"))
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
if (!strcmp(argv[i], "0")
|| !strcmp(argv[i], "1"))
{
OutputOptions["context"] = argv[i];
License.Feature(feature::EncodingOptions);
return 0;
}
return Error_NotTested(argv[i - 1], argv[i]);
}
if (!strcmp(argv[i], "-f"))
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
if (!strcmp(argv[i], "matroska"))
{
OutputOptions["f"] = argv[i];
return 0;
}
return 0;
}
if (!strcmp(argv[i], "-framerate"))
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
if (atof(argv[i]))
{
VideoInputOptions["framerate"] = argv[i];
License.Feature(feature::InputOptions);
return 0;
}
return 0;
}
if (!strcmp(argv[i], "-g"))
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
if (atoi(argv[i]))
{
OutputOptions["g"] = argv[i];
License.Feature(feature::EncodingOptions);
return 0;
}
cerr << "Invalid \"" << argv[i - 1] << " " << argv[i] << "\" value, it must be a number\n";
return 1;
}
if (!strcmp(argv[i], "-level"))
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
if (!strcmp(argv[i], "0")
|| !strcmp(argv[i], "1")
|| !strcmp(argv[i], "3"))
{
OutputOptions["level"] = argv[i];
License.Feature(feature::EncodingOptions);
return 0;
}
return Error_NotTested(argv[i - 1], argv[i]);
}
if (!strcmp(argv[i], "-loglevel"))
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
if (!strcmp(argv[i], "error")
|| !strcmp(argv[i], "warning"))
{
OutputOptions["loglevel"] = argv[i];
License.Feature(feature::GeneralOptions);
return 0;
}
return Error_NotTested(argv[i - 1], argv[i]);
}
if (strcmp(argv[i], "-n") == 0)
{
OutputOptions["n"] = string();
OutputOptions.erase("y");
Mode = AlwaysNo; // Also RAWcooked itself
License.Feature(feature::GeneralOptions);
return 0;
}
if (!strcmp(argv[i], "-slicecrc"))
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
if (!strcmp(argv[i], "0")
|| !strcmp(argv[i], "1"))
{
OutputOptions["slicecrc"] = argv[i];
License.Feature(feature::EncodingOptions);
return 0;
}
return Error_NotTested(argv[i - 1], argv[i]);
}
if (!strcmp(argv[i], "-slices"))
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
int SliceCount = atoi(argv[i]);
if (SliceCount) //TODO: not all slice counts are accepted by FFmpeg, we should filter
{
OutputOptions["slices"] = argv[i];
License.Feature(feature::EncodingOptions);
return 0;
}
return Error_NotTested(argv[i - 1], argv[i]);
}
if (!strcmp(argv[i], "-threads"))
{
if (++i >= argc)
return Error_NotTested(argv[i - 1]);
OutputOptions["threads"] = argv[i];
License.Feature(feature::GeneralOptions);
return 0;
}
if (strcmp(argv[i], "-y") == 0)
{
OutputOptions["y"] = string();
OutputOptions.erase("n");
Mode = AlwaysYes; // Also RAWcooked itself
License.Feature(feature::GeneralOptions);
return 0;
}
return Error_NotTested(argv[i]);
}
//---------------------------------------------------------------------------
int global::ManageCommandLine(const char* argv[], int argc)
{
if (argc < 2)
return Usage(argv[0]);
AttachmentMaxSize = (size_t)-1;
IgnoreLicenseKey = !License.IsSupported_License();
SubLicenseId = 0;
SubLicenseDur = 1;
ShowLicenseKey = false;
StoreLicenseKey = false;
DisplayCommand = false;
AcceptFiles = false;
OutputFileName_IsProvided = false;
Quiet = false;
Actions.set(Action_Encode);
Actions.set(Action_Decode);
Actions.set(Action_Coherency);
Hashes = hashes(&Errors);
ProgressIndicator_Thread = NULL;
for (int i = 1; i < argc; i++)
{
if ((argv[i][0] == '.' && argv[i][1] == '\0')
|| (argv[i][0] == '.' && (argv[i][1] == '/' || argv[i][1] == '\\') && argv[i][2] == '\0'))
{
//translate to "../xxx" in order to get the top level directory name
char buff[FILENAME_MAX];
if (getcwd(buff, FILENAME_MAX))
{
string Arg = buff;
size_t Path_Pos = Arg.find_last_of("/\\");
Arg = ".." + Arg.substr(Path_Pos);
Inputs.push_back(Arg);
}
else
{
cerr << "Error: " << argv[i] << " can not be transformed to a directory name." << endl;
return 1;
}
}
else if (strcmp(argv[i], "--all") == 0)
{
int Value = SetAll(true);
if (Value)
return Value;
}
else if ((strcmp(argv[i], "--attachment-max-size") == 0 || strcmp(argv[i], "-s") == 0))
{
if (i + 1 == argc)
return Error_Missing(argv[i]);
AttachmentMaxSize = atoi(argv[++i]);
License.Feature(feature::GeneralOptions);
}
else if ((strcmp(argv[i], "--bin-name") == 0 || strcmp(argv[i], "-b") == 0))
{
if (i + 1 == argc)
return Error_Missing(argv[i]);
int Value = SetBinName(argv[++i]);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--check") == 0)
{
if (i + 1 < argc)
{
// Deprecated version handling
int Value = SetCheck(argv[i + 1], i);
if (Value)
return Value;
}
else
{
int Value = SetCheck(true);
License.Feature(feature::GeneralOptions);
if (Value)
return Value;
}
}
else if (strcmp(argv[i], "--check-padding") == 0)
{
int Value = SetCheckPadding(true);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--accept-gaps") == 0)
{
int Value = SetAcceptGaps(true);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--coherency") == 0)
{
int Value = SetCoherency(true);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--conch") == 0)
{
int Value = SetConch(true);
if (Value)
return Value;
}
else if ((strcmp(argv[i], "--display-command") == 0 || strcmp(argv[i], "-d") == 0))
{
int Value = SetDisplayCommand();
if (Value)
return Value;
License.Feature(feature::GeneralOptions);
}
else if (strcmp(argv[i], "--decode") == 0)
{
int Value = SetDecode(true);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--encode") == 0)
{
int Value = SetEncode(true);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--framemd5") == 0)
{
int Value = SetFrameMd5(true);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--framemd5-name") == 0)
{
if (i + 1 == argc)
return Error_Missing(argv[i]);
int Value = SetFrameMd5FileName(argv[++i]);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--hash") == 0)
{
int Value = SetHash(true);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--file") == 0)
{
int Value = SetAcceptFiles();
if (Value)
return Value;
}
else if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0)
{
int Value = Help(argv[0]);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--info") == 0)
{
int Value = SetInfo(true);
if (Value)
return Value;
}
else if ((strcmp(argv[i], "--license") == 0 || strcmp(argv[i], "--licence") == 0))
{
if (i + 1 == argc)
return Error_Missing(argv[i]);
int Value = SetLicenseKey(argv[++i], false);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--no-check") == 0)
{
int Value = SetCheck(false);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--no-check-padding") == 0)
{
int Value = SetCheckPadding(false);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--no-coherency") == 0)
{
int Value = SetCoherency(false);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--no-conch") == 0)
{
int Value = SetConch(false);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--no-decode") == 0)
{
int Value = SetDecode(false);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--no-encode") == 0)
{
int Value = SetEncode(false);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--no-hash") == 0)
{
int Value = SetHash(false);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--no-info") == 0)
{
int Value = SetInfo(false);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--none") == 0)
{
int Value = SetAll(false);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--quick-check") == 0)
{
int Value = SetQuickCheck();
if (Value)
return Value;
}
else if (strcmp(argv[i], "--quick-check-padding") == 0)
{
int Value = SetQuickCheckPadding();
if (Value)
return Value;
}
else if (strcmp(argv[i], "--version") == 0)
{
int Value = Version();
if (Value)
return Value;
}
else if ((strcmp(argv[i], "--output-name") == 0 || strcmp(argv[i], "-o") == 0))
{
if (i + 1 == argc)
return Error_Missing(argv[i]);
int Value = SetOutputFileName(argv[++i]);
if (Value)
return Value;
}
else if (strcmp(argv[i], "--quiet") == 0)
{
Quiet = true;
License.Feature(feature::GeneralOptions);
}
else if ((strcmp(argv[i], "--rawcooked-file-name") == 0 || strcmp(argv[i], "-r") == 0))
{
if (i + 1 == argc)
return Error_Missing(argv[i]);
rawcooked_reversibility_FileName = argv[++i];
}
else if (strcmp(argv[i], "--show-license") == 0 || strcmp(argv[i], "--show-licence") == 0)
{
ShowLicenseKey = true;
}
else if (strcmp(argv[i], "--sublicense") == 0 || strcmp(argv[i], "--sublicence") == 0)
{
if (i + 1 == argc)
return Error_Missing(argv[i]);
License.Feature(feature::SubLicense);
if (auto Value = SetSubLicenseId(atoi(argv[++i])))
return Value;
}
else if (strcmp(argv[i], "--sublicense-dur") == 0 || strcmp(argv[i], "--sublicence-dur") == 0)
{
if (i + 1 == argc)
return Error_Missing(argv[i]);
License.Feature(feature::SubLicense);
if (auto Value = SetSubLicenseDur(atoi(argv[++i])))
return Value;
}
else if ((strcmp(argv[i], "--store-license") == 0 || strcmp(argv[i], "--store-licence") == 0))
{
if (i + 1 == argc)
return Error_Missing(argv[i]);
int Value = SetLicenseKey(argv[++i], true);
if (Value)
return Value;
}
else if (argv[i][0] == '-' && argv[i][1] != '\0')
{
int Value = SetOption(argv, i, argc);
if (Value)
return Value;
}
else
Inputs.push_back(argv[i]);
}
// License
if (License.LoadLicense(LicenseKey, StoreLicenseKey))
return true;
if (!License.IsSupported())
{
cerr << "\nOne or more requested features are not supported with the current license key.\n";
cerr << "****** Please contact info@mediaarea.net for a quote or a temporary key." << endl;
if (!IgnoreLicenseKey)
return 1;
cerr << " Ignoring the license for the moment.\n" << endl;
}
if (License.ShowLicense(ShowLicenseKey, SubLicenseId, SubLicenseDur))
return 1;
if (Inputs.empty() && (ShowLicenseKey || SubLicenseId))
return 0;
return 0;
}
//---------------------------------------------------------------------------
int global::SetDefaults()
{
// Container format
if (OutputOptions.find("f") == OutputOptions.end())
OutputOptions["f"] = "matroska"; // Container format is Matroska
// Video format
if (OutputOptions.find("c:v") == OutputOptions.end())
OutputOptions["c:v"] = "ffv1"; // Video format is FFV1
// Audio format
if (OutputOptions.find("c:a") == OutputOptions.end())
OutputOptions["c:a"] = "flac"; // Audio format is FLAC
// FFV1 specific
if (OutputOptions["c:v"] == "ffv1")
{
if (OutputOptions.find("coder") == OutputOptions.end())
OutputOptions["coder"] = "1"; // Range Coder
if (OutputOptions.find("context") == OutputOptions.end())
OutputOptions["context"] = "1"; // Small context
if (OutputOptions.find("g") == OutputOptions.end())
OutputOptions["g"] = "1"; // Intra
if (OutputOptions.find("level") == OutputOptions.end())
OutputOptions["level"] = "3"; // FFV1 v3
if (OutputOptions.find("slicecrc") == OutputOptions.end())
OutputOptions["slicecrc"] = "1"; // Slice CRC on
// Check incompatible options
if (OutputOptions["level"] == "0" || OutputOptions["level"] == "1")
{
map<string, string>::iterator slices = OutputOptions.find("slices");
if (slices == OutputOptions.end() || slices->second != "1")
{
cerr << "\" -level " << OutputOptions["level"] << "\" does not permit slices, is it intended ? if so, add \" -slices 1\" to the command." << endl;
return 1;
}
}
}
return 0;
}
//---------------------------------------------------------------------------
void global::ProgressIndicator_Start(size_t Total)
{
if (ProgressIndicator_Thread)
return;
ProgressIndicator_Current = 0;
ProgressIndicator_Total = Total;
ProgressIndicator_Thread = new thread(global_ProgressIndicator_Show, this);
}
//---------------------------------------------------------------------------
void global::ProgressIndicator_Stop()
{
if (!ProgressIndicator_Thread)
return;
ProgressIndicator_Current = ProgressIndicator_Total;
ProgressIndicator_IsEnd.notify_one();
ProgressIndicator_Thread->join();
delete ProgressIndicator_Thread;
ProgressIndicator_Thread = NULL;
}
//---------------------------------------------------------------------------
// Progress indicator show
void global::ProgressIndicator_Show()
{
// Configure progress indicator precision
size_t ProgressIndicator_Value = (size_t)-1;
size_t ProgressIndicator_Frequency = 100;
streamsize Precision = 0;
cerr.setf(ios::fixed, ios::floatfield);
// Configure benches
using namespace chrono;
steady_clock::time_point Clock_Init = steady_clock::now();
steady_clock::time_point Clock_Previous = Clock_Init;
uint64_t FileCount_Previous = 0;
// Show progress indicator at a specific frequency
const chrono::seconds Frequency = chrono::seconds(1);
size_t StallDetection = 0;
mutex Mutex;
unique_lock<mutex> Lock(Mutex);
do
{
if (ProgressIndicator_IsPaused)
continue;
size_t ProgressIndicator_New = (size_t)(((float)ProgressIndicator_Current) * ProgressIndicator_Frequency / ProgressIndicator_Total);
if (ProgressIndicator_New == ProgressIndicator_Value)
{
StallDetection++;
if (StallDetection >= 4)
{
while (ProgressIndicator_New == ProgressIndicator_Value && ProgressIndicator_Frequency < 10000)
{
ProgressIndicator_Frequency *= 10;
ProgressIndicator_Value *= 10;
Precision++;
ProgressIndicator_New = (size_t)(((float)ProgressIndicator_Current) * ProgressIndicator_Frequency / ProgressIndicator_Total);
}
}
}
else
StallDetection = 0;
if (ProgressIndicator_New != ProgressIndicator_Value)
{
float FileRate = 0;
if (ProgressIndicator_Value != (size_t)-1)
{
steady_clock::time_point Clock_Current = steady_clock::now();
steady_clock::duration Duration = Clock_Current - Clock_Previous;
FileRate = (float)(ProgressIndicator_Current - FileCount_Previous) * 1000 / duration_cast<milliseconds>(Duration).count();
Clock_Previous = Clock_Current;
FileCount_Previous = ProgressIndicator_Current;
}
cerr << '\r';
cerr << "Analyzing files (" << setprecision(Precision) << ((float)ProgressIndicator_New) * 100 / ProgressIndicator_Frequency << "%)";
if (FileRate)
{
cerr << ", ";
cerr << setprecision(0) << FileRate;
cerr << " files/s";
}
cerr << " "; // Clean up in case there is less content outputed than the previous time
ProgressIndicator_Value = ProgressIndicator_New;
}
} while (ProgressIndicator_IsEnd.wait_for(Lock, Frequency) == cv_status::timeout && ProgressIndicator_Current != ProgressIndicator_Total);
// Show summary
cerr << '\r';
cerr << " \r"; // Clean up in case there is less content outputed than the previous time
}
| 28,956 | 8,607 |
#include "object_filter.h"
#include <tf/transform_listener.h>
using namespace hirop_perception;
float ObjectFilter::minX = 0;
float ObjectFilter::maxX = 0;
float ObjectFilter::minZ = 0;
float ObjectFilter::maxZ = 0;
float ObjectFilter::minY = 0;
float ObjectFilter::maxY = 0;
ObjectFilter::ObjectFilter(){
_n = ros::NodeHandle();
}
ObjectFilter::~ObjectFilter(){
}
void ObjectFilter::declare_params(ecto::tendrils ¶ms){
params.declare<float>("hight", "object hight", 0.1);
params.declare<float>("width", "object width", 0.1);
params.declare<float>("length", "object length", 0.1);
params.declare<std::string>("frame_id", "The world frame id", "base_link");
}
void ObjectFilter::declare_io(const ecto::tendrils ¶ms, ecto::tendrils &in, ecto::tendrils &out){
in.declare<ecto::pcl::PointCloud>("input", "The colud to filter");
out.declare<ecto::pcl::PointCloud>("output", "The colud to out");
}
void ObjectFilter::configure(const ecto::tendrils ¶ms, const ecto::tendrils &inputs, const ecto::tendrils &outputs){
hight = params.get<float>("hight");
width = params.get<float>("width");
length = params.get<float>("length");
_worldFrameId = params.get<std::string>("frame_id");
_objectSub = _n.subscribe("/object_array", 1, &ObjectFilter::objectDetectionCallback, this);
}
int ObjectFilter::process(const ecto::tendrils &in, const ecto::tendrils &out){
_pointCloud = in.get<ecto::pcl::PointCloud>("input");
ecto::pcl::xyz_cloud_variant_t variant = _pointCloud.make_variant();
ecto::pcl::PointCloud outCloud;
FiltersDispatch dispatch(&outCloud);
boost::apply_visitor(dispatch, variant);
out.get<ecto::pcl::PointCloud>("output") = outCloud;
return ecto::OK;
}
void ObjectFilter::objectDetectionCallback(const hirop_msgs::ObjectArray::ConstPtr &msg){
geometry_msgs::PoseStamped _objectCamPose = msg->objects[0].pose;
/**
* @brief _worldPose save the world pose
*/
geometry_msgs::PoseStamped worldPose;
tf::TransformListener listener;
std::cout << "in objectDetectionCallback" << std::endl;
for(int i = 0; i < 5; i++){
try{
listener.waitForTransform(_worldFrameId, _objectCamPose.header.frame_id, ros::Time(0), ros::Duration(1.0));
listener.transformPose(_worldFrameId, _objectCamPose, worldPose);
break;
}catch (tf::TransformException &ex) {
/**
* @brief 获取变换关系失败,等待1秒后继续获取坐标变换
*/
ROS_ERROR("%s",ex.what());
ros::Duration(1.0).sleep();
continue;
}
}
minX = worldPose.pose.position.x - width/2;
minY = worldPose.pose.position.y - length/2;
minZ = worldPose.pose.position.z - hight/2;
maxX = worldPose.pose.position.x + width/2;
maxY = worldPose.pose.position.y + length/2;
maxZ = worldPose.pose.position.z + hight/2;
}
template<typename Point>
void ObjectFilter::FiltersDispatch::operator()(boost::shared_ptr<const pcl::PointCloud<Point> >& cloud) const{
typename pcl::PointCloud<Point>::Ptr outPointCloud(new pcl::PointCloud<Point>);
int size = cloud->points.size();
for(int i = 0; i < size; i++){
if(cloud->points[i].z > minZ && cloud->points[i].z < maxZ \
&& cloud->points[i].x > minX && cloud->points[i].x < maxX \
&& cloud->points[i].y > minY && cloud->points[i].y < maxY)
continue;
outPointCloud->points.push_back(cloud->points[i]);
}
outPointCloud->width = 1;
outPointCloud->height = outPointCloud->points.size();
*_outPointCloud = ecto::pcl::PointCloud(outPointCloud);
}
ObjectFilter::FiltersDispatch::FiltersDispatch(ecto::pcl::PointCloud *outCloud){
_outPointCloud = outCloud;
}
ECTO_CELL(hirop_perception, hirop_perception::ObjectFilter, "ObjectFilter", \
"A point cloud object filters")
| 3,904 | 1,389 |
/*!
\brief Function definitions for the DescriptorSet class.
\file PVRVk/DescriptorSetVk.cpp
\author PowerVR by Imagination, Developer Technology Team
\copyright Copyright (c) Imagination Technologies Limited.
*/
#include "PVRVk/DescriptorSetVk.h"
#include "PVRVk/ImageVk.h"
#include "PVRVk/SamplerVk.h"
#include "PVRVk/BufferVk.h"
#ifdef DEBUG
#include <algorithm>
#endif
namespace pvrvk {
namespace impl {
pvrvk::DescriptorSet DescriptorPool_::allocateDescriptorSet(const DescriptorSetLayout& layout)
{
DescriptorPool descriptorPool = shared_from_this();
return DescriptorSet_::constructShared(layout, descriptorPool);
}
//!\cond NO_DOXYGEN
DescriptorPool_::DescriptorPool_(make_shared_enabler, const DeviceWeakPtr& device, const DescriptorPoolCreateInfo& createInfo)
: PVRVkDeviceObjectBase(device), DeviceObjectDebugUtils()
{
_createInfo = createInfo;
VkDescriptorPoolCreateInfo descPoolInfo;
descPoolInfo.sType = static_cast<VkStructureType>(StructureType::e_DESCRIPTOR_POOL_CREATE_INFO);
descPoolInfo.pNext = NULL;
descPoolInfo.maxSets = _createInfo.getMaxDescriptorSets();
descPoolInfo.flags = static_cast<VkDescriptorPoolCreateFlags>(DescriptorPoolCreateFlags::e_FREE_DESCRIPTOR_SET_BIT);
VkDescriptorPoolSize poolSizes[descriptorTypeSize];
uint32_t poolIndex = 0;
for (uint32_t i = 0; i < descriptorTypeSize; ++i)
{
uint32_t count = _createInfo.getNumDescriptorTypes(DescriptorType(i));
if (count)
{
poolSizes[poolIndex].type = static_cast<VkDescriptorType>(i);
poolSizes[poolIndex].descriptorCount = count;
++poolIndex;
}
} // next type
descPoolInfo.poolSizeCount = poolIndex;
descPoolInfo.pPoolSizes = poolSizes;
vkThrowIfFailed(getDevice()->getVkBindings().vkCreateDescriptorPool(getDevice()->getVkHandle(), &descPoolInfo, nullptr, &_vkHandle), "Create Descriptor Pool failed");
}
DescriptorPool_::~DescriptorPool_()
{
if (getVkHandle() != VK_NULL_HANDLE)
{
if (!_device.expired())
{
getDevice()->getVkBindings().vkDestroyDescriptorPool(getDevice()->getVkHandle(), getVkHandle(), nullptr);
_vkHandle = VK_NULL_HANDLE;
}
else
{
reportDestroyedAfterDevice();
}
}
}
#ifdef DEBUG
static inline bool bindingIdPairComparison(const std::pair<uint32_t, uint32_t>& a, const std::pair<uint32_t, uint32_t>& b) { return a.first < b.first; }
#endif
DescriptorSetLayout_::~DescriptorSetLayout_()
{
if (getVkHandle() != VK_NULL_HANDLE)
{
if (!_device.expired())
{
getDevice()->getVkBindings().vkDestroyDescriptorSetLayout(getDevice()->getVkHandle(), getVkHandle(), nullptr);
_vkHandle = VK_NULL_HANDLE;
}
else
{
reportDestroyedAfterDevice();
}
}
clearCreateInfo();
}
DescriptorSetLayout_::DescriptorSetLayout_(make_shared_enabler, const DeviceWeakPtr& device, const DescriptorSetLayoutCreateInfo& createInfo)
: PVRVkDeviceObjectBase(device), DeviceObjectDebugUtils()
{
_createInfo = createInfo;
VkDescriptorSetLayoutCreateInfo vkLayoutCreateInfo = {};
ArrayOrVector<VkDescriptorSetLayoutBinding, 4> vkBindings(getCreateInfo().getNumBindings());
const DescriptorSetLayoutCreateInfo::DescriptorSetLayoutBinding* bindings = createInfo.getAllBindings();
for (uint32_t i = 0; i < createInfo.getNumBindings(); ++i)
{
vkBindings[i].descriptorType = static_cast<VkDescriptorType>(bindings[i].descriptorType);
vkBindings[i].binding = bindings[i].binding;
vkBindings[i].descriptorCount = bindings[i].descriptorCount;
vkBindings[i].stageFlags = static_cast<VkShaderStageFlags>(bindings[i].stageFlags);
vkBindings[i].pImmutableSamplers = nullptr;
if (bindings[i].immutableSampler) { vkBindings[i].pImmutableSamplers = &bindings[i].immutableSampler->getVkHandle(); }
}
vkLayoutCreateInfo.sType = static_cast<VkStructureType>(StructureType::e_DESCRIPTOR_SET_LAYOUT_CREATE_INFO);
vkLayoutCreateInfo.bindingCount = static_cast<uint32_t>(getCreateInfo().getNumBindings());
vkLayoutCreateInfo.pBindings = vkBindings.get();
vkThrowIfFailed(getDevice()->getVkBindings().vkCreateDescriptorSetLayout(getDevice()->getVkHandle(), &vkLayoutCreateInfo, nullptr, &_vkHandle), "Create Descriptor Set Layout failed");
}
//!\endcond
} // namespace impl
} // namespace pvrvk
| 4,156 | 1,505 |
// Copyright 2014 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "core/fxge/dib/fx_dib.h"
#include <tuple>
#include <utility>
#include "build/build_config.h"
#if defined(OS_WIN)
#include <windows.h>
#endif
#if defined(OS_WIN)
static_assert(sizeof(FX_COLORREF) == sizeof(COLORREF),
"FX_COLORREF vs. COLORREF mismatch");
#endif
FXDIB_Format MakeRGBFormat(int bpp) {
switch (bpp) {
case 1:
return FXDIB_Format::k1bppRgb;
case 8:
return FXDIB_Format::k8bppRgb;
case 24:
return FXDIB_Format::kRgb;
case 32:
return FXDIB_Format::kRgb32;
default:
return FXDIB_Format::kInvalid;
}
}
FXDIB_ResampleOptions::FXDIB_ResampleOptions() = default;
bool FXDIB_ResampleOptions::HasAnyOptions() const {
return bInterpolateBilinear || bHalftone || bNoSmoothing || bLossy;
}
std::tuple<int, int, int, int> ArgbDecode(FX_ARGB argb) {
return std::make_tuple(FXARGB_A(argb), FXARGB_R(argb), FXARGB_G(argb),
FXARGB_B(argb));
}
std::pair<int, FX_COLORREF> ArgbToAlphaAndColorRef(FX_ARGB argb) {
return {FXARGB_A(argb), ArgbToColorRef(argb)};
}
FX_COLORREF ArgbToColorRef(FX_ARGB argb) {
return FXSYS_BGR(FXARGB_B(argb), FXARGB_G(argb), FXARGB_R(argb));
}
FX_ARGB AlphaAndColorRefToArgb(int a, FX_COLORREF colorref) {
return ArgbEncode(a, FXSYS_GetRValue(colorref), FXSYS_GetGValue(colorref),
FXSYS_GetBValue(colorref));
}
| 1,617 | 676 |
/*
* Copyright (C) 2009 Michael Howell <mhowell123@gmail.com>.
* Copyright (C) 2009 Germain Garand <germain@ebooksfrance.org>
* Parts copyright (C) 2007, 2008 Apple Inc. All rights reserved.
* Copyright (C) 2018 afarcat <kabak@sina.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "media_controls.h"
#ifdef QT_WIDGETS_LIB
#include <QHBoxLayout>
#endif
//AFA #include <phonon/seekslider.h>
//AFA #include <phonon/mediaobject.h>
#include <rendering/render_media.h>
//AFA #include <phonon/videowidget.h>
//AFA #include <ktogglefullscreenaction.h>
//AFA #include <kglobalaccel.h>
//AFA #include <klocalizedstring.h>
namespace khtml
{
MediaControls::MediaControls(MediaPlayer *mediaPlayer, QWidget *parent) : QWidget(parent)
{
m_mediaPlayer = mediaPlayer;
#ifdef QT_WIDGETS_LIB
//AFA Phonon::MediaObject *mediaObject = m_mediaPlayer->mediaObject();
setLayout(new QHBoxLayout(this));
m_play = new QPushButton(QIcon::fromTheme("media-playback-start"), i18n("Play"), this);
//AFA connect(m_play, SIGNAL(clicked()), mediaObject, SLOT(play()));
layout()->addWidget(m_play);
m_pause = new QPushButton(QIcon::fromTheme("media-playback-pause"), i18n("Pause"), this);
//AFA connect(m_pause, SIGNAL(clicked()), mediaObject, SLOT(pause()));
layout()->addWidget(m_pause);
//AFA layout()->addWidget(new Phonon::SeekSlider(mediaObject, this));
//AFA QAction *fsac = new KToggleFullScreenAction(this);
//AFA fsac->setObjectName("KHTMLMediaPlayerFullScreenAction"); // needed for global shortcut activation.
m_fullscreen = new QToolButton(this);
//AFA m_fullscreen->setDefaultAction(fsac);
m_fullscreen->setCheckable(true);
//AFA connect(fsac, SIGNAL(toggled(bool)), this, SLOT(slotToggled(bool)));
layout()->addWidget(m_fullscreen);
#else
m_play = nullptr;
m_pause = nullptr;
m_fullscreen = nullptr;
#endif
//AFA slotStateChanged(mediaObject->state());
//AFA connect(mediaObject, SIGNAL(stateChanged(Phonon::State,Phonon::State)), SLOT(slotStateChanged(Phonon::State)));
}
void MediaControls::slotToggled(bool t)
{
if (t) {
//AFA m_mediaPlayer->videoWidget()->enterFullScreen();
//AFA KGlobalAccel::self()->setShortcut(m_fullscreen->defaultAction(), QList<QKeySequence>() << Qt::Key_Escape);
} else {
//AFA m_mediaPlayer->videoWidget()->exitFullScreen();
//AFA KGlobalAccel::self()->removeAllShortcuts(m_fullscreen->defaultAction());
}
}
//AFA
//void MediaControls::slotStateChanged(Phonon::State state)
//{
// if (state == Phonon::PlayingState) {
// m_play->hide();
// m_pause->show();
// } else {
// m_pause->hide();
// m_play->show();
// }
//}
}
| 3,969 | 1,441 |
//Daniel Garcia Molero
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
//Esta solucion tiene un coste en tiempo y espacio de O(x*y), donde x e y son la
//longitud de las palabras 1 y 2 respectivamente
int getLongestSequence(const string &p1, const string &p2) {
//p1 = rows, p2 = cols
vector<vector<int>> matrix = vector<vector<int>>(p1.length() + 1, vector<int>(p2.length() + 1, 0));
int last;
for (size_t i = 1; i <= p1.length(); i++) {
last = -1;
for (size_t j = 1; j <= p2.length(); j++) {
if (p1[i - 1] == p2[j - 1]) {
if ((i == 0 || matrix[i - 1][j] == 0)) {
matrix[i][j]++;
} else {
if (last != -1 && matrix[i - 1][j] != matrix[i - 1][last]) {
matrix[i][j] = matrix[i - 1][j] + 1;
} else {
matrix[i][j] = max(matrix[i - 1][j] + 1, matrix[i][j - 1]);
}
}
last = j;
} else {
matrix[i][j] = max(matrix[i - 1][j], matrix[i][j - 1]);
}
}
}
return matrix[p1.length()][p2.length()];
}
bool solve() {
string palabra1, palabra2;
cin >> palabra1 >> palabra2;
if (!cin) return false;
cout << getLongestSequence(palabra1, palabra2) << endl;
return true;
}
int main() {
while (solve()) {}
return 0;
} | 1,229 | 572 |
//
// ZQStringUtils.cpp
// libzq
//
// Created by staff on 16/11/18.
// Copyright © 2016年 zyqiosexercise. All rights reserved.
//
#include "ZQStringUtils.h"
#include <functional>
using namespace zq;
bool StringUtils::startsWith(const std::string &text, const std::string &start)
{
//if start is bigger than the string than it fails
if (start.length() > text.length()) {
return false;
}
else if (start.length() == text.length()) {
return start == text;
}
//loop through start and check if all char matches
for (int i = 0; i< start.length(); i++) {
if (start[i] != text[i]) {
return false;
}
}
return true;
}
bool StringUtils::endsWith(const std::string &text, const std::string &end)
{
//if end is bigger than the string than it fails
if (end.length() > text.length()) {
return false;
}
else if (end.length() == text.length()) {
return end == text;
}
std::size_t diff = text.length() - end.length();
for (std::size_t i = text.length()-1; i > diff-1; i--) {
if (end[i-diff] != text[i]) {
return false;
}
}
return true;
}
bool StringUtils::contains(const std::string &text, const std::string &str)
{
return text.find(str) != std::string::npos;
}
std::size_t StringUtils::count(const std::string &text, const std::string str, std::size_t start, std::size_t end)
{
if (start == 0) {
start = 0;
}
if (end == 0) {
end = text.length()-1;
}
std::size_t nb = 0;
while (start <= end) {
start = text.find(str, start);
if (start != std::string::npos) {
nb++;
start += str.length();
}
else {
break;
}
}
return nb;
}
std::vector<std::string> StringUtils::split(std::string &text, std::string &separator)
{
std::vector<std::string> elems;
std::size_t last_pos = 0;
std::size_t pos = text.find(separator);
while (pos != std::string::npos && last_pos != std::string::npos)
{
if (pos - last_pos > 0)
{
elems.push_back(text.substr(last_pos, pos - last_pos));
}
last_pos = text.find_first_not_of(separator, pos+separator.length()-1);
pos = text.find(separator, last_pos);
}
if (last_pos != std::string::npos)
{
elems.push_back(text.substr(last_pos));
}
return elems;
}
std::string StringUtils::join(std::vector<std::string> &vect, std::string &delimiter)
{
std::string retval;
std::vector<std::string>::const_iterator began = vect.begin();
std::vector<std::string>::const_iterator end = vect.end();
for (; began != end; ++began)
{
retval.append(*began);
retval.append(delimiter);
}
retval.erase(retval.length() - delimiter.length());
return retval;
}
bool StringUtils::iequals(const std::string a, const std::string b, bool ignore_case)
{
std::size_t sz = a.length();
if (b.length() != sz)
return false;
for (std::size_t i = 0; i < sz; ++i)
{
if (ignore_case)
{
if (::tolower(a[i]) != ::tolower(b[i]))
{
return false;
}
}
else
{
if (a[i] != b[i])
{
return false;
}
}
}
return true;
}
std::string StringUtils::replace(std::string &text, std::string &from, std::string &to)
{
std::string temp(text);
std::size_t start_pos = 0;
start_pos = temp.find(from, start_pos);
if (start_pos != std::string::npos) {
temp.replace(start_pos, from.length(), to);
}
return temp;
}
std::string StringUtils::replace_all(std::string &text, std::string &from, std::string &to)
{
std::string temp(text);
if(!from.empty()) {
size_t start_pos = 0;
while ((start_pos = temp.find(from, start_pos)) != std::string::npos) {
temp.replace(start_pos, from.length(), to);
// In case 'to' contains 'from', like replacing 'x' with 'yx'
start_pos += to.length();
}
}
return temp;
}
std::string StringUtils::tolower(const std::string &text)
{
std::string temp(text);
std::transform(text.begin(),text.end(), temp.begin(), ::tolower);
return temp;
}
std::string StringUtils::toupper(const std::string &text)
{
std::string temp(text);
std::transform(text.begin(),text.end(), temp.begin(), ::toupper);
return temp;
}
std::string StringUtils::capitalize(const std::string &text)
{
std::string temp(text);
std::string::iterator it = temp.begin();
*it = std::toupper(*it);
return temp;
}
std::string &StringUtils::ltrim(std::string &s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(),
std::not1(std::ptr_fun<int, int>(std::isspace))));
return s;
}
// trim from end
std::string &StringUtils::rtrim(std::string &s) {
s.erase(std::find_if(s.rbegin(), s.rend(),
std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
// trim from both ends
std::string &StringUtils::trim(std::string &s) {
return ltrim(rtrim(s));
}
std::string StringUtils::ltrim(const std::string &s) {
std::string temp(s);
StringUtils::ltrim(temp);
return temp;
}
// trim from end
std::string StringUtils::rtrim(const std::string &s) {
std::string temp(s);
StringUtils::rtrim(temp);
return temp;
}
// trim from both ends
std::string StringUtils::trim(const std::string &s) {
std::string temp(s);
StringUtils::trim(temp);
return temp;
}
| 5,746 | 1,979 |
#include <bits/stdc++.h >
using namespace std;
int cnt[200005][26];
char s[200005];
int main()
{
int T;
scanf("%d", &T);
while (T--) {
int n, k;
scanf("%d%d", &n, &k);
scanf("%s", s);
for (int i=0; i<n; i++) {
for (int j=0; j<26; j++) {
cnt [i][j] = 0;
}
}
for (int i=0; i<n; i++) {
int x = i%k;
cnt[x][s[i]-'a'] ++;
}
int ans = 0;
for (int i=0; i<k/2; i++) {
int v = k-i-1;
int all = 0;
int m = 0;
for (int j=0; j<26; j++) {
cnt[i][j] += cnt[v][j];
all += cnt[i][j];
m = max(cnt[i][j], m);
}
ans += all-m;
}
if (k&1) {
int all = 0;
int m = 0;
int xx= k/2;
for (int j=0; j<26; j++) {
all += cnt[xx][j];
m = max(cnt[xx][j], m);
}
ans += all-m;
}
cout << ans << endl;
}
return 0;
}
| 1,118 | 443 |
/***************************************************************************
*
* @package: franka_ros_controllers
* @metapackage: franka_ros_interface
* @author: Saif Sidhik <sxs1412@bham.ac.uk>
*
**************************************************************************/
/***************************************************************************
* Copyright (c) 2019-2020, Saif Sidhik.
*
* 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 <franka_ros_controllers/position_joint_position_controller.h>
#include <cmath>
#include <controller_interface/controller_base.h>
#include <hardware_interface/hardware_interface.h>
#include <hardware_interface/joint_command_interface.h>
#include <pluginlib/class_list_macros.h>
#include <ros/ros.h>
namespace franka_ros_controllers {
bool PositionJointPositionController::init(hardware_interface::RobotHW* robot_hardware,
ros::NodeHandle& node_handle) {
desired_joints_subscriber_ = node_handle.subscribe(
"/franka_ros_interface/motion_controller/arm/joint_commands", 20, &PositionJointPositionController::jointPosCmdCallback, this,
ros::TransportHints().reliable().tcpNoDelay());
position_joint_interface_ = robot_hardware->get<hardware_interface::PositionJointInterface>();
if (position_joint_interface_ == nullptr) {
ROS_ERROR(
"PositionJointPositionController: Error getting position joint interface from hardware!");
return false;
}
if (!node_handle.getParam("/robot_config/joint_names", joint_limits_.joint_names)) {
ROS_ERROR("PositionJointPositionController: Could not parse joint names");
}
if (joint_limits_.joint_names.size() != 7) {
ROS_ERROR_STREAM("PositionJointPositionController: Wrong number of joint names, got "
<< joint_limits_.joint_names.size() << " instead of 7 names!");
return false;
}
std::map<std::string, double> pos_limit_lower_map;
std::map<std::string, double> pos_limit_upper_map;
if (!node_handle.getParam("/robot_config/joint_config/joint_position_limit/lower", pos_limit_lower_map) ) {
ROS_ERROR(
"PositionJointPositionController: Joint limits parameters not provided, aborting "
"controller init!");
return false;
}
if (!node_handle.getParam("/robot_config/joint_config/joint_position_limit/upper", pos_limit_upper_map) ) {
ROS_ERROR(
"PositionJointPositionController: Joint limits parameters not provided, aborting "
"controller init!");
return false;
}
for (size_t i = 0; i < joint_limits_.joint_names.size(); ++i){
if (pos_limit_lower_map.find(joint_limits_.joint_names[i]) != pos_limit_lower_map.end())
{
joint_limits_.position_lower.push_back(pos_limit_lower_map[joint_limits_.joint_names[i]]);
}
else
{
ROS_ERROR("PositionJointPositionController: Unable to find lower position limit values for joint %s...",
joint_limits_.joint_names[i].c_str());
}
if (pos_limit_upper_map.find(joint_limits_.joint_names[i]) != pos_limit_upper_map.end())
{
joint_limits_.position_upper.push_back(pos_limit_upper_map[joint_limits_.joint_names[i]]);
}
else
{
ROS_ERROR("PositionJointPositionController: Unable to find upper position limit values for joint %s...",
joint_limits_.joint_names[i].c_str());
}
}
position_joint_handles_.resize(7);
for (size_t i = 0; i < 7; ++i) {
try {
position_joint_handles_[i] = position_joint_interface_->getHandle(joint_limits_.joint_names[i]);
} catch (const hardware_interface::HardwareInterfaceException& e) {
ROS_ERROR_STREAM(
"PositionJointPositionController: Exception getting joint handles: " << e.what());
return false;
}
}
double controller_state_publish_rate(30.0);
if (!node_handle.getParam("controller_state_publish_rate", controller_state_publish_rate)) {
ROS_INFO_STREAM("PositionJointPositionController: Did not find controller_state_publish_rate. Using default "
<< controller_state_publish_rate << " [Hz].");
}
trigger_publish_ = franka_hw::TriggerRate(controller_state_publish_rate);
dynamic_reconfigure_joint_controller_params_node_ =
ros::NodeHandle("/franka_ros_interface/position_joint_position_controller/arm/controller_parameters_config");
dynamic_server_joint_controller_params_ = std::make_unique<
dynamic_reconfigure::Server<franka_ros_controllers::joint_controller_paramsConfig>>(
dynamic_reconfigure_joint_controller_params_node_);
dynamic_server_joint_controller_params_->setCallback(
boost::bind(&PositionJointPositionController::jointControllerParamCallback, this, _1, _2));
publisher_controller_states_.init(node_handle, "/franka_ros_interface/motion_controller/arm/joint_controller_states", 1);
{
std::lock_guard<realtime_tools::RealtimePublisher<franka_core_msgs::JointControllerStates> > lock(
publisher_controller_states_);
publisher_controller_states_.msg_.controller_name = "position_joint_position_controller";
publisher_controller_states_.msg_.names.resize(joint_limits_.joint_names.size());
publisher_controller_states_.msg_.joint_controller_states.resize(joint_limits_.joint_names.size());
}
return true;
}
void PositionJointPositionController::starting(const ros::Time& /* time */) {
for (size_t i = 0; i < 7; ++i) {
initial_pos_[i] = position_joint_handles_[i].getPosition();
}
pos_d_ = initial_pos_;
prev_pos_ = initial_pos_;
pos_d_target_ = initial_pos_;
}
void PositionJointPositionController::update(const ros::Time& time,
const ros::Duration& period) {
for (size_t i = 0; i < 7; ++i) {
position_joint_handles_[i].setCommand(pos_d_[i]);
}
double filter_val = filter_joint_pos_ * filter_factor_;
for (size_t i = 0; i < 7; ++i) {
prev_pos_[i] = position_joint_handles_[i].getPosition();
pos_d_[i] = filter_val * pos_d_target_[i] + (1.0 - filter_val) * pos_d_[i];
}
if (trigger_publish_() && publisher_controller_states_.trylock()) {
for (size_t i = 0; i < 7; ++i){
publisher_controller_states_.msg_.joint_controller_states[i].set_point = pos_d_target_[i];
publisher_controller_states_.msg_.joint_controller_states[i].process_value = pos_d_[i];
publisher_controller_states_.msg_.joint_controller_states[i].time_step = period.toSec();
publisher_controller_states_.msg_.joint_controller_states[i].header.stamp = time;
}
publisher_controller_states_.unlockAndPublish();
}
// update parameters changed online either through dynamic reconfigure or through the interactive
// target by filtering
filter_joint_pos_ = param_change_filter_ * target_filter_joint_pos_ + (1.0 - param_change_filter_) * filter_joint_pos_;
}
bool PositionJointPositionController::checkPositionLimits(std::vector<double> positions)
{
// bool retval = true;
for (size_t i = 0; i < 7; ++i){
if (!((positions[i] <= joint_limits_.position_upper[i]) && (positions[i] >= joint_limits_.position_lower[i]))){
return true;
}
}
return false;
}
void PositionJointPositionController::jointPosCmdCallback(const franka_core_msgs::JointCommandConstPtr& msg) {
if (msg->mode == franka_core_msgs::JointCommand::POSITION_MODE){
if (msg->position.size() != 7) {
ROS_ERROR_STREAM(
"PositionJointPositionController: Published Commands are not of size 7");
pos_d_ = prev_pos_;
pos_d_target_ = prev_pos_;
}
else if (checkPositionLimits(msg->position)) {
ROS_ERROR_STREAM(
"PositionJointPositionController: Commanded positions are beyond allowed position limits.");
pos_d_ = prev_pos_;
pos_d_target_ = prev_pos_;
}
else
{
std::copy_n(msg->position.begin(), 7, pos_d_target_.begin());
}
}
// else ROS_ERROR_STREAM("PositionJointPositionController: Published Command msg are not of JointCommand::POSITION_MODE! Dropping message");
}
void PositionJointPositionController::jointControllerParamCallback(franka_ros_controllers::joint_controller_paramsConfig& config,
uint32_t level){
target_filter_joint_pos_ = config.position_joint_delta_filter;
}
} // namespace franka_ros_controllers
PLUGINLIB_EXPORT_CLASS(franka_ros_controllers::PositionJointPositionController,
controller_interface::ControllerBase)
| 9,123 | 2,818 |
#include <hal.h>
#include <algorithm>
namespace hal
{
using namespace device;
namespace internal
{
template<uint32_t x, uint32_t b, uint8_t nbits>
static constexpr uint32_t encode()
{
static_assert(x < (1 << nbits), "bit field overflow");
return ((x & (1 << 0)) ? (b << 0) : 0)
| ((x & (1 << 1)) ? (b << 1) : 0)
| ((x & (1 << 2)) ? (b << 2) : 0)
| ((x & (1 << 3)) ? (b << 3) : 0)
| ((x & (1 << 4)) ? (b << 4) : 0)
| ((x & (1 << 5)) ? (b << 5) : 0)
| ((x & (1 << 6)) ? (b << 6) : 0)
| ((x & (1 << 7)) ? (b << 7) : 0)
| ((x & (1 << 8)) ? (b << 8) : 0)
;
}
} // namespace internal
void sys_tick::delay_ms(uint32_t ms)
{
uint32_t now = ms_counter, then = now + ms;
while (ms_counter >= now && ms_counter < then)
; // busy wait
}
void sys_tick::delay_us(uint32_t us)
{
#if defined(STM32F051) || defined(STM32F072) || defined (STM32F767) || defined(STM32H743) || defined(STM32G070)
volatile uint32_t& c = STK.CVR;
const uint32_t c_max = STK.RVR;
#elif defined(STM32F103) || defined(STM32F411) || defined(STM32G431)
volatile uint32_t& c = STK.VAL;
const uint32_t c_max = STK.LOAD;
#else
static_assert(false, "no featured sys-tick micro-second delay");
#endif
const uint32_t fuzz = ticks_per_us - (ticks_per_us >> 2); // approx 3/4
const uint32_t n = us * ticks_per_us - fuzz;
const uint32_t now = c;
const uint32_t then = now >= n ? now - n : (c_max - n + now);
if (now > then)
while (c > then && c < now);
else
while (!(c > now && c < then));
}
void sys_tick::init(uint32_t n)
{
using namespace hal;
typedef stk_t _;
ms_counter = 0; // start new epoq
ticks_per_us = n / 1000; // for us in delay_us
#if defined(STM32F051) || defined(STM32F072) || defined (STM32F767) || defined(STM32H743) || defined(STM32G070)
STK.CSR = _::CSR_RESET_VALUE; // reset controls
STK.RVR = n - 1; // reload value
STK.CVR = _::CVR_RESET_VALUE; // current counter value
STK.CSR |= _::CSR_CLKSOURCE; // systick clock source
STK.CSR |= _::CSR_ENABLE | _::CSR_TICKINT; // enable counter & interrupts
#elif defined(STM32F103) || defined(STM32F411) || defined(STM32G431)
STK.CTRL = _::CTRL_RESET_VALUE; // reset controls
STK.LOAD = n - 1; // reload value
STK.VAL = _::VAL_RESET_VALUE; // current counter value
STK.CTRL |= _::CTRL_CLKSOURCE; // systick clock source
STK.CTRL |= _::CTRL_ENABLE | _::CTRL_TICKINT; // enable counter & interrupts
#else
static_assert(false, "no featured sys-tick initialzation");
#endif
}
volatile uint32_t sys_tick::ms_counter = 0;
uint32_t sys_tick::ticks_per_us = 0;
inline void sys_tick_init(uint32_t n) { sys_tick::init(n); }
inline void sys_tick_update() { ++sys_tick::ms_counter; } // N.B. wraps in 49 days!
uint32_t sys_clock::m_freq;
void sys_clock::init()
{
using namespace hal;
typedef rcc_t _;
// reset clock control registers (common for all families)
RCC.CR = _::CR_RESET_VALUE;
RCC.CFGR = _::CFGR_RESET_VALUE;
#if defined(STM32F051) || defined(STM32F072)
m_freq = 48000000;
// reset clock control registers
RCC.CFGR2 = _::CFGR2_RESET_VALUE;
RCC.CFGR3 = _::CFGR3_RESET_VALUE;
RCC.CR2 = _::CR2_RESET_VALUE;
RCC.CIR = _::CIR_RESET_VALUE;
// set system clock to HSI-PLL 48MHz
FLASH.ACR |= flash_t::ACR_PRFTBE | flash_t::ACR_LATENCY<0x1>;
RCC.CFGR |= _::CFGR_PLLMUL<0xa>; // PLL multiplier 12
RCC.CR |= _::CR_PLLON; // enable PLL
while (!(RCC.CR & _::CR_PLLRDY)); // wait for PLL to be ready
RCC.CFGR |= _::CFGR_SW<0x2>; // select PLL as system clock
// wait for PLL as system clock
while ((RCC.CFGR & _::CFGR_SWS<0x3>) != _::CFGR_SWS<0x2>);
#elif defined(STM32F103)
m_freq = 72000000;
// set system clock to HSE-PLL 72MHz
FLASH.ACR |= flash_t::ACR_PRFTBE | flash_t::template ACR_LATENCY<0x2>;
RCC.CR |= _::CR_HSEON; // enable external clock
while (!(RCC.CR & _::CR_HSERDY)); // wait for HSE ready
RCC.CFGR |= _::CFGR_PLLSRC // clock from PREDIV1
| _::CFGR_PLLMUL<0x7> // pll multiplier = 9
| _::CFGR_PPRE1<0x4> // APB low-speed prescale = 2
;
RCC.CR |= _::CR_PLLON; // enable external clock
while (!(RCC.CR & _::CR_PLLRDY)); // wait for pll ready
RCC.CFGR |= _::CFGR_SW<0x2>; // use pll as clock source
// wait for clock switch completion
while ((RCC.CFGR & _::CFGR_SWS<0x3>) != _::CFGR_SWS<0x2>);
#elif defined(STM32F411)
m_freq = 100000000;
// reset clock control registers
RCC.CIR = _::CIR_RESET_VALUE;
// set system clock to HSI-PLL 100MHz
constexpr uint8_t wait_states = 0x3; // 3 wait-states for 100MHz at 2.7-3.3V
FLASH.ACR |= flash_t::ACR_PRFTEN | flash_t::ACR_LATENCY<wait_states>;
while ((FLASH.ACR & flash_t::ACR_LATENCY<0x7>) != flash_t::ACR_LATENCY<wait_states>); // wait to take effect
enum pllP_t { pllP_2 = 0x0, pllP_4 = 0x1, pllP_6 = 0x2, pllP_8 = 0x3 };
// fVCO = hs[ei] * pllN / pllM // must be 100MHz - 400MHz
// fSYS = fVCO / pllP // <= 100MHz
// fUSB = fVCO / pllQ // <= 48MHz
// pllN = 200, pllM = 8, pllP = 4, pllQ = 9, fSYS = 1.0e8, fUSB = 4.4445e7
constexpr uint16_t pllN = 200; // 9 bits, valid range [50..432]
constexpr uint8_t pllM = 8; // 6 bits, valid range [2..63]
constexpr pllP_t pllP = pllP_4; // 2 bits, enum range [2, 4, 6, 8]
constexpr uint8_t pllQ = 9; // 4 bits, valid range [2..15]
constexpr uint8_t pllSRC = 0; // 1 bit, 0 = HSI, 1 = HSE
using internal::encode;
RCC.PLLCFGR = encode<pllSRC, _::PLLCFGR_PLLSRC, 1>()
| encode<pllN, _::PLLCFGR_PLLN0, 9>()
| encode<pllM, _::PLLCFGR_PLLM0, 6>()
| encode<pllP, _::PLLCFGR_PLLP0, 2>()
| encode<pllQ, _::PLLCFGR_PLLQ0, 4>()
;
RCC.CR |= _::CR_PLLON; // enable PLL
while (!(RCC.CR & _::CR_PLLRDY)); // wait for PLL to be ready
RCC.CFGR |= encode<0x2, _::CFGR_SW0, 2>(); // select PLL as system clock
// wait for PLL as system clock
while ((RCC.CFGR & encode<0x3, _::CFGR_SWS0, 2>()) != encode<0x2, _::CFGR_SWS0, 2>());
#elif defined(STM32F767)
m_freq = 16000000;
#elif defined(STM32H743)
m_freq = 8000000;
#elif defined(STM32G070)
m_freq = 64000000;
// set system clock to HSI-PLL 64MHz and p-clock = 64MHz
constexpr uint8_t wait_states = 0x2; // 2 wait-states for 64Hz at Vcore range 1
FLASH.ACR |= flash_t::ACR_PRFTEN | flash_t::ACR_LATENCY<wait_states>;
while ((FLASH.ACR & flash_t::ACR_LATENCY<0x7>) != flash_t::ACR_LATENCY<wait_states>); // wait to take effect
// fR (fSYS) = fVCO / pllR // <= 64MHz
// fP = fVCO / pllP // <= 122MHz
// pllN = 8.0, pllM = 1.0, pllP = 2.0, pllR = 2.0, fSYS = 6.4e7, fPllP = 6.4e7, fVCO = 1.28e8
constexpr uint16_t pllN = 8; // 7 bits, valid range [8..86]
constexpr uint8_t pllM = 1 - 1; // 3 bits, valid range [1..8]-1
constexpr uint8_t pllP = 2 - 1; // 5 bits, valid range [2..32]-1
constexpr uint8_t pllR = 2 - 1; // 3 bits, valid range [2..8]-1
constexpr uint8_t pllSRC = 2; // 2 bits, 2 = HSI16, 3 = HSE
RCC.PLLSYSCFGR = _::PLLSYSCFGR_PLLSRC<pllSRC>
| _::PLLSYSCFGR_PLLN<pllN>
| _::PLLSYSCFGR_PLLM<pllM>
| _::PLLSYSCFGR_PLLP<pllP>
| _::PLLSYSCFGR_PLLR<pllR>
| _::PLLSYSCFGR_PLLREN
| _::PLLSYSCFGR_PLLPEN
;
RCC.CR |= _::CR_PLLON; // enable PLL
while (!(RCC.CR & _::CR_PLLRDY)); // wait for PLL to be ready
RCC.CFGR |= _::CFGR_SW<0x2>; // select PLL as system clock
// wait for PLL as system clock
while ((RCC.CFGR & _::CFGR_SWS<0x3>) != _::CFGR_SWS<0x2>);
#elif defined(STM32G431)
m_freq = 170000000;
// set system clock to HSI-PLL 170MHz (R) and same for P and Q clocks
constexpr uint8_t wait_states = 0x8; // 8 wait-states for 170MHz at Vcore range 1
FLASH.ACR = flash_t::ACR_RESET_VALUE;
FLASH.ACR |= flash_t::ACR_PRFTEN | flash_t::ACR_LATENCY<wait_states>;
while ((FLASH.ACR & flash_t::ACR_LATENCY<0xf>) != flash_t::ACR_LATENCY<wait_states>); // wait to take effect
#if defined(HSE)
RCC.CR |= _::CR_HSEON; // enable external clock
while (!(RCC.CR & _::CR_HSERDY)); // wait for HSE ready
#if HSE == 24000000
constexpr uint8_t pllM = 6 - 1; // 3 bits, valid range [1..15]-1
#elif HSE == 8000000
constexpr uint8_t pllM = 2 - 1; // 3 bits, valid range [1..15]-1
#else
static_assert(false, "unsupported HSE frequency");
#endif
constexpr uint8_t pllSRC = 3; // 2 bits, 2 = HSI16, 3 = HSE
#else
// pllN = 85.0, pllM = 4.0, pllP = 7.0, pllPDIV = 2.0, pllQ = 2.0, pllR = 2.0, fSYS = 1.7e8, fPllP = 1.7e8, fPllQ = 1.7e8, fVCO = 3.4e8
constexpr uint8_t pllM = 4 - 1; // 3 bits, valid range [1..15]-1
constexpr uint8_t pllSRC = 2; // 2 bits, 2 = HSI16, 3 = HSE
#endif
constexpr uint16_t pllN = 85; // 7 bits, valid range [8..127]
constexpr uint8_t pllPDIV = 2; // 5 bits, valid range [2..31]
constexpr uint8_t pllR = 0; // 2 bits, 0 = 2, 1 = 4, 2 = 6, 3 = 8
constexpr uint8_t pllQ = 0; // 2 bits, 0 = 2, 1 = 4, 2 = 6, 3 = 8
RCC.PLLSYSCFGR = _::PLLSYSCFGR_PLLSRC<pllSRC>
| _::PLLSYSCFGR_PLLSYSN<pllN>
| _::PLLSYSCFGR_PLLSYSM<pllM>
| _::PLLSYSCFGR_PLLSYSPDIV<pllPDIV>
| _::PLLSYSCFGR_PLLSYSQ<pllQ>
| _::PLLSYSCFGR_PLLSYSR<pllR>
| _::PLLSYSCFGR_PLLPEN
| _::PLLSYSCFGR_PLLSYSQEN
| _::PLLSYSCFGR_PLLSYSREN
;
RCC.CR |= _::CR_PLLSYSON; // enable PLL
while (!(RCC.CR & _::CR_PLLSYSRDY)); // wait for PLL to be ready
RCC.CFGR |= _::CFGR_SW<0x3>; // select PLL as system clock
// wait for PLL as system clock
while ((RCC.CFGR & _::CFGR_SWS<0x3>) != _::CFGR_SWS<0x3>);
// enable FPU
FPU_CPACR.CPACR |= fpu_cpacr_t::CPACR_CP<0xf>; // enable co-processors
__asm volatile ("dsb"); // data pipe-line reset
__asm volatile ("isb"); // instruction pipe-line reset
#else
static_assert(false, "no featured clock initialzation");
#endif
// initialize sys-tick for milli-second counts
hal::sys_tick_init(m_freq / 1000);
}
} // namespace hal
template<> void handler<interrupt::SYSTICK>()
{
hal::sys_tick_update();
}
extern void system_init(void)
{
hal::sys_clock::init();
}
| 11,744 | 5,051 |
#include "platform/constants.hpp"
#include "platform/measurement_utils.hpp"
#include "platform/platform.hpp"
#include "platform/settings.hpp"
#include "coding/file_reader.hpp"
#include "base/logging.hpp"
#include "platform/target_os.hpp"
#include <algorithm>
#include <future>
#include <memory>
#include <regex>
#include <string>
#include <boost/filesystem.hpp>
#include <boost/range/iterator_range.hpp>
namespace fs = boost::filesystem;
using namespace std;
unique_ptr<ModelReader> Platform::GetReader(string const & file, string const & searchScope) const
{
return make_unique<FileReader>(ReadPathForFile(file, searchScope), READER_CHUNK_LOG_SIZE,
READER_CHUNK_LOG_COUNT);
}
bool Platform::GetFileSizeByName(string const & fileName, uint64_t & size) const
{
try
{
return GetFileSizeByFullPath(ReadPathForFile(fileName), size);
}
catch (RootException const &)
{
return false;
}
}
void Platform::GetFilesByRegExp(string const & directory, string const & regexp,
FilesList & outFiles)
{
boost::system::error_code ec{};
regex exp(regexp);
for (auto const & entry : boost::make_iterator_range(fs::directory_iterator(directory, ec), {}))
{
string const name = entry.path().filename().string();
if (regex_search(name.begin(), name.end(), exp))
outFiles.push_back(name);
}
}
// static
Platform::EError Platform::MkDir(string const & dirName)
{
boost::system::error_code ec{};
fs::path dirPath{dirName};
if (fs::exists(dirPath, ec))
return Platform::ERR_FILE_ALREADY_EXISTS;
if (!fs::create_directory(dirPath, ec))
{
LOG(LWARNING, ("Can't create directory: ", dirName));
return Platform::ERR_UNKNOWN;
}
return Platform::ERR_OK;
}
extern Platform & GetPlatform()
{
static Platform platform;
return platform;
}
| 1,857 | 608 |
/**
* Copyright (c) 2019 - Pieter De Clercq. All rights reserved.
*
* https://github.com/thepieterdc/mailbridge/
*/
#include <sys/socket.h>
#include <unistd.h>
#include <iostream>
#include "server.h"
#include "../configurations/slack_configuration.h"
#include "../handlers/slack_handler.h"
#include "../handlers/stdout_handler.h"
bool Server::authenticate(Authentication *authentication) {
for (auto &handler : this->configuration()->get_handlers()) {
auto auth = handler.first;
if (*auth == *authentication) {
return true;
}
}
return false;
}
void Server::handle(Authentication *authentication, SmtpMessage *message) {
for (auto &handler : this->configuration()->get_handlers()) {
auto auth = handler.first;
if (*auth == *authentication) {
handler.second->handle(message);
}
}
} | 878 | 268 |
#include <bits/stdc++.h>
#define N 100020
#define ll long long
using namespace std;
inline ll read(){
ll x=0,f=1;char ch=getchar();
while(ch>'9'||ch<'0')ch=='-'&&(f=0)||(ch=getchar());
while(ch<='9'&&ch>='0')x=(x<<3)+(x<<1)+ch-'0',ch=getchar();
return f?x:-x;
}
typedef pair<ll, ll> pairs;
inline ll calc(ll x) {
switch (x % 4) {
case 0: return 0;
case 1: return x + x - 1;
case 2: return 2;
case 3: return x + x + 1;
}
return 19260817;
}
inline ll calc(ll l, ll r) {
return calc(l) ^ calc(r);
}
multiset<pairs> st;
deque<multiset<pairs>::iterator> rub;
ll now;
void update_left(multiset<pairs>::iterator x) {
if (x != st.begin()) {
ll u = (ll)x->first * x->first;
--x;
now ^= u - ((ll)x->second * x->second);
}
}
void update_right(multiset<pairs>::iterator x) {
if (x != --st.end()) {
ll u = (ll)x->second * x->second;
++x;
now ^= ((ll)x->first * x->first) - u;
}
}
void insert(ll l, ll r) {
pairs x = make_pair(l, r);
auto t = st.lower_bound(x), u = t;
while (true) {
if (u == st.begin())
break;
--u;
if (x.first - 1 <= u->second)
rub.push_front(u);
else
break;
}
u = t;
while (true) {
if (u == st.end())
break;
if (x.second + 1 >= u->first)
rub.push_back(u);
else
break;
++u;
}
for (auto u : rub) {
if (u->first < x.first)
x.first = u->first;
if (u->second > x.second)
x.second = u->second;
update_left(u);
now ^= calc(u -> first, u -> second);
}
if (rub.size())
update_right(*--rub.end());
else {
auto t = st.lower_bound(x);
if (t != st.end())
update_left(t);
}
for (auto u : rub)
st.erase(u);
rub.clear();
st.insert(x);
update_left(st.find(x));
update_right(st.find(x));
now ^= calc(x.second) ^ calc(x.first);
}
int main(int argc, char const *argv[]) {
// freopen("../tmp/.in", "r", stdin);
ll n = read();
while (n --) {
ll op = read();
if (op == 1) {
ll l = read(), r = read();
insert(l, r);
} else {
printf("%d\n", now);
}
}
return 0;
} | 2,113 | 934 |
#include <CDirFTW.h>
#include <ftw.h>
#include <iostream>
typedef int (*FtwProc)(const char *file, const struct stat *sb, int flag, struct FTW *ftw);
CDirFTW *CDirFTW::walk_ = NULL;
CDirFTW::
CDirFTW(const std::string &dirname) :
dirname_(dirname), follow_links_(false), change_dir_(false), debug_(false)
{
}
bool
CDirFTW::
walk()
{
walk_ = this;
#if defined(sun) || defined(__linux__)
int flags = 0;
if (! getFollowLinks()) flags |= FTW_PHYS;
if (! getChangeDir ()) flags |= FTW_CHDIR;
nftw(dirname_.c_str(), (FtwProc) CDirFTW::processCB, 10, flags);
#else
ftw (dirname_.c_str(), (FtwProc) CDirFTW::processCB, 10);
#endif
return true;
}
int
CDirFTW::
#if defined(sun) || defined(__linux__)
processCB(const char *filename, struct stat *stat, int type)
#else
processCB(const char *filename, struct stat *stat, int type, struct FTW *)
#endif
{
if (walk_->getDebug()) {
switch (type) {
case FTW_D : std::cerr << "Dir : " << filename << std::endl; break;
case FTW_DNR: std::cerr << "DirE: " << filename << std::endl; break;
case FTW_DP : std::cerr << "DirP: " << filename << std::endl; break;
case FTW_F : std::cerr << "File: " << filename << std::endl; break;
case FTW_NS : std::cerr << "LnkE: " << filename << std::endl; break;
case FTW_SL : std::cerr << "Lnk : " << filename << std::endl; break;
case FTW_SLN: std::cerr << "LnkN: " << filename << std::endl; break;
default : std::cerr << "?? : " << filename << std::endl; break;
}
}
if (type == FTW_NS)
return 0;
CFileType file_type = CFILE_TYPE_INODE_REG;
if (type == FTW_D || type == FTW_DNR || type == FTW_DP)
file_type = CFILE_TYPE_INODE_DIR;
walk_->callProcess(filename, stat, file_type);
return 0;
}
void
CDirFTW::
callProcess(const char *filename, struct stat *stat, CFileType type)
{
filename_ = filename;
stat_ = stat;
type_ = type;
process();
}
| 1,939 | 762 |
#pragma once
#include <string>
namespace afk {
namespace io {
auto get_date_time() -> std::string;
}
}
| 113 | 42 |
#include <type_traits>
#include <iostream>
//#define NDEBUG
#include <cassert> // assert
template<class T>
void countdown(T start) {
// Compile time
static_assert(std::is_integral<T>::value
&& std::is_signed<T>::value,
"Requires signed integral type");
assert(start >= 0); // Runtime error
while (start >= 0) {
std::cout << start-- << std::endl;
}
}
| 413 | 134 |
//
// Created by 张俊伟 on 2020/7/1.
//
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode *reverseList(struct ListNode *head) {
struct ListNode *pre = nullptr;
struct ListNode *cur = head;
while (cur!= nullptr){
struct ListNode *temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
} | 381 | 138 |
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#ifndef _SVX_FMVIEW_HXX
#define _SVX_FMVIEW_HXX
#include <svx/view3d.hxx>
#include <comphelper/uno3.hxx>
#include "svx/svxdllapi.h"
FORWARD_DECLARE_INTERFACE(util,XNumberFormats)
FORWARD_DECLARE_INTERFACE(beans,XPropertySet)
class OutputDevice;
class FmFormModel;
class FmPageViewWinRec;
class FmFormObj;
class FmFormPage;
class FmFormShell;
class FmXFormView;
namespace svx {
class ODataAccessDescriptor;
struct OXFormsDescriptor;
}
class SdrUnoObj;
namespace com { namespace sun { namespace star { namespace form {
class XForm;
namespace runtime {
class XFormController;
}
} } } }
class SVX_DLLPUBLIC FmFormView : public E3dView
{
FmXFormView* pImpl;
FmFormShell* pFormShell;
void Init();
public:
TYPEINFO();
FmFormView(FmFormModel* pModel, OutputDevice* pOut = 0L);
virtual ~FmFormView();
/** create a control pair (label/bound control) for the database field description given.
@param rFieldDesc
description of the field. see clipboard format SBA-FIELDFORMAT
@deprecated
This method is deprecated. Use the version with a ODataAccessDescriptor instead.
*/
SdrObject* CreateFieldControl(const UniString& rFieldDesc) const;
/** create a control pair (label/bound control) for the database field description given.
*/
SdrObject* CreateFieldControl( const ::svx::ODataAccessDescriptor& _rColumnDescriptor );
/** create a control pair (label/bound control) for the xforms description given.
*/
SdrObject* CreateXFormsControl( const ::svx::OXFormsDescriptor &_rDesc );
virtual void MarkListHasChanged();
virtual void AddWindowToPaintView(OutputDevice* pNewWin);
virtual void DeleteWindowFromPaintView(OutputDevice* pOldWin);
static void createControlLabelPair(
OutputDevice* _pOutDev,
sal_Int32 _nXOffsetMM,
sal_Int32 _nYOffsetMM,
const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxField,
const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormats >& _rxNumberFormats,
sal_uInt16 _nControlObjectID,
const ::rtl::OUString& _rFieldPostfix,
sal_uInt32 _nInventor,
sal_uInt16 _nLabelObjectID,
SdrPage* _pLabelPage,
SdrPage* _pControlPage,
SdrModel* _pModel,
SdrUnoObj*& _rpLabel,
SdrUnoObj*& _rpControl
);
virtual SdrPageView* ShowSdrPage(SdrPage* pPage);
virtual void HideSdrPage();
// for copying complete form structures, not only control models
virtual SdrModel* GetMarkedObjModel() const;
using E3dView::Paste;
virtual sal_Bool Paste(const SdrModel& rMod, const Point& rPos, SdrObjList* pLst=NULL, sal_uInt32 nOptions=0);
virtual sal_Bool MouseButtonDown( const MouseEvent& _rMEvt, Window* _pWin );
/** grab the focus to the first form control on the view
@param _bForceSync
<TRUE/> if the handling should be done synchronously.
*/
SVX_DLLPRIVATE void GrabFirstControlFocus( sal_Bool _bForceSync = sal_False );
/** returns the form controller for a given form and a given device
*/
SVX_DLLPRIVATE ::com::sun::star::uno::Reference< ::com::sun::star::form::runtime::XFormController >
GetFormController( const ::com::sun::star::uno::Reference< ::com::sun::star::form::XForm >& _rxForm, const OutputDevice& _rDevice ) const;
// SdrView
sal_Bool KeyInput(const KeyEvent& rKEvt, Window* pWin);
/// shortcut to "GetSdrPageView() ? PTR_CAST( FmFormPage, GetSdrPageView() ) : NULL"
FmFormPage* GetCurPage();
SVX_DLLPRIVATE void ActivateControls(SdrPageView*);
SVX_DLLPRIVATE void DeactivateControls(SdrPageView*);
SVX_DLLPRIVATE void ChangeDesignMode(sal_Bool bDesign);
SVX_DLLPRIVATE FmXFormView* GetImpl() const { return pImpl; }
SVX_DLLPRIVATE FmFormShell* GetFormShell() const { return pFormShell; }
struct FormShellAccess { friend class FmFormShell; private: FormShellAccess() { } };
void SetFormShell( FmFormShell* pShell, FormShellAccess ) { pFormShell = pShell; }
struct ImplAccess { friend class FmXFormView; private: ImplAccess() { } };
void SetMoveOutside( bool _bMoveOutside, ImplAccess ) { E3dView::SetMoveOutside( _bMoveOutside ); }
virtual void InsertControlContainer(const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer >& xCC);
virtual void RemoveControlContainer(const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer >& xCC);
virtual SdrPaintWindow* BeginCompleteRedraw(OutputDevice* pOut);
virtual void EndCompleteRedraw(SdrPaintWindow& rPaintWindow, bool bPaintFormLayer);
SVX_DLLPRIVATE const OutputDevice* GetActualOutDev() const {return pActualOutDev;}
SVX_DLLPRIVATE sal_Bool checkUnMarkAll(const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _xSource);
private:
SVX_DLLPRIVATE void AdjustMarks(const SdrMarkList& rMarkList);
SVX_DLLPRIVATE FmFormObj* getMarkedGrid() const;
protected:
using E3dView::SetMoveOutside;
};
#endif // _FML_FMVIEW_HXX
| 5,862 | 1,981 |
/**
* @author Samuel Larkin
* @file filter_models.cc
* @brief Program that filters TMs and LMs.
*
* LMs & TMs filtering
*
* Technologies langagieres interactives / Interactive Language Technologies
* Inst. de technologie de l'information / Institute for Information Technology
* Conseil national de recherches Canada / National Research Council Canada
* Copyright 2004, Sa Majeste la Reine du Chef du Canada /
* Copyright 2004, Her Majesty in Right of Canada
*/
#include "filter_models.h"
#include "exception_dump.h"
#include "printCopyright.h"
#include "config_io.h"
#include "phrasetable_filter_grep.h"
#include "phrasetable_filter_joint.h"
#include "phrasetable_filter_lm.h"
#include "inputparser.h"
#include "basicmodel.h"
#include "lm.h"
#include "lmtext.h" // LMText::isA
#include <sstream>
using namespace std;
using namespace Portage;
using namespace Portage::filter_models;
/******************************************************************************
Here's a graph of all possible LM/TM filtering
,-LM-+-filter_LM
|
-+ ,-filter_grep
| |
| +-online--+-tm_hard_limit-+-complete
| | | `-src-grep
`-TM-+ `-tm_soft_limit-+-complete
| `-src-grep
|
`-general-+-tm_hard_limit-+-complete
| `-src-grep
`-tm_soft_limit-+-complete
`-src-grep
online => not in memory, processing on the fly TMs must be sorted
general => loaded in memory before processing
tm_hard_limit => tm_hard_limit_weights -> exactly L or less entries are kept
tm_soft_limit => LimitTM in Badr et al, 2007
complete => all TM entries are processed no filtering based on source sentences is done
src-grep => source are required and are used to prefilter the phrase table entries
******************************************************************************/
/// Logger for filter_models
Logging::logger filter_models_Logger(Logging::getLogger("verbose.canoe.filter_models"));
/**
*
* @return Returns true if a filtered CPT was created.
*/
bool processOnline(const CanoeConfig& c, const ARG& arg,
VocabFilter& tgt_vocab, const VectorPSrcSent& src_sents)
{
LOG_VERBOSE1(filter_models_Logger, "Processing online/streaming");
// In online mode there can only be one multiTM and we must be
// in either hard or soft mode
if (!(arg.limit() && c.multiProbTMFiles.size() == 1))
error(ETFatal, "When using the tm-online mode there can only be one multi-prob TM!");
const string filename = c.multiProbTMFiles.front();
// What's the final cpt filename.
const string filtered_cpt_filename = arg.prepareFilename(arg.limit_file);
// If the filtered TM exists there is nothing to do.
if (arg.isReadOnly(filtered_cpt_filename)) {
error(ETWarn, "Translation Model %s has already been filtered. Skipping...", filename.c_str());
return false;
}
else if (arg.isReadOnlyOnDisk(filtered_cpt_filename)) {
error(ETWarn,
"Cannot filter %s since %s is read-only.",
filename.c_str(),
filtered_cpt_filename.c_str());
return false;
}
error_unless_exists(filename, true, "translation model");
// Instanciate the proper pruning style.
const pruningStyle* pruning_style = pruningStyle::create(arg.pruning_strategy_switch, c.phraseTableSizeLimit);
assert(pruning_style);
PhraseTableFilterJoint phraseTable(
arg.limitPhrases(),
tgt_vocab,
pruning_style,
arg.phraseTablePruneType,
c.forwardWeights,
c.transWeights,
arg.tm_hard_limit,
c.appendJointCounts);
// Parses the input source sentences
phraseTable.addSourceSentences(src_sents);
// Do the actual online filtering.
phraseTable.filter(filename, filtered_cpt_filename);
delete pruning_style; pruning_style = NULL;
return true;
}
/**
* Program filter_models's entry point.
* @return Returns 0 if successful.
*/
int MAIN(argc, argv)
{
typedef vector<string> FileList;
typedef FileList::iterator FL_iterator;
printCopyright(2006, "filter_models");
ARG arg(argc, argv);
CanoeConfig c;
c.read(arg.config.c_str());
c.check(); // Check that the canoe.ini file is coherent
if (arg.phraseTablePruneType.empty())
arg.phraseTablePruneType = c.phraseTablePruneType;
const Uint ttable_limit_from_config = c.phraseTableSizeLimit; // save for write-back
if (arg.ttable_limit >= 0) // use ttable_limit for pruning, instead of config file value
c.phraseTableSizeLimit = Uint(arg.ttable_limit);
if (arg.limit() && arg.phraseTablePruneType == "full") {
error(ETWarn, "filter_models -tm-soft-limit or -tm-hard-limit implements \"-ttable-prune-type full\" approximately.\n");
if (arg.ttable_limit < 0 && arg.pruning_strategy_switch.empty()) {
c.phraseTableSizeLimit = (1.0 + arg.full_prune_extra/100.0) * c.phraseTableSizeLimit;
error(ETWarn, "Increasing -ttable-limit by %u%% -- to %u -- to compensate for approximated \"full\" implementation.",
arg.full_prune_extra, c.phraseTableSizeLimit);
}
}
if (arg.filterLDMs and c.LDMFiles.empty()) {
error(ETWarn, "You asked to filter lexicalized DMs but your config file doesn't contain any.");
// Disable filtering LDMs since there are no LDMs in the canoe.ini file.
arg.filterLDMs = false;
}
// Print the requested running mode from user
if (arg.verbose) {
if (arg.tm_online) cerr << " Running in online / streaming mode" << endl;
else cerr << " Running in load all in memory" << endl;
if (arg.no_src_grep) cerr << " Running without source sentences => processing all table entries" << endl;
else cerr << " Running with source sentences => filtering phrase table base on source phrases" << endl;
if (arg.tm_soft_limit) cerr << " Running in SOFT mode using limit(" << c.phraseTableSizeLimit << ")" << endl;
if (arg.tm_hard_limit) cerr << " Running in HARD mode using limit(" << c.phraseTableSizeLimit << ")" << endl;
}
if (arg.tm_online) error(ETWarn, "Be sure that your phrasetable is sorted before calling filter_models (LC_ALL=C)");
// Setting the value of log_almost_zero
PhraseTable::log_almost_0 = c.phraseTableLogZero;
// Prepares the source sentences
VectorPSrcSent src_sents;
if (arg.limitPhrases()) {
LOG_VERBOSE1(filter_models_Logger, "Loading source sentences");
string line;
iSafeMagicStream is(arg.input);
InputParser reader(is);
PSrcSent ss;
while (ss = reader.getMarkedSent())
src_sents.push_back(ss);
if (src_sents.empty())
error(ETFatal, "No source sentences, nothing to do! (or did you forget to say -no-src-grep?");
else
cerr << "Using " << src_sents.size() << " source sentences" << endl;
}
// CHECKING consistency in user's request.
LOG_VERBOSE1(filter_models_Logger, "Consistency check of user's request");
// Logic checking
if (arg.limit() and !c.allNonMultiProbPTs.empty())
error(ETFatal, "You can't use limit aka filter30 with ttables other than multi-prob ones");
if (arg.limit() and !(c.phraseTableSizeLimit > NO_SIZE_LIMIT))
error(ETFatal, "You're using filter TM, please set a value greater than 0 to [ttable-limit]");
// When using tm hard limit, user must provide the tms-weights
if (arg.tm_hard_limit and c.transWeights.empty())
error(ETFatal, "You must provide the TMs weights when doing a tm_hard_limit");
if (src_sents.empty() and arg.limitPhrases())
error(ETFatal, "You must provide source sentences when doing grep");
if (arg.filterLMs and !c.allNonMultiProbPTs.empty())
error(ETFatal, "Filtering Language Models (-L) only works for multi-prob phrase tables");
if (arg.filterLDMs and (!(arg.limit() or c.multiProbTMFiles.size() == 1))) {
if (arg.limitPhrases())
error(ETWarn, "Filtering LDMs with multiple CPTs and no hard/soft filtering; taking only source phrases into account for LDM filtering, not target phrases.");
else
error(ETFatal, "To filter LDMs, we must either have one cpt or use hard/soft filtering to produce one cpt before filtering LDMs. Alternatively, use filter-grep mode, in which case LDM filtering takes into account source phrases, but not target phrases, as it would normally.");
}
if (arg.filterLDMs and !c.allNonMultiProbPTs.empty()) {
if (arg.limitPhrases())
error(ETWarn, "Filtering LDMs when using phrase tables other than multi-prob takes only source phrases into account for LDM filtering, not target phrases.");
else
error(ETFatal, "Filtering LDMs when using phrase tables other than multi-prob and not limiting phrases is not supported.");
}
// online mode only applies to tm_hard_limit or tm_soft_limit.
if (!arg.limit()) arg.tm_online = false;
// hack - rely on a side effect of maxSourceSentence4filtering to disable
// per-sentence filtering
if ( arg.nopersent ) VocabFilter::maxSourceSentence4filtering = 1;
////////////////////////////////////////
// Changing what to do based on what the user asked for and what has already been done.
if (arg.limit()) {
// What's the final cpt filename.
const string filtered_cpt_filename = arg.prepareFilename(arg.limit_file);
if (check_if_exists(filtered_cpt_filename)) {
if (arg.readonly) {
error(ETWarn, "Translation Model %s has already been filtered. Skipping...", filtered_cpt_filename.c_str());
// The filtered TM already exists thus we don't want to redo the
// work. We will disable soft/hard filtering and also disable grep
// filtering. If the user requested LM filtering, the TM's
// vocabulary will be loaded.
arg.tm_soft_limit = false;
arg.tm_hard_limit = false;
arg.tm_online = false;
arg.no_src_grep = true;
// Change the config file to reflect the new filtered TM.
c.readStatus("ttable-multi-prob") = true;
c.multiProbTMFiles.clear(); // We should end up with only one multi-prob
c.multiProbTMFiles.push_back(filtered_cpt_filename);
}
// The filtered model exists but it's read-only and we are supposed to overwrite it.
// We can't proceed since we should be filtering a new model and thus
// loading the vocabulary for potentially filtering LMs & LDMs.
else if (arg.isReadOnlyOnDisk(filtered_cpt_filename)) {
error(ETFatal,
"Incoherent scenario, a filtered TM exists (%s), is read-only but user want to overwrite. Cannot proceed....",
filtered_cpt_filename.c_str());
}
// The filtered model exists and it's not readonly in any shape or form thus we will generate a new one.
else {
error(ETWarn,
"A filtered TM exists (%s) but we have no indication from the user that we shouldn't overwrite it. Overwriting...",
filtered_cpt_filename.c_str());
}
}
}
else if (arg.limitPhrases()) {
if (c.multiProbTMFiles.size() == 1) {
string& file = c.multiProbTMFiles.front();
const string translationModelFilename = file;
const string filteredTranslationModelFilename = arg.prepareFilename(translationModelFilename);
error_unless_exists(translationModelFilename, true, "translation model");
if (arg.readonly && check_if_exists(filteredTranslationModelFilename)) {
// The filtered version exists let's use the much faster tm vocab loading mechanism with PhraseTable_filter_lm.
if (arg.filterLMs) arg.no_src_grep = true;
file = filteredTranslationModelFilename;
error(ETWarn, "Translation Model %s has already been filtered. Skipping...",
filteredTranslationModelFilename.c_str());
}
else if (arg.isReadOnlyOnDisk(filteredTranslationModelFilename)) {
error(ETFatal, "Cannot filter %s since %s is read-only.",
translationModelFilename.c_str(),
filteredTranslationModelFilename.c_str());
}
}
/*
else
if (arg.filterLDMs)
error(ETFatal, "It is impossible to either filter LDMs in source grep mode unless you only have one TM.");
*/
}
VocabFilter tgt_vocab(src_sents.size());
GlobalVoc::set(&tgt_vocab);
////////////////////////////////////////
// Filter Conditional Phrase Tables.
bool weve_created_a_cpt = false;
// We are doing either soft or hard filtering.
if (arg.limit()) {
// What's the final cpt filename.
const string filtered_cpt_filename = arg.prepareFilename(arg.limit_file);
if (arg.tm_online) {
weve_created_a_cpt = processOnline(c, arg, tgt_vocab, src_sents);
}
else {
// Creating what will be needed for filtering
LOG_VERBOSE1(filter_models_Logger, "Creating the models");
// Get the proper pruning specifier.
const pruningStyle* pruning_style = pruningStyle::create(arg.pruning_strategy_switch, c.phraseTableSizeLimit);
assert(pruning_style != NULL);
PhraseTableFilterJoint phraseTable(
arg.limitPhrases(),
tgt_vocab,
pruning_style,
arg.phraseTablePruneType,
c.forwardWeights,
c.transWeights,
arg.tm_hard_limit,
c.appendJointCounts);
// Parses the input source sentences
phraseTable.addSourceSentences(src_sents);
// Read in memory all Translation Models.
// Side effect: load vocabulary into tgt_vocab.
LOG_VERBOSE1(filter_models_Logger, "Processing multi-probs");
for (FL_iterator file(c.multiProbTMFiles.begin()); file!=c.multiProbTMFiles.end(); ++file) {
LOG_VERBOSE2(filter_models_Logger,
"Translation Model filename: %s", file->c_str());
error_unless_exists(*file, true, "translation model");
// If there exists a filtered version of *file, use it instead.
phraseTable.readMultiProb(*file);
}
LOG_VERBOSE1(filter_models_Logger, "Filtering with filter_joint with: %d", c.phraseTableSizeLimit);
const time_t start_time = time(NULL);
// Perform hard or soft filtering on the in-memory trie strucutre and writes it to disk.
phraseTable.filter(filtered_cpt_filename);
weve_created_a_cpt = true;
delete pruning_style; pruning_style = NULL;
if (arg.verbose) {
cerr << " ... done in " << (time(NULL) - start_time) << "s" << endl;
}
}
// Change the config file to reflect the new filtered TM.
c.readStatus("ttable-multi-prob") = true;
c.multiProbTMFiles.clear(); // We should end up with only one multi-prob
c.multiProbTMFiles.push_back(filtered_cpt_filename);
}
// This is grep filtering.
else if (arg.limitPhrases()) {
// Creating what will be needed for filtering
LOG_VERBOSE1(filter_models_Logger, "Creating the models");
PhraseTableFilterGrep phraseTable(arg.limitPhrases(), tgt_vocab,
arg.phraseTablePruneType, c.appendJointCounts);
// Parses the input source sentences
phraseTable.addSourceSentences(src_sents);
// Add multi-prob TMs to vocab and filter them
LOG_VERBOSE1(filter_models_Logger, "Processing multi-probs");
for (FL_iterator file(c.multiProbTMFiles.begin()); file!=c.multiProbTMFiles.end(); ++file) {
const string translationModelFilename = *file;
const string filteredTranslationModelFilename = arg.prepareFilename(translationModelFilename);
LOG_VERBOSE2(filter_models_Logger,
"Translation Model filename: %s filtered Translation Model filename: %s",
translationModelFilename.c_str(),
filteredTranslationModelFilename.c_str());
error_unless_exists(translationModelFilename, true, "translation model");
if (arg.readonly && check_if_exists(filteredTranslationModelFilename)) {
error(ETWarn, "Translation Model %s has already been filtered. Skipping...",
filteredTranslationModelFilename.c_str());
}
else if (arg.isReadOnlyOnDisk(filteredTranslationModelFilename)) {
error(ETWarn, "Cannot filter %s since %s is read-only.",
translationModelFilename.c_str(),
filteredTranslationModelFilename.c_str());
}
else {
phraseTable.filter(translationModelFilename, filteredTranslationModelFilename);
weve_created_a_cpt = true;
}
*file = filteredTranslationModelFilename;
}
}
// Reading the vocabulary in the TMs in order to filter LMs.
// Here, we don't create a new TM.
else if (arg.filterLMs) {
// PhraseTableFilterLM will not load the phrase table in memory but it will simply populate tgt_vocab.
PhraseTableFilterLM phraseTable(arg.limitPhrases(),
tgt_vocab, arg.phraseTablePruneType, c.appendJointCounts);
// Parses the input source sentences
phraseTable.addSourceSentences(src_sents);
// Add multi-prob TMs to vocab and filter them
if (!c.multiProbTMFiles.empty()) LOG_VERBOSE1(filter_models_Logger, "Processing multi-probs");
for (FL_iterator file(c.multiProbTMFiles.begin()); file!=c.multiProbTMFiles.end(); ++file) {
LOG_VERBOSE2(filter_models_Logger,
"Reading in %s's vocab to filter the LMs.",
file->c_str());
error_unless_exists(*file, true, "translation model");
string filename, dummy;
arg.getFilenames(*file, filename, dummy);
// This function call doesn't actually load the LM in memory but
// rather populates the tgt_vocab for us.
phraseTable.readMultiProb(filename);
}
}
else {
LOG_VERBOSE2(filter_models_Logger, "No filtering of TM was performed.");
}
////////////////////////////////////////
// Filter Language Models.
// In order to filter LMs, we need tgt_vocab to be populated at this point.
if (arg.filterLMs and !c.lmFiles.empty()) {
// We must get the vocab from the TPPTs first
if ( !c.allNonMultiProbPTs.empty() && arg.limitPhrases() && c.lmFiles.size() > 0 ) {
LOG_VERBOSE1(filter_models_Logger, "Extracting vocabulary from TPPTs");
const time_t start_time = time(NULL);
if (arg.verbose)
cerr << "Extracting target vocabulary from TPPTs";
PhraseTable phraseTable(tgt_vocab, NULL, c.appendJointCounts);
phraseTable.extractVocabFromTPPTs(0); // Will extract the TPPT voc into tgt_vocab.
if (arg.verbose) {
cerr << " ... done in " << (time(NULL) - start_time) << "s" << endl;
}
}
// At this point, we must have a populated voc or else filtering will remove everything.
assert(!tgt_vocab.empty());
LOG_VERBOSE1(filter_models_Logger, "Processing Language Models");
for (FL_iterator file(c.lmFiles.begin()); file!=c.lmFiles.end(); ++file) {
// Extract the physical file name.
const size_t hash_pos = file->rfind(PLM::lm_order_separator);
const string lm = file->substr(0, hash_pos);
const string option = (hash_pos != string::npos ? file->substr(hash_pos+1) : "");
const string flm = arg.prepareFilename(lm);
// Let's skip Language Model types that we cannot filter.
if (!LMText::isA(lm)) {
error(ETWarn, "Cannot filter Language Models of types other than ARPA LM! Skipping %s...", lm.c_str());
continue;
}
error_unless_exists(lm, true, "language model");
if (arg.readonly && check_if_exists(flm)) {
error(ETWarn, "Language Model %s has already been filtered. Skipping...", lm.c_str());
}
else if (arg.isReadOnlyOnDisk(flm)) {
error(ETWarn, "Cannot filter %s since %s is read-only.", lm.c_str(), flm.c_str());
}
else {
if (arg.verbose) {
cerr << "loading Language Model from " << lm << " to " << flm << endl;
}
const time_t start_time = time(NULL);
oSafeMagicStream os_filtered(flm);
const PLM *lm_model = PLM::Create(lm, &tgt_vocab, PLM::ClosedVoc,
LOG_ALMOST_0, arg.limitPhrases(), c.lmOrder, &os_filtered);
if (arg.verbose) {
cerr << " ... done in " << (time(NULL) - start_time) << "s" << endl;
}
if (lm_model) { delete lm_model; lm_model = NULL; }
*file = flm + option;
}
}
}
////////////////////////////////////////
// Filter Lexicalized Distortion Models.
if (arg.filterLDMs && !c.LDMFiles.empty()) {
LOG_VERBOSE1(filter_models_Logger, "Processing Lexicalized Distortion Models");
// There can only be one cpt to filter ldms.
if (c.multiProbTMFiles.size() != 1 or !c.allNonMultiProbPTs.empty()) {
if (arg.limitPhrases())
error(ETWarn, "There is more than one CPT or there are other types of phrase tables, so LDM filtering can't look at target phrases; doing filter-grep only on the LDM(s).");
else
error(ETFatal, "In order to filter LDMs, we must have only one CPT and no TPPTs, or do filter-grep.");
}
const string cpt_filename = c.multiProbTMFiles.front();
for (FL_iterator file(c.LDMFiles.begin()); file!=c.LDMFiles.end(); ++file) {
// We don't know how to filter TPLDMs, let's skip it.
if (isSuffix(".tpldm", *file)) {
error(ETWarn, "Cannot filter Lexicalized Distortion Models of TPLDM type (%s)! Skipping...", file->c_str());
continue;
}
error_unless_exists(*file, true, "Lexicalized Distortion Model");
// Don't redo work if there exists a filtered ldm.
const string filtered_ldm = arg.prepareFilename(*file, arg.preserve_ldm_paths);
if (arg.readonly && check_if_exists(filtered_ldm)) {
if (weve_created_a_cpt)
error(ETFatal, "%s hasn't been filtered even though a new cpt was created (%s) since you asked not to overwrite models.",
file->c_str(),
cpt_filename.c_str());
else
error(ETWarn, "Lexicalized Distortion Model %s has already been filtered. Skipping...", file->c_str());
}
else if (arg.isReadOnlyOnDisk(filtered_ldm)) {
error(ETWarn, "Cannot filter %s since %s is read-only.", file->c_str(), filtered_ldm.c_str());
}
else {
if (c.multiProbTMFiles.size() != 1 || !c.allNonMultiProbPTs.empty()) {
assert(arg.limitPhrases());
PhraseTableFilterGrep phraseTable(arg.limitPhrases(),
tgt_vocab, arg.phraseTablePruneType,
c.appendJointCounts);
phraseTable.addSourceSentences(src_sents);
error_unless_exists(*file, true, "LDM");
phraseTable.filter(*file, filtered_ldm);
const string bkoff_file = (isZipFile(*file) ? removeExtension(*file) : *file) + ".bkoff";
const string filt_bkoff_file = (isZipFile(filtered_ldm) ? removeExtension(filtered_ldm) : filtered_ldm) + ".bkoff";
iSafeMagicStream bk_in(bkoff_file.c_str());
oSafeMagicStream bk_out(filt_bkoff_file.c_str());
string line;
while (getline(bk_in, line))
bk_out << line;
} else {
// filter-distortion-model.pl -v ${CPT} ${LDM} ${FLDM}
const string cmd = "filter-distortion-model.pl -v " + cpt_filename
+ " " + *file
+ " " + filtered_ldm;
if (arg.verbose)
cerr << "Filtering LDM using: " << cmd << endl; // SAM DEBUGGING
const int rc = system(cmd.c_str());
if (rc != 0)
error(ETFatal, "Error filtering Lexicalized Distortion Model with filter-distortion-model.pl! (rc=%d)", rc);
// NOTE: the associated .bkoff for the newly filtered LDM will be created by filter-distortion-model.pl.
}
}
// Replace unfiltered ldm in config file with the filtered one.
*file = filtered_ldm;
}
}
// Print out the vocab if necessary
if (arg.vocab_file.size() > 0) {
if (arg.verbose) {
cerr << "Dumping Vocab" << endl;
}
if (tgt_vocab.per_sentence_vocab) {
fprintf(stderr, "Average vocabulary size per source sentences: %f\n",
tgt_vocab.per_sentence_vocab->averageVocabSizePerSentence());
}
oSafeMagicStream os_vocab(arg.vocab_file);
tgt_vocab.write(os_vocab);
}
// Builds a new canoe.ini with the modified models
LOG_VERBOSE1(filter_models_Logger, "Creating new canoe.ini");
const string configFile(addExtension(arg.config, arg.suffix));
if (arg.ttable_limit >= 0) // restore original configfile limit
c.phraseTableSizeLimit = ttable_limit_from_config;
if (arg.output_config) {
if (arg.verbose) {
cerr << "New config file is: " << configFile << endl;
}
c.write(configFile.c_str(), 1, true);
}
} END_MAIN
| 25,953 | 7,959 |
/*
* Copyright (c) 2014-2021, NVIDIA CORPORATION. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "vulkan-backend.h"
namespace nvrhi::vulkan
{
CommandList::CommandList(Device* device, const VulkanContext& context, const CommandListParameters& parameters)
: m_Device(device)
, m_Context(context)
, m_CommandListParameters(parameters)
, m_StateTracker(context.messageCallback)
, m_UploadManager(std::make_unique<UploadManager>(device, parameters.uploadChunkSize, 0, false))
, m_ScratchManager(std::make_unique<UploadManager>(device, parameters.scratchChunkSize, parameters.scratchMaxMemory, true))
{
}
nvrhi::Object CommandList::getNativeObject(ObjectType objectType)
{
switch (objectType)
{
case ObjectTypes::VK_CommandBuffer:
return Object(m_CurrentCmdBuf->cmdBuf);
default:
return nullptr;
}
}
void CommandList::open()
{
m_CurrentCmdBuf = m_Device->getQueue(m_CommandListParameters.queueType)->getOrCreateCommandBuffer();
auto beginInfo = vk::CommandBufferBeginInfo()
.setFlags(vk::CommandBufferUsageFlagBits::eOneTimeSubmit);
(void)m_CurrentCmdBuf->cmdBuf.begin(&beginInfo);
m_CurrentCmdBuf->referencedResources.push_back(this); // prevent deletion of e.g. UploadManager
clearState();
}
void CommandList::close()
{
endRenderPass();
m_StateTracker.keepBufferInitialStates();
m_StateTracker.keepTextureInitialStates();
commitBarriers();
#ifdef NVRHI_WITH_RTXMU
if (!m_CurrentCmdBuf->rtxmuBuildIds.empty())
{
m_Context.rtxMemUtil->PopulateCompactionSizeCopiesCommandList(m_CurrentCmdBuf->cmdBuf, m_CurrentCmdBuf->rtxmuBuildIds);
}
#endif
m_CurrentCmdBuf->cmdBuf.end();
clearState();
flushVolatileBufferWrites();
}
void CommandList::clearState()
{
endRenderPass();
m_CurrentPipelineLayout = vk::PipelineLayout();
m_CurrentPipelineShaderStages = vk::ShaderStageFlagBits();
m_CurrentGraphicsState = GraphicsState();
m_CurrentComputeState = ComputeState();
m_CurrentMeshletState = MeshletState();
m_CurrentRayTracingState = rt::State();
m_CurrentShaderTablePointers = ShaderTableState();
m_AnyVolatileBufferWrites = false;
// TODO: add real context clearing code here
}
void CommandList::setPushConstants(const void* data, size_t byteSize)
{
assert(m_CurrentCmdBuf);
m_CurrentCmdBuf->cmdBuf.pushConstants(m_CurrentPipelineLayout, m_CurrentPipelineShaderStages, 0, uint32_t(byteSize), data);
}
void CommandList::executed(Queue& queue, const uint64_t submissionID)
{
assert(m_CurrentCmdBuf);
m_CurrentCmdBuf->submissionID = submissionID;
const CommandQueue queueID = queue.getQueueID();
const uint64_t recordingID = m_CurrentCmdBuf->recordingID;
m_CurrentCmdBuf = nullptr;
submitVolatileBuffers(recordingID, submissionID);
m_StateTracker.commandListSubmitted();
m_UploadManager->submitChunks(
MakeVersion(recordingID, queueID, false),
MakeVersion(submissionID, queueID, true));
m_ScratchManager->submitChunks(
MakeVersion(recordingID, queueID, false),
MakeVersion(submissionID, queueID, true));
m_VolatileBufferStates.clear();
}
} | 4,566 | 1,433 |
/*
* Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include "UiCanvasEditor_precompiled.h"
#include "EditorCommon.h"
UndoStackExecutionScope::UndoStackExecutionScope(UndoStack* stack)
: m_stack(stack)
{
m_stack->SetIsExecuting(true);
}
UndoStackExecutionScope::~UndoStackExecutionScope()
{
m_stack->SetIsExecuting(false);
}
| 507 | 173 |
#include "listen/tcp_listen_service.h"
#include <string.h>
#include "log/log.h"
#include "common/config/listen_flags.h"
#include "connector/connector_manager.h"
TCPListenService::TCPListenService() {
stop_ = false;
}
TCPListenService::~TCPListenService() {
stop();
close(listen_fd_);
}
void TCPListenService::stop() {
ListenService::stop();
}
void TCPListenService::init_config() {
}
bool TCPListenService::init_socket() {
DEBUG_LOG("listen port = %d", FLAGS_port);
DEBUG_LOG("communication type = %s", FLAGS_communication_type.c_str());
struct sockaddr_in listen_addr;
listen_fd_ = socket(AF_INET, SOCK_STREAM, 0);
bzero(&listen_addr, sizeof(listen_addr));
listen_addr.sin_family = AF_INET;
listen_addr.sin_port = htons(FLAGS_port);
listen_addr.sin_addr.s_addr = htonl(INADDR_ANY);
int ret = bind(listen_fd_, (struct sockaddr*)&listen_addr, sizeof(listen_addr));
if (ret == invalid_id) {
const char* error = "error occured while bind";
switch (errno) {
case EADDRINUSE:
error = "The given address is already in use";
break;
case EINVAL:
error = "The socket is already bound to an address.";
break;
default:
break;
}
ERROR_LOG(error);
close(listen_fd_);
return false;
}
listen(listen_fd_, 256);
epoll_fd_ = epoll_create(MAX_EVENT);
if (epoll_fd_ == invalid_id) {
ERROR_LOG("create epoll error!");
close(listen_fd_);
return false;
}
struct epoll_event event;
event.data.fd = listen_fd_;
event.events = EPOLLIN | EPOLLHUP |EPOLLERR;
ret = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, listen_fd_, &event);
if (ret == invalid_id) {
ERROR_LOG("add epoll error!");
close(listen_fd_);
return false;
}
DEBUG_LOG("create socket success!");
return true;
}
void TCPListenService::run_logic() {
ListenService::run_logic();
// init ConnectorManager
ConnectorManager::instance();
}
void TCPListenService::main_loop() {
struct epoll_event events[MAX_EVENT];
while(!stop_) {
int fds = epoll_wait(epoll_fd_, events, MAX_EVENT, 100);
for (int i = 0; i < fds; ++i) {
struct epoll_event& tmp_ev = events[i];
if (tmp_ev.data.fd == listen_fd_) {
accept_connection();
}
else if (tmp_ev.events & EPOLLIN) {
}
else if (tmp_ev.events & EPOLLOUT) {
}
}
}
}
bool TCPListenService::accept_connection() {
struct sockaddr_in socket_in;
socklen_t socket_len = sizeof(struct sockaddr_in);
int new_socket_fd = accept(listen_fd_, (struct sockaddr*)&socket_in, &socket_len);
if (new_socket_fd == -1) {
const char* err_con = nullptr;
switch(errno) {
case EAGAIN:
err_con = "The socket is marked nonblocking and no connections are "
"present to be accepted";
break;
case EBADF:
err_con = "sockfd is not an open file descriptor";
break;
case EFAULT:
err_con = "The addr argument is not in a writable part of the user "
"address space";
break;
case EINTR:
err_con = "The system call was interrupted by a signal";
break;
case EINVAL:
err_con = "Socket is not listening for connections, or addrlen is invalid";
break;
case ENOMEM:
err_con = "Not enough free memory";
break;
case EPERM:
err_con = "Firewall rules forbid connection";
break;
default:
err_con = "unknown error";
break;
}
ERROR_LOG(err_con);
return false;
}
const char* addr_in = inet_ntoa(socket_in.sin_addr);
DEBUG_LOG("establish connection from %s", addr_in);
int flag = fcntl(new_socket_fd, F_GETFL, 0);
int ret = fcntl(new_socket_fd, F_SETFL, flag | O_NONBLOCK);
if (ret == invalid_id) {
ERROR_LOG("set non block for socket %d failed, errno = %d", new_socket_fd, ret);
return false;
}
ConnectorManager::instance()->accept_connector(new_socket_fd);
return true;
}
| 4,296 | 1,426 |
// Copyright (c) 2016 Nuxi, https://nuxi.nl/
//
// SPDX-License-Identifier: BSD-2-Clause
#include <stdbool.h>
#include <stdlib.h>
#include <wchar.h>
#include <iterator>
#include "gtest/gtest.h"
TEST(wmemmem, null) {
// wmemmem() should not attempt to access any buffers if the needle
// has length 0 or is larger than the haystack.
ASSERT_EQ(NULL, wmemmem(NULL, 0, NULL, 123));
ASSERT_EQ(NULL, wmemmem(NULL, 123, NULL, 0));
ASSERT_EQ(NULL, wmemmem(NULL, 123, NULL, 456));
}
TEST(wmemmem, examples) {
const wchar_t *str = L"Hello world";
ASSERT_EQ(str + 4, wmemmem(str, 11, L"o worl", 6));
ASSERT_EQ(NULL, wmemmem(str, 11, L"o worl", 7));
ASSERT_EQ(str + 6, wmemmem(str, 11, L"world", 5));
ASSERT_EQ(NULL, wmemmem(str, 11, L"world", 6));
ASSERT_EQ(str + 6, wmemmem(str, 12, L"world", 6));
ASSERT_EQ(NULL, wmemmem(str, 11, L"word", 4));
ASSERT_EQ(NULL, wmemmem(str, 11, L"world!", 6));
}
// Fills a buffer with random letters between A and D.
static void fill_random(wchar_t *buf, size_t len) {
arc4random_buf(buf, len * sizeof(wchar_t));
for (size_t i = 0; i < len; ++i)
buf[i] = (buf[i] & 0x3) + L'A';
}
// Performs a naïve wmemmem() operation.
static wchar_t *naive_memmem(const wchar_t *haystack, size_t haystacklen,
const wchar_t *needle, size_t needlelen) {
if (needlelen > haystacklen)
return NULL;
for (size_t i = 0; i + needlelen <= haystacklen; ++i) {
bool match = true;
for (size_t j = 0; j < needlelen; ++j) {
if (haystack[i + j] != needle[j]) {
match = false;
break;
}
}
if (match)
return (wchar_t *)haystack + i;
}
return NULL;
}
// Compares the output of wmemmem() against a naïve implementation.
TEST(wmemmem, random) {
for (size_t i = 0; i < 1000; ++i) {
wchar_t haystack[40000];
wchar_t needle[8];
size_t needlelen = arc4random_uniform(std::size(needle));
SCOPED_TRACE(needlelen);
fill_random(haystack, std::size(haystack));
fill_random(needle, needlelen);
ASSERT_EQ(naive_memmem(haystack, std::size(haystack), needle, needlelen),
wmemmem(haystack, std::size(haystack), needle, needlelen));
}
}
| 2,189 | 961 |
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create a JSON value
json j =
{
{"number", 1}, {"string", "foo"}, {"array", {1, 2}}
};
std::cout << std::boolalpha
<< j.contains("/number"_json_pointer) << '\n'
<< j.contains("/string"_json_pointer) << '\n'
<< j.contains("/string"_json_pointer) << '\n'
<< j.contains("/array"_json_pointer) << '\n'
<< j.contains("/array/1"_json_pointer) << '\n'
<< j.contains("/array/-"_json_pointer) << '\n'
<< j.contains("/array/4"_json_pointer) << '\n'
<< j.contains("/baz"_json_pointer) << std::endl;
// out_of_range.106
try
{
// try to use an array index with leading '0'
j.contains("/array/01"_json_pointer);
}
catch (json::parse_error& e)
{
std::cout << e.what() << '\n';
}
// out_of_range.109
try
{
// try to use an array index that is not a number
j.contains("/array/one"_json_pointer);
}
catch (json::parse_error& e)
{
std::cout << e.what() << '\n';
}
}
| 1,189 | 410 |
bool isOdd(int n) { return n & 1; } | 35 | 17 |
//
// FBullCowModel.cpp
// Bull Cow Game Model
//
// Created by Diego Becciolini on 11/01/2017.
// Copyright © 2017 Itizir.
// This work is free. You can redistribute it and/or modify it under the
// terms of the Do What The Fuck You Want To Public License, Version 2,
// as published by Sam Hocevar. See the LICENSE file for more details.
//
#include "FBullCowModel.hpp"
// ****** MARK: - Constructors ******
FBullCowModel::FBullCowModel(const FString& DictionaryPath) : FBullCowModelProtected(DictionaryPath) {}
FBullCowModelProtected::FBullCowModelProtected(const FString& DictionaryPath) : DictionaryName(DictionaryPath)
{
LoadDictionary(DictionaryPath);
}
// ****** MARK: - Getters ******
EBCGameStatus FBullCowModelProtected::GetStatus() const { return CurrentStatus; }
int32 FBullCowModelProtected::GetMaxTries() const { return MyMaxTries; }
int32 FBullCowModelProtected::GetCurrentTry() const { return MyCurrentTry; }
int32 FBullCowModelProtected::GetHiddenWordLength() const
{
return (int32)MyHiddenWord.length();
}
int32 FBullCowModelProtected::GetMinLetters() const { return MinLetters; }
int32 FBullCowModelProtected::GetMaxLetters() const { return MaxLetters; }
FBullCowCount FBullCowModelProtected::GetCurrentScore() const { return MyCurrentScore; }
FString FBullCowModelProtected::GetCurrentGuess() const { return MyCurrentGuess; }
TMap<FString, FBullCowCount> const& FBullCowModelProtected::GetGuessHistory() const { return MyGuessHistory; }
std::vector< TMap<FString, FBullCowCount>::const_iterator > const& FBullCowModelProtected::GetGuessChronology() const { return MyGuessChronology; }
FString FBullCowModelProtected::GetDictionaryName() const { return DictionaryName; }
bool FBullCowModelProtected::IsGameWon() const { return bGameIsWon; }
FString FBullCowModelProtected::RevealHiddenWord() const
{
if (GetStatus() == EBCGameStatus::Round_Over)
return MyHiddenWord;
else
return "NO CHEATING, NAUGHTY!";
}
// ****** MARK: - Game state update / game logic ******
void FBullCowModelProtected::ResetRound()
{
MyCurrentGuess = "";
MyGuessChronology.clear();
MyGuessHistory.clear();
MyCurrentTry = 1;
bGameIsWon = false;
// Needs to be set afterwards by calling SetRandomHiddenWord()!
MyHiddenWord = "";
MyMaxTries = 0;
CurrentStatus = EBCGameStatus::Round_Reset;
return;
}
// Argument optional, default value = 0.
void FBullCowModelProtected::SetRandomHiddenWord(int32 WordLength)
{
std::uniform_int_distribution<unsigned long> PickWordLength(GetMinLetters(),GetMaxLetters());
// Since Dictionary is map of word lenghts, easy check...
// While word length not in range or if one specific category in range is empty.
while (Dictionary.count(WordLength)==0)
WordLength = (int32)PickWordLength(RD);
std::uniform_int_distribution<unsigned long> UniformDistr(0,Dictionary[WordLength].size()-1);
MyHiddenWord = Dictionary[WordLength][UniformDistr(RD)];
SetMaxTries(); // Now that word length is known, can decide number of tries.
CurrentStatus = EBCGameStatus::Round_Ready;
return;
}
void FBullCowModelProtected::SetMaxTries()
{
// !!!: Still unsure what the scaling should be.
MyMaxTries = (int32)MyHiddenWord.length()+5;
return;
}
void FBullCowModelProtected::SubmitGuess(const FString& Guess)
{
// So MyCurrentGuess may not be valid!
// Store to make sure it is capitalised (to check against history).
MyCurrentGuess = Guess;
transform(MyCurrentGuess.begin(), MyCurrentGuess.end(), MyCurrentGuess.begin(), toupper);
if (!IsAlpha(GetCurrentGuess()))
CurrentStatus = EBCGameStatus::Guess_Not_Word;
else if (GetCurrentGuess().length() < GetHiddenWordLength())
CurrentStatus = EBCGameStatus::Guess_Too_Short;
else if (GetCurrentGuess().length() > GetHiddenWordLength())
CurrentStatus = EBCGameStatus::Guess_Too_Long;
else if (!IsIsogram(GetCurrentGuess()))
CurrentStatus = EBCGameStatus::Guess_Not_Isogram;
// Looks like the count(k) analogue in TMap would be Contains(k).
else if ( GetGuessHistory().count(GetCurrentGuess()) )
CurrentStatus = EBCGameStatus::Guess_Not_New;
// Could put a 'return' here, to make it clear last condition only if all tests passed.
else // If guess passed all tests: is valid.
{
++MyCurrentTry;
if (GetCurrentTry() > GetMaxTries())
CurrentStatus = EBCGameStatus::Round_Over;
else
CurrentStatus = EBCGameStatus::Guess_Accepted;
ScoreCurrentGuess();
}
return;
}
void FBullCowModelProtected::ScoreCurrentGuess()
{
int32 WordLength = GetHiddenWordLength();
// In that case, current guess cannot be valid, thus score is 0 (i.e. untouched).
// But should never be happening.
if (GetStatus() != EBCGameStatus::Guess_Accepted && GetStatus() != EBCGameStatus::Round_Over)
return;
MyCurrentScore = FBullCowCount(); // Reset current score!
// For valid guess, guaranteed that both words same length.
// Probably not most efficient algorithm, but small words...
for(int32 MHWi = 0; MHWi < WordLength; ++MHWi)
for(int32 Gi = 0; Gi < WordLength; ++Gi)
{
if (MyHiddenWord[MHWi] == GetCurrentGuess()[Gi])
{
if (MHWi==Gi)
++MyCurrentScore.Bulls;
else
++MyCurrentScore.Cows;
}
}
// Record new score in history.
MyGuessChronology.push_back(
MyGuessHistory.emplace(GetCurrentGuess(), GetCurrentScore()).first
);
bGameIsWon = (GetCurrentScore().Bulls == WordLength);
if (bGameIsWon)
CurrentStatus = EBCGameStatus::Round_Over;
return;
}
// ****** MARK: - Word checking ******
bool FBullCowModelProtected::IsAlpha(const FString& Word) const
{
return ( find_if_not(Word.cbegin(), Word.cend(), isalpha) == Word.end() );
}
bool FBullCowModelProtected::IsIsogram(const FString& Word) const
{
if (Word.length()<2) { return true; }
// Idea of using bitset from Lukáš Venhoda.
// Take full char range so to not rely on Word being only letters.
std::bitset< 1<<8*sizeof(Word[0]) > LetterSeen; // Should be 256 for standard 8-bit chars.
LetterSeen.reset();
for (auto Letter : Word)
{
// Here just to make sure mixed case still counts as same letter.
// Acutally unneccessary now that all words treated immediately converted to ALLCAPS.
// Still leaving in for security.
Letter = toupper(Letter);
if (LetterSeen[Letter])
return false;
else
LetterSeen[Letter] = 1;
}
return true;
}
// ****** MARK: - Load and use dictionary ******
void FBullCowModelProtected::LoadDictionary(const FString& DictionaryName)
{
FString Word;
std::ifstream File;
File.open(DictionaryName);
// Initialise with most extreme values before reading through the dictionary.
MinLetters = 27;
MaxLetters = 0;
if (!File.is_open())
{
CurrentStatus = EBCGameStatus::No_Dictionary;
return;
}
while (File >> Word)
{
transform(Word.begin(), Word.end(), Word.begin(), toupper); // Make sure all in upper-case.
if (!IsAlpha(Word))
{
CurrentStatus = EBCGameStatus::NotWord_Dictionary;
return;
}
else if (!IsIsogram(Word))
{
CurrentStatus = EBCGameStatus::NotIsogram_Dictionary;
return;
}
else
{
MaxLetters = std::max(MaxLetters, (int32)Word.length());
MinLetters = std::min(MinLetters, (int32)Word.length());
Dictionary[(int32)Word.length()].push_back(Word);
}
// // Could also simply skip invalid words instead of putting game in error state:
// if (IsAlpha(Word) && IsIsogram(Word))
// Dictionary[(int32)Word.length()].push_back(Word);
}
if (Dictionary.empty())
{
CurrentStatus = EBCGameStatus::Empty_Dictionary;
return;
}
CurrentStatus = EBCGameStatus::New;
return;
}
| 7,566 | 2,755 |
/*
* Simd Library (http://ermig1979.github.io/Simd).
*
* Copyright (c) 2011-2020 Yermalayeu Ihar,
* 2019-2019 Facundo Galan.
*
* 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 __SimdDetection_hpp__
#define __SimdDetection_hpp__
#include "Simd/SimdLib.hpp"
#include "Simd/SimdParallel.hpp"
#include <vector>
#include <map>
#include <memory>
#include <limits.h>
#ifndef SIMD_CHECK_PERFORMANCE
#define SIMD_CHECK_PERFORMANCE()
#endif
namespace Simd
{
/*! @ingroup cpp_detection
\short The Detection structure provides object detection with using of HAAR and LBP cascade classifiers.
Using example (face detection in the image):
\code
#include "Simd/SimdDetection.hpp"
#include "Simd/SimdDrawing.hpp"
int main()
{
typedef Simd::Detection<Simd::Allocator> Detection;
Detection::View image;
image.Load("../../data/image/face/lena.pgm");
Detection detection;
detection.Load("../../data/cascade/haar_face_0.xml");
detection.Init(image.Size());
Detection::Objects objects;
detection.Detect(image, objects);
for (size_t i = 0; i < objects.size(); ++i)
Simd::DrawRectangle(image, objects[i].rect, uint8_t(255));
image.Save("result.pgm");
return 0;
}
\endcode
Using example (face detection in the video captured by OpenCV):
\code
#include <iostream>
#include <string>
#include "opencv2/opencv.hpp"
#ifndef SIMD_OPENCV_ENABLE
#define SIMD_OPENCV_ENABLE
#endif
#include "Simd/SimdDetection.hpp"
#include "Simd/SimdDrawing.hpp"
int main(int argc, char * argv[])
{
if (argc < 2)
{
std::cout << "You have to set video source! It can be 0 for camera or video file name." << std::endl;
return 1;
}
std::string source = argv[1];
cv::VideoCapture capture;
if (source == "0")
capture.open(0);
else
capture.open(source);
if (!capture.isOpened())
{
std::cout << "Can't capture '" << source << "' !" << std::endl;
return 1;
}
typedef Simd::Detection<Simd::Allocator> Detection;
Detection detection;
detection.Load("../../data/cascade/haar_face_0.xml");
bool inited = false;
const char * WINDOW_NAME = "FaceDetection";
cv::namedWindow(WINDOW_NAME, 1);
for (;;)
{
cv::Mat frame;
capture >> frame;
Detection::View image = frame;
if (!inited)
{
detection.Init(image.Size(), 1.2, image.Size() / 20);
inited = true;
}
Detection::Objects objects;
detection.Detect(image, objects);
for (size_t i = 0; i < objects.size(); ++i)
Simd::DrawRectangle(image, objects[i].rect, Simd::Pixel::Bgr24(0, 255, 255));
cv::imshow(WINDOW_NAME, frame);
if (cvWaitKey(1) == 27)// "press 'Esc' to break video";
break;
}
return 0;
}
\endcode
\note This is wrapper around low-level \ref object_detection API.
*/
template <template<class> class A>
struct Detection
{
typedef A<uint8_t> Allocator; /*!< Allocator type definition. */
typedef Simd::View<A> View; /*!< An image type definition. */
typedef Simd::Point<ptrdiff_t> Size; /*!< An image size type definition. */
typedef std::vector<Size> Sizes; /*!< A vector of image sizes type definition. */
typedef Simd::Rectangle<ptrdiff_t> Rect; /*!< A rectangle type definition. */
typedef std::vector<Rect> Rects; /*!< A vector of rectangles type definition. */
typedef int Tag; /*!< A tag type definition. */
static const Tag UNDEFINED_OBJECT_TAG = -1; /*!< The undefined object tag. */
/*!
\short The Object structure describes detected object.
*/
struct Object
{
Rect rect; /*!< \brief A bounding box around of detected object. */
int weight; /*!< \brief An object weight (number of elementary detections). */
Tag tag; /*!< \brief An object tag. It's useful if more than one detector works. */
/*!
Creates a new Object structure.
\param [in] r - initial bounding box.
\param [in] w - initial weight.
\param [in] t - initial tag.
*/
Object(const Rect & r = Rect(), int w = 0, Tag t = UNDEFINED_OBJECT_TAG)
: rect(r)
, weight(w)
, tag(t)
{
}
/*!
Creates a new Object structure on the base of another object.
\param [in] o - another object.
*/
Object(const Object & o)
: rect(o.rect)
, weight(o.weight)
, tag(o.tag)
{
}
};
typedef std::vector<Object> Objects; /*!< A vector of objects type defenition. */
/*!
Creates a new empty Detection structure.
*/
Detection()
{
}
/*!
A Detection destructor.
*/
~Detection()
{
for (size_t i = 0; i < _data.size(); ++i)
::SimdRelease(_data[i].handle);
}
/*!
Loads from file classifier cascade. Supports OpenCV HAAR and LBP cascades type.
You can call this function more than once if you want to use several object detectors at the same time.
\note Tree based cascades and old cascade formats are not supported!
\param [in] xml - a string containing XML with cascade.
\param [in] tag - an user defined tag. This tag will be inserted in output Object structure.
\return a result of this operation.
*/
bool LoadStringXml(const std::string & xml, Tag tag = UNDEFINED_OBJECT_TAG)
{
// Copy the received string to a non const char pointer.
char * xmlTmp = new char[xml.size() + 1];
std::copy(xml.begin(), xml.end(), xmlTmp);
xmlTmp[xml.size()] = '\0';
Handle handle = ::SimdDetectionLoadStringXml(xmlTmp);
if (handle)
{
Data data;
data.handle = handle;
data.tag = tag;
::SimdDetectionInfo(handle, (size_t*)&data.size.x, (size_t*)&data.size.y, &data.flags);
_data.push_back(data);
}
return handle != NULL;
}
/*!
Loads from file classifier cascade. Supports OpenCV HAAR and LBP cascades type.
You can call this function more than once if you want to use several object detectors at the same time.
\note Tree based cascades and old cascade formats are not supported!
\param [in] path - a path to cascade.
\param [in] tag - an user defined tag. This tag will be inserted in output Object structure.
\return a result of this operation.
*/
bool Load(const std::string & path, Tag tag = UNDEFINED_OBJECT_TAG)
{
Handle handle = ::SimdDetectionLoadA(path.c_str());
if (handle)
{
Data data;
data.handle = handle;
data.tag = tag;
::SimdDetectionInfo(handle, (size_t*)&data.size.x, (size_t*)&data.size.y, &data.flags);
_data.push_back(data);
}
return handle != NULL;
}
/*!
Prepares Detection structure to work with image of given size.
\param [in] imageSize - a size of input image.
\param [in] scaleFactor - a scale factor. To detect objects of different sizes the algorithm uses many scaled image.
This parameter defines size difference between neighboring images. This parameter strongly affects to performance.
\param [in] sizeMin - a minimal size of detected objects. This parameter strongly affects to performance.
\param [in] sizeMax - a maximal size of detected objects.
\param [in] roi - a 8-bit image mask which defines Region Of Interest. User can restricts detection region with using this mask.
The mask affects to the center of detected object.
\param [in] threadNumber - a number of work threads. It useful for multi core CPU. Use value -1 to auto choose of thread number.
\return a result of this operation.
*/
bool Init(const Size & imageSize, double scaleFactor = 1.1, const Size & sizeMin = Size(0, 0),
const Size & sizeMax = Size(INT_MAX, INT_MAX), const View & roi = View(), ptrdiff_t threadNumber = -1)
{
if (_data.empty())
return false;
_imageSize = imageSize;
ptrdiff_t threadNumberMax = std::thread::hardware_concurrency();
_threadNumber = (threadNumber <= 0 || threadNumber > threadNumberMax) ? threadNumberMax : threadNumber;
return InitLevels(scaleFactor, sizeMin, sizeMax, roi);
}
/*!
Detects objects at given image.
\param [in] src - a input image.
\param [out] objects - detected objects.
\param [in] groupSizeMin - a minimal weight (number of elementary detections) of detected image.
\param [in] sizeDifferenceMax - a parameter to group elementary detections.
\param [in] motionMask - an using of motion detection flag. Useful for dynamical restriction of detection region to addition to ROI.
\param [in] motionRegions - a set of rectangles (motion regions) to restrict detection region to addition to ROI.
The regions affect to the center of detected object.
\return a result of this operation.
*/
bool Detect(const View & src, Objects & objects, int groupSizeMin = 3, double sizeDifferenceMax = 0.2,
bool motionMask = false, const Rects & motionRegions = Rects())
{
SIMD_CHECK_PERFORMANCE();
if (_levels.empty() || src.Size() != _imageSize)
return false;
FillLevels(src);
typedef std::map<Tag, Objects> Candidates;
Candidates candidates;
for (size_t i = 0; i < _levels.size(); ++i)
{
Level & level = *_levels[i];
View mask = level.roi;
Rect rect = level.rect;
if (motionMask)
{
FillMotionMask(motionRegions, level, rect);
mask = level.mask;
}
if (rect.Empty())
continue;
for (size_t j = 0; j < level.hids.size(); ++j)
{
Hid & hid = level.hids[j];
hid.Detect(mask, rect, level.dst, _threadNumber, level.throughColumn);
AddObjects(candidates[hid.data->tag], level.dst, rect, hid.data->size, level.scale,
level.throughColumn ? 2 : 1, hid.data->tag);
}
}
objects.clear();
for (typename Candidates::iterator it = candidates.begin(); it != candidates.end(); ++it)
GroupObjects(objects, it->second, groupSizeMin, sizeDifferenceMax);
return true;
}
private:
typedef void * Handle;
struct Data
{
Handle handle;
Tag tag;
Size size;
::SimdDetectionInfoFlags flags;
bool Haar() const { return (flags&::SimdDetectionInfoFeatureMask) == ::SimdDetectionInfoFeatureHaar; }
bool Tilted() const { return (flags&::SimdDetectionInfoHasTilted) != 0; }
bool Int16() const { return (flags&::SimdDetectionInfoCanInt16) != 0; }
};
typedef void(*DetectPtr)(const void * hid, const uint8_t * mask, size_t maskStride,
ptrdiff_t left, ptrdiff_t top, ptrdiff_t right, ptrdiff_t bottom, uint8_t * dst, size_t dstStride);
struct Worker;
typedef std::shared_ptr<Worker> WorkerPtr;
typedef std::vector<WorkerPtr> WorkerPtrs;
struct Hid
{
Handle handle;
Data * data;
DetectPtr detect;
void Detect(const View & mask, const Rect & rect, View & dst, size_t threadNumber, bool throughColumn)
{
SIMD_CHECK_PERFORMANCE();
Size s = dst.Size() - data->size;
View m = mask.Region(s, View::MiddleCenter);
Rect r = rect.Shifted(-data->size / 2).Intersection(Rect(s));
Simd::Fill(dst, 0);
::SimdDetectionPrepare(handle);
Parallel(r.top, r.bottom, [&](size_t thread, size_t begin, size_t end)
{
detect(handle, m.data, m.stride, r.left, begin, r.right, end, dst.data, dst.stride);
}, rect.Area() >= (data->Haar() ? 10000 : 30000) ? threadNumber : 1, throughColumn ? 2 : 1);
}
};
typedef std::vector<Hid> Hids;
struct Level
{
Hids hids;
double scale;
View src;
View roi;
View mask;
Rect rect;
View sum;
View sqsum;
View tilted;
View dst;
bool throughColumn;
bool needSqsum;
bool needTilted;
~Level()
{
for (size_t i = 0; i < hids.size(); ++i)
::SimdRelease(hids[i].handle);
}
};
typedef std::unique_ptr<Level> LevelPtr;
typedef std::vector<LevelPtr> LevelPtrs;
std::vector<Data> _data;
Size _imageSize;
bool _needNormalization;
ptrdiff_t _threadNumber;
LevelPtrs _levels;
bool InitLevels(double scaleFactor, const Size & sizeMin, const Size & sizeMax, const View & roi)
{
_needNormalization = false;
_levels.clear();
_levels.reserve(100);
double scale = 1.0;
do
{
std::vector<bool> inserts(_data.size(), false);
bool exit = true, insert = false;
for (size_t i = 0; i < _data.size(); ++i)
{
Size windowSize = _data[i].size * scale;
if (windowSize.x <= sizeMax.x && windowSize.y <= sizeMax.y &&
windowSize.x <= _imageSize.x && windowSize.y <= _imageSize.y)
{
if (windowSize.x >= sizeMin.x && windowSize.y >= sizeMin.y)
insert = inserts[i] = true;
exit = false;
}
}
if (exit)
break;
if (insert)
{
_levels.push_back(LevelPtr(new Level()));
Level & level = *_levels.back();
level.scale = scale;
level.throughColumn = scale <= 2.0;
Size scaledSize(_imageSize / scale);
level.src.Recreate(scaledSize, View::Gray8);
level.roi.Recreate(scaledSize, View::Gray8);
level.mask.Recreate(scaledSize, View::Gray8);
level.sum.Recreate(scaledSize + Size(1, 1), View::Int32);
level.sqsum.Recreate(scaledSize + Size(1, 1), View::Int32);
level.tilted.Recreate(scaledSize + Size(1, 1), View::Int32);
level.dst.Recreate(scaledSize, View::Gray8);
level.needSqsum = false, level.needTilted = false;
for (size_t i = 0; i < _data.size(); ++i)
{
if (!inserts[i])
continue;
Handle handle = ::SimdDetectionInit(_data[i].handle, level.sum.data, level.sum.stride, level.sum.width, level.sum.height,
level.sqsum.data, level.sqsum.stride, level.tilted.data, level.tilted.stride, level.throughColumn, _data[i].Int16());
if (handle)
{
Hid hid;
hid.handle = handle;
hid.data = &_data[i];
if (_data[i].Haar())
hid.detect = level.throughColumn ? ::SimdDetectionHaarDetect32fi : ::SimdDetectionHaarDetect32fp;
else
{
if (_data[i].Int16())
hid.detect = level.throughColumn ? ::SimdDetectionLbpDetect16ii : ::SimdDetectionLbpDetect16ip;
else
hid.detect = level.throughColumn ? ::SimdDetectionLbpDetect32fi : ::SimdDetectionLbpDetect32fp;
}
level.hids.push_back(hid);
}
else
return false;
level.needSqsum = level.needSqsum | _data[i].Haar();
level.needTilted = level.needTilted | _data[i].Tilted();
_needNormalization = _needNormalization | _data[i].Haar();
}
level.rect = Rect(level.roi.Size());
if (roi.format == View::None)
Simd::Fill(level.roi, 255);
else
{
Simd::ResizeBilinear(roi, level.roi);
Simd::Binarization(level.roi, 0, 255, 0, level.roi, SimdCompareGreater);
Simd::SegmentationShrinkRegion(level.roi, 255, level.rect);
}
}
scale *= scaleFactor;
} while (true);
return !_levels.empty();
}
void FillLevels(View src)
{
View gray;
if (src.format != View::Gray8)
{
gray.Recreate(src.Size(), View::Gray8);
Convert(src, gray);
src = gray;
}
Simd::ResizeBilinear(src, _levels[0]->src);
if (_needNormalization)
Simd::NormalizeHistogram(_levels[0]->src, _levels[0]->src);
EstimateIntegral(*_levels[0]);
for (size_t i = 1; i < _levels.size(); ++i)
{
Simd::ResizeBilinear(_levels[0]->src, _levels[i]->src);
EstimateIntegral(*_levels[i]);
}
}
void EstimateIntegral(Level & level)
{
if (level.needSqsum)
{
if (level.needTilted)
Simd::Integral(level.src, level.sum, level.sqsum, level.tilted);
else
Simd::Integral(level.src, level.sum, level.sqsum);
}
else
Simd::Integral(level.src, level.sum);
}
void FillMotionMask(const Rects & rects, Level & level, Rect & rect) const
{
Simd::Fill(level.mask, 0);
rect = Rect();
for (size_t i = 0; i < rects.size(); i++)
{
Rect r = rects[i] / level.scale;
rect |= r;
Simd::Fill(level.mask.Region(r).Ref(), 0xFF);
}
rect &= level.rect;
Simd::OperationBinary8u(level.mask, level.roi, level.mask, SimdOperationBinary8uAnd);
}
void AddObjects(Objects & objects, const View & dst, const Rect & rect, const Size & size, double scale, size_t step, Tag tag)
{
Size s = dst.Size() - size;
Rect r = rect.Shifted(-size / 2).Intersection(Rect(s));
for (ptrdiff_t row = r.top; row < r.bottom; row += step)
{
const uint8_t * mask = dst.data + row*dst.stride;
for (ptrdiff_t col = r.left; col < r.right; col += step)
{
if (mask[col] != 0)
objects.push_back(Object(Rect(col, row, col + size.x, row + size.y)*scale, 1, tag));
}
}
}
struct Similar
{
Similar(double sizeDifferenceMax)
: _sizeDifferenceMax(sizeDifferenceMax)
{}
SIMD_INLINE bool operator() (const Object & o1, const Object & o2) const
{
const Rect & r1 = o1.rect;
const Rect & r2 = o2.rect;
double delta = _sizeDifferenceMax*(std::min(r1.Width(), r2.Width()) + std::min(r1.Height(), r2.Height()))*0.5;
return
std::abs(r1.left - r2.left) <= delta && std::abs(r1.top - r2.top) <= delta &&
std::abs(r1.right - r2.right) <= delta && std::abs(r1.bottom - r2.bottom) <= delta;
}
private:
double _sizeDifferenceMax;
};
template<typename T> int Partition(const std::vector<T> & vec, std::vector<int> & labels, double sizeDifferenceMax)
{
Similar similar(sizeDifferenceMax);
int i, j, N = (int)vec.size();
const int PARENT = 0;
const int RANK = 1;
std::vector<int> _nodes(N * 2);
int(*nodes)[2] = (int(*)[2])&_nodes[0];
for (i = 0; i < N; i++)
{
nodes[i][PARENT] = -1;
nodes[i][RANK] = 0;
}
for (i = 0; i < N; i++)
{
int root = i;
while (nodes[root][PARENT] >= 0)
root = nodes[root][PARENT];
for (j = 0; j < N; j++)
{
if (i == j || !similar(vec[i], vec[j]))
continue;
int root2 = j;
while (nodes[root2][PARENT] >= 0)
root2 = nodes[root2][PARENT];
if (root2 != root)
{
int rank = nodes[root][RANK], rank2 = nodes[root2][RANK];
if (rank > rank2)
nodes[root2][PARENT] = root;
else
{
nodes[root][PARENT] = root2;
nodes[root2][RANK] += rank == rank2;
root = root2;
}
assert(nodes[root][PARENT] < 0);
int k = j, parent;
while ((parent = nodes[k][PARENT]) >= 0)
{
nodes[k][PARENT] = root;
k = parent;
}
k = i;
while ((parent = nodes[k][PARENT]) >= 0)
{
nodes[k][PARENT] = root;
k = parent;
}
}
}
}
labels.resize(N);
int nclasses = 0;
for (i = 0; i < N; i++)
{
int root = i;
while (nodes[root][PARENT] >= 0)
root = nodes[root][PARENT];
if (nodes[root][RANK] >= 0)
nodes[root][RANK] = ~nclasses++;
labels[i] = ~nodes[root][RANK];
}
return nclasses;
}
void GroupObjects(Objects & dst, const Objects & src, size_t groupSizeMin, double sizeDifferenceMax)
{
if (groupSizeMin == 0 || src.size() < groupSizeMin)
return;
std::vector<int> labels;
int nclasses = Partition(src, labels, sizeDifferenceMax);
Objects buffer;
buffer.resize(nclasses);
for (size_t i = 0; i < labels.size(); ++i)
{
int cls = labels[i];
buffer[cls].rect += src[i].rect;
buffer[cls].weight++;
buffer[cls].tag = src[i].tag;
}
for (size_t i = 0; i < buffer.size(); i++)
buffer[i].rect = buffer[i].rect / double(buffer[i].weight);
for (size_t i = 0; i < buffer.size(); i++)
{
Rect r1 = buffer[i].rect;
int n1 = buffer[i].weight;
if (n1 < (int)groupSizeMin)
continue;
size_t j;
for (j = 0; j < buffer.size(); j++)
{
int n2 = buffer[j].weight;
if (j == i || n2 < (int)groupSizeMin)
continue;
Rect r2 = buffer[j].rect;
int dx = Simd::Round(r2.Width() * sizeDifferenceMax);
int dy = Simd::Round(r2.Height() * sizeDifferenceMax);
if (i != j && (n2 > std::max(3, n1) || n1 < 3) &&
r1.left >= r2.left - dx && r1.top >= r2.top - dy &&
r1.right <= r2.right + dx && r1.bottom <= r2.bottom + dy)
break;
}
if (j == buffer.size())
dst.push_back(buffer[i]);
}
}
};
}
#endif//__SimdDetection_hpp__
| 27,224 | 7,781 |
#ifndef __KF_CLIENT_MODULE_H__
#define __KF_CLIENT_MODULE_H__
/************************************************************************
// @Module : tcp客户端
// @Author : __凌_痕__
// @QQ : 7969936
// @Mail : lori227@qq.com
// @Date : 2017-1-8
************************************************************************/
#include "KFrame.h"
#include "KFTcpClientInterface.h"
#include "KFMessage/KFMessageInterface.h"
#include "KFNetwork/KFNetClientEngine.hpp"
namespace KFrame
{
class KFTcpClientModule : public KFTcpClientInterface
{
public:
KFTcpClientModule() = default;
~KFTcpClientModule() = default;
// 初始化
virtual void InitModule();
// 逻辑
virtual void BeforeRun();
virtual void Run();
// 关闭
virtual void BeforeShut();
virtual void ShutDown();
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
// 添加客户端连接
virtual void StartClient( const KFNetData* netdata );
virtual void StartClient( const std::string& name, const std::string& type, uint64 id, const std::string& ip, uint32 port );
// 断开连接
virtual void CloseClient( uint64 serverid, const char* function, uint32 line );
/////////////////////////////////////////////////////////////////////////
// 发送消息
virtual void SendNetMessage( uint32 msgid, google::protobuf::Message* message, uint32 delay = 0 );
virtual bool SendNetMessage( uint64 serverid, uint32 msgid, google::protobuf::Message* message, uint32 delay = 0 );
virtual bool SendNetMessage( uint64 serverid, uint64 recvid, uint32 msgid, google::protobuf::Message* message, uint32 delay = 0 );
virtual void SendNetMessage( uint32 msgid, const char* data, uint32 length );
virtual bool SendNetMessage( uint64 serverid, uint32 msgid, const char* data, uint32 length );
virtual bool SendNetMessage( uint64 serverid, uint64 recvid, uint32 msgid, const char* data, uint32 length );
virtual void SendMessageToName( const std::string& servername, uint32 msgid, google::protobuf::Message* message );
virtual void SendMessageToName( const std::string& servername, uint32 msgid, const char* data, uint32 length );;
virtual void SendMessageToType( const std::string& servertype, uint32 msgid, google::protobuf::Message* message );
virtual void SendMessageToType( const std::string& servertype, uint32 msgid, const char* data, uint32 length );
virtual void SendMessageToServer( const std::string& servername, const std::string& servertype, uint32 msgid, google::protobuf::Message* message );
virtual void SendMessageToServer( const std::string& servername, const std::string& servertype, uint32 msgid, const char* data, uint32 length );
////////////////////////////////////////////////////////////////////////////////////////////////////////
protected:
// 客户端连接
__KF_NET_EVENT_FUNCTION__( OnClientConnected );
// 客户端断开
__KF_NET_EVENT_FUNCTION__( OnClientDisconnect );
// 客户端关闭
__KF_NET_EVENT_FUNCTION__( OnClientShutdown );
// 客户端连接失败
__KF_NET_EVENT_FUNCTION__( OnClientFailed );
// 注册回馈
__KF_MESSAGE_FUNCTION__( HandleRegisterAck );
private:
// 连接回调
void AddConnectionFunction( KFModule* module, KFNetEventFunction& function );
void RemoveConnectionFunction( KFModule* module );
void CallClientConnectionFunction( const KFNetData* netdata );
// 断线函数
virtual void AddLostFunction( KFModule* module, KFNetEventFunction& function );
void RemoveLostFunction( KFModule* module );
void CallClientLostFunction( const KFNetData* netdata );
// 添加关闭函数
virtual void AddShutdownFunction( KFModule* module, KFNetEventFunction& function );
virtual void RemoveShutdownFunction( KFModule* module );
void CallClientShutdownFunction( const KFNetData* netdata );
// 添加失败函数
virtual void AddFailedFunction( KFModule* module, KFNetEventFunction& function );
virtual void RemoveFailedFunction( KFModule* module );
void CallClientFailedFunction( const KFNetData* netdata );
// 转发函数
virtual void AddTranspondFunction( KFModule* module, KFTranspondFunction& function );
virtual void RemoveTranspondFunction( KFModule* module );
////////////////////////////////////////////////////////////////
// 处理客户端消息
void HandleNetMessage( const Route& route, uint32 msgid, const char* data, uint32 length );
// 是否连接自己
bool IsSelfConnection( const std::string& name, const std::string& type, uint64 id );
public:
// 客户端引擎
KFNetClientEngine* _client_engine = nullptr;
// 转发函数
KFTranspondFunction _kf_transpond_function = nullptr;
// 注册成功回调函数
KFFunctionMap< KFModule*, KFModule*, KFNetEventFunction > _kf_connection_function;
// 客户端掉线
KFFunctionMap< KFModule*, KFModule*, KFNetEventFunction > _kf_lost_function;
// 客户端关闭
KFFunctionMap< KFModule*, KFModule*, KFNetEventFunction > _kf_shutdown_function;
// 客户端失败
KFFunctionMap< KFModule*, KFModule*, KFNetEventFunction > _kf_failed_function;
};
}
#endif | 5,499 | 1,683 |
/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <QCoreApplication>
#include <Components/Slots/Execution/ExecutionSlotLayoutComponent.h>
#include <Components/Slots/Execution/ExecutionSlotConnectionPin.h>
namespace GraphCanvas
{
////////////////////////
// ExecutionSlotLayout
////////////////////////
ExecutionSlotLayout::ExecutionSlotLayout(ExecutionSlotLayoutComponent& owner)
: m_connectionType(ConnectionType::CT_Invalid)
, m_owner(owner)
, m_textDecoration(nullptr)
{
setInstantInvalidatePropagation(true);
setOrientation(Qt::Horizontal);
m_slotConnectionPin = aznew ExecutionSlotConnectionPin(owner.GetEntityId());
m_slotText = aznew GraphCanvasLabel();
}
ExecutionSlotLayout::~ExecutionSlotLayout()
{
}
void ExecutionSlotLayout::Activate()
{
SceneMemberNotificationBus::Handler::BusConnect(m_owner.GetEntityId());
SlotNotificationBus::Handler::BusConnect(m_owner.GetEntityId());
StyleNotificationBus::Handler::BusConnect(m_owner.GetEntityId());
m_slotConnectionPin->Activate();
}
void ExecutionSlotLayout::Deactivate()
{
m_slotConnectionPin->Deactivate();
SceneMemberNotificationBus::Handler::BusDisconnect();
SlotNotificationBus::Handler::BusDisconnect();
StyleNotificationBus::Handler::BusDisconnect();
}
void ExecutionSlotLayout::OnSceneSet(const AZ::EntityId&)
{
SlotRequests* slotRequests = SlotRequestBus::FindFirstHandler(m_owner.GetEntityId());
if (slotRequests)
{
m_connectionType = slotRequests->GetConnectionType();
m_slotText->SetLabel(slotRequests->GetName());
OnTooltipChanged(slotRequests->GetTooltip());
const SlotConfiguration& configuration = slotRequests->GetSlotConfiguration();
if (!configuration.m_textDecoration.empty())
{
SetTextDecoration(configuration.m_textDecoration, configuration.m_textDecorationToolTip);
}
}
UpdateLayout();
OnStyleChanged();
}
void ExecutionSlotLayout::OnSceneReady()
{
OnStyleChanged();
}
void ExecutionSlotLayout::OnRegisteredToNode(const AZ::EntityId& /*nodeId*/)
{
OnStyleChanged();
}
void ExecutionSlotLayout::OnNameChanged(const AZStd::string& name)
{
m_slotText->SetLabel(name);
}
void ExecutionSlotLayout::OnTooltipChanged(const AZStd::string& tooltip)
{
m_slotConnectionPin->setToolTip(tooltip.c_str());
m_slotText->setToolTip(tooltip.c_str());
}
void ExecutionSlotLayout::OnStyleChanged()
{
m_style.SetStyle(m_owner.GetEntityId());
ApplyTextStyle(m_slotText);
if (m_textDecoration)
{
ApplyTextStyle(m_textDecoration);
}
m_slotConnectionPin->RefreshStyle();
qreal padding = m_style.GetAttribute(Styling::Attribute::Padding, 2.);
setContentsMargins(padding, padding, padding, padding);
setSpacing(m_style.GetAttribute(Styling::Attribute::Spacing, 2.));
UpdateGeometry();
}
void ExecutionSlotLayout::SetTextDecoration(const AZStd::string& textDecoration, const AZStd::string& toolTip)
{
if (m_textDecoration)
{
delete m_textDecoration;
m_textDecoration = nullptr;
}
if (!textDecoration.empty())
{
m_textDecoration = new GraphCanvasLabel();
m_textDecoration->SetLabel(textDecoration);
m_textDecoration->setToolTip(toolTip.c_str());
ApplyTextStyle(m_textDecoration);
}
}
void ExecutionSlotLayout::ClearTextDecoration()
{
delete m_textDecoration;
m_textDecoration = nullptr;
}
void ExecutionSlotLayout::ApplyTextStyle(GraphCanvasLabel* graphCanvasLabel)
{
switch (m_connectionType)
{
case ConnectionType::CT_Input:
graphCanvasLabel->SetStyle(m_owner.GetEntityId(), ".inputSlotName");
break;
case ConnectionType::CT_Output:
graphCanvasLabel->SetStyle(m_owner.GetEntityId(), ".outputSlotName");
break;
default:
graphCanvasLabel->SetStyle(m_owner.GetEntityId(), ".slotName");
break;
};
}
void ExecutionSlotLayout::UpdateLayout()
{
for (int i = count() - 1; i >= 0; --i)
{
removeAt(i);
}
switch (m_connectionType)
{
case ConnectionType::CT_Input:
addItem(m_slotConnectionPin);
setAlignment(m_slotConnectionPin, Qt::AlignLeft);
addItem(m_slotText);
setAlignment(m_slotText, Qt::AlignLeft);
if (m_textDecoration)
{
addItem(m_textDecoration);
setAlignment(m_textDecoration, Qt::AlignLeft);
}
break;
case ConnectionType::CT_Output:
if (m_textDecoration)
{
addItem(m_textDecoration);
setAlignment(m_textDecoration, Qt::AlignRight);
}
addItem(m_slotText);
setAlignment(m_slotText, Qt::AlignRight);
addItem(m_slotConnectionPin);
setAlignment(m_slotConnectionPin, Qt::AlignRight);
break;
default:
if (m_textDecoration)
{
addItem(m_textDecoration);
}
addItem(m_slotConnectionPin);
addItem(m_slotText);
break;
}
}
void ExecutionSlotLayout::UpdateGeometry()
{
m_slotConnectionPin->updateGeometry();
m_slotText->update();
invalidate();
updateGeometry();
}
/////////////////////////////////
// ExecutionSlotLayoutComponent
/////////////////////////////////
void ExecutionSlotLayoutComponent::Reflect(AZ::ReflectContext* reflectContext)
{
AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(reflectContext);
if (serializeContext)
{
serializeContext->Class<ExecutionSlotLayoutComponent, AZ::Component>()
->Version(1)
;
}
}
ExecutionSlotLayoutComponent::ExecutionSlotLayoutComponent()
: m_layout(nullptr)
{
}
void ExecutionSlotLayoutComponent::Init()
{
SlotLayoutComponent::Init();
m_layout = aznew ExecutionSlotLayout((*this));
SetLayout(m_layout);
}
void ExecutionSlotLayoutComponent::Activate()
{
SlotLayoutComponent::Activate();
m_layout->Activate();
}
void ExecutionSlotLayoutComponent::Deactivate()
{
SlotLayoutComponent::Deactivate();
m_layout->Deactivate();
}
}
| 7,084 | 2,090 |
/*
* See header file for a description of this class.
*
* \author Paolo Ronchese INFN Padova
*
*/
//-----------------------
// This Class' Header --
//-----------------------
#include "HeavyFlavorAnalysis/RecoDecay/interface/BPHKinematicFit.h"
//-------------------------------
// Collaborating Class Headers --
//-------------------------------
#include "HeavyFlavorAnalysis/RecoDecay/interface/BPHRecoCandidate.h"
#include "RecoVertex/KinematicFitPrimitives/interface/KinematicParticleFactoryFromTransientTrack.h"
#include "RecoVertex/KinematicFitPrimitives/interface/RefCountedKinematicParticle.h"
#include "RecoVertex/KinematicFit/interface/KinematicParticleVertexFitter.h"
#include "RecoVertex/KinematicFit/interface/KinematicConstrainedVertexFitter.h"
#include "RecoVertex/KinematicFit/interface/KinematicParticleFitter.h"
#include "RecoVertex/KinematicFit/interface/MassKinematicConstraint.h"
#include "RecoVertex/KinematicFit/interface/TwoTrackMassKinematicConstraint.h"
#include "RecoVertex/KinematicFit/interface/MultiTrackMassKinematicConstraint.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
//---------------
// C++ Headers --
//---------------
#include <iostream>
using namespace std;
//-------------------
// Initializations --
//-------------------
//----------------
// Constructors --
//----------------
BPHKinematicFit::BPHKinematicFit():
BPHDecayVertex( 0 ),
massConst( -1.0 ),
massSigma( -1.0 ),
oldKPs( true ),
oldFit( true ),
oldMom( true ),
kinTree( 0 ) {
}
BPHKinematicFit::BPHKinematicFit( const BPHKinematicFit* ptr ):
BPHDecayVertex( ptr, 0 ),
massConst( -1.0 ),
massSigma( -1.0 ),
oldKPs( true ),
oldFit( true ),
oldMom( true ),
kinTree( 0 ) {
map<const reco::Candidate*,const reco::Candidate*> iMap;
const vector<const reco::Candidate*>& daug = daughters();
const vector<Component>& list = ptr->componentList();
int i;
int n = daug.size();
for ( i = 0; i < n; ++i ) {
const reco::Candidate* cand = daug[i];
iMap[originalReco( cand )] = cand;
}
for ( i = 0; i < n; ++i ) {
const Component& c = list[i];
dMSig[iMap[c.cand]] = c.msig;
}
const vector<BPHRecoConstCandPtr>& dComp = daughComp();
int j;
int m = dComp.size();
for ( j = 0; j < m; ++j ) {
const map<const reco::Candidate*,double>& dMap = dComp[j]->dMSig;
dMSig.insert( dMap.begin(), dMap.end() );
}
}
//--------------
// Destructor --
//--------------
BPHKinematicFit::~BPHKinematicFit() {
}
//--------------
// Operations --
//--------------
void BPHKinematicFit::setConstraint( double mass, double sigma ) {
oldFit = oldMom = true;
massConst = mass;
massSigma = sigma;
return;
}
double BPHKinematicFit::constrMass() const {
return massConst;
}
double BPHKinematicFit::constrSigma() const {
return massSigma;
}
const vector<RefCountedKinematicParticle>& BPHKinematicFit::kinParticles()
const {
if ( oldKPs ) buildParticles();
return allParticles;
}
vector<RefCountedKinematicParticle> BPHKinematicFit::kinParticles(
const vector<string>& names ) const {
if ( oldKPs ) buildParticles();
const vector<const reco::Candidate*>& daugs = daughFull();
vector<RefCountedKinematicParticle> plist;
if ( allParticles.size() != daugs.size() ) return plist;
set<RefCountedKinematicParticle> pset;
int i;
int n = names.size();
int m = daugs.size();
plist.reserve( m );
for ( i = 0; i < n; ++i ) {
const string& pname = names[i];
if ( pname == "*" ) {
int j = m;
while ( j-- ) {
RefCountedKinematicParticle& kp = allParticles[j];
if ( pset.find( kp ) != pset.end() ) continue;
plist.push_back( kp );
pset .insert ( kp );
}
break;
}
map<const reco::Candidate*,
RefCountedKinematicParticle>::const_iterator iter = kinMap.find(
getDaug( pname ) );
map<const reco::Candidate*,
RefCountedKinematicParticle>::const_iterator iend = kinMap.end();
if ( iter != iend ) {
const RefCountedKinematicParticle& kp = iter->second;
if ( pset.find( kp ) != pset.end() ) continue;
plist.push_back( kp );
pset .insert ( kp );
}
else {
edm::LogPrint( "ParticleNotFound" )
<< "BPHKinematicFit::kinParticles: "
<< pname << " not found";
}
}
return plist;
}
const RefCountedKinematicTree& BPHKinematicFit::kinematicTree() const {
if ( oldFit ) return kinematicTree( "", massConst, massSigma );
return kinTree;
}
const RefCountedKinematicTree& BPHKinematicFit::kinematicTree(
const string& name,
double mass, double sigma ) const {
if ( sigma < 0 ) return kinematicTree( name, mass );
ParticleMass mc = mass;
MassKinematicConstraint kinConst( mc, sigma );
return kinematicTree( name, &kinConst );
}
const RefCountedKinematicTree& BPHKinematicFit::kinematicTree(
const string& name,
double mass ) const {
if ( mass < 0 ) {
kinTree = RefCountedKinematicTree( 0 );
oldFit = false;
return kinTree;
}
int nn = daughFull().size();
ParticleMass mc = mass;
if ( nn == 2 ) {
TwoTrackMassKinematicConstraint kinConst( mc );
return kinematicTree( name, &kinConst );
}
else {
MultiTrackMassKinematicConstraint kinConst( mc, nn );
return kinematicTree( name, &kinConst );
}
}
const RefCountedKinematicTree& BPHKinematicFit::kinematicTree(
const string& name,
KinematicConstraint* kc ) const {
kinTree = RefCountedKinematicTree( 0 );
oldFit = false;
kinParticles();
if ( allParticles.size() != daughFull().size() ) return kinTree;
vector<RefCountedKinematicParticle> kComp;
vector<RefCountedKinematicParticle> kTail;
if ( name != "" ) {
const BPHRecoCandidate* comp = getComp( name ).get();
if ( comp == 0 ) {
edm::LogPrint( "ParticleNotFound" )
<< "BPHKinematicFit::kinematicTree: "
<< name << " daughter not found";
return kinTree;
}
const vector<string>& names = comp->daugNames();
int ns;
int nn = ns = names.size();
vector<string> nfull( nn + 1 );
nfull[nn] = "*";
while ( nn-- ) nfull[nn] = name + "/" + names[nn];
vector<RefCountedKinematicParticle> kPart = kinParticles( nfull );
vector<RefCountedKinematicParticle>::const_iterator iter = kPart.begin();
vector<RefCountedKinematicParticle>::const_iterator imid = iter + ns;
vector<RefCountedKinematicParticle>::const_iterator iend = kPart.end();
kComp.insert( kComp.end(), iter, imid );
kTail.insert( kTail.end(), imid, iend );
}
else {
kComp = allParticles;
}
try {
KinematicParticleVertexFitter vtxFitter;
RefCountedKinematicTree compTree = vtxFitter.fit( kComp );
if ( compTree->isEmpty() ) return kinTree;
KinematicParticleFitter kinFitter;
compTree = kinFitter.fit( kc, compTree );
if ( compTree->isEmpty() ) return kinTree;
compTree->movePointerToTheTop();
if ( kTail.size() ) {
RefCountedKinematicParticle compPart = compTree->currentParticle();
if ( !compPart->currentState().isValid() ) return kinTree;
kTail.push_back( compPart );
kinTree = vtxFitter.fit( kTail );
}
else {
kinTree = compTree;
}
}
catch ( std::exception e ) {
edm::LogPrint( "FitFailed" )
<< "BPHKinematicFit::kinematicTree: "
<< "kin fit reset";
kinTree = RefCountedKinematicTree( 0 );
}
return kinTree;
}
const RefCountedKinematicTree& BPHKinematicFit::kinematicTree(
const string& name,
MultiTrackKinematicConstraint* kc ) const {
kinTree = RefCountedKinematicTree( 0 );
oldFit = false;
kinParticles();
if ( allParticles.size() != daughFull().size() ) return kinTree;
vector<string> nfull;
if ( name != "" ) {
const BPHRecoCandidate* comp = getComp( name ).get();
if ( comp == 0 ) {
edm::LogPrint( "ParticleNotFound" )
<< "BPHKinematicFit::kinematicTree: "
<< name << " daughter not found";
return kinTree;
}
const vector<string>& names = comp->daugNames();
int nn = names.size();
nfull.resize( nn + 1 );
nfull[nn] = "*";
while ( nn-- ) nfull[nn] = name + "/" + names[nn];
}
else {
nfull.push_back( "*" );
}
try {
KinematicConstrainedVertexFitter cvf;
kinTree = cvf.fit( kinParticles( nfull ), kc );
}
catch ( std::exception e ) {
edm::LogPrint( "FitFailed" )
<< "BPHKinematicFit::kinematicTree: "
<< "kin fit reset";
kinTree = RefCountedKinematicTree( 0 );
}
return kinTree;
}
void BPHKinematicFit::resetKinematicFit() const {
oldKPs = oldFit = oldMom = true;
return;
}
bool BPHKinematicFit::isEmpty() const {
kinematicTree();
if ( kinTree.get() == 0 ) return true;
return kinTree->isEmpty();
}
bool BPHKinematicFit::isValidFit() const {
const RefCountedKinematicParticle kPart = currentParticle();
if ( kPart.get() == 0 ) return false;
return kPart->currentState().isValid();
}
const RefCountedKinematicParticle BPHKinematicFit::currentParticle() const {
if ( isEmpty() ) return RefCountedKinematicParticle( 0 );
return kinTree->currentParticle();
}
const RefCountedKinematicVertex BPHKinematicFit::currentDecayVertex() const {
if ( isEmpty() ) return RefCountedKinematicVertex( 0 );
return kinTree->currentDecayVertex();
}
ParticleMass BPHKinematicFit::mass() const {
const RefCountedKinematicParticle kPart = currentParticle();
if ( kPart.get() == 0 ) return -1.0;
const KinematicState kStat = kPart->currentState();
if ( kStat.isValid() ) return kStat.mass();
return -1.0;
}
const math::XYZTLorentzVector& BPHKinematicFit::p4() const {
if ( oldMom ) fitMomentum();
return totalMomentum;
}
void BPHKinematicFit::addK( const string& name,
const reco::Candidate* daug,
double mass, double sigma ) {
addK( name, daug, "cfhpmig", mass, sigma );
return;
}
void BPHKinematicFit::addK( const string& name,
const reco::Candidate* daug,
const string& searchList,
double mass, double sigma ) {
addV( name, daug, searchList, mass );
dMSig[daughters().back()] = sigma;
return;
}
void BPHKinematicFit::addK( const string& name,
const BPHRecoConstCandPtr& comp ) {
addV( name, comp );
const map<const reco::Candidate*,double>& dMap = comp->dMSig;
dMSig.insert( dMap.begin(), dMap.end() );
return;
}
void BPHKinematicFit::setNotUpdated() const {
BPHDecayVertex::setNotUpdated();
resetKinematicFit();
return;
}
void BPHKinematicFit::buildParticles() const {
kinMap.clear();
allParticles.clear();
const vector<const reco::Candidate*>& daug = daughFull();
KinematicParticleFactoryFromTransientTrack pFactory;
int n = daug.size();
allParticles.reserve( n );
float chi = 0.0;
float ndf = 0.0;
while ( n-- ) {
const reco::Candidate* cand = daug[n];
ParticleMass mass = cand->mass();
float sigma = dMSig.find( cand )->second;
if ( sigma < 0 ) sigma = 1.0e-7;
reco::TransientTrack* tt = getTransientTrack( cand );
if ( tt != 0 ) allParticles.push_back( kinMap[cand] =
pFactory.particle( *tt,
mass, chi, ndf, sigma ) );
}
oldKPs = false;
return;
}
void BPHKinematicFit::fitMomentum() const {
if ( isValidFit() ) {
const KinematicState& ks = currentParticle()->currentState();
GlobalVector tm = ks.globalMomentum();
double x = tm.x();
double y = tm.y();
double z = tm.z();
double m = ks.mass();
double e = sqrt( ( x * x ) + ( y * y ) + ( z * z ) + ( m * m ) );
totalMomentum.SetPxPyPzE( x, y, z, e );
}
else {
edm::LogPrint( "FitNotFound" )
<< "BPHKinematicFit::fitMomentum: "
<< "simple momentum sum computed";
math::XYZTLorentzVector tm;
const vector<const reco::Candidate*>& daug = daughters();
int n = daug.size();
while ( n-- ) tm += daug[n]->p4();
const vector<BPHRecoConstCandPtr>& comp = daughComp();
int m = comp.size();
while ( m-- ) tm += comp[m]->p4();
totalMomentum = tm;
}
oldMom = false;
return;
}
| 12,684 | 4,419 |
#ifndef TNT_PCG_RANDOM_HPP
#define TNT_PCG_RANDOM_HPP
#include <concepts>
#include "core/Config.hpp"
#include "math/Vector.hpp"
// TODO:
// randomColor, etc.
// constexpr halton*
namespace tnt
{
/// @brief Get a random float on range @c [min_,max_].
/// @param min_ The minimum value of the float.
/// @param max_ The maximum value of the float.
/// @return float
TNT_API float randomFloat(float min_, float max_);
/// @brief Get a random int on range @c [min_,max_].
/// @param min_ The minimum value of the int.
/// @param max_ The maximum value of the int.
/// @return int
TNT_API int randomInt(int min_, int max_);
/// @brief Get a tnt::Vector with randomly generated coordinates.
/// @param minX The minimum value of the x coordinate.
/// @param maxX The maximum value of the x coordinate.
/// @param minY The minimum value of the y coordinate.
/// @param maxY The maximum value of the y coordinate.
/// @return @ref tnt::Vector
TNT_API Vector randomVector(float minX, float maxX, float minY, float maxY);
/// @brief Create a randomly generated Vector with magnitude 1.
/// @return @ref tnt::Vector
TNT_API Vector randomUnitVector();
/// @brief Generate a random number using a Halton sequence.
template <std::integral I>
inline auto halton1(I const base, I index) noexcept
{
I result{0};
for (I denom{1}; index > 0; index = floor(index / base))
{
denom *= base;
result += (index % base) / denom;
}
return result;
}
/// @brief Generate a random Vector using Halton sequences.
template <std::integral I>
inline Vector halton2(I const baseX, I const baseY, I index) noexcept
{
return {(float)halton1<I>(baseX, index), (float)halton1<I>(baseY, index)};
}
} // namespace tnt
#endif //!TNT_PCG_RANDOM_HPP | 1,906 | 611 |
/*
See the header file for detailed explanations
of the below functions.
*/
#include "range_based_tunnel_localizer.hh"
RangeBasedTunnelLocalizer::RangeBasedTunnelLocalizer(int max_iter, double yz_tol, double yaw_tol){
_cloud = pcl::PointCloud<pcl::PointXYZ>().makeShared();
_cloud_aligned = pcl::PointCloud<pcl::PointXYZ>().makeShared();
_max_iters = max_iter;
_yz_tol = yz_tol;
_yaw_tol = yaw_tol;
}
bool RangeBasedTunnelLocalizer::_reset(){
_cloud->points.clear();
_cloud_aligned->points.clear();
_num_laser_pushes = 0;
_num_rgbd_pushes = 0;
_fim = Eigen::Matrix6d::Zero();
return true;
}
bool RangeBasedTunnelLocalizer::set_map(const pcl::PointCloud<pcl::PointXYZ>::Ptr &map){
// ### This will cause memory leak!!!
_octree = new pcl::octree::OctreePointCloudSearch<pcl::PointXYZ>(0.05);
_octree->setInputCloud(map);
_octree->addPointsFromInputCloud();
return true;
}
bool RangeBasedTunnelLocalizer::push_laser_data(const LaserProc &laser_proc, bool clean_start){
const vector<int> &mask = laser_proc.get_mask();
const vector<Eigen::Vector3d> &_3d_pts = laser_proc.get_3d_points();
if(clean_start == true)
_reset();
// Reserve required space to prevent repetitive memory allocation
_cloud->points.reserve(_cloud->points.size() + mask.size());
for(int i = 0 ; i < (int)mask.size() ; i++){
if(mask[i] <= 0)
continue;
_cloud->points.push_back(pcl::PointXYZ(_3d_pts[i](0), _3d_pts[i](1), _3d_pts[i](2)));
}
// Accumulate information due to the laser scanner onto the _fim matrix.
// Each additional information is in the body frame. In the 'get_covariance(...)'
// function (if points have to been registered) this is projected onto the world
// frame.
Eigen::Matrix3d fim_xyz = Eigen::Matrix3d::Zero(); // Fisher information for x, y, z coords.
Eigen::Matrix3d dcm = laser_proc.get_calib_params().relative_pose.topLeftCorner<3, 3>(); // Rotation matrix
Eigen::Matrix3d fim_xyp; // Fisher information for x, y, yaw
double fi_p = 0; // Fisher information for yaw only (neglecting correlative information)
fim_xyp = laser_proc.get_fim();
//cout << "fim_xyp = " << fim_xyp << endl;
fim_xyz.topLeftCorner<2, 2>() = fim_xyp.topLeftCorner<2, 2>();
fim_xyz = dcm * fim_xyz * dcm.transpose();
fi_p = fabs(fim_xyp(2, 2)) * fabs(dcm(2, 2));
//cout << "dcm = [" << dcm << "];" << endl;
// Here we use the ypr convention for compatibility with the 'quadrotor_ukf_lite' node.
_fim.block<3, 3>(0, 0) += fim_xyz;
_fim(3, 3) += fi_p;
//cout << "_fim = [" << _fim << "];" << endl;
return true;
}
bool RangeBasedTunnelLocalizer::push_laser_data(const Eigen::Matrix4d &rel_pose, const sensor_msgs::LaserScan &data, const vector<char> &mask, char cluster_id, bool clean_start){
// ### This still does not incorporate the color information
ASSERT(mask.size() == 0 || data.ranges.size() == mask.size(), "mask and data size should be the same.");
ASSERT(cluster_id != 0, "Cluster \"0\" is reserved.");
if(clean_start == true)
_reset();
// Reserve required space to prevent repetitive memory allocation
_cloud->points.reserve(_cloud->points.size() + data.ranges.size());
Eigen::Vector4d pt;
double th = data.angle_min;
for(int i = 0 ; i < (int)data.ranges.size() ; i++, th += data.angle_increment){
if(mask.size() != 0 && mask[i] != cluster_id)
continue;
utils::laser::polar2euclidean(data.ranges[i], th, pt(0), pt(1));
pt(2) = pt(3) = 0;
pt = rel_pose * pt;
_cloud->points.push_back(pcl::PointXYZ(pt(0), pt(1), pt(2)));
}
// Accumulate information due to the laser scanner onto the _fim matrix.
// Each additional information is in the body frame. In the 'get_covariance(...)'
// function (if points have to been registered) this is projected onto the world
// frame.
Eigen::Matrix3d fim_xyz = Eigen::Matrix3d::Zero(); // Fisher information for x, y, z coords.
Eigen::Matrix3d dcm = rel_pose.topLeftCorner<3, 3>(); // Rotation matrix
Eigen::Matrix3d fim_xyp; // Fisher information for x, y, yaw
double fi_p = 0; // Fisher information for yaw only (neglecting correlative information)
utils::laser::get_fim(data, mask, fim_xyp, cluster_id);
fim_xyz.topLeftCorner<2, 2>() = fim_xyp.topLeftCorner<2, 2>();
fim_xyz = dcm.transpose() * fim_xyz * dcm;
fi_p = fim_xyp(2, 2) * dcm(2, 2);
// Here we use the ypr convention for compatibility with the 'quadrotor_ukf_lite' node.
_fim.block<3, 3>(0, 0) += fim_xyz;
_fim(3, 3) += fi_p;
_num_laser_pushes++;
return true;
}
bool RangeBasedTunnelLocalizer::push_rgbd_data(const Eigen::Matrix4d &rel_pose, const sensor_msgs::PointCloud2 &data, const vector<char> &mask, char cluster_id, bool clean_start){
// ### This still does not incorporate the color information
ASSERT(mask.size() == 0 || data.data.size() == mask.size(), "mask and data size should be the same.");
ASSERT(cluster_id != 0, "Cluster \"0\" is reserved.");
if(clean_start == true)
_reset();
// Reserve required space to prevent repetitive memory allocation
_cloud->points.reserve(_cloud->points.size() + data.data.size());
Eigen::Vector4d pt;
ROS_WARN("\"push_rgbd_data(...)\" is not implemented yet!");
for(int i = 0 ; i < (int)data.data.size() ; i++){
if(mask.size() != 0 || mask[i] == false)
continue;
// ### To be implemented!
}
_num_rgbd_pushes++;
return true;
}
int RangeBasedTunnelLocalizer::estimate_pose(const Eigen::Matrix4d &init_pose, double heading){
// ### This will cause memory leak!!!
_cloud_aligned = pcl::PointCloud<pcl::PointXYZ>().makeShared();
// Initialize '_cloud_aligned' by transforming the collective point cloud
// with the initial pose.
pcl::transformPointCloud(*_cloud, *_cloud_aligned, init_pose);
// Steps :
// (1) - For each ray, find the point of intersection. Use ray-casting of PCL-Octree
// (2) - Prepare the matrix A and vector b s.t. A*x = b
// (3) - Solve for A*x = b where x = [cos(th) sin(th), dy, dz]'.
// (4) - Repeat for _max_iter's or tolerance conditions are met
// (*) - Use weighing to eliminate outliers.
int num_pts = _cloud_aligned->points.size();
int num_valid_pts = 0; // # of data points intersecting with the map.
double dTz = 0; // update along the z-coordinate.
Eigen::MatrixXd A(num_pts, 3);
Eigen::VectorXd b(num_pts);
Eigen::Vector3d x, rpy; // solution to Ax=b,
// roll-pitch-yaw
Eigen::Vector3f pos; // initial position of the robot.
// This is given as argument to ray-caster.
Eigen::Vector3f ray;
Eigen::Vector3d res_vec;
Eigen::Matrix4d curr_pose = init_pose; // 'current' pose after each iteration.
// container for ray-casting results :
pcl::octree::OctreePointCloudSearch<pcl::PointXYZ>::AlignedPointTVector voxel_centers;
pos = curr_pose.topRightCorner<3, 1>().cast<float>();
_matched_map_pts.resize(num_pts);
int iter;
for(iter = 0 ; iter < _max_iters ; iter++){
//cout << "projection pos = " << pos << endl;
num_valid_pts = 0;
_fitness_scores[0] = _fitness_scores[1] = _fitness_scores[2] = 0;
for(int i = 0 ; i < num_pts ; i++){
// Get the ray in the body frame ()
ray(0) = _cloud_aligned->points[i].x - pos(0);
ray(1) = _cloud_aligned->points[i].y - pos(1);
ray(2) = _cloud_aligned->points[i].z - pos(2);
A(i, 0) = ray(1);
A(i, 1) = -ray(0);
A(i, 2) = 1;
// Fetch only the first intersection point
_octree->getIntersectedVoxelCenters(pos, ray, voxel_centers , 1);
// If there is no intersection, nullify the effect by zero'ing the corresponding equation
if(voxel_centers.size() == 0){
A.block<1, 3>(i, 0) *= 0;
b(i) = 0;
_matched_map_pts[i].x =
_matched_map_pts[i].y =
_matched_map_pts[i].z = std::numeric_limits<float>::infinity();
} else {
// Save the matched point
_matched_map_pts[i] = voxel_centers[0];
// Use only the y-comp of the residual vector. Because
// this is going to contribute to y and yaw updates only.
b(i) = voxel_centers[0].y - pos(1);
// Get the residual vector
res_vec(0) = _cloud_aligned->points[i].x - voxel_centers[0].x;
res_vec(1) = _cloud_aligned->points[i].y - voxel_centers[0].y;
res_vec(2) = _cloud_aligned->points[i].z - voxel_centers[0].z;
// Update the delta-z-estimate according to the direction of the
// corresponding ray's z component. The update factor is weighed using
// ML outlier elimination.
dTz += -res_vec(2) * (exp(fabs(ray(2) / ray.norm())) - 1);
// Calculate a weighing coefficent for ML outlier elimination
// regarding y-yaw DOFs
double weight = exp(-pow(res_vec.squaredNorm(), 1.5));
b(i) *= weight;
A.block<1, 3>(i, 0) *= weight;
num_valid_pts++;
_fitness_scores[0] += res_vec[1] * res_vec[1];
_fitness_scores[1] += res_vec[2] * res_vec[2];
_fitness_scores[2] += res_vec[1] * res_vec[1] * ray(0) * ray(0);
}
}
// ####
/*
if(num_valid_pts < 100){
continue;
}
*/
/*
cout << "heading = " << heading << endl;
cout << "A = " << A << endl;
cout << "b = " << b << endl;
*/
// Solve for the least squares solution.
x = (A.transpose() * A).inverse() * A.transpose() * b;
// Get the mean of dTz since it has been accumulated
dTz /= num_valid_pts;
_fitness_scores[0] /= num_valid_pts;
_fitness_scores[1] /= num_valid_pts;
_fitness_scores[2] /= num_valid_pts;
// x = [cos(yaw) sin(yaw) dY]
x(0) = fabs(x(0)) > 1 ? x(0) / fabs(x(0)) : x(0);
double dyaw = -1.2 * atan2(x(1), x(0));
// Update the position
pos(1) += x(2); // y-update
pos(2) += dTz; // z-update
// Convert the orientation to 'rpy', update yaw and
// convert back to dcm.
Eigen::Matrix3d dcm = curr_pose.topLeftCorner<3, 3>();
rpy = utils::trans::dcm2rpy(dcm);
rpy(2) += dyaw;
//rpy(2) = heading; //####
dcm = utils::trans::rpy2dcm(rpy);
// Update the global pose matrix.
curr_pose.topLeftCorner(3, 3) = dcm;
curr_pose(1, 3) = pos(1);
curr_pose(2, 3) = pos(2);
// Transform points for next iteration.
pcl::transformPointCloud(*_cloud, *_cloud_aligned, curr_pose);
if(fabs(x(2)) < _yz_tol && fabs(dTz) < _yz_tol && fabs(dyaw) < _yaw_tol)
break;
}
_pose = curr_pose;
return iter;
}
bool RangeBasedTunnelLocalizer::get_pose(Eigen::Matrix4d &pose){
pose = _pose.cast<double>();
return true;
}
bool RangeBasedTunnelLocalizer::get_registered_pointcloud(pcl::PointCloud<pcl::PointXYZ>::Ptr &pc){
pc = _cloud_aligned;
return true;
}
bool RangeBasedTunnelLocalizer::get_covariance(Eigen::Matrix6d &cov, bool apply_fitness_result){
// ### I have to find a way to project uncertainties in orientation
// to other frame sets.
// ### I might have to fix some elements before inverting
Eigen::EigenSolver<Eigen::Matrix6d> es;
es.compute(_fim, true);
Eigen::MatrixXd D = es.eigenvalues().real().asDiagonal();
Eigen::MatrixXd V = es.eigenvectors().real();
bool reconstruct = false;
for(int i = 0 ; i < 6 ; i++)
if(D(i, i) < 0.00001){
D(i, i) = 0.00001;
reconstruct = true;
}
if(reconstruct)
_fim = (V.transpose() * D * V).real();
//cout << "FIM = [" << _fim << "];" << endl;
// ### This assumes uniform covariance for each rays, and superficially
// handles the uncertainties. I should first run ICP and then
// find '_fim' and so on. This will require a lot of bookkeeping etc.
// Thus leaving to a later version :)
if(apply_fitness_result){
// ### Is the rotation ypr/rpy ???
// We assume that 0.001 m^2 variance is perfect fit, or unit information.
D(0, 0) /= exp(_fitness_scores[0] / 0.001);
D(1, 1) /= exp(_fitness_scores[1] / 0.001);
D(2, 2) /= exp(_fitness_scores[2] / 0.001);
}
for(int i = 0 ; i < 6 ; i++)
D(i, i) = 1 / D(i, i) + 0.00001;
cov = (V * D * V.transpose());
//cout << "V = [" << V << "];" << endl;
//cout << "D = [" << D << "];" << endl;
//cout << "cov = [ " << cov << "];" << endl;
cov.topLeftCorner<3, 3> () = _pose.topLeftCorner<3, 3>().transpose() *
cov.topLeftCorner<3, 3>() *
_pose.topLeftCorner<3, 3>();
// Exclude the pose estimate along the x direction.
es.compute(cov, true);
D = es.eigenvalues().real().asDiagonal();
V = es.eigenvectors().real();
D(0, 0) = 0.00001;
D(4, 4) = 0.00009;
D(5, 5) = 0.00009;
cov = (V * D * V.transpose());
return true;
}
bool RangeBasedTunnelLocalizer::get_fitness_scores(double &y, double &z, double &yaw){
y = _fitness_scores[0];
z = _fitness_scores[1];
yaw = _fitness_scores[2];
return true;
}
bool RangeBasedTunnelLocalizer::get_correspondences(vector<pcl::PointXYZ> &sensor_pts, vector<pcl::PointXYZ> &map_pts){
int num_valid_pts = 0;
for(int i = 0 ; i < (int)_matched_map_pts.size() ; i++)
if(isfinite(_matched_map_pts[i].y))
num_valid_pts++;
map_pts.resize(num_valid_pts);
sensor_pts.resize(num_valid_pts);
for(int i = 0, j = 0 ; i < (int)_cloud_aligned->points.size() ; i++){
if(isfinite(_matched_map_pts[i].y)){
sensor_pts[j] = _cloud_aligned->points[i];
map_pts[j] = _matched_map_pts[i];
j++;
}
}
return true;
}
| 13,010 | 5,473 |
/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH *
* *
* This program is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include <gtest/gtest.h>
#include <string>
using std::string ;
#include <SofaSimulationGraph/DAGSimulation.h>
using sofa::simulation::graph::DAGSimulation ;
#include <sofa/simulation/Simulation.h>
using sofa::simulation::Simulation ;
#include <sofa/simulation/Node.h>
using sofa::simulation::Node ;
#include <SofaSimulationCommon/SceneLoaderXML.h>
using sofa::simulation::SceneLoaderXML ;
#include <SofaComponentBase/messageHandlerComponent.h>
using sofa::component::logging::MessageHandlerComponent ;
#include <SofaComponentBase/initComponentBase.h>
TEST(MessageHandlerComponent, simpleInit)
{
sofa::component::initComponentBase();
string scene =
"<?xml version='1.0'?> "
"<Node name='Root' gravity='0 0 0' time='0' animate='0' > "
" <Node> "
" <MessageHandlerComponent handler='silent'/> "
" </Node> "
"</Node> " ;
sofa::simulation::setSimulation(new DAGSimulation());
Node::SPtr root = SceneLoaderXML::loadFromMemory ( "test1",
scene.c_str(),
scene.size() ) ;
EXPECT_TRUE(root!=NULL) ;
MessageHandlerComponent* component = NULL;
root->getTreeObject(component) ;
EXPECT_TRUE(component!=NULL) ;
}
TEST(MessageHandlerComponent, missingHandler)
{
sofa::component::initComponentBase();
string scene =
"<?xml version='1.0'?> "
"<Node name='Root' gravity='0 0 0' time='0' animate='0' > "
" <MessageHandlerComponent/> "
"</Node> " ;
Node::SPtr root = SceneLoaderXML::loadFromMemory ( "test1",
scene.c_str(),
scene.size() ) ;
MessageHandlerComponent* component = NULL;
root->getTreeObject(component) ;
EXPECT_TRUE(component!=NULL) ;
EXPECT_FALSE(component->isValid()) ;
}
TEST(MessageHandlerComponent, invalidHandler)
{
sofa::component::initComponentBase();
string scene =
"<?xml version='1.0'?> "
"<Node name='Root' gravity='0 0 0' time='0' animate='0' > "
" <MessageHandlerComponent handler='thisisinvalid'/> "
"</Node> " ;
Node::SPtr root = SceneLoaderXML::loadFromMemory ( "test1",
scene.c_str(),
scene.size() ) ;
MessageHandlerComponent* component = NULL;
root->getTreeObject(component) ;
EXPECT_TRUE(component!=NULL) ;
EXPECT_FALSE(component->isValid()) ;
}
TEST(MessageHandlerComponent, clangHandler)
{
sofa::component::initComponentBase();
string scene =
"<?xml version='1.0'?> "
"<Node name='Root' gravity='0 0 0' time='0' animate='0' > "
" <MessageHandlerComponent handler='clang'/> "
"</Node> " ;
Node::SPtr root = SceneLoaderXML::loadFromMemory ( "test1",
scene.c_str(),
scene.size() ) ;
MessageHandlerComponent* component = NULL;
root->getTreeObject(component) ;
EXPECT_TRUE(component!=NULL) ;
EXPECT_TRUE(component->isValid()) ;
}
| 5,493 | 1,374 |
/*=============================================================================
Copyright (c) 2013 Ville Ruusutie
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.
=============================================================================*/
#pragma once
#ifndef fileos_path_inl
#define fileos_path_inl
namespace fileos {
__forceinline Path::Path()
: m_buffer()
{
}
__forceinline Path::Path(size_t capasity)
: m_buffer(capasity)
{
}
__forceinline Path::Path(Path const& other)
: m_buffer(other.m_buffer)
{
}
/*template<typename T>
__forceinline Path::Path(T const* path)
: m_buffer(path)
{
fixSlashes();
}*/
template<typename T>
__forceinline Path::Path(T const* path, size_t count)
: m_buffer(path, count)
{
fixSlashes();
}
template<size_t Count>
__forceinline Path::Path(char const (&str)[Count])
: m_buffer(str)
{
fixSlashes();
}
template<size_t Count>
__forceinline Path::Path(wchar_t const (&str)[Count])
: m_buffer(str)
{
fixSlashes();
}
__forceinline void Path::reserve(size_t capasity)
{
m_buffer.reserve(capasity);
}
__forceinline void Path::clear()
{
m_buffer.clear();
}
__forceinline void Path::set(Path const& other)
{
m_buffer = other.m_buffer;
}
__forceinline void Path::set(containos::Utf8Slice const& slice)
{
m_buffer.set(slice);
fixSlashes();
}
template<>
__forceinline void Path::set(Path const* other)
{
m_buffer = other->m_buffer;
}
template<>
__forceinline void Path::set(containos::Utf8Slice const* slice)
{
m_buffer.set(*slice);
fixSlashes();
}
template<typename T>
__forceinline void Path::set(T const* path)
{
m_buffer.set(path);
fixSlashes();
}
template<typename T>
__forceinline void Path::set(T const* path, size_t count)
{
m_buffer.set(path, count);
fixSlashes();
}
__forceinline void Path::append(Path const& other)
{
if(m_buffer.length() > 0) m_buffer.append('/');
m_buffer.append(other.m_buffer);
fixSlashes();
}
__forceinline void Path::append(Utf8Slice const& slice)
{
if(m_buffer.length() > 0) m_buffer.append('/');
m_buffer.append(slice);
fixSlashes();
}
template<>
__forceinline void Path::append(Path const* other)
{
if(m_buffer.length() > 0) m_buffer.append('/');
m_buffer.append(other->m_buffer);
fixSlashes();
}
template<>
__forceinline void Path::append(Utf8Slice const* slice)
{
if(m_buffer.length() > 0) m_buffer.append('/');
m_buffer.append(*slice);
fixSlashes();
}
template<typename T>
__forceinline void Path::append(T const* str)
{
if(m_buffer.length() > 0) m_buffer.append('/');
m_buffer.append(str);
fixSlashes();
}
template<typename T>
__forceinline void Path::append(T const* str, size_t count)
{
if(m_buffer.length() > 0) m_buffer.append('/');
m_buffer.append(str, count);
fixSlashes();
}
__forceinline void Path::clone(Path const& from)
{
m_buffer.clone(from.m_buffer);
}
template<typename T>
__forceinline void Path::convertTo(T* buffer, size_t count) const
{
m_buffer.convertTo(buffer, count);
}
__forceinline uint8_t const* Path::data() const
{
return m_buffer.data();
}
__forceinline size_t Path::length() const
{
return m_buffer.length();
}
__forceinline bool Path::operator==(Path const& other) const
{
return m_buffer == other.m_buffer;
}
__forceinline bool Path::operator==(containos::Utf8Slice const& slice) const
{
return m_buffer == slice;
}
__forceinline bool Path::operator==(char const* str) const
{
return m_buffer == str;
}
__forceinline bool Path::operator==(wchar_t const* str) const
{
return m_buffer == str;
}
} // end of fileos
#endif
| 4,617 | 1,622 |
//: S03:Enum.cpp
// From "Thinking in C++, 2nd Edition, Volume 1, Annotated Solutions Guide"
// by Chuck Allison, (c) 2001 MindView, Inc. all rights reserved
// Available at www.BruceEckel.com.
#include <iostream>
enum color {
BLACK,
RED,
GREEN,
BLUE,
WHITE
};
int main() {
using namespace std;
for (int hue = BLACK; hue <= WHITE; ++hue)
cout << hue << ' ';
}
/* Output:
0 1 2 3 4
*/
///:~
| 453 | 194 |
/****************************************************************************
** Meta object code from reading C++ file 'interface_toolbar.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.6.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "interface_toolbar.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'interface_toolbar.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.6.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_InterfaceToolbar_t {
QByteArrayData data[23];
char stringdata0[337];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_InterfaceToolbar_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_InterfaceToolbar_t qt_meta_stringdata_InterfaceToolbar = {
{
QT_MOC_LITERAL(0, 0, 16), // "InterfaceToolbar"
QT_MOC_LITERAL(1, 17, 11), // "closeReader"
QT_MOC_LITERAL(2, 29, 0), // ""
QT_MOC_LITERAL(3, 30, 20), // "interfaceListChanged"
QT_MOC_LITERAL(4, 51, 15), // "controlReceived"
QT_MOC_LITERAL(5, 67, 6), // "ifname"
QT_MOC_LITERAL(6, 74, 3), // "num"
QT_MOC_LITERAL(7, 78, 7), // "command"
QT_MOC_LITERAL(8, 86, 7), // "message"
QT_MOC_LITERAL(9, 94, 17), // "startReaderThread"
QT_MOC_LITERAL(10, 112, 10), // "control_in"
QT_MOC_LITERAL(11, 123, 13), // "updateWidgets"
QT_MOC_LITERAL(12, 137, 22), // "onControlButtonClicked"
QT_MOC_LITERAL(13, 160, 18), // "onLogButtonClicked"
QT_MOC_LITERAL(14, 179, 19), // "onHelpButtonClicked"
QT_MOC_LITERAL(15, 199, 22), // "onRestoreButtonClicked"
QT_MOC_LITERAL(16, 222, 17), // "onCheckBoxChanged"
QT_MOC_LITERAL(17, 240, 5), // "state"
QT_MOC_LITERAL(18, 246, 17), // "onComboBoxChanged"
QT_MOC_LITERAL(19, 264, 3), // "idx"
QT_MOC_LITERAL(20, 268, 17), // "onLineEditChanged"
QT_MOC_LITERAL(21, 286, 8), // "closeLog"
QT_MOC_LITERAL(22, 295, 41) // "on_interfacesComboBox_current..."
},
"InterfaceToolbar\0closeReader\0\0"
"interfaceListChanged\0controlReceived\0"
"ifname\0num\0command\0message\0startReaderThread\0"
"control_in\0updateWidgets\0"
"onControlButtonClicked\0onLogButtonClicked\0"
"onHelpButtonClicked\0onRestoreButtonClicked\0"
"onCheckBoxChanged\0state\0onComboBoxChanged\0"
"idx\0onLineEditChanged\0closeLog\0"
"on_interfacesComboBox_currentIndexChanged"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_InterfaceToolbar[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
14, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
1, // signalCount
// signals: name, argc, parameters, tag, flags
1, 0, 84, 2, 0x06 /* Public */,
// slots: name, argc, parameters, tag, flags
3, 0, 85, 2, 0x0a /* Public */,
4, 4, 86, 2, 0x0a /* Public */,
9, 2, 95, 2, 0x08 /* Private */,
11, 0, 100, 2, 0x08 /* Private */,
12, 0, 101, 2, 0x08 /* Private */,
13, 0, 102, 2, 0x08 /* Private */,
14, 0, 103, 2, 0x08 /* Private */,
15, 0, 104, 2, 0x08 /* Private */,
16, 1, 105, 2, 0x08 /* Private */,
18, 1, 108, 2, 0x08 /* Private */,
20, 0, 111, 2, 0x08 /* Private */,
21, 0, 112, 2, 0x08 /* Private */,
22, 1, 113, 2, 0x08 /* Private */,
// signals: parameters
QMetaType::Void,
// slots: parameters
QMetaType::Void,
QMetaType::Void, QMetaType::QString, QMetaType::Int, QMetaType::Int, QMetaType::QByteArray, 5, 6, 7, 8,
QMetaType::Void, QMetaType::QString, QMetaType::VoidStar, 5, 10,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, QMetaType::Int, 17,
QMetaType::Void, QMetaType::Int, 19,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, QMetaType::QString, 5,
0 // eod
};
void InterfaceToolbar::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
InterfaceToolbar *_t = static_cast<InterfaceToolbar *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->closeReader(); break;
case 1: _t->interfaceListChanged(); break;
case 2: _t->controlReceived((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3])),(*reinterpret_cast< QByteArray(*)>(_a[4]))); break;
case 3: _t->startReaderThread((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< void*(*)>(_a[2]))); break;
case 4: _t->updateWidgets(); break;
case 5: _t->onControlButtonClicked(); break;
case 6: _t->onLogButtonClicked(); break;
case 7: _t->onHelpButtonClicked(); break;
case 8: _t->onRestoreButtonClicked(); break;
case 9: _t->onCheckBoxChanged((*reinterpret_cast< int(*)>(_a[1]))); break;
case 10: _t->onComboBoxChanged((*reinterpret_cast< int(*)>(_a[1]))); break;
case 11: _t->onLineEditChanged(); break;
case 12: _t->closeLog(); break;
case 13: _t->on_interfacesComboBox_currentIndexChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
void **func = reinterpret_cast<void **>(_a[1]);
{
typedef void (InterfaceToolbar::*_t)();
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&InterfaceToolbar::closeReader)) {
*result = 0;
return;
}
}
}
}
const QMetaObject InterfaceToolbar::staticMetaObject = {
{ &QFrame::staticMetaObject, qt_meta_stringdata_InterfaceToolbar.data,
qt_meta_data_InterfaceToolbar, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *InterfaceToolbar::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *InterfaceToolbar::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_InterfaceToolbar.stringdata0))
return static_cast<void*>(const_cast< InterfaceToolbar*>(this));
return QFrame::qt_metacast(_clname);
}
int InterfaceToolbar::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QFrame::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 14)
qt_static_metacall(this, _c, _id, _a);
_id -= 14;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 14)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 14;
}
return _id;
}
// SIGNAL 0
void InterfaceToolbar::closeReader()
{
QMetaObject::activate(this, &staticMetaObject, 0, Q_NULLPTR);
}
QT_END_MOC_NAMESPACE
| 7,472 | 3,054 |
#include <gtest/gtest.h>
#include <string>
using std::string;
#include "../src/Utils.h"
TEST(testUtils, parseInsertStatement){
Row* row = new Row;
string target = "insert 1 username email@email.com";
parseInsertStatement(target, *row);
EXPECT_EQ(1, row->id);
EXPECT_STREQ("username", row->username);
EXPECT_STREQ("email@email.com", row->email);
// Second test
row = new Row;
target = "insert 2 vasya ema@company.com";
parseInsertStatement(target, *row);
EXPECT_EQ(2, row->id);
EXPECT_STREQ("vasya", row->username);
EXPECT_STREQ("ema@company.com", row->email);
}
| 594 | 238 |
#include "R_Mesh.h"
#include "OpenGL.h"
R_Mesh::R_Mesh() : Resource(ResourceType::MESH)
{
isExternal = true;
for (uint i = 0; i < max_buffer_type; i++)
{
buffers[i] = 0;
buffersSize[i] = 0;
}
}
R_Mesh::~R_Mesh()
{
}
void R_Mesh::CreateAABB()
{
aabb.SetNegativeInfinity();
aabb.Enclose((math::vec*)vertices, buffersSize[b_vertices]);
}
void R_Mesh::LoadOnMemory()
{
// Create a vertex array object which will hold all buffer objects
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
// Create a vertex buffer object to hold vertex positions
glGenBuffers(1, &buffers[b_vertices]);
glBindBuffer(GL_ARRAY_BUFFER, buffers[b_vertices]);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * buffersSize[b_vertices] * 3, vertices, GL_STATIC_DRAW);
// Create an element buffer object to hold indices
glGenBuffers(1, &buffers[b_indices]);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[b_indices]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(uint) * buffersSize[b_indices], indices, GL_STATIC_DRAW);
// Set the vertex attrib pointer
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// Create the array buffer for tex coords and enable attrib pointer
if (buffersSize[b_tex_coords] > 0)
{
glGenBuffers(1, &buffers[b_tex_coords]);
glBindBuffer(GL_ARRAY_BUFFER, buffers[b_tex_coords]);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * buffersSize[b_tex_coords] * 2, tex_coords, GL_STATIC_DRAW);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)0);
glEnableVertexAttribArray(1);
}
// Create the array buffer for normals and enable attrib pointer
if (buffersSize[b_normals] > 0)
{
glGenBuffers(1, &buffers[b_normals]);
glBindBuffer(GL_ARRAY_BUFFER, buffers[b_normals]);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * buffersSize[b_normals] * 3, normals, GL_STATIC_DRAW);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)0);
glEnableVertexAttribArray(2);
}
glBindVertexArray(0);
}
void R_Mesh::LoadSkinnedBuffers(bool init)
{
if (init)
{
// Create a vertex array object which will hold all buffer objects
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
// Create a vertex buffer object to hold vertex positions
glGenBuffers(1, &buffers[b_vertices]);
// Create an element buffer object to hold indices
glGenBuffers(1, &buffers[b_indices]);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[b_indices]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(uint) * buffersSize[b_indices], indices, GL_STATIC_DRAW);
// Set the vertex attrib pointer
glEnableVertexAttribArray(0);
//Create the array buffer for tex coords and enable attrib pointer
if (buffersSize[b_tex_coords] > 0)
{
glGenBuffers(1, &buffers[b_tex_coords]);
glBindBuffer(GL_ARRAY_BUFFER, buffers[b_tex_coords]);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * buffersSize[b_tex_coords] * 2, tex_coords, GL_STATIC_DRAW);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)0);
glEnableVertexAttribArray(1);
}
glGenBuffers(1, &buffers[b_normals]);
}
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, buffers[b_vertices]);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * buffersSize[b_vertices] * 3, vertices, GL_STREAM_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
// Create the array buffer for normals and enable attrib pointer
if (buffersSize[b_normals] > 0)
{
glBindBuffer(GL_ARRAY_BUFFER, buffers[b_normals]);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * buffersSize[b_normals] * 3, normals, GL_STREAM_DRAW);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(2);
}
glBindVertexArray(0);
}
void R_Mesh::FreeMemory()
{
//glDeleteBuffers(max_buffer_type, buffers);
} | 3,869 | 1,622 |
/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
// This test only works with the GPU backend.
#include "gm.h"
#if SK_SUPPORT_GPU
#include "GrContext.h"
#include "GrTest.h"
#include "effects/GrYUVtoRGBEffect.h"
#include "SkBitmap.h"
#include "SkGr.h"
#include "SkGradientShader.h"
namespace skiagm {
/**
* This GM directly exercises GrYUVtoRGBEffect.
*/
class YUVtoRGBEffect : public GM {
public:
YUVtoRGBEffect() {
this->setBGColor(0xFFFFFFFF);
}
protected:
virtual SkString onShortName() SK_OVERRIDE {
return SkString("yuv_to_rgb_effect");
}
virtual SkISize onISize() SK_OVERRIDE {
return SkISize::Make(334, 128);
}
virtual uint32_t onGetFlags() const SK_OVERRIDE {
// This is a GPU-specific GM.
return kGPUOnly_Flag;
}
virtual void onOnceBeforeDraw() SK_OVERRIDE {
SkImageInfo info = SkImageInfo::MakeA8(24, 24);
fBmp[0].allocPixels(info);
fBmp[1].allocPixels(info);
fBmp[2].allocPixels(info);
unsigned char* pixels[3];
for (int i = 0; i < 3; ++i) {
pixels[i] = (unsigned char*)fBmp[i].getPixels();
}
int color[] = {0, 85, 170};
const int limit[] = {255, 0, 255};
const int invl[] = {0, 255, 0};
const int inc[] = {1, -1, 1};
for (int j = 0; j < 576; ++j) {
for (int i = 0; i < 3; ++i) {
pixels[i][j] = (unsigned char)color[i];
color[i] = (color[i] == limit[i]) ? invl[i] : color[i] + inc[i];
}
}
}
virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {
GrRenderTarget* rt = canvas->internal_private_accessTopLayerRenderTarget();
if (NULL == rt) {
return;
}
GrContext* context = rt->getContext();
if (NULL == context) {
return;
}
GrTestTarget tt;
context->getTestTarget(&tt);
if (NULL == tt.target()) {
SkDEBUGFAIL("Couldn't get Gr test target.");
return;
}
SkAutoTUnref<GrTexture> texture[3];
texture[0].reset(GrRefCachedBitmapTexture(context, fBmp[0], NULL));
texture[1].reset(GrRefCachedBitmapTexture(context, fBmp[1], NULL));
texture[2].reset(GrRefCachedBitmapTexture(context, fBmp[2], NULL));
if (!texture[0] || !texture[1] || !texture[2]) {
return;
}
static const SkScalar kDrawPad = 10.f;
static const SkScalar kTestPad = 10.f;
static const SkScalar kColorSpaceOffset = 64.f;
for (int space = kJPEG_SkYUVColorSpace; space <= kLastEnum_SkYUVColorSpace;
++space) {
SkRect renderRect = SkRect::MakeWH(SkIntToScalar(fBmp[0].width()),
SkIntToScalar(fBmp[0].height()));
renderRect.outset(kDrawPad, kDrawPad);
SkScalar y = kDrawPad + kTestPad + space * kColorSpaceOffset;
SkScalar x = kDrawPad + kTestPad;
const int indices[6][3] = {{0, 1, 2}, {0, 2, 1}, {1, 0, 2},
{1, 2, 0}, {2, 0, 1}, {2, 1, 0}};
for (int i = 0; i < 6; ++i) {
SkAutoTUnref<GrFragmentProcessor> fp(
GrYUVtoRGBEffect::Create(texture[indices[i][0]],
texture[indices[i][1]],
texture[indices[i][2]],
static_cast<SkYUVColorSpace>(space)));
if (fp) {
SkMatrix viewMatrix;
viewMatrix.setTranslate(x, y);
GrDrawState drawState;
drawState.setRenderTarget(rt);
drawState.addColorProcessor(fp);
tt.target()->drawSimpleRect(&drawState, GrColor_WHITE, viewMatrix, renderRect);
}
x += renderRect.width() + kTestPad;
}
}
}
private:
SkBitmap fBmp[3];
typedef GM INHERITED;
};
DEF_GM( return SkNEW(YUVtoRGBEffect); )
}
#endif
| 4,249 | 1,453 |
#include "gui/grouping/grouping_manager_widget.h"
#include "gui/gui_globals.h"
#include "gui/graph_tab_widget/graph_tab_widget.h"
#include "gui/grouping/grouping_color_delegate.h"
#include "gui/grouping/grouping_proxy_model.h"
#include "gui/input_dialog/input_dialog.h"
#include "gui/searchbar/searchbar.h"
#include "gui/gui_utils/graphics.h"
#include "gui/toolbar/toolbar.h"
#include "hal_core/utilities/log.h"
#include <QAction>
#include <QMenu>
#include <QResizeEvent>
#include <QSize>
#include <QVBoxLayout>
#include <QHeaderView>
#include <QColorDialog>
#include <QStringList>
namespace hal
{
GroupingManagerWidget::GroupingManagerWidget(GraphTabWidget* tab_view, QWidget* parent)
: ContentWidget("Groupings", parent),
mProxyModel(new GroupingProxyModel(this)),
mSearchbar(new Searchbar(this)),
mNewGroupingAction(new QAction(this)),
mRenameAction(new QAction(this)),
mColorSelectAction(new QAction(this)),
mDeleteAction(new QAction(this)),
mToSelectionAction(new QAction(this))
{
//needed to load the properties
ensurePolished();
mTabView = tab_view;
mNewGroupingAction->setIcon(gui_utility::getStyledSvgIcon(mNewGroupingIconStyle, mNewGroupingIconPath));
mRenameAction->setIcon(gui_utility::getStyledSvgIcon(mRenameGroupingIconStyle, mRenameGroupingIconPath));
mDeleteAction->setIcon(gui_utility::getStyledSvgIcon(mDeleteIconStyle, mDeleteIconPath));
mColorSelectAction->setIcon(gui_utility::getStyledSvgIcon(mColorSelectIconStyle, mColorSelectIconPath));
mToSelectionAction->setIcon(gui_utility::getStyledSvgIcon(mToSelectionIconStyle, mToSelectionIconPath));
mNewGroupingAction->setToolTip("New");
mRenameAction->setToolTip("Rename");
mColorSelectAction->setToolTip("Color");
mDeleteAction->setToolTip("Delete");
mToSelectionAction->setToolTip("To selection");
mNewGroupingAction->setText("Create new grouping");
mRenameAction->setText("Rename grouping");
mColorSelectAction->setText("Select color for grouping");
mDeleteAction->setText("Delete grouping");
mToSelectionAction->setText("Add grouping to selection");
//mOpenAction->setEnabled(false);
//mRenameAction->setEnabled(false);
//mDeleteAction->setEnabled(false);
mGroupingTableModel = new GroupingTableModel;
mProxyModel->setSourceModel(mGroupingTableModel);
mProxyModel->setSortRole(Qt::UserRole);
mGroupingTableView = new QTableView(this);
mGroupingTableView->setModel(mProxyModel);
mGroupingTableView->setSelectionBehavior(QAbstractItemView::SelectRows);
mGroupingTableView->setSelectionMode(QAbstractItemView::SingleSelection); // ERROR ???
mGroupingTableView->setContextMenuPolicy(Qt::ContextMenuPolicy::CustomContextMenu);
mGroupingTableView->verticalHeader()->hide();
mGroupingTableView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
mGroupingTableView->setItemDelegateForColumn(2,new GroupingColorDelegate(mGroupingTableView));
mGroupingTableView->setSortingEnabled(true);
mGroupingTableView->sortByColumn(0, Qt::SortOrder::AscendingOrder);
mGroupingTableView->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
mGroupingTableView->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
mGroupingTableView->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents);
mGroupingTableView->horizontalHeader()->setDefaultAlignment(Qt::AlignHCenter | Qt::AlignCenter);
QFont font = mGroupingTableView->horizontalHeader()->font();
font.setBold(true);
mGroupingTableView->horizontalHeader()->setFont(font);
mContentLayout->addWidget(mGroupingTableView);
mContentLayout->addWidget(mSearchbar);
mSearchbar->hide();
connect(mSearchbar, &Searchbar::textEdited, this, &GroupingManagerWidget::filter);
connect(mNewGroupingAction, &QAction::triggered, this, &GroupingManagerWidget::handleCreateGroupingClicked);
connect(mRenameAction, &QAction::triggered, this, &GroupingManagerWidget::handleRenameGroupingClicked);
connect(mColorSelectAction, &QAction::triggered, this, &GroupingManagerWidget::handleColorSelectClicked);
connect(mToSelectionAction, &QAction::triggered, this, &GroupingManagerWidget::handleToSelectionClicked);
connect(mDeleteAction, &QAction::triggered, this, &GroupingManagerWidget::handleDeleteGroupingClicked);
connect(mGroupingTableView, &QTableView::customContextMenuRequested, this, &GroupingManagerWidget::handleContextMenuRequest);
connect(mGroupingTableView->selectionModel(), &QItemSelectionModel::currentChanged, this, &GroupingManagerWidget::handleCurrentChanged);
connect(mGroupingTableModel, &GroupingTableModel::lastEntryDeleted, this, &GroupingManagerWidget::handleLastEntryDeleted);
connect(mGroupingTableModel, &GroupingTableModel::newEntryAdded, this, &GroupingManagerWidget::handleNewEntryAdded);
handleCurrentChanged();
}
QList<QShortcut*> GroupingManagerWidget::createShortcuts()
{
QShortcut* search_shortcut = gKeybindManager->makeShortcut(this, "keybinds/searchbar_toggle");
connect(search_shortcut, &QShortcut::activated, this, &GroupingManagerWidget::toggleSearchbar);
QList<QShortcut*> list;
list.append(search_shortcut);
return list;
}
void GroupingManagerWidget::handleCreateGroupingClicked()
{
mGroupingTableModel->addDefaultEntry();
}
void GroupingManagerWidget::handleColorSelectClicked()
{
QModelIndex currentIndex = mProxyModel->mapToSource(mGroupingTableView->currentIndex());
if (!currentIndex.isValid()) return;
QModelIndex nameIndex = mGroupingTableModel->index(currentIndex.row(),0);
QString name = mGroupingTableModel->data(nameIndex,Qt::DisplayRole).toString();
QModelIndex modelIndex = mGroupingTableModel->index(currentIndex.row(),2);
QColor color = mGroupingTableModel->data(modelIndex,Qt::BackgroundRole).value<QColor>();
color = QColorDialog::getColor(color,this,"Select color for grouping " + name);
if (color.isValid())
mGroupingTableModel->setData(modelIndex,color,Qt::EditRole);
}
void GroupingManagerWidget::handleToSelectionClicked()
{
QModelIndex currentIndex = mProxyModel->mapToSource(mGroupingTableView->currentIndex());
if (!currentIndex.isValid()) return;
Grouping* grp = getCurrentGrouping().grouping();
if (!grp) return;
for (Module* m : grp->get_modules())
gSelectionRelay->mSelectedModules.insert(m->get_id());
for (Gate* g : grp->get_gates())
gSelectionRelay->mSelectedGates.insert(g->get_id());
for (Net* n : grp->get_nets())
gSelectionRelay->mSelectedNets.insert(n->get_id());
gSelectionRelay->relaySelectionChanged(this);
}
void GroupingManagerWidget::handleRenameGroupingClicked()
{
QModelIndex currentIndex = mProxyModel->mapToSource(mGroupingTableView->currentIndex());
if (!currentIndex.isValid()) return;
QModelIndex modelIndex = mGroupingTableModel->index(currentIndex.row(),0);
InputDialog ipd;
ipd.setWindowTitle("Rename Grouping");
ipd.setInfoText("Please select a new unique name for the grouping.");
QString oldName = mGroupingTableModel->data(modelIndex,Qt::DisplayRole).toString();
mGroupingTableModel->setAboutToRename(oldName);
ipd.setInputText(oldName);
ipd.addValidator(mGroupingTableModel);
if (ipd.exec() == QDialog::Accepted)
mGroupingTableModel->renameGrouping(modelIndex.row(),ipd.textValue());
mGroupingTableModel->setAboutToRename(QString());
}
void GroupingManagerWidget::handleDeleteGroupingClicked()
{
mGroupingTableModel->removeRows(mProxyModel->mapToSource(mGroupingTableView->currentIndex()).row());
}
void GroupingManagerWidget::handleSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
{
Q_UNUSED(deselected);
if(selected.indexes().isEmpty())
setToolbarButtonsEnabled(false);
else
setToolbarButtonsEnabled(true);
}
void GroupingManagerWidget::handleContextMenuRequest(const QPoint& point)
{
const QModelIndex clicked_index = mGroupingTableView->indexAt(point);
QMenu context_menu;
context_menu.addAction(mNewGroupingAction);
if (clicked_index.isValid())
{
context_menu.addAction(mRenameAction);
context_menu.addAction(mColorSelectAction);
context_menu.addAction(mToSelectionAction);
context_menu.addAction(mDeleteAction);
}
context_menu.exec(mGroupingTableView->viewport()->mapToGlobal(point));
}
GroupingTableEntry GroupingManagerWidget::getCurrentGrouping()
{
QModelIndex modelIndex = mProxyModel->mapToSource(mGroupingTableView->currentIndex());
return mGroupingTableModel->groupingAt(modelIndex.row());
}
void GroupingManagerWidget::setupToolbar(Toolbar* toolbar)
{
toolbar->addAction(mNewGroupingAction);
toolbar->addAction(mRenameAction);
toolbar->addAction(mColorSelectAction);
toolbar->addAction(mToSelectionAction);
toolbar->addAction(mDeleteAction);
}
void GroupingManagerWidget::setToolbarButtonsEnabled(bool enabled)
{
mRenameAction->setEnabled(enabled);
mColorSelectAction->setEnabled(enabled);
mToSelectionAction->setEnabled(enabled);
mDeleteAction->setEnabled(enabled);
}
void GroupingManagerWidget::handleNewEntryAdded(const QModelIndex& modelIndex)
{
if (!modelIndex.isValid()) return;
QModelIndex proxyIndex = mProxyModel->mapFromSource(modelIndex);
if (!proxyIndex.isValid()) return;
mGroupingTableView->setCurrentIndex(proxyIndex);
handleCurrentChanged(proxyIndex);
}
void GroupingManagerWidget::handleLastEntryDeleted()
{
if (mProxyModel->rowCount())
{
QModelIndex inx = mProxyModel->index(0,0);
mGroupingTableView->setCurrentIndex(inx);
handleCurrentChanged(inx);
}
else
handleCurrentChanged();
}
void GroupingManagerWidget::handleCurrentChanged(const QModelIndex& current, const QModelIndex& previous)
{
Q_UNUSED(previous);
bool enable = mGroupingTableModel->rowCount() > 0 && current.isValid();
QAction* entryBasedAction[] = { mRenameAction, mColorSelectAction,
mDeleteAction, mToSelectionAction, nullptr};
QStringList iconPath, iconStyle;
iconPath << mRenameGroupingIconPath << mColorSelectIconPath
<< mDeleteIconPath << mToSelectionIconPath;
iconStyle << mRenameGroupingIconStyle << mColorSelectIconStyle
<< mDeleteIconStyle << mToSelectionIconStyle;
for (int iacc = 0; entryBasedAction[iacc]; iacc++)
{
entryBasedAction[iacc]->setEnabled(enable);
entryBasedAction[iacc]->setIcon(
gui_utility::getStyledSvgIcon(enable
? iconStyle.at(iacc)
: disabledIconStyle(),
iconPath.at(iacc)));
}
}
void GroupingManagerWidget::toggleSearchbar()
{
if (mSearchbar->isHidden())
{
mSearchbar->show();
mSearchbar->setFocus();
}
else
mSearchbar->hide();
}
void GroupingManagerWidget::filter(const QString& text)
{
QRegExp* regex = new QRegExp(text);
if (regex->isValid())
{
mProxyModel->setFilterRegExp(*regex);
QString output = "Groupings widget regular expression '" + text + "' entered.";
log_info("user", output.toStdString());
}
}
QString GroupingManagerWidget::disabledIconStyle() const
{
return mDisabledIconStyle;
}
QString GroupingManagerWidget::newGroupingIconPath() const
{
return mNewGroupingIconPath;
}
QString GroupingManagerWidget::newGroupingIconStyle() const
{
return mNewGroupingIconStyle;
}
QString GroupingManagerWidget::renameGroupingIconPath() const
{
return mRenameGroupingIconPath;
}
QString GroupingManagerWidget::renameGroupingIconStyle() const
{
return mRenameGroupingIconStyle;
}
QString GroupingManagerWidget::deleteIconPath() const
{
return mDeleteIconPath;
}
QString GroupingManagerWidget::deleteIconStyle() const
{
return mDeleteIconStyle;
}
QString GroupingManagerWidget::colorSelectIconPath() const
{
return mColorSelectIconPath;
}
QString GroupingManagerWidget::colorSelectIconStyle() const
{
return mColorSelectIconStyle;
}
QString GroupingManagerWidget::toSelectionIconPath() const
{
return mToSelectionIconPath;
}
QString GroupingManagerWidget::toSelectionIconStyle() const
{
return mToSelectionIconStyle;
}
void GroupingManagerWidget::setDisabledIconStyle(const QString& style)
{
mDisabledIconStyle = style;
}
void GroupingManagerWidget::setNewGroupingIconPath(const QString& path)
{
mNewGroupingIconPath = path;
}
void GroupingManagerWidget::setNewGroupingIconStyle(const QString& style)
{
mNewGroupingIconStyle = style;
}
void GroupingManagerWidget::setRenameGroupingIconPath(const QString& path)
{
mRenameGroupingIconPath = path;
}
void GroupingManagerWidget::setRenameGroupingIconStyle(const QString& style)
{
mRenameGroupingIconStyle = style;
}
void GroupingManagerWidget::setDeleteIconPath(const QString& path)
{
mDeleteIconPath = path;
}
void GroupingManagerWidget::setDeleteIconStyle(const QString& style)
{
mDeleteIconStyle = style;
}
void GroupingManagerWidget::setColorSelectIconPath(const QString& path)
{
mColorSelectIconPath = path;
}
void GroupingManagerWidget::setColorSelectIconStyle(const QString& style)
{
mColorSelectIconStyle = style;
}
void GroupingManagerWidget::setToSelectionIconPath(const QString& path)
{
mToSelectionIconPath = path;
}
void GroupingManagerWidget::setToSelectionIconStyle(const QString& style)
{
mToSelectionIconStyle = style;
}
}
| 15,054 | 4,280 |
#include "seasonlistmodel.h"
SeasonListModel::SeasonListModel(QObject *parent, DatabaseManager* dbmanager) :
QObject(parent)
{
m_dbmanager = dbmanager;
}
SeasonListModel::~SeasonListModel()
{
for (auto season : m_seasonListModel) {
delete season;
season = 0;
}
}
QQmlListProperty<SeasonData> SeasonListModel::getSeasonList()
{
return QQmlListProperty<SeasonData>(this, &m_seasonListModel, &SeasonListModel::seasonListCount, &SeasonListModel::seasonListAt);
}
// list handling methods
void SeasonListModel::seasonListAppend(QQmlListProperty<SeasonData>* prop, SeasonData* val)
{
SeasonListModel* seasonListModel = qobject_cast<SeasonListModel*>(prop->object);
seasonListModel->m_seasonListModel.append(val);
}
SeasonData* SeasonListModel::seasonListAt(QQmlListProperty<SeasonData>* prop, int index)
{
return (qobject_cast<SeasonListModel*>(prop->object))->m_seasonListModel.at(index);
}
int SeasonListModel::seasonListCount(QQmlListProperty<SeasonData>* prop)
{
return qobject_cast<SeasonListModel*>(prop->object)->m_seasonListModel.size();
}
void SeasonListModel::seasonListClear(QQmlListProperty<SeasonData>* prop)
{
qobject_cast<SeasonListModel*>(prop->object)->m_seasonListModel.clear();
}
void SeasonListModel::populateSeasonList(QString seriesID)
{
m_seasonListModel.clear();
int seasonsCount = m_dbmanager->seasonCount(seriesID.toInt());
for (int i = 1; i <= seasonsCount; ++i) {
QString banner = m_dbmanager->getSeasonBanner(seriesID.toInt(),i);
int watchedCount = m_dbmanager->watchedCountBySeason(seriesID.toInt(),i);
int totalCount = m_dbmanager->totalCountBySeason(seriesID.toInt(),i);
SeasonData* seasonData = new SeasonData(this, i, banner, watchedCount, totalCount);
m_seasonListModel.append(seasonData);
}
emit seasonListChanged();
}
| 1,880 | 622 |
/// Simulate a MIPS R2/3000 processor.
///
/// This code has been adapted from Ousterhout's MIPSSIM package. Byte
/// ordering is little-endian, so we can be compatible with DEC RISC systems.
///
/// DO NOT CHANGE -- part of the machine emulation
///
/// Copyright (c) 1992-1993 The Regents of the University of California.
/// 2016-2017 Docentes de la Universidad Nacional de Rosario.
/// All rights reserved. See `copyright.h` for copyright notice and
/// limitation of liability and disclaimer of warranty provisions.
#include "instruction.hh"
#include "machine.hh"
#include "threads/system.hh"
/// Simulate the execution of a user-level program on Nachos.
///
/// Called by the kernel when the program starts up; never returns.
///
/// This routine is re-entrant, in that it can be called multiple times
/// concurrently -- one for each thread executing user code.
void
Machine::Run()
{
Instruction * instr = new Instruction;
// Storage for decoded instruction.
if (debug.IsEnabled('m'))
printf("Starting to run at time %u\n", stats->totalTicks);
interrupt->SetStatus(USER_MODE);
for (;;) {
if (FetchInstruction(instr))
ExecInstruction(instr);
interrupt->OneTick();
if (singleStepper != nullptr && !singleStepper->Step())
singleStepper = nullptr;
}
}
/// Simulate effects of a delayed load.
///
/// NOTE -- `RaiseException`/`CheckInterrupts` must also call `DelayedLoad`,
/// since any delayed load must get applied before we trap to the kernel.
void
Machine::DelayedLoad(unsigned nextReg, int nextValue)
{
registers[registers[LOAD_REG]] = registers[LOAD_VALUE_REG];
registers[LOAD_REG] = nextReg;
registers[LOAD_VALUE_REG] = nextValue;
registers[0] = 0; // And always make sure R0 stays zero.
}
bool
Machine::FetchInstruction(Instruction * instr)
{
ASSERT(instr != nullptr);
int raw;
if (!ReadMem(registers[PC_REG], 4, &raw))
return false; // Exception occurred.
instr->value = raw;
instr->Decode();
if (debug.IsEnabled('m')) {
const struct OpString * str = &OP_STRINGS[instr->opCode];
ASSERT(instr->opCode <= MAX_OPCODE);
DEBUG('P', "At PC = 0x%X: ", registers[PC_REG]);
DEBUG_CONT('P', str->string, instr->RegFromType(str->args[0]),
instr->RegFromType(str->args[1]),
instr->RegFromType(str->args[2]));
DEBUG_CONT('P', "\n");
}
return true;
}
/// Simulate R2000 multiplication.
///
/// The words at `*hiPtr` and `*loPtr` are overwritten with the double-length
/// result of the multiplication.
static void
Mult(int a, int b, bool signedArith, int * hiPtr, int * loPtr)
{
ASSERT(hiPtr != nullptr);
ASSERT(loPtr != nullptr);
if (a == 0 || b == 0) {
*hiPtr = *loPtr = 0;
return;
}
// Compute the sign of the result, then make everything positive so
// unsigned computation can be done in the main loop.
bool negative = false;
if (signedArith) {
if (a < 0) {
negative = !negative;
a = -a;
}
if (b < 0) {
negative = !negative;
b = -b;
}
}
// Compute the result in unsigned arithmetic (check `a`'s bits one at a
// time, and add in a shifted value of `b`).
unsigned bLo = b;
unsigned bHi = 0;
unsigned lo = 0;
unsigned hi = 0;
for (unsigned i = 0; i < 32; i++) {
if (a & 1) {
lo += bLo;
if (lo < bLo) // Carry out of the low bits?
hi += 1;
hi += bHi;
if ((a & 0xFFFFFFFE) == 0)
break;
}
bHi <<= 1;
if (bLo & 0x80000000)
bHi |= 1;
bLo <<= 1;
a >>= 1;
}
// If the result is supposed to be negative, compute the two's complement
// of the double-word result.
if (negative) {
hi = ~hi;
lo = ~lo;
lo++;
if (lo == 0)
hi++;
}
*hiPtr = (int) hi;
*loPtr = (int) lo;
} // Mult
/// Execute one instruction from a user-level program.
///
/// If there is any kind of exception or interrupt, we invoke the exception
/// handler, and when it returns, we return to `Run`, which will re-invoke us
/// in a loop. This allows us to re-start the instruction execution from the
/// beginning, in case any of our state has changed. On a syscall, the OS
/// software must increment the PC so execution begins at the instruction
/// immediately after the syscall.
///
/// This routine is re-entrant, in that it can be called multiple times
/// concurrently -- one for each thread executing user code. We get
/// re-entrancy by never caching any data -- we always re-start the
/// simulation from scratch each time we are called (or after trapping back
/// to the Nachos kernel on an exception or interrupt), and we always store
/// all data back to the machine registers and memory before leaving. This
/// allows the Nachos kernel to control our behavior by controlling the
/// contents of memory, the translation table, and the register set.
void
Machine::ExecInstruction(const Instruction * instr)
{
int nextLoadReg = 0;
int nextLoadValue = 0; // Record delayed load operation, to apply in the
// future.
// Compute next pc, but do not install in case there is an error or
// branch.
int pcAfter = registers[NEXT_PC_REG] + 4;
int sum, diff, tmp, value;
unsigned rs, rt, imm;
// Execute the instruction (cf. Kane's book).
switch (instr->opCode) {
case OP_ADD:
sum = registers[instr->rs] + registers[instr->rt];
if (!((registers[instr->rs] ^ registers[instr->rt]) & SIGN_BIT) &&
(registers[instr->rs] ^ sum) & SIGN_BIT)
{
RaiseException(OVERFLOW_EXCEPTION, 0);
return;
}
registers[instr->rd] = sum;
break;
case OP_ADDI:
sum = registers[instr->rs] + instr->extra;
if (!((registers[instr->rs] ^ instr->extra) & SIGN_BIT) &&
(instr->extra ^ sum) & SIGN_BIT)
{
RaiseException(OVERFLOW_EXCEPTION, 0);
return;
}
registers[instr->rt] = sum;
break;
case OP_ADDIU:
registers[instr->rt] = registers[instr->rs] + instr->extra;
break;
case OP_ADDU:
registers[instr->rd] = registers[instr->rs]
+ registers[instr->rt];
break;
case OP_AND:
registers[instr->rd] = registers[instr->rs]
& registers[instr->rt];
break;
case OP_ANDI:
registers[instr->rt] = registers[instr->rs]
& (instr->extra & 0xFFFF);
break;
case OP_BEQ:
if (registers[instr->rs] == registers[instr->rt])
pcAfter = registers[NEXT_PC_REG] + IndexToAddr(instr->extra);
break;
case OP_BGEZAL:
registers[RET_ADDR_REG] = registers[NEXT_PC_REG] + 4;
case OP_BGEZ:
if (!(registers[instr->rs] & SIGN_BIT))
pcAfter = registers[NEXT_PC_REG] + IndexToAddr(instr->extra);
break;
case OP_BGTZ:
if (registers[instr->rs] > 0)
pcAfter = registers[NEXT_PC_REG] + IndexToAddr(instr->extra);
break;
case OP_BLEZ:
if (registers[instr->rs] <= 0)
pcAfter = registers[NEXT_PC_REG] + IndexToAddr(instr->extra);
break;
case OP_BLTZAL:
registers[RET_ADDR_REG] = registers[NEXT_PC_REG] + 4;
case OP_BLTZ:
if (registers[instr->rs] & SIGN_BIT)
pcAfter = registers[NEXT_PC_REG] + IndexToAddr(instr->extra);
break;
case OP_BNE:
if (registers[instr->rs] != registers[instr->rt])
pcAfter = registers[NEXT_PC_REG] + IndexToAddr(instr->extra);
break;
case OP_DIV:
if (registers[instr->rt] == 0) {
registers[LO_REG] = 0;
registers[HI_REG] = 0;
} else {
registers[LO_REG] = registers[instr->rs]
/ registers[instr->rt];
registers[HI_REG] = registers[instr->rs]
% registers[instr->rt];
}
break;
case OP_DIVU:
rs = (unsigned) registers[instr->rs];
rt = (unsigned) registers[instr->rt];
if (rt == 0) {
registers[LO_REG] = 0;
registers[HI_REG] = 0;
} else {
tmp = rs / rt;
registers[LO_REG] = (int) tmp;
tmp = rs % rt;
registers[HI_REG] = (int) tmp;
}
break;
case OP_JAL:
registers[RET_ADDR_REG] = registers[NEXT_PC_REG] + 4;
case OP_J:
pcAfter = (pcAfter & 0xF0000000) | IndexToAddr(instr->extra);
break;
case OP_JALR:
registers[instr->rd] = registers[NEXT_PC_REG] + 4;
case OP_JR:
pcAfter = registers[instr->rs];
break;
case OP_LB:
case OP_LBU:
tmp = registers[instr->rs] + instr->extra;
if (!ReadMem(tmp, 1, &value))
return;
if (value & 0x80 && instr->opCode == OP_LB)
value |= 0xFFFFFF00;
else
value &= 0xFF;
nextLoadReg = instr->rt;
nextLoadValue = value;
break;
case OP_LH:
case OP_LHU:
tmp = registers[instr->rs] + instr->extra;
if (tmp & 0x1) {
RaiseException(ADDRESS_ERROR_EXCEPTION, tmp);
return;
}
if (!ReadMem(tmp, 2, &value))
return;
if (value & 0x8000 && instr->opCode == OP_LH)
value |= 0xFFFF0000;
else
value &= 0xFFFF;
nextLoadReg = instr->rt;
nextLoadValue = value;
break;
case OP_LUI:
DEBUG('P', "Executing: LUI r%d,%d\n", instr->rt, instr->extra);
registers[instr->rt] = instr->extra << 16;
break;
case OP_LW:
tmp = registers[instr->rs] + instr->extra;
if (tmp & 0x3) {
RaiseException(ADDRESS_ERROR_EXCEPTION, tmp);
return;
}
if (!ReadMem(tmp, 4, &value))
return;
nextLoadReg = instr->rt;
nextLoadValue = value;
break;
case OP_LWL:
tmp = registers[instr->rs] + instr->extra;
// `ReadMem` assumes all 4 byte requests are aligned on an even
// word boundary. Also, the little endian/big endian swap code
// would fail (I think) if the other cases are ever exercised.
ASSERT((tmp & 0x3) == 0);
if (!ReadMem(tmp, 4, &value))
return;
if (registers[LOAD_REG] == instr->rt)
nextLoadValue = registers[LOAD_VALUE_REG];
else
nextLoadValue = registers[instr->rt];
switch (tmp & 0x3) {
case 0:
nextLoadValue = value;
break;
case 1:
nextLoadValue = (nextLoadValue & 0xFF) | value << 8;
break;
case 2:
nextLoadValue = (nextLoadValue & 0xFFFF) | value << 16;
break;
case 3:
nextLoadValue = (nextLoadValue & 0xFFFFFF) | value << 24;
break;
}
nextLoadReg = instr->rt;
break;
case OP_LWR:
tmp = registers[instr->rs] + instr->extra;
// `ReadMem` assumes all 4 byte requests are aligned on an even
// word boundary. Also, the little endian/big endian swap code
// would fail (I think) if the other cases are ever exercised.
ASSERT((tmp & 0x3) == 0);
if (!ReadMem(tmp, 4, &value))
return;
if (registers[LOAD_REG] == instr->rt)
nextLoadValue = registers[LOAD_VALUE_REG];
else
nextLoadValue = registers[instr->rt];
switch (tmp & 0x3) {
case 0:
nextLoadValue = (nextLoadValue & 0xFFFFFF00)
| (value >> 24 & 0xFF);
break;
case 1:
nextLoadValue = (nextLoadValue & 0xFFFF0000)
| (value >> 16 & 0xFFFF);
break;
case 2:
nextLoadValue = (nextLoadValue & 0xFF000000)
| (value >> 8 & 0xFFFFFF);
break;
case 3:
nextLoadValue = value;
break;
}
nextLoadReg = instr->rt;
break;
case OP_MFHI:
registers[instr->rd] = registers[HI_REG];
break;
case OP_MFLO:
registers[instr->rd] = registers[LO_REG];
break;
case OP_MTHI:
registers[HI_REG] = registers[instr->rs];
break;
case OP_MTLO:
registers[LO_REG] = registers[instr->rs];
break;
case OP_MULT:
Mult(registers[instr->rs], registers[instr->rt],
true, ®isters[HI_REG], ®isters[LO_REG]);
break;
case OP_MULTU:
Mult(registers[instr->rs], registers[instr->rt],
false, ®isters[HI_REG], ®isters[LO_REG]);
break;
case OP_NOR:
registers[instr->rd] = ~(registers[instr->rs]
| registers[instr->rt]);
break;
case OP_OR:
registers[instr->rd] = registers[instr->rs]
| registers[instr->rt];
break;
case OP_ORI:
registers[instr->rt] = registers[instr->rs]
| (instr->extra & 0xFFFF);
break;
case OP_SB:
if (!WriteMem((unsigned) (registers[instr->rs] + instr->extra),
1, registers[instr->rt]))
return;
break;
case OP_SH:
if (!WriteMem((unsigned) (registers[instr->rs] + instr->extra),
2, registers[instr->rt]))
return;
break;
case OP_SLL:
registers[instr->rd] = registers[instr->rt] << instr->extra;
break;
case OP_SLLV:
registers[instr->rd] = registers[instr->rt]
<< (registers[instr->rs] & 0x1F);
break;
case OP_SLT:
if (registers[instr->rs] < registers[instr->rt])
registers[instr->rd] = 1;
else
registers[instr->rd] = 0;
break;
case OP_SLTI:
if (registers[instr->rs] < instr->extra)
registers[instr->rt] = 1;
else
registers[instr->rt] = 0;
break;
case OP_SLTIU:
rs = registers[instr->rs];
imm = instr->extra;
if (rs < imm)
registers[instr->rt] = 1;
else
registers[instr->rt] = 0;
break;
case OP_SLTU:
rs = registers[instr->rs];
rt = registers[instr->rt];
if (rs < rt)
registers[instr->rd] = 1;
else
registers[instr->rd] = 0;
break;
case OP_SRA:
registers[instr->rd] = registers[instr->rt] >> instr->extra;
break;
case OP_SRAV:
registers[instr->rd] = registers[instr->rt]
>> (registers[instr->rs] & 0x1F);
break;
case OP_SRL:
tmp = registers[instr->rt];
tmp >>= instr->extra;
registers[instr->rd] = tmp;
break;
case OP_SRLV:
tmp = registers[instr->rt];
tmp >>= registers[instr->rs] & 0x1F;
registers[instr->rd] = tmp;
break;
case OP_SUB:
diff = registers[instr->rs] - registers[instr->rt];
if ((registers[instr->rs] ^ registers[instr->rt]) & SIGN_BIT &&
(registers[instr->rs] ^ diff) & SIGN_BIT)
{
RaiseException(OVERFLOW_EXCEPTION, 0);
return;
}
registers[instr->rd] = diff;
break;
case OP_SUBU:
registers[instr->rd] = registers[instr->rs]
- registers[instr->rt];
break;
case OP_SW:
if (!WriteMem((unsigned) (registers[instr->rs] + instr->extra),
4, registers[instr->rt]))
return;
break;
case OP_SWL:
tmp = registers[instr->rs] + instr->extra;
// The little endian/big endian swap code would fail (I think) if
// the other cases are ever exercised.
ASSERT((tmp & 0x3) == 0);
if (!ReadMem(tmp & ~0x3, 4, &value))
return;
switch (tmp & 0x3) {
case 0:
value = registers[instr->rt];
break;
case 1:
value = (value & 0xFF000000)
| (registers[instr->rt] >> 8 & 0xFFFFFF);
break;
case 2:
value = (value & 0xFFFF0000)
| (registers[instr->rt] >> 16 & 0xFFFF);
break;
case 3:
value = (value & 0xFFFFFF00)
| (registers[instr->rt] >> 24 & 0xFF);
break;
}
if (!WriteMem(tmp & ~0x3, 4, value))
return;
break;
case OP_SWR:
tmp = registers[instr->rs] + instr->extra;
// The little endian/big endian swap code would fail (I think) if
// the other cases are ever exercised.
ASSERT((tmp & 0x3) == 0);
if (!ReadMem(tmp & ~0x3, 4, &value))
return;
switch (tmp & 0x3) {
case 0:
value = (value & 0xFFFFFF)
| registers[instr->rt] << 24;
break;
case 1:
value = (value & 0xFFFF)
| registers[instr->rt] << 16;
break;
case 2:
value = (value & 0xFF) | registers[instr->rt] << 8;
break;
case 3:
value = registers[instr->rt];
break;
}
if (!WriteMem(tmp & ~0x3, 4, value))
return;
break;
case OP_SYSCALL:
RaiseException(SYSCALL_EXCEPTION, 0);
return;
case OP_XOR:
registers[instr->rd] = registers[instr->rs]
^ registers[instr->rt];
break;
case OP_XORI:
registers[instr->rt] = registers[instr->rs]
^ (instr->extra & 0xFFFF);
break;
case OP_RES:
case OP_UNIMP:
RaiseException(ILLEGAL_INSTR_EXCEPTION, 0);
return;
default:
ASSERT(false);
}
// Now we have successfully executed the instruction.
// Do any delayed load operation.
DelayedLoad(nextLoadReg, nextLoadValue);
// Advance program counters.
registers[PREV_PC_REG] = registers[PC_REG];
// For debugging, in case we are jumping into lala-land.
registers[PC_REG] = registers[NEXT_PC_REG];
registers[NEXT_PC_REG] = pcAfter;
} // Machine::ExecInstruction
| 20,129 | 6,190 |
#include <math.h>
#include <iostream>
#include <math.h>
#include "prediction.h"
using std::cout;
using std::endl;
using std::min;
using std::max;
Prediction::Prediction()
{
init_lanes();
}
Prediction::~Prediction() { }
void Prediction::update(vector<vector<double>>& sensor_fusion, Vehicle& egocar, Trajectory& prev_path)
{
int prev_path_size = prev_path.size();
int ego_lane = egocar.get_lane();
double ego_s = egocar.s;
if (prev_path_size > 2) {
ego_s = prev_path.end_s;
}
reset_lanes();
for (int i = 0; i < sensor_fusion.size(); ++i)
{
if (sensor_fusion[i][6] < 0) continue;
Vehicle car((int)sensor_fusion[i][0], //id
sensor_fusion[i][1], //x
sensor_fusion[i][2], //y
sensor_fusion[i][3], //vx
sensor_fusion[i][4], //vy
sensor_fusion[i][5], //s
sensor_fusion[i][6]); //d
// projection of s value of the car in the future
// (i.e. when we would have passed through all the
// points in previous_path)
int car_lane = car.get_lane();
double car_speed = sqrt(car.vx*car.vx + car.vy*car.vy); // m/s
car.s += (double)prev_path_size * TIMESTEP * car_speed;
// distance from ego car to the car in front of us
double dist = car.s - ego_s;
Lane& lane = lanes[car_lane];
if (lane.id == ego_lane) {
if(dist >= 0 && dist < TOO_CLOSE_GAP) {
lane.blocked = true;
}
} else {
double delta_v = egocar.speed - car_speed;
double adapted_lcgap_f = LANE_CHANGE_GAP_FRONT + delta_v;
double adapted_lcgap_r = min(LANE_CHANGE_GAP_REAR + delta_v, -10.0);
if (adapted_lcgap_r < dist && dist < adapted_lcgap_f) {
lane.blocked = true;
}
}
if(dist >= 0) {
lane.front_dist = min(lane.front_dist, dist);
if (dist < TOO_CLOSE_GAP) {
lane.front_v = min(lane.front_v, car_speed);
} else {
lane.front_v = min(lane.front_v, MAX_SPEED);
}
}
}
bool all_bloked = true;
for (int i = 0; i < NUM_LANES; i++) {
all_bloked &= lanes[i].blocked;
}
all_lanes_blocked = all_bloked;
}
void Prediction::init_lanes()
{
for (int i = 0; i < NUM_LANES; i++)
{
Lane lane;
lane.id = i;
lane.blocked = false;
lane.front_dist = PREDICTION_HIROZON;
lane.front_v = MAX_SPEED;
lanes.push_back(lane);
}
}
void Prediction::reset_lanes()
{
all_lanes_blocked = false;
for (int i = 0; i < NUM_LANES; i++)
{
lanes[i].blocked = false;
lanes[i].front_dist = PREDICTION_HIROZON;
lanes[i].front_v = MAX_SPEED;
}
}
std::ostream& operator<<(std::ostream &strm, const Prediction &pred) {
for (int i = 0; i < NUM_LANES; i++)
{
const Lane& lane = pred.lanes[i];
strm << "Lane " << i
<< ": blocked=" << lane.blocked
<< ", front_dist=" << lane.front_dist
<< ", front_v=" << lane.front_v << endl;
}
strm << "---- ALL_BLOCKED=" << pred.all_lanes_blocked << endl;
return strm;
}
| 3,398 | 1,277 |
#include "global.h"
#include "ArchHooks_Win32.h"
#include "RageUtil.h"
#include "RageLog.h"
#include "RageThreads.h"
#include "ProductInfo.h"
#include "archutils/win32/AppInstance.h"
#include "archutils/win32/crash.h"
#include "archutils/win32/DebugInfoHunt.h"
#include "archutils/win32/ErrorStrings.h"
#include "archutils/win32/RestartProgram.h"
#include "archutils/win32/GotoURL.h"
#include "archutils/Win32/RegistryAccess.h"
static HANDLE g_hInstanceMutex;
static bool g_bIsMultipleInstance = false;
#if _MSC_VER >= 1400 // VC8
void InvalidParameterHandler( const wchar_t *szExpression, const wchar_t *szFunction, const wchar_t *szFile,
unsigned int iLine, uintptr_t pReserved )
{
FAIL_M( "Invalid parameter" ); //TODO: Make this more informative
}
#endif
ArchHooks_Win32::ArchHooks_Win32()
{
HOOKS = this;
/* Disable critical errors, and handle them internally. We never want the
* "drive not ready", etc. dialogs to pop up. */
SetErrorMode( SetErrorMode(0) | SEM_FAILCRITICALERRORS );
CrashHandler::CrashHandlerHandleArgs( g_argc, g_argv );
SetUnhandledExceptionFilter( CrashHandler::ExceptionHandler );
#if _MSC_VER >= 1400 // VC8
_set_invalid_parameter_handler( InvalidParameterHandler );
#endif
/* Windows boosts priority on keyboard input, among other things. Disable that for
* the main thread. */
SetThreadPriorityBoost( GetCurrentThread(), TRUE );
g_hInstanceMutex = CreateMutex( NULL, TRUE, PRODUCT_ID );
g_bIsMultipleInstance = false;
if( GetLastError() == ERROR_ALREADY_EXISTS )
g_bIsMultipleInstance = true;
}
ArchHooks_Win32::~ArchHooks_Win32()
{
CloseHandle( g_hInstanceMutex );
}
void ArchHooks_Win32::DumpDebugInfo()
{
/* This is a good time to do the debug search: before we actually
* start OpenGL (in case something goes wrong). */
SearchForDebugInfo();
}
struct CallbackData
{
HWND hParent;
HWND hResult;
};
// Like GW_ENABLEDPOPUP:
static BOOL CALLBACK GetEnabledPopup( HWND hWnd, LPARAM lParam )
{
CallbackData *pData = (CallbackData *) lParam;
if( GetParent(hWnd) != pData->hParent )
return TRUE;
if( (GetWindowLong(hWnd, GWL_STYLE) & WS_POPUP) != WS_POPUP )
return TRUE;
if( !IsWindowEnabled(hWnd) )
return TRUE;
pData->hResult = hWnd;
return FALSE;
}
bool ArchHooks_Win32::CheckForMultipleInstances(int argc, char* argv[])
{
if( !g_bIsMultipleInstance )
return false;
/* Search for the existing window. Prefer to use the class name, which is less likely to
* have a false match, and will match the gameplay window. If that fails, try the window
* name, which should match the loading window. */
HWND hWnd = FindWindow( PRODUCT_ID, NULL );
if( hWnd == NULL )
hWnd = FindWindow( NULL, PRODUCT_ID );
if( hWnd != NULL )
{
/* If the application has a model dialog box open, we want to be sure to give focus to it,
* not the main window. */
CallbackData data;
data.hParent = hWnd;
data.hResult = NULL;
EnumWindows( GetEnabledPopup, (LPARAM) &data );
if( data.hResult != NULL )
SetForegroundWindow( data.hResult );
else
SetForegroundWindow( hWnd );
// Send the command line to the existing window.
vector<RString> vsArgs;
for( int i=0; i<argc; i++ )
vsArgs.push_back( argv[i] );
RString sAllArgs = join("|", vsArgs);
COPYDATASTRUCT cds;
cds.dwData = 0;
cds.cbData = sAllArgs.size();
cds.lpData = (void*)sAllArgs.data();
SendMessage(
(HWND)hWnd, // HWND hWnd = handle of destination window
WM_COPYDATA,
(WPARAM)NULL, // HANDLE OF SENDING WINDOW
(LPARAM)&cds ); // 2nd msg parameter = pointer to COPYDATASTRUCT
}
return true;
}
void ArchHooks_Win32::RestartProgram()
{
Win32RestartProgram();
}
void ArchHooks_Win32::SetTime( tm newtime )
{
SYSTEMTIME st;
ZERO( st );
st.wYear = (WORD)newtime.tm_year+1900;
st.wMonth = (WORD)newtime.tm_mon+1;
st.wDay = (WORD)newtime.tm_mday;
st.wHour = (WORD)newtime.tm_hour;
st.wMinute = (WORD)newtime.tm_min;
st.wSecond = (WORD)newtime.tm_sec;
st.wMilliseconds = 0;
SetLocalTime( &st );
}
void ArchHooks_Win32::BoostPriority()
{
/* We just want a slight boost, so we don't skip needlessly if something happens
* in the background. We don't really want to be high-priority--above normal should
* be enough. However, ABOVE_NORMAL_PRIORITY_CLASS is only supported in Win2000
* and later. */
OSVERSIONINFO version;
version.dwOSVersionInfoSize=sizeof(version);
if( !GetVersionEx(&version) )
{
LOG->Warn( werr_ssprintf(GetLastError(), "GetVersionEx failed") );
return;
}
#ifndef ABOVE_NORMAL_PRIORITY_CLASS
#define ABOVE_NORMAL_PRIORITY_CLASS 0x00008000
#endif
DWORD pri = HIGH_PRIORITY_CLASS;
if( version.dwMajorVersion >= 5 )
pri = ABOVE_NORMAL_PRIORITY_CLASS;
/* Be sure to boost the app, not the thread, to make sure the
* sound thread stays higher priority than the main thread. */
SetPriorityClass( GetCurrentProcess(), pri );
}
void ArchHooks_Win32::UnBoostPriority()
{
SetPriorityClass( GetCurrentProcess(), NORMAL_PRIORITY_CLASS );
}
void ArchHooks_Win32::SetupConcurrentRenderingThread()
{
SetThreadPriority( GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL );
}
bool ArchHooks_Win32::GoToURL( const RString &sUrl )
{
return ::GotoURL( sUrl );
}
float ArchHooks_Win32::GetDisplayAspectRatio()
{
DEVMODE dm;
ZERO( dm );
dm.dmSize = sizeof(dm);
BOOL bResult = EnumDisplaySettings( NULL, ENUM_REGISTRY_SETTINGS, &dm );
ASSERT( bResult != 0 );
return dm.dmPelsWidth / (float)dm.dmPelsHeight;
}
RString ArchHooks_Win32::GetClipboard()
{
HGLOBAL hgl;
LPTSTR lpstr;
RString ret;
// First make sure that the clipboard actually contains a string
// (or something stringifiable)
if(unlikely( !IsClipboardFormatAvailable( CF_TEXT ) )) return "";
// Yes. All this mess just to gain access to the string stored by the clipboard.
// I'm having flashbacks to Berkeley sockets.
if(unlikely( !OpenClipboard( NULL ) ))
{ LOG->Warn(werr_ssprintf( GetLastError(), "InputHandler_DirectInput: OpenClipboard() failed" )); return ""; }
hgl = GetClipboardData( CF_TEXT );
if(unlikely( hgl == NULL ))
{ LOG->Warn(werr_ssprintf( GetLastError(), "InputHandler_DirectInput: GetClipboardData() failed" )); CloseClipboard(); return ""; }
lpstr = (LPTSTR) GlobalLock( hgl );
if(unlikely( lpstr == NULL ))
{ LOG->Warn(werr_ssprintf( GetLastError(), "InputHandler_DirectInput: GlobalLock() failed" )); CloseClipboard(); return ""; }
// And finally, we have a char (or wchar_t) array of the clipboard contents,
// pointed to by sToPaste.
// (Hopefully.)
#ifdef UNICODE
ret = WStringToRString( wstring()+*lpstr );
#else
ret = RString( lpstr );
#endif
// And now we clean up.
GlobalUnlock( hgl );
CloseClipboard();
return ret;
}
/*
* (c) 2003-2004 Glenn Maynard, Chris Danford
* All rights reserved.
*
* 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, and/or sell copies of the Software, and to permit persons to
* whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* 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 OF
* THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
* INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT
* OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
| 8,022 | 3,086 |
class Solution {
public:
void Perm(vector<vector<int>>& ret, vector<int>& nums, int index, int size){
//结束条件
if(index == size){
vector<int> tmp = nums;
ret.push_back(tmp);
return;
}
for(int i = index; i < size; i++){
//在0位置依次固定nums中的每一个数
//之后再固定1,2,3位置
swap(nums[i], nums[index]);
//向下递归(分治思想)
Perm(ret, nums, index + 1, size);
//还原原数组,避免重复
swap(nums[i], nums[index]);
}
}
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> ret;
Perm(ret, nums, 0, nums.size());
return ret;
}
};
| 709 | 280 |
#include <cstdio>
#include <cstdlib>
using namespace std;
char cmd[100];
int main() {
for (int i = 1; i <= 10; i++) {
sprintf(cmd, "cp star%d.in star.in", i);
system(cmd);
sprintf(cmd, "./star");
system(cmd);
sprintf(cmd, "mv star.out star%d.out", i);
system(cmd);
sprintf(cmd, "rm star.in");
system(cmd);
}
return 0;
}
| 399 | 155 |
/*
* Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
*
* This file is part of ZLToolKit(https://github.com/xiongziliang/ZLToolKit).
*
* Use of this source code is governed by MIT license that can be found in the
* LICENSE file in the root of the source tree. All contributing project authors
* may be found in the AUTHORS file in the root of the source tree.
*/
#include <type_traits>
#include "sockutil.h"
#include "Socket.h"
#include "Util/util.h"
#include "Util/logger.h"
#include "Util/uv_errno.h"
#include "Thread/semaphore.h"
#include "Poller/EventPoller.h"
#include "Thread/WorkThreadPool.h"
using namespace std;
#define LOCK_GUARD(mtx) lock_guard<decltype(mtx)> lck(mtx)
namespace toolkit {
Socket::Socket(const EventPoller::Ptr &poller,bool enableMutex) :
_mtx_sockFd(enableMutex),
_mtx_bufferWaiting(enableMutex),
_mtx_bufferSending(enableMutex),
_mtx_event(enableMutex){
_poller = poller;
if(!_poller){
_poller = EventPollerPool::Instance().getPoller();
}
_canSendSock = true;
setOnRead(nullptr);
setOnErr(nullptr);
setOnAccept(nullptr);
setOnFlush(nullptr);
setOnBeforeAccept(nullptr);
}
Socket::~Socket() {
closeSock();
//TraceL << endl;
}
void Socket::setOnRead(const onReadCB &cb) {
LOCK_GUARD(_mtx_event);
if (cb) {
_readCB = cb;
} else {
_readCB = [](const Buffer::Ptr &buf,struct sockaddr * , int) {
WarnL << "Socket not set readCB";
};
}
}
void Socket::setOnErr(const onErrCB &cb) {
LOCK_GUARD(_mtx_event);
if (cb) {
_errCB = cb;
} else {
_errCB = [](const SockException &err) {
WarnL << "Socket not set errCB";
};
}
}
void Socket::setOnAccept(const onAcceptCB &cb) {
LOCK_GUARD(_mtx_event);
if (cb) {
_acceptCB = cb;
} else {
_acceptCB = [](Socket::Ptr &sock) {
WarnL << "Socket not set acceptCB";
};
}
}
void Socket::setOnFlush(const onFlush &cb) {
LOCK_GUARD(_mtx_event);
if (cb) {
_flushCB = cb;
} else {
_flushCB = []() {return true;};
}
}
//设置Socket生成拦截器
void Socket::setOnBeforeAccept(const onBeforeAcceptCB &cb){
LOCK_GUARD(_mtx_event);
if (cb) {
_beforeAcceptCB = cb;
} else {
_beforeAcceptCB = [](const EventPoller::Ptr &poller) {
return nullptr;
};
}
}
void Socket::connect(const string &url, uint16_t port,const onErrCB &connectCB, float timeoutSec,const char *localIp,uint16_t localPort) {
//重置当前socket
closeSock();
auto poller = _poller;
weak_ptr<Socket> weakSelf = shared_from_this();
//是否已经触发连接超时回调
shared_ptr<bool> timeOuted = std::make_shared<bool>(false);
auto asyncConnectCB = std::make_shared<function<void(int)> >([poller,weakSelf,connectCB,timeOuted](int sock){
poller->async([weakSelf,connectCB,timeOuted,sock](){
auto strongSelf = weakSelf.lock();
if(!strongSelf || *timeOuted ){
//本对象已经销毁或已经超时回调
if(sock != -1){
close(sock);
}
return;
}
if(sock == -1){
//发起连接服务器失败,一般都是dns解析失败导致
connectCB(SockException(Err_dns, get_uv_errmsg(true)));
//取消超时定时器
strongSelf->_conTimer.reset();
return;
}
auto sockFD = strongSelf->makeSock(sock,SockNum::Sock_TCP);
weak_ptr<SockFD> weakSock = sockFD;
//监听该socket是否可写,可写表明已经连接服务器成功
int result = strongSelf->_poller->addEvent(sock, Event_Write, [weakSelf,weakSock,connectCB,timeOuted](int event) {
auto strongSelf = weakSelf.lock();
auto strongSock = weakSock.lock();
if(!strongSelf || !strongSock || *timeOuted) {
//自己或该Socket已经被销毁或已经触发超时回调
return;
}
//socket可写事件,说明已经连接服务器成功
strongSelf->onConnected(strongSock,connectCB);
});
if(result == -1){
WarnL << "开始Poll监听失败";
connectCB(SockException(Err_other,"开始Poll监听失败"));
strongSelf->_conTimer.reset();
return;
}
//保存fd
LOCK_GUARD(strongSelf->_mtx_sockFd);
strongSelf->_sockFd = sockFD;
});
});
weak_ptr<function<void(int)> > weakTask = asyncConnectCB;
_asyncConnectCB = asyncConnectCB;
//DNS解析放在后台线程执行
string strLocalIp = localIp;
WorkThreadPool::Instance().getExecutor()->async([url,port,strLocalIp,localPort,weakTask](){
//注释式dns解析,并且异步连接服务器
int sock = SockUtil::connect(url.data(), port, true, strLocalIp.data(), localPort);
auto strongTask = weakTask.lock();
if(strongTask){
(*strongTask)(sock);
} else if(sock != -1){
//本次连接被取消
close(sock);
}
});
//连接超时定时器
_conTimer = std::make_shared<Timer>(timeoutSec, [weakSelf,connectCB,timeOuted]() {
auto strongSelf = weakSelf.lock();
if(!strongSelf) {
//自己已经销毁
return false;
}
*timeOuted = true;
SockException err(Err_timeout, uv_strerror(UV_ETIMEDOUT));
strongSelf->emitErr(err);
connectCB(err);
return false;
},_poller, false);
}
void Socket::onConnected(const SockFD::Ptr &pSock,const onErrCB &connectCB) {
_conTimer.reset();
auto err = getSockErr(pSock, false);
do {
if (!err) {
_poller->delEvent(pSock->rawFd());
if (!attachEvent(pSock, false)) {
WarnL << "开始Poll监听失败";
err.reset(Err_other, "开始Poll监听失败");
break;
}
pSock->setConnected();
connectCB(err);
return;
}
}while(0);
emitErr(err);
connectCB(err);
}
SockException Socket::getSockErr(const SockFD::Ptr &sock, bool tryErrno) {
int error = 0, len;
len = sizeof(int);
getsockopt(sock->rawFd(), SOL_SOCKET, SO_ERROR, (char *)&error, (socklen_t *) &len);
if (error == 0) {
if(tryErrno){
error = get_uv_error(true);
}
}else {
error = uv_translate_posix_error(error);
}
switch (error) {
case 0:
case UV_EAGAIN:
return SockException(Err_success, "success");
case UV_ECONNREFUSED:
return SockException(Err_refused, uv_strerror(error),error);
case UV_ETIMEDOUT:
return SockException(Err_timeout, uv_strerror(error),error);
default:
return SockException(Err_other, uv_strerror(error),error);
}
}
bool Socket::attachEvent(const SockFD::Ptr &pSock,bool isUdp) {
weak_ptr<Socket> weakSelf = shared_from_this();
weak_ptr<SockFD> weakSock = pSock;
_enableRecv = true;
if(!_readBuffer){
//udp包最大能达到64KB
_readBuffer = std::make_shared<BufferRaw>(isUdp ? 0xFFFF : 128 * 1024);
}
int result = _poller->addEvent(pSock->rawFd(), Event_Read | Event_Error | Event_Write, [weakSelf,weakSock,isUdp](int event) {
auto strongSelf = weakSelf.lock();
auto strongSock = weakSock.lock();
if(!strongSelf || !strongSock) {
return;
}
if (event & Event_Error) {
strongSelf->onError(strongSock);
return;
}
if (event & Event_Read) {
strongSelf->onRead(strongSock,isUdp);
}
if (event & Event_Write) {
strongSelf->onWriteAble(strongSock);
}
});
return -1 != result;
}
void Socket::setReadBuffer(const BufferRaw::Ptr &readBuffer){
if(!readBuffer || readBuffer->getCapacity() < 2){
return;
}
weak_ptr<Socket> weakSelf = shared_from_this();
_poller->async([readBuffer,weakSelf](){
auto strongSelf = weakSelf.lock();
if(strongSelf){
strongSelf->_readBuffer = std::move(readBuffer);
}
});
}
int Socket::onRead(const SockFD::Ptr &pSock,bool isUdp) {
int ret = 0 , nread = 0 ,sock = pSock->rawFd();
struct sockaddr peerAddr;
socklen_t len = sizeof(struct sockaddr);
//保存_readBuffer的临时变量,防止onRead事件中设置_readBuffer
auto readBuffer = _readBuffer;
auto data = readBuffer->data();
//最后一个字节设置为'\0'
auto capacity = readBuffer->getCapacity() - 1;
while (_enableRecv) {
do {
nread = recvfrom(sock, data, capacity, 0, &peerAddr, &len);
} while (-1 == nread && UV_EINTR == get_uv_error(true));
if (nread == 0) {
if (!isUdp) {
emitErr(SockException(Err_eof, "end of file"));
}
return ret;
}
if (nread == -1) {
if (get_uv_error(true) != UV_EAGAIN) {
onError(pSock);
}
return ret;
}
ret += nread;
data[nread] = '\0';
//设置buffer有效数据大小
readBuffer->setSize(nread);
//触发回调
LOCK_GUARD(_mtx_event);
_readCB(readBuffer, &peerAddr, len);
}
return 0;
}
void Socket::onError(const SockFD::Ptr &pSock) {
emitErr(getSockErr(pSock));
}
bool Socket::emitErr(const SockException& err) {
{
LOCK_GUARD(_mtx_sockFd);
if (!_sockFd) {
//防止多次触发onErr事件
return false;
}
}
closeSock();
weak_ptr<Socket> weakSelf = shared_from_this();
_poller->async([weakSelf,err]() {
auto strongSelf=weakSelf.lock();
if (!strongSelf) {
return;
}
LOCK_GUARD(strongSelf->_mtx_event);
strongSelf->_errCB(err);
});
return true;
}
int Socket::send(const char *buf, int size, struct sockaddr *addr, socklen_t addr_len, bool try_flush) {
if (size <= 0) {
size = strlen(buf);
if (!size) {
return 0;
}
}
BufferRaw::Ptr ptr = obtainBuffer();
ptr->assign(buf, size);
return send(ptr, addr, addr_len, try_flush);
}
int Socket::send(const string &buf, struct sockaddr *addr, socklen_t addr_len, bool try_flush) {
return send(std::make_shared<BufferString>(buf), addr, addr_len, try_flush);
}
int Socket::send(string &&buf, struct sockaddr *addr, socklen_t addr_len, bool try_flush) {
return send(std::make_shared<BufferString>(std::move(buf)), addr, addr_len, try_flush);
}
int Socket::send(const Buffer::Ptr &buf , struct sockaddr *addr, socklen_t addr_len, bool try_flush){
auto size = buf ? buf->size() : 0;
if (!size) {
return 0;
}
SockFD::Ptr sock;
{
LOCK_GUARD(_mtx_sockFd);
sock = _sockFd;
}
if (!sock) {
//如果已断开连接或者发送超时
return -1;
}
{
LOCK_GUARD(_mtx_bufferWaiting);
_bufferWaiting.emplace_back(sock->type() == SockNum::Sock_UDP ? std::make_shared<BufferSock>(buf,addr,addr_len) : buf);
}
if(try_flush){
if (_canSendSock) {
//该socket可写
return flushData(sock, false) ? size : -1;
}
//该socket不可写,判断发送超时
if (_lastFlushTicker.elapsedTime() > _sendTimeOutMS) {
//如果发送列队中最老的数据距今超过超时时间限制,那么就断开socket连接
emitErr(SockException(Err_other, "Socket send timeout"));
return -1;
}
}
return size;
}
void Socket::onFlushed(const SockFD::Ptr &pSock) {
bool flag;
{
LOCK_GUARD(_mtx_event);
flag = _flushCB();
}
if (!flag) {
setOnFlush(nullptr);
}
}
void Socket::closeSock() {
_conTimer.reset();
_asyncConnectCB.reset();
LOCK_GUARD(_mtx_sockFd);
_sockFd.reset();
}
int Socket::getSendBufferCount(){
int ret = 0;
{
LOCK_GUARD(_mtx_bufferWaiting);
ret += _bufferWaiting.size();
}
{
LOCK_GUARD(_mtx_bufferSending);
_bufferSending.for_each([&](BufferList::Ptr &buf){
ret += buf->count();
});
}
return ret;
}
uint64_t Socket::elapsedTimeAfterFlushed(){
return _lastFlushTicker.elapsedTime();
}
bool Socket::listen(const SockFD::Ptr &pSock){
closeSock();
weak_ptr<SockFD> weakSock = pSock;
weak_ptr<Socket> weakSelf = shared_from_this();
_enableRecv = true;
int result = _poller->addEvent(pSock->rawFd(), Event_Read | Event_Error, [weakSelf,weakSock](int event) {
auto strongSelf = weakSelf.lock();
auto strongSock = weakSock.lock();
if(!strongSelf || !strongSock) {
return;
}
strongSelf->onAccept(strongSock,event);
});
if(result == -1){
WarnL << "开始Poll监听失败";
return false;
}
LOCK_GUARD(_mtx_sockFd);
_sockFd = pSock;
return true;
}
bool Socket::listen(const uint16_t port, const char* localIp, int backLog) {
int sock = SockUtil::listen(port, localIp, backLog);
if (sock == -1) {
return false;
}
return listen(makeSock(sock,SockNum::Sock_TCP));
}
bool Socket::bindUdpSock(const uint16_t port, const char* localIp) {
closeSock();
int sock = SockUtil::bindUdpSock(port, localIp);
if (sock == -1) {
return false;
}
auto pSock = makeSock(sock,SockNum::Sock_UDP);
if(!attachEvent(pSock,true)){
WarnL << "开始Poll监听失败";
return false;
}
LOCK_GUARD(_mtx_sockFd);
_sockFd = pSock;
return true;
}
int Socket::onAccept(const SockFD::Ptr &pSock,int event) {
int peerfd;
while (true) {
if (event & Event_Read) {
do{
peerfd = accept(pSock->rawFd(), NULL, NULL);
}while(-1 == peerfd && UV_EINTR == get_uv_error(true));
if (peerfd == -1) {
int err = get_uv_error(true);
if (err == UV_EAGAIN) {
//没有新连接
return 0;
}
ErrorL << "tcp服务器监听异常:" << uv_strerror(err);
onError(pSock);
return -1;
}
SockUtil::setNoSigpipe(peerfd);
SockUtil::setNoBlocked(peerfd);
SockUtil::setNoDelay(peerfd);
SockUtil::setSendBuf(peerfd);
SockUtil::setRecvBuf(peerfd);
SockUtil::setCloseWait(peerfd);
SockUtil::setCloExec(peerfd);
//拦截默认的Socket构造行为,
//在TcpServer中,默认的行为是子Socket的网络事件会派发到其他poll线程
//这样就可以发挥最大的网络性能
Socket::Ptr peerSock ;
{
LOCK_GUARD(_mtx_event);
peerSock = _beforeAcceptCB(_poller);
}
if(!peerSock){
//此处是默认构造行为,也就是子Socket
//共用父Socket的poll线程以及事件执行线程
peerSock = std::make_shared<Socket>(_poller);
}
//设置好fd,以备在TcpSession的构造函数中可以正常访问该fd
auto sockFD = peerSock->setPeerSock(peerfd);
//在accept事件中,TcpServer对象会创建TcpSession对象并绑定该Socket的相关事件(onRead/onErr)
//所以在这之前千万不能就把peerfd加入poll监听
{
LOCK_GUARD(_mtx_event);
_acceptCB(peerSock);
}
//把该peerfd加入poll监听,这个时候可能会触发其数据接收事件
if(!peerSock->attachEvent(sockFD, false)){
//加入poll监听失败,我们通知TcpServer该Socket无效
peerSock->emitErr(SockException(Err_eof,"attachEvent failed"));
}
}
if (event & Event_Error) {
ErrorL << "tcp服务器监听异常:" << get_uv_errmsg();
onError(pSock);
return -1;
}
}
}
SockFD::Ptr Socket::setPeerSock(int sock) {
closeSock();
auto pSock = makeSock(sock,SockNum::Sock_TCP);
LOCK_GUARD(_mtx_sockFd);
_sockFd = pSock;
return pSock;
}
string Socket::get_local_ip() {
LOCK_GUARD(_mtx_sockFd);
if (!_sockFd) {
return "";
}
return SockUtil::get_local_ip(_sockFd->rawFd());
}
uint16_t Socket::get_local_port() {
LOCK_GUARD(_mtx_sockFd);
if (!_sockFd) {
return 0;
}
return SockUtil::get_local_port(_sockFd->rawFd());
}
string Socket::get_peer_ip() {
LOCK_GUARD(_mtx_sockFd);
if (!_sockFd) {
return "";
}
return SockUtil::get_peer_ip(_sockFd->rawFd());
}
uint16_t Socket::get_peer_port() {
LOCK_GUARD(_mtx_sockFd);
if (!_sockFd) {
return 0;
}
return SockUtil::get_peer_port(_sockFd->rawFd());
}
string Socket::getIdentifier() const{
static string class_name = "Socket:";
return class_name + to_string(reinterpret_cast<uint64_t>(this));
}
bool Socket::flushData(const SockFD::Ptr &pSock,bool bPollerThread) {
decltype(_bufferSending) bufferSendingTmp;
{
LOCK_GUARD(_mtx_bufferSending);
if(!_bufferSending.empty()){
bufferSendingTmp.swap(_bufferSending);
}
}
if (bufferSendingTmp.empty()) {
_lastFlushTicker.resetTime();
do{
{
//_bufferSending列队中数据为空,那么我们接着消费_bufferWaiting列队中的数据
LOCK_GUARD(_mtx_bufferWaiting);
if (!_bufferWaiting.empty()) {
//把_bufferWaiting列队数据放置到_bufferSending列队
bufferSendingTmp.emplace_back(std::make_shared<BufferList>(_bufferWaiting));
break;
}
}
//如果_bufferWaiting列队中数据也为空,那么说明消费完所有未发送缓存数据
if (bPollerThread) {
//主线程触发该函数,那么该socket应该已经加入了可写事件的监听;
//那么在数据列队清空的情况下,我们需要关闭监听以免触发无意义的事件回调
stopWriteAbleEvent(pSock);
onFlushed(pSock);
}
return true;
}while(0);
}
int sockFd = pSock->rawFd();
bool isUdp = pSock->type() == SockNum::Sock_UDP;
while (!bufferSendingTmp.empty()) {
auto &packet = bufferSendingTmp.front();
int n = packet->send(sockFd,_sock_flags,isUdp);
if(n > 0){
//全部或部分发送成功
if(packet->empty()){
//全部发送成功
bufferSendingTmp.pop_front();
continue;
}
//部分发送成功
if (!bPollerThread) {
//如果该函数是主线程触发的,那么该socket应该已经加入了可写事件的监听,所以我们不需要再次加入监听
startWriteAbleEvent(pSock);
}
break;
}
//一个都没发送成功
int err = get_uv_error(true);
if (err == UV_EAGAIN) {
//等待下一次发送
if(!bPollerThread){
//如果该函数是主线程触发的,那么该socket应该已经加入了可写事件的监听,所以我们不需要再次加入监听
startWriteAbleEvent(pSock);
}
break;
}
//其他错误代码,发生异常
onError(pSock);
return false;
}
//回滚未发送完毕的数据
if(!bufferSendingTmp.empty()){
//有剩余数据
LOCK_GUARD(_mtx_bufferSending);
bufferSendingTmp.swap(_bufferSending);
_bufferSending.append(bufferSendingTmp);
//bufferSendingTmp未全部发送完毕,说明该socket不可写,直接返回
return true;
}
//bufferSendingTmp已经全部发送完毕,说明该socket还可写,我们尝试继续写
//如果是poller线程,我们尝试再次写一次(因为可能其他线程调用了send函数又有新数据了)
//如果是非poller线程,那么本次操作本来就是send函数触发的,所以不可能还有新的数据(我们假定send函数只有其他单独一个线程调用)
return bPollerThread ? flushData(pSock,bPollerThread) : true;
}
void Socket::onWriteAble(const SockFD::Ptr &pSock) {
bool emptyWaiting;
bool emptySending;
{
LOCK_GUARD(_mtx_bufferWaiting);
emptyWaiting = _bufferWaiting.empty();
}
{
LOCK_GUARD(_mtx_bufferSending);
emptySending = _bufferSending.empty();
}
if(emptyWaiting && emptySending){
//数据已经清空了,我们停止监听可写事件
stopWriteAbleEvent(pSock);
}else {
//我们尽量让其他线程来发送数据,不要占用主线程太多性能
//WarnL << "主线程发送数据";
flushData(pSock, true);
}
}
void Socket::startWriteAbleEvent(const SockFD::Ptr &pSock) {
//ErrorL;
_canSendSock = false;
int flag = _enableRecv ? Event_Read : 0;
_poller->modifyEvent(pSock->rawFd(), flag | Event_Error | Event_Write);
}
void Socket::stopWriteAbleEvent(const SockFD::Ptr &pSock) {
//ErrorL;
_canSendSock = true;
int flag = _enableRecv ? Event_Read : 0;
_poller->modifyEvent(pSock->rawFd(), flag | Event_Error);
}
void Socket::enableRecv(bool enabled) {
if(_enableRecv == enabled){
return;
}
_enableRecv = enabled;
int flag = _enableRecv ? Event_Read : 0;
_poller->modifyEvent(rawFD(), flag | Event_Error | Event_Write);
}
SockFD::Ptr Socket::makeSock(int sock,SockNum::SockType type){
return std::make_shared<SockFD>(sock,type,_poller);
}
int Socket::rawFD() const{
LOCK_GUARD(_mtx_sockFd);
if(!_sockFd){
return -1;
}
return _sockFd->rawFd();
}
void Socket::setSendTimeOutSecond(uint32_t second){
_sendTimeOutMS = second * 1000;
}
BufferRaw::Ptr Socket::obtainBuffer() {
return std::make_shared<BufferRaw>();//_bufferPool.obtain();
}
bool Socket::isSocketBusy() const{
return !_canSendSock.load();
}
const EventPoller::Ptr &Socket::getPoller() const{
return _poller;
}
bool Socket::cloneFromListenSocket(const Socket &other){
SockFD::Ptr fd;
{
LOCK_GUARD(other._mtx_sockFd);
if(!other._sockFd){
WarnL << "sockfd of src socket is null!";
return false;
}
fd = std::make_shared<SockFD>(*(other._sockFd), _poller);
}
return listen(fd);
}
bool Socket::setSendPeerAddr(const struct sockaddr *peerAddr) {
LOCK_GUARD(_mtx_sockFd);
if(!_sockFd){
return false;
}
if(_sockFd->type() != SockNum::Sock_UDP){
return false;
}
return 0 == ::connect(_sockFd->rawFd(),peerAddr, sizeof(struct sockaddr));
}
void Socket::setSendFlags(int flags) {
_sock_flags = flags;
}
///////////////SockSender///////////////////
SockSender &SockSender::operator<<(const char *buf) {
send(buf);
return *this;
}
SockSender &SockSender::operator<<(const string &buf) {
send(buf);
return *this;
}
SockSender &SockSender::operator<<(string &&buf) {
send(std::move(buf));
return *this;
}
SockSender &SockSender::operator<<(const Buffer::Ptr &buf) {
send(buf);
return *this;
}
int SockSender::send(const string &buf) {
auto buffer = std::make_shared<BufferString>(buf);
return send(buffer);
}
int SockSender::send(string &&buf) {
auto buffer = std::make_shared<BufferString>(std::move(buf));
return send(buffer);
}
int SockSender::send(const char *buf, int size) {
auto buffer = std::make_shared<BufferRaw>();
buffer->assign(buf,size);
return send(buffer);
}
///////////////SocketHelper///////////////////
SocketHelper::SocketHelper(const Socket::Ptr &sock) {
setSock(sock);
}
SocketHelper::~SocketHelper() {}
void SocketHelper::setSock(const Socket::Ptr &sock) {
_sock = sock;
if(_sock){
_poller = _sock->getPoller();
}
}
EventPoller::Ptr SocketHelper::getPoller(){
return _poller;
}
int SocketHelper::send(const Buffer::Ptr &buf) {
if (!_sock) {
return -1;
}
return _sock->send(buf, nullptr, 0, _try_flush);
}
BufferRaw::Ptr SocketHelper::obtainBuffer(const void *data, int len) {
BufferRaw::Ptr buffer;
if (!_sock) {
buffer = std::make_shared<BufferRaw>();
}else{
buffer = _sock->obtainBuffer();
}
if(data && len){
buffer->assign((const char *)data,len);
}
return buffer;
};
void SocketHelper::shutdown(const SockException &ex) {
if (_sock) {
_sock->emitErr(ex);
}
}
string SocketHelper::get_local_ip(){
if(_sock && _local_ip.empty()){
_local_ip = _sock->get_local_ip();
}
return _local_ip;
}
uint16_t SocketHelper::get_local_port() {
if(_sock && _local_port == 0){
_local_port = _sock->get_local_port();
}
return _local_port;
}
string SocketHelper::get_peer_ip(){
if(_sock && _peer_ip.empty()){
_peer_ip = _sock->get_peer_ip();
}
return _peer_ip;
}
uint16_t SocketHelper::get_peer_port() {
if(_sock && _peer_port == 0){
_peer_port = _sock->get_peer_port();
}
return _peer_port;
}
bool SocketHelper::isSocketBusy() const{
if (!_sock) {
return true;
}
return _sock->isSocketBusy();
}
Task::Ptr SocketHelper::async(TaskIn &&task, bool may_sync) {
return _poller->async(std::move(task),may_sync);
}
Task::Ptr SocketHelper::async_first(TaskIn &&task, bool may_sync) {
return _poller->async_first(std::move(task),may_sync);
}
void SocketHelper::setSendFlushFlag(bool try_flush){
_try_flush = try_flush;
}
void SocketHelper::setSendFlags(int flags){
if(!_sock){
return;
}
_sock->setSendFlags(flags);
}
} // namespace toolkit
| 24,619 | 9,330 |
#ifndef GPCPP_CHAPTER03_INPUTCOMPONENT_HPP
#define GPCPP_CHAPTER03_INPUTCOMPONENT_HPP
#include "MoveComponent.hpp"
namespace gpcpp::c03 {
class InputComponent : public MoveComponent {
public:
explicit InputComponent(class Actor *Owner);
void processInput(const uint8_t *KeyState) override;
[[nodiscard]] float getMaxAngularSpeed() const { return MaxAngularSpeed; }
[[nodiscard]] float getMaxForward() const { return MaxForwardSpeed; }
[[nodiscard]] int getForwardKey() const { return ForwardKey; }
[[nodiscard]] int getBackKey() const { return BackKey; }
[[nodiscard]] int getClockwiseKey() const { return ClockwiseKey; }
[[nodiscard]] int getCounterClockwiseKey() const {
return CounterClockwiseKey;
}
void setMaxAngularSpeed(float Speed) { MaxAngularSpeed = Speed; }
void setMaxForwardSpeed(float Speed) { MaxForwardSpeed = Speed; }
void setForwardKey(int Key) { ForwardKey = Key; }
void setBackKey(int Key) { BackKey = Key; }
void setClockwiseKey(int Key) { ClockwiseKey = Key; }
void setCounterClockwiseKey(int Key) { CounterClockwiseKey = Key; }
private:
float MaxAngularSpeed;
float MaxForwardSpeed;
int ForwardKey;
int BackKey;
int ClockwiseKey;
int CounterClockwiseKey;
};
} // namespace gpcpp::c03
#endif // GPCPP_CHAPTER03_INPUTCOMPONENT_HPP
| 1,307 | 466 |
server {
listen 80;
server_name youth.cc;
charset utf-8;
root /home/work/dev/app/youth/public;
access_log logs/youth.app.access.log main;
location / {
index index.html index.htm index.php;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# 不记录 favicon.ico 错误日志
location ~ (favicon.ico){
log_not_found off;
expires 100d;
access_log off;
break;
}
# 静态文件设置过期时间
location ~* \.(ico|css|js|gif|jpe?g|png)(\?[0-9]+)?$ {
expires 100d;
break;
}
# 静态文件代理
location ~ /static/ {
rewrite "^/static/(.*)$" /static/$1 break;
}
location ~ /chart.php {
fastcgi_pass 127.0.0.1:9000;
fastcgi_param SCRIPT_FILENAME /home/work/rd/analyze/chart.php;
include fastcgi_params;
}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#location ~ \.php$ {
# 其他请求一律单一入口处理
location ~ / {
rewrite "^(.*)$" /index.php break;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
| 1,388 | 568 |
#ifndef RECTANGLE_HPP
#define RECTANGLE_HPP
#include "vector2.hpp"
namespace blub
{
class rectangle
{
public:
vector2 topLeft, rightBottom;
rectangle(void);
rectangle(const vector2 &topLeft_, const vector2 &rightBottom_);
void merge(const rectangle &other);
void merge(const vector2 &other);
};
}
#endif // RECTANGLE_HPP
| 348 | 124 |
/**
* Copyright 2019 Huawei Technologies Co., Ltd
*
* 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 "init_schedule.h"
namespace akg {
namespace ir {
namespace poly {
void InitSchedule::RemoveUninitializedCopyin(isl::union_map ©_in, const Binds &binds) {
isl::union_set copyin_range = copy_in.range();
auto ForeachSetFn = [©_in, &binds](const isl::set &set) {
std::string tensor_name = set.get_tuple_name();
bool defined = false;
for (auto bind : binds) {
if (bind.first->op->name == tensor_name) {
defined = true;
}
}
if (!defined) {
copy_in = copy_in.subtract_range(set);
LOG(WARNING) << "remove uninitialized copyin, tensor name=" << tensor_name << ", access=" << set;
}
};
copyin_range.foreach_set(ForeachSetFn);
}
void InitSchedule::ModDependencesBeforeGroup(const isl::schedule &schedule) {
if (!scop_info_.cube_info_.IsSpecGemm()) {
if (scop_info_.user_config_.GetRemoveSelfDependence()) {
pass_info_.dependences_ = RemoveReduceOpSelfDependence(scop_info_, pass_info_);
}
if (scop_info_.user_config_.GetForceRemoveSelfDependence()) {
pass_info_.dependences_ = RemoveSelfDependence(pass_info_);
}
}
if (scop_info_.user_config_.GetRemoveInvariantDependence()) {
pass_info_.dependences_ = RemoveInvariantDependence(schedule, pass_info_);
}
}
void InitSchedule::ComputeCopyIn(const isl::schedule &schedule) {
auto reads = scop_info_.analysis_result_.GetReads().domain_factor_domain();
auto writes = scop_info_.analysis_result_.GetWrites().domain_factor_domain();
auto uai = isl::union_access_info(reads);
uai = uai.set_kill(writes);
uai = uai.set_may_source(writes);
uai = uai.set_schedule(schedule);
auto flow = uai.compute_flow();
auto mayNoSource = flow.get_may_no_source();
scop_info_.analysis_result_.RecordCopyin(scop_info_.analysis_result_.GetReads().intersect_range(mayNoSource.range()));
}
isl::schedule InitSchedule::Run(isl::schedule sch) {
ComputeCopyIn(sch);
RemoveUninitializedCopyin(scop_info_.analysis_result_.GetCopyin(), scop_info_.user_config_.GetOriginBind());
pass_info_.dependences_ = ComputeAllDependences(sch, scop_info_.analysis_result_.GetReads(),
scop_info_.analysis_result_.GetWrites());
pass_info_.orig_dependences_ = pass_info_.dependences_;
ModDependencesBeforeGroup(sch);
return sch;
}
} // namespace poly
} // namespace ir
} // namespace akg
| 2,999 | 1,000 |
/**
* @ Author: KaiserLancelot
* @ Create Time: 2020-05-14 06:26:07
* @ Modified time: 2020-05-15 02:16:50
*/
#include <cstdint>
struct A {
std::int32_t x;
std::int32_t y;
std::int32_t z;
};
// TODO 编译器实现不完整
int main() {}
| 236 | 140 |
#ifndef __RANDOM_H_
#define __RANDOM_H_
#include <chrono>
#include <cmath>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <random>
namespace R {
// float R(float min, float max) {
// return min + static_cast<float>(rand()) /
// (static_cast<float>(RAND_MAX / (max - min)));
// ;
// }
// float R() { return static_cast<float>(rand()) / static_cast<float>(RAND_MAX); }
// int Z(int min, int max) { return rand() % (max - min + 1) + min; }
// int Z() { return rand() % 100; }
// int N(int mean, int dev) {
// std::normal_distribution<> d{double(mean), double(dev)};
// return std::round(d(gen));
// }
class Generator {
private:
std::mt19937 *gen;
public:
int seed;
Generator() { updateSeed(); }
void updateSeed() {
setSeed(std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch())
.count());
}
void setSeed(int s) {
seed = s;
gen = new std::mt19937(seed);
}
int R() {
std::uniform_int_distribution<> dis(0, RAND_MAX);
return dis(*gen);
}
int R(float min, float max) {
std::uniform_real_distribution<> dis(min, max);
return dis(*gen);
}
int R(int min, int max) {
std::uniform_int_distribution<> dis(min, max);
return dis(*gen);
}
};
} // namespace R
#endif // __RANDOM_H_
| 1,374 | 522 |
#include "Boids2D.h"
#include <vector>
#include <iostream>
#include <Core/Engine.h>
#include "Object2DBoids2D.h"
using namespace std;
Boids2D::Boids2D()
{
}
Boids2D::~Boids2D()
{
}
void Boids2D::Init()
{
glm::ivec2 resolution = window->GetResolution();
auto camera = GetSceneCamera();
camera->SetOrthographic(0, (float)resolution.x, 0, (float)resolution.y, 0.01f, 400);
camera->SetPosition(glm::vec3(0, 0, 50));
camera->SetRotation(glm::vec3(0, 0, 0));
camera->Update();
GetCameraInput()->SetActive(false);
glm::vec3 corner = glm::vec3(0, 0, 0);
float squareSide = 100;
// compute coordinates of square center
float cx = corner.x + squareSide / 2;
float cy = corner.y + squareSide / 2;
glm::vec3 color = glm::vec3(1, 1, 1);
color /= 4;
AddMeshToList(Object2DBoids2D::CreateCircle("circle", corner, senseRadius, color, true));
createBoids(resolution.x, resolution.y);
}
void Boids2D::createBoids(int xRes, int yRes) {
int xCoord, yCoord;
float xVel, yVel;
Mesh* boid;
glm::vec2 velocity, position;
std::string name;
glm::vec3 color;
for (int boid_num = 0; boid_num < total_boid_num; boid_num++) {
name = "boid" + std::to_string(boid_num);
if (boid_num == 0) {
color = glm::vec3(1, 0, 0);
}
else {
color = glm::vec3(0, 0.5, 0.5);
}
boid = Object2DBoids2D::CreateTriangle(name, glm::vec3(0, 0, 0), triangleSide, color, true);
xCoord = rand() % (xRes + 1);
yCoord = rand() % (yRes + 1);
position = glm::vec2(xCoord, yCoord);
// generate random float number between 0 and 1
xVel = (static_cast <float> (rand()) / static_cast <float> (RAND_MAX));
yVel = (static_cast <float> (rand()) / static_cast <float> (RAND_MAX));
// convert it to a number between -1 and 1
xVel = (xVel * 2) - 1;
yVel = (yVel * 2) - 1;
// apply a base speed increase to it
velocity = normalize(glm::vec2(xVel, yVel)) * glm::vec2(maxVelocity);
this->boids[name] = new BoidStructure2D(boid, position, velocity);
}
}
void Boids2D::FrameStart()
{
// clears the color buffer (using the previously set color) and depth buffer
glClearColor(0, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glm::ivec2 resolution = window->GetResolution();
// sets the screen area where to draw
glViewport(0, 0, resolution.x, resolution.y);
}
double Boids2D::getAngleAbsoluteVelocity(glm::vec2 absoluteVelocity) {
double angle = atan2(absoluteVelocity.y, absoluteVelocity.x);
return angle;
}
void Boids2D::drawBoids() {
static glm::mat3 modelMatrix;
static double angle;
for (int boid_num = total_boid_num - 1; boid_num > 0; boid_num--) {
std::string name = "boid" + std::to_string(boid_num);
BoidStructure2D *bs = this->boids[name];
modelMatrix = Object2DBoids2D::Translate(glm::mat3(1), bs->getPosition());
angle = getAngleAbsoluteVelocity(bs->getVelocity());
modelMatrix = Object2DBoids2D::Rotate(modelMatrix, AI_DEG_TO_RAD(-90) + angle);
RenderMesh2D(bs->getMesh(), shaders["VertexColor"], modelMatrix);
}
RenderMesh2D(meshes["circle"], shaders["VertexColor"], modelMatrix);
}
//Boids try to fly towards the centre of mass of neighbouring boids.
glm::vec2 Boids2D::rule1(BoidStructure2D *bs) {
if (this->rule1TurnedOn == false)
return glm::vec2(0);
glm::vec2 result = glm::vec2(0);
int num = -1;
for (auto boid : boids) {
if (Object2DBoids2D::distanceBetweenPoints(bs->getPosition(), boid.second->getPosition()) < senseRadius) {
result = result + boid.second->getPosition();
num++;
}
}
if (num > 0) {
result -= bs->getPosition();
result /= num;
result -= bs->getPosition();
result /= ruleDamping;
}
else {
result = glm::vec2(0);
}
return result;
}
//Boids try to keep a small distance away from other objects (including other boids).
glm::vec2 Boids2D::rule2(BoidStructure2D *bs) {
if (this->rule2TurnedOn == false)
return glm::vec2(0);
glm::vec2 result = glm::vec2(0);
int num = -1;
for (auto boid : boids) {
if (Object2DBoids2D::distanceBetweenPoints(bs->getPosition(), boid.second->getPosition()) < senseRadius) {
num++;
result = result - (boid.second->getPosition() - bs->getPosition());
}
}
if (num > 0) {
result /= num;
result *= 2;
result /= ruleDamping;
}
else {
result = glm::vec2(0);
}
return result;
}
//Boids try to match velocity with near boids.
glm::vec2 Boids2D::rule3(BoidStructure2D *bs) {
if (this->rule3TurnedOn == false)
return glm::vec2(0);
glm::vec2 result = glm::vec2(0);
int num = -1;
for (auto boid : boids) {
if (Object2DBoids2D::distanceBetweenPoints(bs->getPosition(), boid.second->getPosition()) < senseRadius) {
num++;
result = result + boid.second->getVelocity();
}
}
if (num > 0) {
result -= bs->getVelocity();
result /= num;
result /= ruleDamping;
}
else {
result = glm::vec2(0);
}
return result;
}
void Boids2D::moveBoids2NewPosition(float deltaTimeSeconds) {
glm::vec2 v1, v2, v3;
for (int boid_num = 0; boid_num < total_boid_num; boid_num++) {
std::string name = "boid" + std::to_string(boid_num);
BoidStructure2D *bs = this->boids[name];
v1 = rule1(bs);
v2 = rule2(bs);
v3 = rule3(bs);
double modulus = Object2DBoids2D::distanceBetweenPoints(bs->getVelocity(), glm::vec2(0));
glm::vec2 velocity = glm::vec2(modulus) * normalize(bs->getVelocity() + v1 + v2 + v3);
bs->setVelocity(velocity);
bs->setPosition(bs->getPosition() + velocity * deltaTimeSeconds);
}
}
void Boids2D::checkBoundary() {
glm::vec2 res = window->GetResolution();
double rightBoundary = res.x + triangleSide * 0.86602540378;
double leftBoundary = 0 - triangleSide * 0.86602540378;
double upperBoundary = res.y + triangleSide * 0.86602540378;
double lowerBoundary = 0 - triangleSide * 0.86602540378;
for (auto boid : this->boids) {
glm::vec2 position = boid.second->getPosition();
if (position.x > rightBoundary) {
position.x = leftBoundary;
}
else if (position.x < leftBoundary) {
position.x = rightBoundary;
}
if (position.y > upperBoundary) {
position.y = lowerBoundary;
}
else if (position.y < lowerBoundary) {
position.y = upperBoundary;
}
boid.second->setPosition(position);
}
}
void Boids2D::Update(float deltaTimeSeconds)
{
drawBoids();
moveBoids2NewPosition(deltaTimeSeconds);
checkBoundary();
}
void Boids2D::FrameEnd()
{
}
void Boids2D::OnInputUpdate(float deltaTime, int mods)
{
}
void Boids2D::OnKeyPress(int key, int mods)
{
if (key == GLFW_KEY_Q)
this->rule1TurnedOn = !this->rule1TurnedOn;
if (key == GLFW_KEY_W)
this->rule2TurnedOn = !this->rule2TurnedOn;
if (key == GLFW_KEY_E)
this->rule3TurnedOn = !this->rule3TurnedOn;
}
void Boids2D::OnKeyRelease(int key, int mods)
{
// add key release event
}
void Boids2D::OnMouseMove(int mouseX, int mouseY, int deltaX, int deltaY)
{
// add mouse move event
}
void Boids2D::OnMouseBtnPress(int mouseX, int mouseY, int button, int mods)
{
// add mouse button press event
}
void Boids2D::OnMouseBtnRelease(int mouseX, int mouseY, int button, int mods)
{
// add mouse button release event
}
void Boids2D::OnMouseScroll(int mouseX, int mouseY, int offsetX, int offsetY)
{
}
void Boids2D::OnWindowResize(int width, int height)
{
}
| 7,415 | 3,110 |
#include "network.hpp"
#include "network_impl.hpp"
namespace Shadow {
Network::Network() { engine_ = std::make_shared<NetworkImpl>(); }
void Network::LoadXModel(const shadow::NetParam& net_param,
const ArgumentHelper& arguments) {
engine_->LoadXModel(net_param, arguments);
}
void Network::Forward(
const std::map<std::string, void*>& data_map,
const std::map<std::string, std::vector<int>>& shape_map) {
engine_->Forward(data_map, shape_map);
}
#define INSTANTIATE_GET_BLOB(T) \
template <> \
const T* Network::GetBlobDataByName<T>(const std::string& blob_name, \
const std::string& locate) { \
return engine_->GetBlobDataByName<T>(blob_name, locate); \
} \
template <> \
std::vector<int> Network::GetBlobShapeByName<T>( \
const std::string& blob_name) const { \
return engine_->GetBlobShapeByName(blob_name); \
}
INSTANTIATE_GET_BLOB(std::int64_t);
INSTANTIATE_GET_BLOB(std::int32_t);
INSTANTIATE_GET_BLOB(std::int16_t);
INSTANTIATE_GET_BLOB(std::int8_t);
INSTANTIATE_GET_BLOB(std::uint64_t);
INSTANTIATE_GET_BLOB(std::uint32_t);
INSTANTIATE_GET_BLOB(std::uint16_t);
INSTANTIATE_GET_BLOB(std::uint8_t);
INSTANTIATE_GET_BLOB(float);
INSTANTIATE_GET_BLOB(bool);
#undef INSTANTIATE_GET_BLOB
const std::vector<std::string>& Network::in_blob() const {
return engine_->in_blob();
}
const std::vector<std::string>& Network::out_blob() const {
return engine_->out_blob();
}
bool Network::has_argument(const std::string& name) const {
return engine_->has_argument(name);
}
#define INSTANTIATE_ARGUMENT(T) \
template <> \
T Network::get_single_argument<T>(const std::string& name, \
const T& default_value) const { \
return engine_->get_single_argument<T>(name, default_value); \
} \
template <> \
std::vector<T> Network::get_repeated_argument<T>( \
const std::string& name, const std::vector<T>& default_value) const { \
return engine_->get_repeated_argument<T>(name, default_value); \
}
INSTANTIATE_ARGUMENT(float);
INSTANTIATE_ARGUMENT(int);
INSTANTIATE_ARGUMENT(bool);
INSTANTIATE_ARGUMENT(std::string);
#undef INSTANTIATE_ARGUMENT
} // namespace Shadow
| 2,840 | 872 |
#include "translationgraphwidget.h"
TranslationGraphWidget::TranslationGraphWidget(QWidget *parent)
: PolygonGraphWidget(parent), p(QPoint(0, 0))
{
}
void TranslationGraphWidget::translateXYChanged(const QPoint &p)
{
this->p = p;
}
void TranslationGraphWidget::performOperation()
{
foreach (auto pp, polygon)
{
editPixMap(QPoint(pp.x() + p.x(), pp.y() + p.y()), qMakePair(true, false));
}
}
| 422 | 149 |
#include <output.hpp>
#include <core.hpp>
#include "../../shared/config.hpp"
#include <linux/input-event-codes.h>
#include <compositor.h>
class wayfire_rotator : public wayfire_plugin_t {
key_callback up, down, left, right;
public:
void init(wayfire_config *config) {
grab_interface->name = "rotator";
grab_interface->abilities_mask = WF_ABILITY_NONE;
auto section = config->get_section("rotator");
wayfire_key up_key = section->get_key("rotate_up",
{MODIFIER_ALT|MODIFIER_CTRL, KEY_UP});
wayfire_key down_key = section->get_key("rotate_down",
{MODIFIER_ALT|MODIFIER_CTRL, KEY_DOWN});
wayfire_key left_key = section->get_key("rotate_left",
{MODIFIER_ALT|MODIFIER_CTRL, KEY_LEFT});
wayfire_key right_key = section->get_key("rotate_right",
{MODIFIER_ALT|MODIFIER_CTRL, KEY_RIGHT});
up = [=] (weston_keyboard*, uint32_t) {
output->set_transform(WL_OUTPUT_TRANSFORM_NORMAL);
};
down = [=] (weston_keyboard*, uint32_t) {
output->set_transform(WL_OUTPUT_TRANSFORM_180);
};
left = [=] (weston_keyboard*, uint32_t) {
output->set_transform(WL_OUTPUT_TRANSFORM_270);
};
right = [=] (weston_keyboard*, uint32_t) {
output->set_transform(WL_OUTPUT_TRANSFORM_90);
};
output->add_key((weston_keyboard_modifier)up_key.mod, up_key.keyval, &up);
output->add_key((weston_keyboard_modifier)down_key.mod, down_key.keyval, &down);
output->add_key((weston_keyboard_modifier)left_key.mod, left_key.keyval, &left);
output->add_key((weston_keyboard_modifier)right_key.mod, right_key.keyval, &right);
}
};
extern "C" {
wayfire_plugin_t *newInstance() {
return new wayfire_rotator();
}
}
| 1,868 | 679 |
// Copyright 1996-2020 Cyberbotics Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef WB_CONTACT_PROPERTIES_HPP
#define WB_CONTACT_PROPERTIES_HPP
#include "WbBaseNode.hpp"
#include "WbMFDouble.hpp"
#include "WbSFDouble.hpp"
#include "WbSFString.hpp"
#include "WbSFVector2.hpp"
class WbSoundClip;
class WbContactProperties : public WbBaseNode {
Q_OBJECT
public:
// constructors and destructor
explicit WbContactProperties(WbTokenizer *tokenizer = NULL);
WbContactProperties(const WbContactProperties &other);
explicit WbContactProperties(const WbNode &other);
virtual ~WbContactProperties();
// reimplemented public functions
int nodeType() const override { return WB_NODE_CONTACT_PROPERTIES; }
void preFinalize() override;
void postFinalize() override;
// field accessors
const QString &material1() const { return mMaterial1->value(); }
const QString &material2() const { return mMaterial2->value(); }
int coulombFrictionSize() const { return mCoulombFriction->size(); }
double coulombFriction(int index) const { return mCoulombFriction->item(index); }
WbVector2 frictionRotation() const { return mFrictionRotation->value(); }
double bounce() const { return mBounce->value(); }
double bounceVelocity() const { return mBounceVelocity->value(); }
int forceDependentSlipSize() const { return mForceDependentSlip->size(); }
double forceDependentSlip(int index) const { return mForceDependentSlip->item(index); }
double softERP() const { return mSoftErp->value(); }
double softCFM() const { return mSoftCfm->value(); }
const WbSoundClip *bumpSoundClip() const { return mBumpSoundClip; }
const WbSoundClip *rollSoundClip() const { return mRollSoundClip; }
const WbSoundClip *slideSoundClip() const { return mSlideSoundClip; }
signals:
void valuesChanged();
void needToEnableBodies();
private:
// user accessible fields
WbSFString *mMaterial1;
WbSFString *mMaterial2;
WbMFDouble *mCoulombFriction;
WbSFVector2 *mFrictionRotation;
WbSFDouble *mBounce;
WbSFDouble *mBounceVelocity;
WbMFDouble *mForceDependentSlip;
WbSFDouble *mSoftCfm;
WbSFDouble *mSoftErp;
WbSFString *mBumpSound;
WbSFString *mRollSound;
WbSFString *mSlideSound;
WbSoundClip *mBumpSoundClip;
WbSoundClip *mRollSoundClip;
WbSoundClip *mSlideSoundClip;
WbContactProperties &operator=(const WbContactProperties &); // non copyable
WbNode *clone() const override { return new WbContactProperties(*this); }
void init();
private slots:
void updateCoulombFriction();
void updateFrictionRotation();
void updateBounce();
void updateBounceVelocity();
void updateSoftCfm();
void updateSoftErp();
void updateBumpSound();
void updateRollSound();
void updateSlideSound();
void updateForceDependentSlip();
void enableBodies();
};
#endif
| 3,328 | 1,131 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <iostream>
#include "../include/tests/ConcDCTTest.h"
#include "../include/tests/ConcMATTest.h"
#include "../include/tests/ConcSegHashTableTest.h"
#include "../include/tests/ConcInvertedIndexTest.h"
#include "../include/tests/QueueLockTest.h"
using namespace std;
int main()
{
int res1 = 0;
int res2 = 0;
int res3 = 0;
res1 = testDCT(0);
if (res1)
throw;
res2 = testMAT(0);
if (res2)
throw;
testSegHashTable(0);
res3 = testInvertedIndex(0);
if (res3)
throw;
cout <<"All tests passed"<<endl;
}
| 1,340 | 438 |
/**
* @file autotype8.cpp
* @brief C++11/14/17 program to demonstrate auto type of 8
* @ref https://stackoverflow.com/questions/38060436/what-are-the-new-features-in-c17
* @details http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3922.html
*
* COMPILATION TIP : -Wall warning all, -g debugger, gdb can step through
* g++ -Wall -g autotype8.cpp -o autotype8
* */
#include <iostream>
#include <typeinfo> // typeid
int main() {
auto x{8};
auto x1 = { 1, 2}; // decltype(x1) is std::initializer_list<int>
auto x4 = { 3 }; // decltype(x4) is std::initializer_list<int>
std::cout << typeid( decltype( x )).name() << std::endl; // i
std::cout << typeid( decltype( x1 )).name() << std::endl; // St16initializer_listIiE
std::cout << typeid( decltype( x4 )).name() << std::endl; // St16initializer_listIiE
}
| 851 | 380 |
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <queue>
#include <map>
using namespace std;
int main(void)
{
int qnum, r, n, f, s;
char c[10];
priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq;
map<int, int> m;
while (EOF != scanf("%s", c) && strcmp(c, "#")) {
scanf("%d %d", &qnum, &r);
pq.push(pair<int, int> (r, qnum));
m[qnum] = r;
}
scanf("%d", &n);
for (int i = 0; i < n; i++) {
printf("%d\n", pq.top().second);
f = pq.top().first;
s = pq.top().second;
pq.push(pair<int, int> (((f/m[s])+1)*m[s], s));
pq.pop();
}
return 0;
}
| 647 | 305 |
#include "../BVH.h"
| 21 | 13 |
/* Copyright 2012-2013 Peter Goodman, all rights reserved. */
/*
* trace_log.cc
*
* Created on: 2013-05-06
* Author: Peter Goodman
*/
#include "granary/globals.h"
#include "granary/trace_log.h"
#if CONFIG_DEBUG_TRACE_EXECUTION
# include "granary/instruction.h"
# include "granary/emit_utils.h"
# include "granary/state.h"
#endif
namespace granary {
#if CONFIG_DEBUG_TRACE_EXECUTION
# if !CONFIG_DEBUG_TRACE_PRINT_LOG
/// An item in the trace log.
struct trace_log_item {
/// Previous log item in this thread.
trace_log_item *prev;
/// A code cache address into a basic block.
void *code_cache_addr;
# if CONFIG_DEBUG_TRACE_RECORD_REGS
/// State of the general purpose registers on entry to this basic block.
simple_machine_state state;
# endif /* CONFIG_DEBUG_TRACE_RECORD_REGS */
};
/// Head of the log.
static std::atomic<trace_log_item *> TRACE = ATOMIC_VAR_INIT(nullptr);
static std::atomic<uint64_t> NUM_TRACE_ENTRIES = ATOMIC_VAR_INIT(0);
/// A ring buffer representing the trace log.
static trace_log_item LOGS[CONFIG_DEBUG_NUM_TRACE_LOG_ENTRIES];
# endif /* CONFIG_DEBUG_TRACE_PRINT_LOG */
#endif /* CONFIG_DEBUG_TRACE_EXECUTION */
/// Log a lookup in the code cache.
void trace_log::add_entry(
app_pc IF_TRACE(code_cache_addr),
simple_machine_state *IF_TRACE(state)
) {
#if CONFIG_DEBUG_TRACE_EXECUTION
# if CONFIG_DEBUG_TRACE_PRINT_LOG
printf("app=%p cache=%p\n", app_addr, target_addr);
(void) kind;
# else
trace_log_item *prev(nullptr);
trace_log_item *item(&(LOGS[
NUM_TRACE_ENTRIES.fetch_add(1) % CONFIG_DEBUG_NUM_TRACE_LOG_ENTRIES]));
item->code_cache_addr = code_cache_addr;
# if CONFIG_DEBUG_TRACE_RECORD_REGS
// Have to use our internal `memcpy`, because even when telling the
// compiler not to use xmm registers, it will sometimes optimize an
// assignment of `item->state = *state` into a libc `memcpy`.
memcpy(&(item->state), state, sizeof *state);
item->state.rsp.value_64 += IF_USER_ELSE(REDZONE_SIZE + 8, 8);
# else
(void) state;
# endif /* CONFIG_DEBUG_TRACE_RECORD_REGS */
do {
prev = TRACE.load();
item->prev = prev;
} while(!TRACE.compare_exchange_weak(prev, item));
# endif /* CONFIG_DEBUG_TRACE_PRINT_LOG */
#endif
}
extern "C" void **kernel_get_cpu_state(void *ptr[]);
#if CONFIG_DEBUG_TRACE_EXECUTION
static app_pc trace_logger(void) {
static volatile app_pc routine(nullptr);
if(routine) {
return routine;
}
instruction_list ls;
instruction in;
instruction xmm_tail;
register_manager all_regs;
all_regs.kill_all();
ls.append(push_(reg::rsp));
in = save_and_restore_registers(all_regs, ls, ls.last());
in = ls.insert_after(in,
mov_ld_(reg::arg1, reg::rsp[sizeof(simple_machine_state)]));
# if CONFIG_DEBUG_TRACE_RECORD_REGS
in = ls.insert_after(in, mov_st_(reg::arg2, reg::rsp));
# endif /* CONFIG_DEBUG_TRACE_RECORD_REGS */
in = insert_save_flags_after(ls, in);
in = insert_align_stack_after(ls, in);
xmm_tail = ls.insert_after(in, label_());
# if 0 && !CONFIG_ENV_KERNEL
// In some user space programs (e.g. kcachegrind), we need to
// unconditionally save all XMM registers.
in = save_and_restore_xmm_registers(
all_regs, ls, in, XMM_SAVE_ALIGNED);
# endif /* CONFIG_ENV_KERNEL */
in = insert_cti_after(ls, in,
unsafe_cast<app_pc>(trace_log::add_entry),
CTI_STEAL_REGISTER, reg::ret,
CTI_CALL);
xmm_tail = insert_restore_old_stack_alignment_after(ls, xmm_tail);
xmm_tail = insert_restore_flags_after(ls, xmm_tail);
ls.append(lea_(reg::rsp, reg::rsp[8]));
ls.append(ret_());
// Encode.
const unsigned size(ls.encoded_size());
app_pc temp(global_state::FRAGMENT_ALLOCATOR-> \
allocate_array<uint8_t>(size));
ls.encode(temp, size);
BARRIER;
routine = temp;
return temp;
}
static void add_trace_log_call(
instruction_list &ls,
instruction in
) {
IF_USER( in = ls.insert_after(in,
lea_(reg::rsp, reg::rsp[-REDZONE_SIZE])); )
in = insert_cti_after(ls, in,
trace_logger(),
CTI_DONT_STEAL_REGISTER, operand(),
CTI_CALL);
in.set_mangled();
IF_USER( in = ls.insert_after(in,
lea_(reg::rsp, reg::rsp[REDZONE_SIZE])); )
}
#endif /* CONFIG_DEBUG_TRACE_EXECUTION */
/// Log the run of some code. This will add a lot of instructions to the
/// beginning of an instruction list, as well as replace RET instructions
/// with tail-calls to the trace logger so that we can observe ourselves
/// re-entering a given basic block after a CALL.
void trace_log::log_execution(instruction_list &IF_TRACE(ls)) {
#if CONFIG_DEBUG_TRACE_EXECUTION
// The first instruction will be a label.
instruction in(ls.first());
ASSERT(in.is_valid());
instruction in_next(in.next());
add_trace_log_call(ls, in);
UNUSED(in_next);
// TODO: It's a bit weird that this works in user space but not kernel
// space!!
# if 0 && !CONFIG_ENV_KERNEL
for(in = in_next; in.is_valid(); in = in_next) {
in_next = in.next();
if(in.is_return()) {
// We don't need to guard against the redzone for RETs
// because they're popping their return address off of the
// stack.
insert_cti_after(ls, in,
trace_logger(),
CTI_DONT_STEAL_REGISTER, operand(),
CTI_JMP).set_mangled();
ls.remove(in);
}
}
# endif
#endif
}
}
| 6,107 | 2,130 |
#pragma once
#include <engine/MovementComponent.hpp>
#include <engine/Transform2D.hpp>
#include <engine/InputSystem.hpp>
#include <engine/TimerGuard.hpp>
#include <engine/Animation.hpp>
#include <engine/Mob.hpp>
#include <engine/Attack.hpp>
#include <gamebase/Buff.hpp>
#include <gamebase/Inventory.hpp>
#include <Sprite.hpp>
#include <DrawSprites.hpp>
#include <glm/glm.hpp>
#include <chrono>
#include <string>
#include <unordered_map>
#include <string>
#include <vector>
class Room;
class Player : public Mob {
public:
virtual void UpdateImpl(float elapsed) override;
virtual void OnDie() override;
virtual Animation* GetAnimation(AnimationState state) override;
void UpdatePhysics(float elapsed, const std::vector<Collider*>& colliders_to_consider);
void StopMovement() { movement_component_.StopMovement(); }
void SetPosition(const glm::vec2& pos);
void Reset();
void AddBuff(const Buff& buff) { buff_ = buff; }
void ClearBuff();
void AddHp(int hp);
void AddMp(int mp);
void AddExp(int exp);
void AddCoin(int coin);
int GetLevel() {return cur_level_;}
int GetCurLevelExp() {return exp_;}
int GetCurLevelMaxExp() {
if (GetLevel() < (int)level_exps_.size()) {
return level_exps_[GetLevel()];
}
else {
return 10000;
}
}
int GetCoin() {return coin_;}
// Inventory
bool PickupItem(ItemPrototype* item);
void UseItem(size_t slot_num);
void UnequipItem(size_t slot_num);
void DropItem(size_t slot_num);
void DropEquipment(size_t slot_num);
ItemPrototype* GetItem(size_t slot_num);
EquipmentPrototype* GetEquipment(size_t slot_num);
bool IsInventoryFull() const { return inventory_.IsFull(); }
static Player* Create(Room** room, const std::string& player_config_file);
std::vector<Attack> GetAttackInfo() const;
virtual int GetAttackPoint() override;
virtual int GetDefense() override;
int GetMaxHP() { return max_hp_; }
virtual void OnTakeDamage() override;
protected:
virtual void DrawImpl(DrawSprites& draw) override;
private:
std::unordered_map<Mob::AnimationState, Animation*> animations_;
MovementComponent movement_component_;
Room** room_;
int max_hp_ { 100 };
int mp_ { 100 };
int max_mp_ { 100 };
int exp_ { 0 };
int cur_level_ {0};
int coin_ { 0 };
std::vector<int> level_exps_;
std::vector<Attack> skills_;
Buff buff_;
float shining_duration_ { 0.0f };
bool is_shining_ { false };
Inventory inventory_;
Player(const Player& player);
Player(Room** room, const glm::vec4 bounding_box);
void LevelUp();
void Shine(float duration) { shining_duration_ = duration; }
};
| 2,569 | 946 |
//===--- Utils/FileSystem.cpp - File system utilities -----------*- C++ -*-===//
//
// The North Compiler Infrastructure
//
// This file is distributed under the MIT License.
// See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Utils/FileSystem.h"
namespace north::utils {
llvm::SourceMgr *openFile(llvm::StringRef Path) {
auto MemBuff = llvm::MemoryBuffer::getFile(Path);
if (auto Error = MemBuff.getError()) {
llvm::errs() << Path << ": " << Error.message() << '\n';
std::exit(0);
}
if (!MemBuff->get()->getBufferSize())
std::exit(0);
auto SourceManager = new llvm::SourceMgr();
SourceManager->AddNewSourceBuffer(std::move(*MemBuff), llvm::SMLoc());
SourceManager->setDiagHandler([](const llvm::SMDiagnostic &SMD, void *Context) {
SMD.print("", llvm::errs());
std::exit(0);
});
return SourceManager;
}
} // north::utils
| 1,006 | 324 |
/**************************************************************************
** This file is a part of our work (Siggraph'16 paper, binary, code and dataset):
**
** Roto++: Accelerating Professional Rotoscoping using Shape Manifolds
** Wenbin Li, Fabio Viola, Jonathan Starck, Gabriel J. Brostow and Neill D.F. Campbell
**
** w.li AT cs.ucl.ac.uk
** http://visual.cs.ucl.ac.uk/pubs/rotopp
**
** Copyright (c) 2016, Wenbin Li
** 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 and data must retain the above
** copyright notice, this list of conditions and the following disclaimer.
** -- Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
**
** THIS WORK AND THE RELATED SOFTWARE, SOURCE CODE AND DATA 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.
***************************************************************************/
#ifndef IMGICON_H
#define IMGICON_H
#include <QLabel>
#include <QPainter>
#include <QWidget>
#include <QMouseEvent>
#include "include/designZone/SpCurve.hpp"
#include "include/utils.hpp"
class QLabel;
class ImgIcon: public QLabel
{
Q_OBJECT
private:
QImage *img;
qreal num;
QColor color;
QList<SpCurve*> curves;
public:
EditType status;
explicit ImgIcon(QImage *image,QWidget *parent = 0);
explicit ImgIcon(QImage *image, int i,QWidget *parent = 0);
~ImgIcon(){}
void setStatus(EditType);
void paintEvent(QPaintEvent *event);
void setImage(QImage* im){img=im;}
QImage* getImage(){return img;}
int getNum(){return num;}
void designActionClick();
signals:
void pushImgIconClicked(qreal);
// void pushRecheckDesignActions();
protected:
void mousePressEvent(QMouseEvent *event);
public slots:
void updateCurves(QList<SpCurve*>);
void setEditingStatus();
void setNoEditStatus();
void setSuggestStatus();
void setKeyFrameStatus();
};
typedef QList<ImgIcon*> ImgIconList;
typedef QList<EditType> StatusList;
#endif
| 3,000 | 1,034 |
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <memory>
#include <lib/async-loop/cpp/loop.h>
#include <trace-provider/provider.h>
#include "lib/component/cpp/startup_context.h"
#include "lib/fsl/syslogger/init.h"
#include "lib/fxl/command_line.h"
#include "lib/fxl/log_settings_command_line.h"
#include "lib/fxl/logging.h"
#include "garnet/bin/ui/scenic/app.h"
int main(int argc, const char** argv) {
auto command_line = fxl::CommandLineFromArgcArgv(argc, argv);
if (!fxl::SetLogSettingsFromCommandLine(command_line))
return 1;
if (fsl::InitLoggerFromCommandLine(command_line, {"scenic"}) != ZX_OK)
return 1;
async::Loop loop(&kAsyncLoopConfigAttachToThread);
trace::TraceProvider trace_provider(loop.dispatcher());
std::unique_ptr<component::StartupContext> app_context(
component::StartupContext::CreateFromStartupInfo());
scenic_impl::App app(app_context.get(), [&loop] { loop.Quit(); });
loop.Run();
return 0;
}
| 1,083 | 396 |
/////////////////////////////////////////////////
// Includes
#include "fa.h"
/////////////////////////////////////////////////
// Finite-Automata-Transition
PFaTrans TFaTrans::LoadCustomXml(const PXmlTok& XmlTok){
IAssert(XmlTok->IsTag("Trans"));
// collect transition values
TStr MsgNm=XmlTok->GetArgVal("Msg");
TStr DstStateNm=XmlTok->GetArgVal("DstState");
TStr ScriptStr;
if (XmlTok->IsSubTag("Script")){
ScriptStr=XmlTok->GetTagTok("Script")->GetTokStr(false);}
// create transition
PFaTrans Trans=TFaTrans::New(MsgNm, DstStateNm, ScriptStr);
// return result
return Trans;
}
void TFaTrans::_ChangeStateNm(const TStr& OldStateNm, const TStr& NewStateNm){
if (SrcStateNm==OldStateNm){SrcStateNm=NewStateNm;}
if (DstStateNm==OldStateNm){DstStateNm=NewStateNm;}
}
/////////////////////////////////////////////////
// Finite-Automata-State
PFaState TFaState::LoadCustomXml(const PXmlTok& XmlTok){
IAssert(XmlTok->IsTag("State"));
// collect state values
// name
TStr Nm=XmlTok->GetArgVal("Nm");
// script
TStr ScriptStr;
if (XmlTok->IsSubTag("Script")){
ScriptStr=XmlTok->GetTagTok("Script")->GetTokStr(false);}
// transitions
TXmlTokV TransTokV; XmlTok->GetTagTokV("Trans", TransTokV);
TFaTransV TransV;
for (int TransN=0; TransN<TransTokV.Len(); TransN++){
PFaTrans Trans=TFaTrans::LoadCustomXml(TransTokV[TransN]);
TransV.Add(Trans);
}
// create transition
PFaState State=TFaState::New(Nm, ScriptStr);
for (int TransN=0; TransN<TransV.Len(); TransN++){
State->AddTrans(TransV[TransN]);}
// return result
return State;
}
void TFaState::_ChangeStateNm(const TStr& OldStateNm, const TStr& NewStateNm){
if (Nm==OldStateNm){Nm=NewStateNm;}
for (int TransN=0; TransN<FaTransV.Len(); TransN++){
FaTransV[TransN]->_ChangeStateNm(OldStateNm, NewStateNm);}
}
bool TFaState::IsTransTo(const TStr& StateNm) const {
for (int TransN=0; TransN<FaTransV.Len(); TransN++){
if (FaTransV[TransN]->GetDstStateNm()==StateNm){return true;}
}
return false;
}
void TFaState::DelTrans(const PFaTrans& Trans){
for (int TransN=FaTransV.Len()-1; TransN>=0; TransN--){
if (FaTransV[TransN]()==Trans()){
FaTransV.Del(TransN);}
}
}
void TFaState::DelTransIfDstState(const TStr& DstStateNm){
for (int TransN=FaTransV.Len()-1; TransN>=0; TransN--){
if (FaTransV[TransN]->GetDstStateNm()==DstStateNm){
FaTransV.Del(TransN);}
}
}
/////////////////////////////////////////////////
// Finite-Automata
TStr TFaDef::GetNewStateNm() const {
int StateN=0;
while (IsState(TInt::GetStr(StateN, "State%d"))){StateN++;}
return TInt::GetStr(StateN, "State%d");
}
void TFaDef::ChangeStateNm(const TStr& OldStateNm, const TStr& NewStateNm){
// return if no change
if (OldStateNm==NewStateNm){return;}
// get state
PFaState State=GetState(OldStateNm);
// assert new name doesn't exist yet and is not start or end state
IAssert(!IsState(NewStateNm));
IAssert(State()!=GetStartState()());
IAssert(State()!=GetEndState()());
// change references to state in states and transitions
TFaStateV StateV; GetStateV(StateV);
for (int StateN=0; StateN<StateV.Len(); StateN++){
StateV[StateN]->_ChangeStateNm(OldStateNm, NewStateNm);}
for (int TransN=0; TransN<GlobalTransV.Len(); TransN++){
GlobalTransV[TransN]->_ChangeStateNm(OldStateNm, NewStateNm);}
// reinsert the state
NmToFaStateH.DelKey(OldStateNm);
NmToFaStateH.AddDat(State->GetNm(), State);
}
void TFaDef::DelState(const TStr& StateNm){
// cannot delete start & end state
IAssert(StateNm!=GetStartState()->GetNm());
IAssert(StateNm!=GetEndState()->GetNm());
// get state
PFaState State=GetState(StateNm);
// delete local state transitions
TFaStateV StateV; GetStateV(StateV);
for (int StateN=0; StateN<StateV.Len(); StateN++){
StateV[StateN]->DelTransIfDstState(StateNm);}
// delete global transitions
for (int TransN=GlobalTransV.Len()-1; TransN>=0; TransN--){
PFaTrans Trans=GlobalTransV[TransN];
if ((Trans->GetSrcStateNm()==StateNm)||(Trans->GetDstStateNm()==StateNm)){
GlobalTransV.Del(TransN);}
}
// delete state from hash table
NmToFaStateH.DelKey(StateNm);
}
TStr TFaDef::GetStateNmAtXY(const double& X, const double& Y) const {
TFaStateV StateV; GetStateV(StateV);
for (int StateN=StateV.Len()-1; StateN>=0; StateN--){
if (StateV[StateN]->GetRect().IsXYIn(X, Y)){
return StateV[StateN]->GetNm();}
}
return "";
}
void TFaDef::DelTrans(const PFaTrans& Trans){
// delete local state transition
TFaStateV StateV; GetStateV(StateV);
for (int StateN=0; StateN<StateV.Len(); StateN++){
StateV[StateN]->DelTrans(Trans);}
// delete global transitions
for (int TransN=GlobalTransV.Len()-1; TransN>=0; TransN--){
if (GlobalTransV[TransN]()==Trans()){
GlobalTransV.Del(TransN);}
}
}
PFaTrans TFaDef::GetTransAtXY(const double& X, const double& Y) const {
// get states
TFaStateV StateV; GetStateV(StateV);
// traverse states
for (int StateN=0; StateN<StateV.Len(); StateN++){
// get state data
PFaState SrcFaState=StateV[StateN];
// traverse transitions
for (int TransN=0; TransN<SrcFaState->GetTranss(); TransN++){
// get transition
PFaTrans FaTrans=SrcFaState->GetTrans(TransN);
// check point being in the transition rectangle
if (FaTrans->GetRect().IsXYIn(X, Y)){return FaTrans;}
}
}
// no transition found
return NULL;
}
const TStr TFaDef::FaDefVerStr="Automaton Definition / 09.03.2004";
const TStr TFaDef::DfFNm="Automaton.Xml";
const TStr TFaDef::FExt=".Xml";
PFaDef TFaDef::LoadBin(const TStr& FNm){
PSIn SIn=TFIn::New(FNm);
char* VerCStr;
SIn->Load(VerCStr, FaDefVerStr.Len(), FaDefVerStr.Len());
if (FaDefVerStr!=VerCStr){
TExcept::Throw("Invalid version of Faulation Definition file.");}
return TFaDef::Load(*SIn);
}
void TFaDef::SaveBin(const TStr& FNm) const {
PSOut SOut=TFOut::New(FNm);
SOut->Save(FaDefVerStr.CStr(), FaDefVerStr.Len());
Save(*SOut);
}
PFaDef TFaDef::LoadXml(const TStr& FNm){
PFaDef FaDef=TFaDef::New();
XLoadFromFile(FNm, "FaDef", *FaDef);
return FaDef;
}
void TFaDef::SaveXml(const TStr& FNm){
PSOut SOut=TFOut::New(FNm);
SaveXml(*SOut, "FaDef");
}
PFaDef TFaDef::LoadCustomXml(const TStr& FNm){
// create finite automaton
PFaDef FaDef=TFaDef::New();
// load xml file
PXmlDoc XmlDoc=TXmlDoc::LoadTxt(FNm);
// global transitions
TXmlTokV GlobalTransTokV;
XmlDoc->GetTagTokV("FinAut|Trans", GlobalTransTokV);
for (int TransN=0; TransN<GlobalTransTokV.Len(); TransN++){
PFaTrans Trans=TFaTrans::LoadCustomXml(GlobalTransTokV[TransN]);
FaDef->AddGlobalTrans(Trans);
}
// states
TXmlTokV StateTokV; XmlDoc->GetTagTokV("FinAut|State", StateTokV);
for (int StateN=0; StateN<StateTokV.Len(); StateN++){
PFaState State=TFaState::LoadCustomXml(StateTokV[StateN]);
FaDef->AddState(State);
}
// start & end state
TStr StartStateNm=XmlDoc->GetTagVal("StartState", false);
FaDef->PutStartState(FaDef->GetState(StartStateNm));
TStr EndStateNm=XmlDoc->GetTagVal("EndState", false);
FaDef->PutEndState(FaDef->GetState(EndStateNm));
// return finite automaton
return FaDef;
}
/////////////////////////////////////////////////
// Finite-Automata-Expression-Environment
void TFaExpEnv::PutVarVal(const TStr& VarNm, const PExpVal& ExpVal){
VarNmToValH.AddDat(VarNm.GetUc(), ExpVal);
}
PExpVal TFaExpEnv::GetVarVal(const TStr& VarNm, bool& IsVar){
int VarNmToValP;
if (VarNmToValH.IsKey(VarNm.GetUc(), VarNmToValP)){
IsVar=true; return VarNmToValH[VarNmToValP];
} else {
printf("Variable '%s' does not exist\n", VarNm.CStr());
IsVar=false; return TExpVal::GetUndefExpVal();
}
}
PExpVal TFaExpEnv::GetFuncVal(
const TStr& FuncNm, const TExpValV& ArgValV, bool& IsFunc){
IsFunc=true; PExpVal ExpVal=TExpVal::GetUndefExpVal();
//printf("Env. function call %s/%d\n", FuncNm.CStr(), ArgValV.Len());
if (TExpEnv::IsFuncOk("Assign", efatStrAny, FuncNm, ArgValV)){
// assign value to variable
TStr VarNm=ArgValV[0]->GetStrVal();
PutVarVal(VarNm, ArgValV[1]);
} else
if (TExpEnv::IsFuncOk("OnProb", efatFlt, FuncNm, ArgValV)){
// returns true if probability in (_Prb, _PrbUsed) fires
double RqPrb=ArgValV[0]->GetFltVal();
double Prb=GetVarVal("_Prb")->GetFltVal();
double PrbUsed=GetVarVal("_PrbUsed")->GetFltVal();
bool Ok=(PrbUsed<=Prb)&&(Prb<PrbUsed+RqPrb);
PutVarVal("_PrbUsed", TExpVal::New(PrbUsed+RqPrb));
ExpVal=TExpVal::New(double(Ok)); IsFunc=true;
} else
if (TExpEnv::IsFuncOk("AfterTime", efatFlt, FuncNm, ArgValV)){
// returns true if in state longer then arg. number of secons
double MxSecs=ArgValV[0]->GetFltVal();
TSecTm StartStateTm=FaExe->GetActStateStartTm();
bool Ok=TSecTm::GetDSecs(StartStateTm, TSecTm::GetCurTm())>MxSecs;
ExpVal=TExpVal::New(double(Ok)); IsFunc=true;
} else
if (TExpEnv::IsFuncOk("SendMsg", efatStr, FuncNm, ArgValV)){
// send message created from Arg0
TStr MsgNm=ArgValV[0]->GetStrVal();
PFaMsg Msg=TFaMsg::New(MsgNm);
FaExe->PushMsg(Msg);
} else
if (TExpEnv::IsFuncOk("SaveMsgArg", efatStrFlt, FuncNm, ArgValV)){
// saves message on the index Arg1 to the variable from Arg0
TStr VarNm=ArgValV[0]->GetStrVal();
int ArgN=ArgValV[1]->GetFltValAsInt()-1;
PFaMsg Msg=FaExe->GetLastMsg();
if ((!Msg.Empty())&&(0<=ArgN)&&(ArgN<Msg->GetArgs())){
TStr MsgArgValStr=Msg->GetArgVal(ArgN);
PExpVal ExpVal=TExpVal::New(MsgArgValStr);
PutVarVal(VarNm, ExpVal);
printf("Assign '%s'='%s'\n", VarNm.CStr(), MsgArgValStr.CStr());
}
} else
if (TExpEnv::IsFuncOk("SaveMsgArg", efatStr, FuncNm, ArgValV)){
// saves message on the index 1 to the variable from Arg0
TStr VarNm=ArgValV[0]->GetStrVal();
int ArgN=0;
PFaMsg Msg=FaExe->GetLastMsg();
if ((!Msg.Empty())&&(0<=ArgN)&&(ArgN<Msg->GetArgs())){
TStr MsgArgValStr=Msg->GetArgVal(ArgN);
PExpVal ExpVal=TExpVal::New(MsgArgValStr);
PutVarVal(VarNm, ExpVal);
printf("Assign '%s'='%s'\n", VarNm.CStr(), MsgArgValStr.CStr());
}
} else
if (TExpEnv::IsFuncOk("PlayIntro", efatStr, FuncNm, ArgValV)){
// play introduction for number in Arg0
TStr CallNumStr=ArgValV[0]->GetStrVal();
printf(".....Playing Intro for '%s'.....\n", CallNumStr.CStr());
} else
if (TExpEnv::IsFuncOk("PlayCm", efatStrStr, FuncNm, ArgValV)){
// play command
TStr CallNumStr=ArgValV[0]->GetStrVal();
TStr CmNm=ArgValV[1]->GetStrVal();
printf(".....Playing Command '%s' for '%s'.....\n",
CmNm.CStr(), CallNumStr.CStr());
} else {
printf("Bad env. function call %s/%d\n", FuncNm.CStr(), ArgValV.Len());
IsFunc=false;
}
return ExpVal;
}
/////////////////////////////////////////////////
// Finite-Automata-Execution
PExpVal TFaExe::EvalExpStr(const TStr& ExpStr){
bool Ok; TStr MsgStr; bool DbgP; TStr DbgStr; PExpVal ExpVal;
PExp Exp=TExp::LoadTxt(ExpStr, Ok, MsgStr);
if (Ok){
ExpVal=Exp->Eval(Ok, MsgStr, DbgP, DbgStr, ExpEnv);
if (!Ok){Notify->OnNotify(ntErr, MsgStr);}
} else {
Notify->OnNotify(ntErr, MsgStr);
ExpVal=TExpVal::GetUndefExpVal();
}
return ExpVal;
}
TFaExe::TFaExe(const PFaDef& _FaDef, const PNotify& _Notify):
FaDef(_FaDef), Notify(_Notify),
ActState(FaDef->GetStartState()), ActTrans(),
ActStateStartTm(TSecTm::GetCurTm()), MsgQ(),
ExpEnv(TFaExpEnv::New(this)),
LastMsg(){
Notify->OnNotify(ntInfo, TStr("Starting at state: ")+ActState->GetNm());
// execute start-state script
if (!ActState->GetScriptStr().Empty()){
EvalExpStr(ActState->GetScriptStr());
}
}
TFaExe::~TFaExe(){
Notify->OnNotify(ntInfo, TStr("Terminating at state: ")+ActState->GetNm());
}
void TFaExe::ExeStep(){
// get probability random
double Prb=ExpEnv->GetRnd().GetUniDev();
ExpEnv->PutVarVal("_Prb", TExpVal::New(Prb));
ExpEnv->PutVarVal("_PrbUsed", TExpVal::New(0));
// split transitions into conditions and empty
TFaTransV EmptyTransV; TFaTransV CondTransV;
for (int TransN=0; TransN<ActState->GetTranss(); TransN++){
PFaTrans Trans=ActState->GetTrans(TransN);
if (Trans->GetCondStr().GetTrunc().Empty()){EmptyTransV.Add(Trans);}
else {CondTransV.Add(Trans);}
}
// evaluate true conditions
PFaState NewActState; ActTrans=NULL;
for (int CondTransN=0; CondTransN<CondTransV.Len(); CondTransN++){
PFaTrans CondTrans=CondTransV[CondTransN];
PExpVal ExpVal=EvalExpStr(CondTrans->GetCondStr());
if (ExpVal->GetFltVal()!=0){
ActTrans=CondTrans;
TStr NewActStateNm=CondTransV[CondTransN]->GetDstStateNm();
if (FaDef->IsState(NewActStateNm)){
NewActState=FaDef->GetState(NewActStateNm);
} else {
Notify->OnNotify(ntErr, TStr("Invalid state name (")+NewActStateNm+")");
}
break;
}
}
// if no conditions applied
if (NewActState.Empty()){
if (EmptyTransV.Len()>0){
ActTrans=EmptyTransV[0];
TStr NewActStateNm=ActTrans->GetDstStateNm();
if (FaDef->IsState(NewActStateNm)){
NewActState=FaDef->GetState(NewActStateNm);
} else {
Notify->OnNotify(ntErr, TStr("Invalid state name (")+NewActStateNm+")");
}
}
}
// get new active state and execute its script
TStr OldStateNm=ActState->GetNm();
if (!NewActState.Empty()){
ActState=NewActState; ActStateStartTm=TSecTm::GetCurTm();
if (!ActState->GetScriptStr().Empty()){
EvalExpStr(ActState->GetScriptStr());
}
TStr NewStateNm=ActState->GetNm();
Notify->OnNotify(ntInfo, TStr("Transition: ")+OldStateNm+" -> "+NewStateNm);
}
}
void TFaExe::SendMsg(const PFaMsg& Msg){
if (!Msg.Empty()){
MsgQ.Push(Msg);}
while ((ActState()!=FaDef->GetEndState()())&&(!MsgQ.Empty())){
// process messages
if (!MsgQ.Empty()){
LastMsg=MsgQ.Top(); MsgQ.Pop();
printf("Msg: '%s'\n", LastMsg->GetNm()());
PFaTrans Trans;//**=FaDef->GetTrans(State, LastMsg);
if (!Trans.Empty()){
// execute transition script
if (!Trans->GetScriptStr().Empty()){
bool Ok; TStr MsgStr;
TExp::LoadAndEvalExpL(Trans->GetScriptStr(), Ok, MsgStr, ExpEnv);
}
// get new state
ActState=FaDef->GetState(Trans->GetDstStateNm());
// execute state script
if (!ActState->GetScriptStr().Empty()){
bool Ok; TStr MsgStr;
TExp::LoadAndEvalExpL(ActState->GetScriptStr(), Ok, MsgStr, ExpEnv);
}
} else {
printf("No transition for Msg: '%s'\n", LastMsg->GetNm()());
}
}
printf("State: '%s'\n", ActState->GetNm().CStr());
}
}
| 14,668 | 5,663 |
/*
MIT License
Copyright (c) 2018 Federico Terzi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "Variable.h"
ninx::lexer::token::Variable::Variable(int line_number, const std::string &name) : Token(line_number), name(name) {}
ninx::lexer::token::Type ninx::lexer::token::Variable::get_type() {
return Type::VARIABLE;
}
std::string ninx::lexer::token::Variable::dump() const {
return "VARIABLE: '" + this->name + "'";
}
const std::string &ninx::lexer::token::Variable::get_name() const {
return name;
}
int ninx::lexer::token::Variable::get_trailing_spaces() const {
return trailing_spaces;
}
void ninx::lexer::token::Variable::set_trailing_spaces(int trailing_spaces) {
Variable::trailing_spaces = trailing_spaces;
}
| 1,735 | 572 |
// =============================================================================
//
// Copyright (c) 2009-2013 Christopher Baker <http://christopherbaker.net>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// =============================================================================
#include "ofApp.h"
//------------------------------------------------------------------------------
void ofApp::setup()
{
ofSetVerticalSync(true);
useGrabber = false;
vidGrabber.setVerbose(false);
vidGrabber.initGrabber(160,120);
fingerMovie.loadMovie("movies/fingers_160x120x15fps.mov");
fingerMovie.play();
// are we connected to the server - if this fails we
// will check every few seconds to see if the server exists
sender.setVerbose(false);
if(sender.setup("127.0.0.1", 8888))
{
connectTime = ofGetElapsedTimeMillis();
}
// some counter text
counter = 0.0;
}
//------------------------------------------------------------------------------
void ofApp::update()
{
// prepare our video frames
fingerMovie.update();
vidGrabber.update();
if(sender.isConnected())
{
if(useGrabber)
{
if (vidGrabber.isFrameNew())
{
sender.sendFrame(vidGrabber.getPixelsRef());
}
}
else
{
if(fingerMovie.isFrameNew())
{
sender.sendFrame(fingerMovie.getPixelsRef());
}
}
}
else
{
//if we are not connected lets try and reconnect every 5 seconds
if((ofGetElapsedTimeMillis() - connectTime) > 5000)
{
sender.setup("127.0.0.1", 8888);
}
}
}
//------------------------------------------------------------------------------
void ofApp::draw()
{
ofBackground(0);
ofSetColor(127);
ofRect(190,20,ofGetWidth()-160-40,ofGetHeight()-40);
ofSetColor(255,255,0);
if(useGrabber)
{
ofRect(18,158,164,124);
} else {
ofRect(18,18,164,124);
}
ofSetColor(255);
fingerMovie.draw(20,20);
vidGrabber.draw(20,160);
// send some text
std::string txt = "sent from of => " + ofToString(counter++);
sender.sendText(txt);
std::stringstream ss;
ss << "This video is being sent over TCP to port 8888 can be" << endl;
ss << "received in Jitter by using [jit.net.recv @port 8888]." << endl;
ss << "See ofxJitterNetworkSender_Example.maxpat for example" << endl;
ss << "usage. This also works in Jitter 4.5, 5, 6, etc." << endl;
ss << endl;
ss << "This message is also being sent:" << endl;
ss << endl;
ss << "[" << txt << "]" << endl;
ss << endl;
ss << "More complex messages including bangs, lists, etc" << endl;
ss << "are not fully implemented yet." << endl;
ss << "" << endl;
ss << endl;
ss << "SPACEBAR toggles between video sources." << endl;
ofDrawBitmapString(ss.str(), 200, 60);
}
//------------------------------------------------------------------------------
void ofApp::keyPressed(int key)
{
useGrabber = !useGrabber;
}
| 4,148 | 1,375 |
/*---------------------------------------------------------------------------*/
#include <string.h>
#include <_types.h>
#include <util/string.h>
#include <util/tables.h>
#include <util/memory.h>
/*---------------------------------------------------------------------------*/
void xlate_to_lowercase (BYTE buf[], WORD buf_len)
{
if (buf_len == 0) return;
translate(buf, buf, buf_len, (BYTE *) &lower_case_chars_tbl[0]);
}
/*---------------------------------------------------------------------------*/
void xlate_to_uppercase (BYTE buf[], WORD buf_len)
{
if (buf_len == 0) return;
translate(buf, buf, buf_len, (BYTE *) &upper_case_chars_tbl[0]);
}
/*---------------------------------------------------------------------------*/
| 751 | 229 |
#include "stdafx.h"
Texture::Texture(const fs::path& path) {
BinaryReader reader = hierarchy.open_file(path);
if (path.extension() == ".blp" || path.extension() == ".BLP") {
auto blp = blp::BLP(reader);
auto[w, h, d] = blp.mipmaps.front();
data = d;
width = w;
height = h;
channels = 4;
// ToDo does this really belong here? Only a few textures have a minimap color
int mipmap_number = std::log2(width) - 2;
if (mipmap_number < blp.mipmaps.size() - 1) {
auto[mipw, miph, mipmap] = blp.mipmaps[mipmap_number];
minimap_color = *reinterpret_cast<glm::u8vec4*>(mipmap.data());
std::swap(minimap_color.r, minimap_color.b);
}
} else {
uint8_t* image_data = SOIL_load_image_from_memory(reader.buffer.data(), reader.buffer.size(), &width, &height, &channels, SOIL_LOAD_AUTO);
data = std::vector<uint8_t>(image_data, image_data + width * height * channels);
delete image_data;
}
} | 916 | 390 |
#include "browser/api/ApiApp.h"
#include "common/NodeRegisterHelp.h"
#include "common/api/EventEmitter.h"
#include "common/ThreadCall.h"
#include "gin/object_template_builder.h"
#include "browser/api/WindowList.h"
#include "base/values.h"
#include "wke.h"
#include "nodeblink.h"
#include "base/strings/string_util.h"
#include "base/files/file_path.h"
#include <shlobj.h>
namespace atom {
App* App::m_instance = nullptr;
App* App::getInstance() {
return m_instance;
}
App::App(v8::Isolate* isolate, v8::Local<v8::Object> wrapper) {
gin::Wrappable<App>::InitWith(isolate, wrapper);
ASSERT(!m_instance);
m_instance = this;
}
App::~App() {
DebugBreak();
}
void App::init(v8::Local<v8::Object> target, v8::Isolate* isolate) {
v8::Local<v8::FunctionTemplate> prototype = v8::FunctionTemplate::New(isolate, newFunction);
prototype->SetClassName(v8::String::NewFromUtf8(isolate, "App"));
gin::ObjectTemplateBuilder builder(isolate, prototype->InstanceTemplate());
builder.SetMethod("quit", &App::quitApi);
builder.SetMethod("exit", &App::exitApi);
builder.SetMethod("focus", &App::focusApi);
builder.SetMethod("getVersion", &App::getVersionApi);
builder.SetMethod("setVersion", &App::setVersionApi);
builder.SetMethod("getName", &App::getNameApi);
builder.SetMethod("setName", &App::setNameApi);
builder.SetMethod("isReady", &App::isReadyApi);
builder.SetMethod("addRecentDocument", &App::addRecentDocumentApi);
builder.SetMethod("clearRecentDocuments", &App::clearRecentDocumentsApi);
builder.SetMethod("setAppUserModelId", &App::setAppUserModelIdApi);
builder.SetMethod("isDefaultProtocolClient", &App::isDefaultProtocolClientApi);
builder.SetMethod("setAsDefaultProtocolClient", &App::setAsDefaultProtocolClientApi);
builder.SetMethod("removeAsDefaultProtocolClient", &App::removeAsDefaultProtocolClientApi);
builder.SetMethod("setBadgeCount", &App::setBadgeCountApi);
builder.SetMethod("getBadgeCount", &App::getBadgeCountApi);
builder.SetMethod("getLoginItemSettings", &App::getLoginItemSettingsApi);
builder.SetMethod("setLoginItemSettings", &App::setLoginItemSettingsApi);
builder.SetMethod("setUserTasks", &App::setUserTasksApi);
builder.SetMethod("getJumpListSettings", &App::getJumpListSettingsApi);
builder.SetMethod("setJumpList", &App::setJumpListApi);
builder.SetMethod("setPath", &App::setPathApi);
builder.SetMethod("getPath", &App::getPathApi);
builder.SetMethod("setDesktopName", &App::setDesktopNameApi);
builder.SetMethod("getLocale", &App::getLocaleApi);
builder.SetMethod("makeSingleInstance", &App::makeSingleInstanceApi);
builder.SetMethod("releaseSingleInstance", &App::releaseSingleInstanceApi);
builder.SetMethod("relaunch", &App::relaunchApi);
builder.SetMethod("isAccessibilitySupportEnabled", &App::isAccessibilitySupportEnabled);
builder.SetMethod("disableHardwareAcceleration", &App::disableHardwareAcceleration);
constructor.Reset(isolate, prototype->GetFunction());
target->Set(v8::String::NewFromUtf8(isolate, "App"), prototype->GetFunction());
}
void App::nullFunction() {
OutputDebugStringA("nullFunction\n");
}
void quit() {
::TerminateProcess(::GetCurrentProcess(), 0);
WindowList::closeAllWindows();
ThreadCall::exitMessageLoop(ThreadCall::getBlinkThreadId());
ThreadCall::exitMessageLoop(ThreadCall::getUiThreadId());
}
void App::quitApi() {
OutputDebugStringA("quitApi\n");
quit();
if (ThreadCall::isUiThread()) {
quit();
return;
}
ThreadCall::callUiThreadAsync([] {
quit();
});
}
void App::exitApi() {
quitApi();
}
void App::focusApi() {
OutputDebugStringA("focusApi\n");
}
bool App::isReadyApi() const {
OutputDebugStringA("isReadyApi\n");
return true;
}
void App::addRecentDocumentApi(const std::string& path) {
OutputDebugStringA("addRecentDocumentApi\n");
}
void App::clearRecentDocumentsApi() {
OutputDebugStringA("clearRecentDocumentsApi\n");
}
void App::setAppUserModelIdApi(const std::string& id) {
OutputDebugStringA("setAppUserModelIdApi\n");
}
// const std::string& protocol, const std::string& path, const std::string& args
bool App::isDefaultProtocolClientApi(const v8::FunctionCallbackInfo<v8::Value>& args) {
OutputDebugStringA("isDefaultProtocolClientApi\n");
return true;
}
//const std::string& protocol, const std::string& path, const std::string& args
bool App::setAsDefaultProtocolClientApi(const v8::FunctionCallbackInfo<v8::Value>& args) {
OutputDebugStringA("setAsDefaultProtocolClientApi\n");
if (0 == args.Length())
return false;
std::string protocol;
if (!gin::ConvertFromV8(args.GetIsolate(), args[0], &protocol))
return false;
return true;
}
// const std::string& protocol, const std::string& path, const std::string& args
bool App::removeAsDefaultProtocolClientApi(const v8::FunctionCallbackInfo<v8::Value>& args) {
OutputDebugStringA("removeAsDefaultProtocolClientApi\n");
return true;
}
bool App::setBadgeCountApi(int count) {
OutputDebugStringA("setBadgeCountApi\n");
return false;
}
int App::getBadgeCountApi() {
OutputDebugStringA("getBadgeCountApi\n");
return 0;
}
// const base::DictionaryValue& obj
int App::getLoginItemSettingsApi(const v8::FunctionCallbackInfo<v8::Value>& args) {
OutputDebugStringA("getLoginItemSettingsApi\n");
DebugBreak();
return 0;
}
// const base::DictionaryValue& obj, const std::string& path, const std::string& args
void App::setLoginItemSettingsApi(const v8::FunctionCallbackInfo<v8::Value>& args) {
OutputDebugStringA("setLoginItemSettingsApi");
DebugBreak();
}
bool App::setUserTasksApi(const v8::FunctionCallbackInfo<v8::Value>& args) {
OutputDebugStringA("setUserTasksApi\n");
return true;
}
void App::setDesktopNameApi(const std::string& desktopName) {
OutputDebugStringA("App::setDesktopNameApi\n");
}
v8::Local<v8::Value> App::getJumpListSettingsApi(const v8::FunctionCallbackInfo<v8::Value>& args) {
OutputDebugStringA("getJumpListSettingsApi\n");
base::DictionaryValue obj;
obj.SetInteger("minItems", 1);
base::ListValue* removedItems = new base::ListValue();
obj.Set("removedItems", removedItems);
v8::Local<v8::Value> result = gin::Converter<base::DictionaryValue>::ToV8(args.GetIsolate(), obj);
return result;
}
// const base::DictionaryValue&
void App::setJumpListApi(const v8::FunctionCallbackInfo<v8::Value>& args) {
OutputDebugStringA("setJumpListApi\n");
}
std::string App::getLocaleApi() {
return "zh-cn";
}
void App::makeSingleInstanceApi(const v8::FunctionCallbackInfo<v8::Value>& args) {
OutputDebugStringA("makeSingleInstanceApi\n");
}
void App::releaseSingleInstanceApi() {
OutputDebugStringA("releaseSingleInstanceApi\n");
}
void App::relaunchApi(const base::DictionaryValue& options) {
OutputDebugStringA("relaunchApi\n");
}
void App::setPathApi(const std::string& name, const std::string& path) {
if (name == "userData" || name == "cache" || name == "userCache" || name == "documents"
|| name == "downloads" || name == "music" || name == "videos" || name == "pepperFlashSystemPlugin") {
m_pathMap.insert(std::make_pair(name, path));
}
}
bool getTempDir(base::FilePath* path) {
wchar_t temp_path[MAX_PATH + 1];
DWORD path_len = ::GetTempPath(MAX_PATH, temp_path);
if (path_len >= MAX_PATH || path_len <= 0)
return false;
// TODO(evanm): the old behavior of this function was to always strip the
// trailing slash. We duplicate this here, but it shouldn't be necessary
// when everyone is using the appropriate FilePath APIs.
*path = base::FilePath(temp_path).StripTrailingSeparators();
return true;
}
base::FilePath getHomeDir() {
wchar_t result[MAX_PATH];
if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PROFILE, NULL, SHGFP_TYPE_CURRENT, result)) && result[0])
return base::FilePath(result);
// Fall back to the temporary directory on failure.
base::FilePath temp;
if (getTempDir(&temp))
return temp;
// Last resort.
return base::FilePath(L"C:\\");
}
std::string App::getPathApi(const std::string& name) const {
base::FilePath path;
std::wstring systemBuffer;
systemBuffer.assign(MAX_PATH, L'\0');
std::wstring pathBuffer;
if (name == "appData") {
if ((::SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, &systemBuffer[0])) < 0)
return "";
} else if (name == "userData" || name == "documents"
|| name == "downloads" || name == "music" || name == "videos" || name == "pepperFlashSystemPlugin") {
std::map<std::string, std::string>::const_iterator it = m_pathMap.find(name);
if (it == m_pathMap.end())
return "";
return it->second;
} else if (name == "home")
systemBuffer = getHomeDir().value();
else if (name == "temp") {
if (!getTempDir(&path))
return "";
systemBuffer = path.value();
} else if (name == "userDesktop" || name == "desktop") {
if (FAILED(SHGetFolderPath(NULL, CSIDL_DESKTOPDIRECTORY, NULL, SHGFP_TYPE_CURRENT, &systemBuffer[0])))
return "";
} else if (name == "exe") {
::GetModuleFileName(NULL, &systemBuffer[0], MAX_PATH);
} else if (name == "module")
::GetModuleFileName(NULL, &systemBuffer[0], MAX_PATH);
else if (name == "cache" || name == "userCache") {
if ((::SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, &systemBuffer[0])) < 0)
return "";
pathBuffer = systemBuffer.c_str();
pathBuffer += L"\\electron";
} else
return "";
pathBuffer = systemBuffer.c_str();
return base::WideToUTF8(pathBuffer);
}
void App::newFunction(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Isolate* isolate = args.GetIsolate();
if (args.IsConstructCall()) {
new App(isolate, args.This());
args.GetReturnValue().Set(args.This());
return;
}
}
void App::onWindowAllClosed() {
if (ThreadCall::isUiThread()) {
emit("window-all-closed");
return;
}
App* self = this;
ThreadCall::callUiThreadAsync([self] {
self->emit("window-all-closed");
});
}
v8::Persistent< v8::Function> App::constructor;
gin::WrapperInfo App::kWrapperInfo = { gin::kEmbedderNativeGin };
static void initializeAppApi(v8::Local<v8::Object> target, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, const NodeNative* native) {
node::Environment* env = node::Environment::GetCurrent(context);
App::init(target, env->isolate());
}
static const char BrowserAppNative[] = "console.log('BrowserAppNative');;";
static NodeNative nativeBrowserAppNative{ "App", BrowserAppNative, sizeof(BrowserAppNative) - 1 };
NODE_MODULE_CONTEXT_AWARE_BUILTIN_SCRIPT_MANUAL(atom_browser_app, initializeAppApi, &nativeBrowserAppNative)
} | 11,335 | 3,631 |
/*
* Modified by LeafLabs, LLC.
*
* Part of the Wiring project - http://wiring.org.co Copyright (c)
* 2004-06 Hernando Barragan Modified 13 August 2006, David A. Mellis
* for Arduino - http://www.arduino.cc/
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
#include <stdlib.h>
#include <wirish/wirish_math.h>
void randomSeed(unsigned int seed) {
if (seed != 0) {
srand(seed);
}
}
long random(long howbig) {
if (howbig == 0) {
return 0;
}
return rand() % howbig;
}
long random(long howsmall, long howbig) {
if (howsmall >= howbig) {
return howsmall;
}
long diff = howbig - howsmall;
return random(diff) + howsmall;
}
| 1,383 | 472 |
// Copyright 2018 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 "third_party/blink/renderer/core/layout/layout_shift_tracker.h"
#include "cc/layers/heads_up_display_layer.h"
#include "cc/layers/picture_layer.h"
#include "cc/trees/layer_tree_host.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/common/input/web_pointer_event.h"
#include "third_party/blink/renderer/core/dom/dom_node_ids.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_client.h"
#include "third_party/blink/renderer/core/frame/location.h"
#include "third_party/blink/renderer/core/frame/visual_viewport.h"
#include "third_party/blink/renderer/core/geometry/dom_rect_read_only.h"
#include "third_party/blink/renderer/core/layout/layout_object.h"
#include "third_party/blink/renderer/core/layout/layout_view.h"
#include "third_party/blink/renderer/core/page/chrome_client.h"
#include "third_party/blink/renderer/core/page/page.h"
#include "third_party/blink/renderer/core/timing/dom_window_performance.h"
#include "third_party/blink/renderer/core/timing/performance_entry.h"
#include "third_party/blink/renderer/core/timing/window_performance.h"
#include "third_party/blink/renderer/platform/graphics/graphics_layer.h"
#include "third_party/blink/renderer/platform/graphics/paint/geometry_mapper.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "ui/gfx/geometry/rect.h"
namespace blink {
using ReattachHookScope = LayoutShiftTracker::ReattachHookScope;
ReattachHookScope* ReattachHookScope::top_ = nullptr;
using ContainingBlockScope = LayoutShiftTracker::ContainingBlockScope;
ContainingBlockScope* ContainingBlockScope::top_ = nullptr;
namespace {
constexpr base::TimeDelta kTimerDelay = base::TimeDelta::FromMilliseconds(500);
const float kMovementThreshold = 3.0; // CSS pixels.
// Calculates the physical coordinates of the starting point in the current
// coordinate space. |paint_offset| is the physical offset of the top-left
// corner. The starting point can be any of the four corners of the box,
// depending on the writing mode and text direction. Note that the result is
// still in physical coordinates, just may be of a different corner.
// See https://wicg.github.io/layout-instability/#starting-point.
FloatPoint StartingPoint(const PhysicalOffset& paint_offset,
const LayoutBox& box,
const LayoutSize& size) {
PhysicalOffset starting_point = paint_offset;
auto writing_direction = box.StyleRef().GetWritingDirection();
if (UNLIKELY(writing_direction.IsFlippedBlocks()))
starting_point.left += size.Width();
if (UNLIKELY(writing_direction.IsRtl())) {
if (writing_direction.IsHorizontal())
starting_point.left += size.Width();
else
starting_point.top += size.Height();
}
return FloatPoint(starting_point);
}
// Returns the part a rect logically below a starting point.
PhysicalRect RectBelowStartingPoint(const PhysicalRect& rect,
const PhysicalOffset& starting_point,
LayoutUnit logical_height,
WritingDirectionMode writing_direction) {
PhysicalRect result = rect;
if (writing_direction.IsHorizontal()) {
result.ShiftTopEdgeTo(starting_point.top);
result.SetHeight(logical_height);
} else {
result.SetWidth(logical_height);
if (writing_direction.IsFlippedBlocks())
result.ShiftRightEdgeTo(starting_point.left);
else
result.ShiftLeftEdgeTo(starting_point.left);
}
return result;
}
float GetMoveDistance(const FloatPoint& old_starting_point,
const FloatPoint& new_starting_point) {
FloatSize location_delta = new_starting_point - old_starting_point;
return std::max(fabs(location_delta.Width()), fabs(location_delta.Height()));
}
bool EqualWithinMovementThreshold(const FloatPoint& a,
const FloatPoint& b,
float threshold_physical_px) {
return fabs(a.X() - b.X()) < threshold_physical_px &&
fabs(a.Y() - b.Y()) < threshold_physical_px;
}
bool SmallerThanRegionGranularity(const LayoutRect& rect) {
// Normally we paint by snapping to whole pixels, so rects smaller than half
// a pixel may be invisible.
return rect.Width() < 0.5 || rect.Height() < 0.5;
}
void RectToTracedValue(const IntRect& rect,
TracedValue& value,
const char* key = nullptr) {
if (key)
value.BeginArray(key);
else
value.BeginArray();
value.PushInteger(rect.X());
value.PushInteger(rect.Y());
value.PushInteger(rect.Width());
value.PushInteger(rect.Height());
value.EndArray();
}
void RegionToTracedValue(const LayoutShiftRegion& region, TracedValue& value) {
Region blink_region;
for (IntRect rect : region.GetRects())
blink_region.Unite(Region(rect));
value.BeginArray("region_rects");
for (const IntRect& rect : blink_region.Rects())
RectToTracedValue(rect, value);
value.EndArray();
}
bool ShouldLog(const LocalFrame& frame) {
if (!VLOG_IS_ON(1))
return false;
DCHECK(frame.GetDocument());
const String& url = frame.GetDocument()->Url().GetString();
return !url.StartsWith("devtools:");
}
} // namespace
LayoutShiftTracker::LayoutShiftTracker(LocalFrameView* frame_view)
: frame_view_(frame_view),
// This eliminates noise from the private Page object created by
// SVGImage::DataChanged.
is_active_(
!frame_view->GetFrame().GetChromeClient().IsSVGImageChromeClient()),
enable_m90_improvements_(
base::FeatureList::IsEnabled(features::kCLSM90Improvements)),
score_(0.0),
weighted_score_(0.0),
timer_(frame_view->GetFrame().GetTaskRunner(TaskType::kInternalDefault),
this,
&LayoutShiftTracker::TimerFired),
frame_max_distance_(0.0),
overall_max_distance_(0.0),
observed_input_or_scroll_(false),
most_recent_input_timestamp_initialized_(false) {}
bool LayoutShiftTracker::NeedsToTrack(const LayoutObject& object) const {
if (!is_active_)
return false;
if (object.GetDocument().IsPrintingOrPaintingPreview())
return false;
// SVG elements don't participate in the normal layout algorithms and are
// more likely to be used for animations.
if (object.IsSVGChild())
return false;
if (object.StyleRef().Visibility() != EVisibility::kVisible)
return false;
if (object.IsText()) {
if (!ContainingBlockScope::top_)
return false;
if (object.IsBR())
return false;
if (enable_m90_improvements_) {
if (To<LayoutText>(object).ContainsOnlyWhitespaceOrNbsp() ==
OnlyWhitespaceOrNbsp::kYes)
return false;
if (object.StyleRef().GetFont().ShouldSkipDrawing())
return false;
}
return true;
}
if (!object.IsBox())
return false;
const auto& box = To<LayoutBox>(object);
if (SmallerThanRegionGranularity(box.VisualOverflowRect()))
return false;
if (auto* display_lock_context = box.GetDisplayLockContext()) {
if (display_lock_context->IsAuto() && display_lock_context->IsLocked())
return false;
}
// Don't report shift of anonymous objects. Will report the children because
// we want report real DOM nodes.
if (box.IsAnonymous())
return false;
// Ignore sticky-positioned objects that move on scroll.
// TODO(skobes): Find a way to detect when these objects shift.
if (box.IsStickyPositioned())
return false;
// A LayoutView can't move by itself.
if (box.IsLayoutView())
return false;
if (Element* element = DynamicTo<Element>(object.GetNode())) {
if (element->IsSliderThumbElement())
return false;
}
if (enable_m90_improvements_ && box.IsLayoutBlock()) {
// Just check the simplest case. For more complex cases, we should suggest
// the developer to use visibility:hidden.
if (To<LayoutBlock>(box).FirstChild())
return true;
if (box.HasBoxDecorationBackground() || box.GetScrollableArea() ||
box.StyleRef().HasVisualOverflowingEffect())
return true;
return false;
}
return true;
}
void LayoutShiftTracker::ObjectShifted(
const LayoutObject& object,
const PropertyTreeStateOrAlias& property_tree_state,
const PhysicalRect& old_rect,
const PhysicalRect& new_rect,
const FloatPoint& old_starting_point,
const FloatSize& translation_delta,
const FloatSize& scroll_delta,
const FloatPoint& new_starting_point) {
// The caller should ensure these conditions.
DCHECK(!old_rect.IsEmpty());
DCHECK(!new_rect.IsEmpty());
float threshold_physical_px =
kMovementThreshold * object.StyleRef().EffectiveZoom();
if (enable_m90_improvements_) {
// Check shift of starting point, including 2d-translation and scroll
// deltas.
if (EqualWithinMovementThreshold(old_starting_point, new_starting_point,
threshold_physical_px))
return;
// Check shift of 2d-translation-indifferent starting point.
if (!translation_delta.IsZero() &&
EqualWithinMovementThreshold(old_starting_point + translation_delta,
new_starting_point, threshold_physical_px))
return;
// Check shift of scroll-indifferent starting point.
if (!scroll_delta.IsZero() &&
EqualWithinMovementThreshold(old_starting_point + scroll_delta,
new_starting_point, threshold_physical_px))
return;
}
// Check shift of 2d-translation-and-scroll-indifferent starting point.
FloatSize translation_and_scroll_delta = scroll_delta + translation_delta;
if (!translation_and_scroll_delta.IsZero() &&
EqualWithinMovementThreshold(
old_starting_point + translation_and_scroll_delta, new_starting_point,
threshold_physical_px))
return;
const auto& root_state =
object.View()->FirstFragment().LocalBorderBoxProperties();
FloatClipRect clip_rect =
GeometryMapper::LocalToAncestorClipRect(property_tree_state, root_state);
if (frame_view_->GetFrame().IsMainFrame()) {
// Apply the visual viewport clip.
clip_rect.Intersect(FloatClipRect(
frame_view_->GetPage()->GetVisualViewport().VisibleRect()));
}
// If the clip region is empty, then the resulting layout shift isn't visible
// in the viewport so ignore it.
if (clip_rect.Rect().IsEmpty())
return;
auto transform = GeometryMapper::SourceToDestinationProjection(
property_tree_state.Transform(), root_state.Transform());
// TODO(crbug.com/1187979): Shift by |scroll_delta| to keep backward
// compatibility in https://crrev.com/c/2754969. See the bug for details.
FloatPoint old_starting_point_in_root = transform.MapPoint(
old_starting_point +
(enable_m90_improvements_ ? scroll_delta : translation_and_scroll_delta));
FloatPoint new_starting_point_in_root =
transform.MapPoint(new_starting_point);
if (EqualWithinMovementThreshold(old_starting_point_in_root,
new_starting_point_in_root,
threshold_physical_px))
return;
if (enable_m90_improvements_) {
DCHECK(frame_scroll_delta_.IsZero());
} else if (EqualWithinMovementThreshold(
old_starting_point_in_root + frame_scroll_delta_,
new_starting_point_in_root, threshold_physical_px)) {
// TODO(skobes): Checking frame_scroll_delta_ is an imperfect solution to
// allowing counterscrolled layout shifts. Ideally, we would map old_rect
// to viewport coordinates using the previous frame's scroll tree.
return;
}
FloatRect old_rect_in_root(old_rect);
// TODO(crbug.com/1187979): Shift by |scroll_delta| to keep backward
// compatibility in https://crrev.com/c/2754969. See the bug for details.
old_rect_in_root.Move(
enable_m90_improvements_ ? scroll_delta : translation_and_scroll_delta);
transform.MapRect(old_rect_in_root);
FloatRect new_rect_in_root(new_rect);
transform.MapRect(new_rect_in_root);
IntRect visible_old_rect =
RoundedIntRect(Intersection(old_rect_in_root, clip_rect.Rect()));
IntRect visible_new_rect =
RoundedIntRect(Intersection(new_rect_in_root, clip_rect.Rect()));
if (visible_old_rect.IsEmpty() && visible_new_rect.IsEmpty())
return;
// If the object moved from or to out of view, ignore the shift if it's in
// the inline direction only.
if (enable_m90_improvements_ &&
(visible_old_rect.IsEmpty() || visible_new_rect.IsEmpty())) {
FloatPoint old_inline_direction_indifferent_starting_point_in_root =
old_starting_point_in_root;
if (object.IsHorizontalWritingMode()) {
old_inline_direction_indifferent_starting_point_in_root.SetX(
new_starting_point_in_root.X());
} else {
old_inline_direction_indifferent_starting_point_in_root.SetY(
new_starting_point_in_root.Y());
}
if (EqualWithinMovementThreshold(
old_inline_direction_indifferent_starting_point_in_root,
new_starting_point_in_root, threshold_physical_px)) {
return;
}
}
// Compute move distance based on unclipped rects, to accurately determine how
// much the element moved.
float move_distance =
GetMoveDistance(old_starting_point_in_root, new_starting_point_in_root);
frame_max_distance_ = std::max(frame_max_distance_, move_distance);
LocalFrame& frame = frame_view_->GetFrame();
if (ShouldLog(frame)) {
VLOG(1) << "in " << (frame.IsMainFrame() ? "" : "subframe ")
<< frame.GetDocument()->Url() << ", " << object << " moved from "
<< old_rect_in_root << " to " << new_rect_in_root
<< " (visible from " << visible_old_rect << " to "
<< visible_new_rect << ")";
if (old_starting_point_in_root != old_rect_in_root.Location() ||
new_starting_point_in_root != new_rect_in_root.Location() ||
!translation_delta.IsZero() || !scroll_delta.IsZero()) {
VLOG(1) << " (starting point from " << old_starting_point_in_root
<< " to " << new_starting_point_in_root << ")";
}
}
region_.AddRect(visible_old_rect);
region_.AddRect(visible_new_rect);
if (Node* node = object.GetNode()) {
MaybeRecordAttribution(
{DOMNodeIds::IdForNode(node), visible_old_rect, visible_new_rect});
}
}
LayoutShiftTracker::Attribution::Attribution() : node_id(kInvalidDOMNodeId) {}
LayoutShiftTracker::Attribution::Attribution(DOMNodeId node_id_arg,
IntRect old_visual_rect_arg,
IntRect new_visual_rect_arg)
: node_id(node_id_arg),
old_visual_rect(old_visual_rect_arg),
new_visual_rect(new_visual_rect_arg) {}
LayoutShiftTracker::Attribution::operator bool() const {
return node_id != kInvalidDOMNodeId;
}
bool LayoutShiftTracker::Attribution::Encloses(const Attribution& other) const {
return old_visual_rect.Contains(other.old_visual_rect) &&
new_visual_rect.Contains(other.new_visual_rect);
}
int LayoutShiftTracker::Attribution::Area() const {
int old_area = old_visual_rect.Width() * old_visual_rect.Height();
int new_area = new_visual_rect.Width() * new_visual_rect.Height();
IntRect intersection = Intersection(old_visual_rect, new_visual_rect);
int shared_area = intersection.Width() * intersection.Height();
return old_area + new_area - shared_area;
}
bool LayoutShiftTracker::Attribution::MoreImpactfulThan(
const Attribution& other) const {
return Area() > other.Area();
}
void LayoutShiftTracker::MaybeRecordAttribution(
const Attribution& attribution) {
Attribution* smallest = nullptr;
for (auto& slot : attributions_) {
if (!slot || attribution.Encloses(slot)) {
slot = attribution;
return;
}
if (slot.Encloses(attribution))
return;
if (!smallest || smallest->MoreImpactfulThan(slot))
smallest = &slot;
}
// No empty slots or redundancies. Replace smallest existing slot if larger.
if (attribution.MoreImpactfulThan(*smallest))
*smallest = attribution;
}
void LayoutShiftTracker::NotifyBoxPrePaint(
const LayoutBox& box,
const PropertyTreeStateOrAlias& property_tree_state,
const PhysicalRect& old_rect,
const PhysicalRect& new_rect,
const PhysicalOffset& old_paint_offset,
const FloatSize& translation_delta,
const FloatSize& scroll_delta,
const PhysicalOffset& new_paint_offset) {
DCHECK(NeedsToTrack(box));
ObjectShifted(box, property_tree_state, old_rect, new_rect,
StartingPoint(old_paint_offset, box, box.PreviousSize()),
translation_delta, scroll_delta,
StartingPoint(new_paint_offset, box, box.Size()));
}
void LayoutShiftTracker::NotifyTextPrePaint(
const LayoutText& text,
const PropertyTreeStateOrAlias& property_tree_state,
const LogicalOffset& old_starting_point,
const LogicalOffset& new_starting_point,
const PhysicalOffset& old_paint_offset,
const FloatSize& translation_delta,
const FloatSize& scroll_delta,
const PhysicalOffset& new_paint_offset,
LayoutUnit logical_height) {
DCHECK(NeedsToTrack(text));
auto* block = ContainingBlockScope::top_;
DCHECK(block);
auto writing_direction = text.StyleRef().GetWritingDirection();
PhysicalOffset old_physical_starting_point =
old_paint_offset + old_starting_point.ConvertToPhysical(writing_direction,
block->old_size_,
PhysicalSize());
PhysicalOffset new_physical_starting_point =
new_paint_offset + new_starting_point.ConvertToPhysical(writing_direction,
block->new_size_,
PhysicalSize());
PhysicalRect old_rect =
RectBelowStartingPoint(block->old_rect_, old_physical_starting_point,
logical_height, writing_direction);
if (old_rect.IsEmpty())
return;
PhysicalRect new_rect =
RectBelowStartingPoint(block->new_rect_, new_physical_starting_point,
logical_height, writing_direction);
if (new_rect.IsEmpty())
return;
ObjectShifted(text, property_tree_state, old_rect, new_rect,
FloatPoint(old_physical_starting_point), translation_delta,
scroll_delta, FloatPoint(new_physical_starting_point));
}
double LayoutShiftTracker::SubframeWeightingFactor() const {
LocalFrame& frame = frame_view_->GetFrame();
if (frame.IsMainFrame())
return 1;
// Map the subframe view rect into the coordinate space of the local root.
FloatClipRect subframe_cliprect =
FloatClipRect(FloatRect(FloatPoint(), FloatSize(frame_view_->Size())));
GeometryMapper::LocalToAncestorVisualRect(
frame_view_->GetLayoutView()->FirstFragment().LocalBorderBoxProperties(),
PropertyTreeState::Root(), subframe_cliprect);
auto subframe_rect = PhysicalRect::EnclosingRect(subframe_cliprect.Rect());
// Intersect with the portion of the local root that overlaps the main frame.
frame.LocalFrameRoot().View()->MapToVisualRectInRemoteRootFrame(
subframe_rect);
IntSize subframe_visible_size = subframe_rect.PixelSnappedSize();
IntSize main_frame_size = frame.GetPage()->GetVisualViewport().Size();
// TODO(crbug.com/940711): This comparison ignores page scale and CSS
// transforms above the local root.
return static_cast<double>(subframe_visible_size.Area()) /
main_frame_size.Area();
}
void LayoutShiftTracker::NotifyPrePaintFinishedInternal() {
if (!is_active_)
return;
if (region_.IsEmpty())
return;
IntRect viewport = frame_view_->GetScrollableArea()->VisibleContentRect();
if (viewport.IsEmpty())
return;
double viewport_area = double(viewport.Width()) * double(viewport.Height());
double impact_fraction = region_.Area() / viewport_area;
DCHECK_GT(impact_fraction, 0);
DCHECK_GT(frame_max_distance_, 0.0);
double viewport_max_dimension = std::max(viewport.Width(), viewport.Height());
double move_distance_factor =
(frame_max_distance_ < viewport_max_dimension)
? double(frame_max_distance_) / viewport_max_dimension
: 1.0;
double score_delta = impact_fraction * move_distance_factor;
double weighted_score_delta = score_delta * SubframeWeightingFactor();
overall_max_distance_ = std::max(overall_max_distance_, frame_max_distance_);
LocalFrame& frame = frame_view_->GetFrame();
if (ShouldLog(frame)) {
VLOG(1) << "in " << (frame.IsMainFrame() ? "" : "subframe ")
<< frame.GetDocument()->Url() << ", viewport was "
<< (impact_fraction * 100) << "% impacted with distance fraction "
<< move_distance_factor;
}
if (pointerdown_pending_data_.saw_pointerdown) {
pointerdown_pending_data_.score_delta += score_delta;
pointerdown_pending_data_.weighted_score_delta += weighted_score_delta;
} else {
ReportShift(score_delta, weighted_score_delta);
}
if (!region_.IsEmpty() && !timer_.IsActive())
SendLayoutShiftRectsToHud(region_.GetRects());
}
void LayoutShiftTracker::NotifyPrePaintFinished() {
NotifyPrePaintFinishedInternal();
// Reset accumulated state.
region_.Reset();
frame_max_distance_ = 0.0;
frame_scroll_delta_ = ScrollOffset();
attributions_.fill(Attribution());
}
LayoutShift::AttributionList LayoutShiftTracker::CreateAttributionList() const {
LayoutShift::AttributionList list;
for (const Attribution& att : attributions_) {
if (att.node_id == kInvalidDOMNodeId)
break;
list.push_back(LayoutShiftAttribution::Create(
DOMNodeIds::NodeForId(att.node_id),
DOMRectReadOnly::FromIntRect(att.old_visual_rect),
DOMRectReadOnly::FromIntRect(att.new_visual_rect)));
}
return list;
}
void LayoutShiftTracker::SubmitPerformanceEntry(double score_delta,
bool had_recent_input) const {
LocalDOMWindow* window = frame_view_->GetFrame().DomWindow();
if (!window)
return;
WindowPerformance* performance = DOMWindowPerformance::performance(*window);
DCHECK(performance);
double input_timestamp = LastInputTimestamp();
LayoutShift* entry =
LayoutShift::Create(performance->now(), score_delta, had_recent_input,
input_timestamp, CreateAttributionList());
performance->AddLayoutShiftEntry(entry);
}
void LayoutShiftTracker::ReportShift(double score_delta,
double weighted_score_delta) {
LocalFrame& frame = frame_view_->GetFrame();
bool had_recent_input = timer_.IsActive();
if (!had_recent_input) {
score_ += score_delta;
if (weighted_score_delta > 0) {
weighted_score_ += weighted_score_delta;
frame.Client()->DidObserveLayoutShift(weighted_score_delta,
observed_input_or_scroll_);
}
}
SubmitPerformanceEntry(score_delta, had_recent_input);
TRACE_EVENT_INSTANT2(
"loading", "LayoutShift", TRACE_EVENT_SCOPE_THREAD, "data",
PerFrameTraceData(score_delta, weighted_score_delta, had_recent_input),
"frame", ToTraceValue(&frame));
if (ShouldLog(frame)) {
VLOG(1) << "in " << (frame.IsMainFrame() ? "" : "subframe ")
<< frame.GetDocument()->Url().GetString() << ", layout shift of "
<< score_delta
<< (had_recent_input ? " excluded by recent input" : " reported")
<< "; cumulative score is " << score_;
}
}
void LayoutShiftTracker::NotifyInput(const WebInputEvent& event) {
const WebInputEvent::Type type = event.GetType();
const bool saw_pointerdown = pointerdown_pending_data_.saw_pointerdown;
const bool pointerdown_became_tap =
saw_pointerdown && type == WebInputEvent::Type::kPointerUp;
const bool event_type_stops_pointerdown_buffering =
type == WebInputEvent::Type::kPointerUp ||
type == WebInputEvent::Type::kPointerCausedUaAction ||
type == WebInputEvent::Type::kPointerCancel;
// Only non-hovering pointerdown requires buffering.
const bool is_hovering_pointerdown =
type == WebInputEvent::Type::kPointerDown &&
static_cast<const WebPointerEvent&>(event).hovering;
const bool should_trigger_shift_exclusion =
type == WebInputEvent::Type::kMouseDown ||
type == WebInputEvent::Type::kKeyDown ||
type == WebInputEvent::Type::kRawKeyDown ||
// We need to explicitly include tap, as if there are no listeners, we
// won't receive the pointer events.
type == WebInputEvent::Type::kGestureTap || is_hovering_pointerdown ||
pointerdown_became_tap;
if (should_trigger_shift_exclusion) {
observed_input_or_scroll_ = true;
// This cancels any previously scheduled task from the same timer.
timer_.StartOneShot(kTimerDelay, FROM_HERE);
UpdateInputTimestamp(event.TimeStamp());
}
if (saw_pointerdown && event_type_stops_pointerdown_buffering) {
double score_delta = pointerdown_pending_data_.score_delta;
if (score_delta > 0)
ReportShift(score_delta, pointerdown_pending_data_.weighted_score_delta);
pointerdown_pending_data_ = PointerdownPendingData();
}
if (type == WebInputEvent::Type::kPointerDown && !is_hovering_pointerdown)
pointerdown_pending_data_.saw_pointerdown = true;
}
void LayoutShiftTracker::UpdateInputTimestamp(base::TimeTicks timestamp) {
if (!most_recent_input_timestamp_initialized_) {
most_recent_input_timestamp_ = timestamp;
most_recent_input_timestamp_initialized_ = true;
} else if (timestamp > most_recent_input_timestamp_) {
most_recent_input_timestamp_ = timestamp;
}
LocalFrame& frame = frame_view_->GetFrame();
frame.Client()->DidObserveInputForLayoutShiftTracking(timestamp);
}
void LayoutShiftTracker::NotifyScroll(mojom::blink::ScrollType scroll_type,
ScrollOffset delta) {
if (!enable_m90_improvements_)
frame_scroll_delta_ += delta;
// Only set observed_input_or_scroll_ for user-initiated scrolls, and not
// other scrolls such as hash fragment navigations.
if (scroll_type == mojom::blink::ScrollType::kUser ||
scroll_type == mojom::blink::ScrollType::kCompositor)
observed_input_or_scroll_ = true;
}
void LayoutShiftTracker::NotifyViewportSizeChanged() {
UpdateTimerAndInputTimestamp();
}
void LayoutShiftTracker::NotifyFindInPageInput() {
UpdateTimerAndInputTimestamp();
}
void LayoutShiftTracker::NotifyChangeEvent() {
UpdateTimerAndInputTimestamp();
}
void LayoutShiftTracker::UpdateTimerAndInputTimestamp() {
// This cancels any previously scheduled task from the same timer.
timer_.StartOneShot(kTimerDelay, FROM_HERE);
UpdateInputTimestamp(base::TimeTicks::Now());
}
double LayoutShiftTracker::LastInputTimestamp() const {
LocalDOMWindow* window = frame_view_->GetFrame().DomWindow();
if (!window)
return 0.0;
WindowPerformance* performance = DOMWindowPerformance::performance(*window);
DCHECK(performance);
return most_recent_input_timestamp_initialized_
? performance->MonotonicTimeToDOMHighResTimeStamp(
most_recent_input_timestamp_)
: 0.0;
}
std::unique_ptr<TracedValue> LayoutShiftTracker::PerFrameTraceData(
double score_delta,
double weighted_score_delta,
bool input_detected) const {
auto value = std::make_unique<TracedValue>();
value->SetDouble("score", score_delta);
value->SetDouble("weighted_score_delta", weighted_score_delta);
value->SetDouble("cumulative_score", score_);
value->SetDouble("overall_max_distance", overall_max_distance_);
value->SetDouble("frame_max_distance", frame_max_distance_);
RegionToTracedValue(region_, *value);
value->SetBoolean("is_main_frame", frame_view_->GetFrame().IsMainFrame());
value->SetBoolean("had_recent_input", input_detected);
value->SetDouble("last_input_timestamp", LastInputTimestamp());
AttributionsToTracedValue(*value);
return value;
}
void LayoutShiftTracker::AttributionsToTracedValue(TracedValue& value) const {
const Attribution* it = attributions_.begin();
if (!*it)
return;
bool should_include_names;
TRACE_EVENT_CATEGORY_GROUP_ENABLED(
TRACE_DISABLED_BY_DEFAULT("layout_shift.debug"), &should_include_names);
value.BeginArray("impacted_nodes");
while (it != attributions_.end() && it->node_id != kInvalidDOMNodeId) {
value.BeginDictionary();
value.SetInteger("node_id", it->node_id);
RectToTracedValue(it->old_visual_rect, value, "old_rect");
RectToTracedValue(it->new_visual_rect, value, "new_rect");
if (should_include_names) {
Node* node = DOMNodeIds::NodeForId(it->node_id);
value.SetString("debug_name", node ? node->DebugName() : "");
}
value.EndDictionary();
it++;
}
value.EndArray();
}
void LayoutShiftTracker::SendLayoutShiftRectsToHud(
const Vector<IntRect>& int_rects) {
// Store the layout shift rects in the HUD layer.
auto* cc_layer = frame_view_->RootCcLayer();
if (cc_layer && cc_layer->layer_tree_host()) {
if (!cc_layer->layer_tree_host()->GetDebugState().show_layout_shift_regions)
return;
if (cc_layer->layer_tree_host()->hud_layer()) {
WebVector<gfx::Rect> rects;
Region blink_region;
for (IntRect rect : int_rects)
blink_region.Unite(Region(rect));
for (const IntRect& rect : blink_region.Rects())
rects.emplace_back(rect);
cc_layer->layer_tree_host()->hud_layer()->SetLayoutShiftRects(
rects.ReleaseVector());
cc_layer->layer_tree_host()->hud_layer()->SetNeedsPushProperties();
}
}
}
void LayoutShiftTracker::Trace(Visitor* visitor) const {
visitor->Trace(frame_view_);
visitor->Trace(timer_);
}
ReattachHookScope::ReattachHookScope(const Node& node) : outer_(top_) {
if (node.GetLayoutObject())
top_ = this;
}
ReattachHookScope::~ReattachHookScope() {
top_ = outer_;
}
void ReattachHookScope::NotifyDetach(const Node& node) {
if (!top_)
return;
auto* layout_object = node.GetLayoutObject();
if (!layout_object || layout_object->ShouldSkipNextLayoutShiftTracking() ||
!layout_object->IsBox())
return;
auto& map = top_->geometries_before_detach_;
auto& fragment = layout_object->GetMutableForPainting().FirstFragment();
// Save the visual rect for restoration on future reattachment.
const auto& box = To<LayoutBox>(*layout_object);
PhysicalRect visual_overflow_rect = box.PreviousPhysicalVisualOverflowRect();
if (visual_overflow_rect.IsEmpty() && box.PreviousSize().IsEmpty())
return;
bool has_paint_offset_transform = false;
if (auto* properties = fragment.PaintProperties())
has_paint_offset_transform = properties->PaintOffsetTranslation();
map.Set(&node, Geometry{fragment.PaintOffset(), box.PreviousSize(),
visual_overflow_rect, has_paint_offset_transform});
}
void ReattachHookScope::NotifyAttach(const Node& node) {
if (!top_)
return;
auto* layout_object = node.GetLayoutObject();
if (!layout_object || !layout_object->IsBox())
return;
auto& map = top_->geometries_before_detach_;
// Restore geometries that was saved during detach. Note: this does not
// affect paint invalidation; we will fully invalidate the new layout object.
auto iter = map.find(&node);
if (iter == map.end())
return;
To<LayoutBox>(layout_object)
->GetMutableForPainting()
.SetPreviousGeometryForLayoutShiftTracking(
iter->value.paint_offset, iter->value.size,
iter->value.visual_overflow_rect);
layout_object->SetShouldSkipNextLayoutShiftTracking(false);
layout_object->SetShouldAssumePaintOffsetTranslationForLayoutShiftTracking(
iter->value.has_paint_offset_translation);
}
} // namespace blink
| 32,329 | 10,073 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include <cstdio>
#include <cstdlib>
#include "net/instaweb/rewriter/public/css_minify.h"
#include "pagespeed/kernel/base/file_message_handler.h"
#include "pagespeed/kernel/base/file_system.h"
#include "pagespeed/kernel/base/file_writer.h"
#include "pagespeed/kernel/base/stdio_file_system.h"
#include "pagespeed/kernel/base/string.h"
#include "pagespeed/kernel/base/string_util.h"
#include "pagespeed/kernel/util/gflags.h"
namespace net_instaweb {
bool MinifyCss_main(int argc, char** argv) {
StdioFileSystem file_system;
FileMessageHandler handler(stderr);
FileSystem::OutputFile* error_file = file_system.Stderr();
// Load command line args.
static const char kUsage[] = "Usage: css_minify infilename\n";
if (argc != 2) {
error_file->Write(kUsage, &handler);
return false;
}
const char* infilename = argv[1];
// Read text from file.
GoogleString in_text;
if (!file_system.ReadFile(infilename, &in_text, &handler)) {
error_file->Write(StringPrintf(
"Failed to read input file %s\n", infilename), &handler);
return false;
}
FileWriter writer(file_system.Stdout());
FileWriter error_writer(error_file);
CssMinify minify(&writer, &handler);
minify.set_error_writer(&error_writer);
return minify.ParseStylesheet(in_text);
}
} // namespace net_instaweb
int main(int argc, char** argv) {
net_instaweb::ParseGflags(argv[0], &argc, &argv);
return net_instaweb::MinifyCss_main(argc, argv) ? EXIT_SUCCESS : EXIT_FAILURE;
}
| 2,299 | 771 |
/*
The MIT License (MIT)
Copyright (c) 2013-2015 SRS(ossrs)
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 SRS_APP_DVR_HPP
#define SRS_APP_DVR_HPP
/*
#include <srs_app_dvr.hpp>
*/
#include <srs_core.hpp>
#include <string>
#include <sstream>
#ifdef SRS_AUTO_DVR
class SrsSource;
class SrsRequest;
class SrsStream;
class SrsRtmpJitter;
class SrsOnMetaDataPacket;
class SrsSharedPtrMessage;
class SrsFileWriter;
class SrsFlvEncoder;
class SrsDvrPlan;
class SrsJsonAny;
class SrsJsonObject;
class SrsThread;
#include <srs_app_source.hpp>
#include <srs_app_reload.hpp>
#include <srs_app_async_call.hpp>
/**
* a piece of flv segment.
* when open segment, support start at 0 or not.
*/
/*
一个视频片段
*/
class SrsFlvSegment : public ISrsReloadHandler
{
private:
SrsRequest* req;
SrsDvrPlan* plan;
private:
/**
* the underlayer dvr stream.
* if close, the flv is reap and closed.
* if open, new flv file is crote.
*/
SrsFlvEncoder* enc;
SrsRtmpJitter* jitter;
SrsRtmpJitterAlgorithm jitter_algorithm;
SrsFileWriter* fs;
private:
/**
* the offset of file for duration value.
* the next 8 bytes is the double value.
*/
int64_t duration_offset;
/**
* the offset of file for filesize value.
* the next 8 bytes is the double value.
*/
int64_t filesize_offset;
private:
std::string tmp_flv_file;
private:
/**
* current segment flv file path.
*/
std::string path;
/**
* whether current segment has keyframe.
*/
bool has_keyframe;
/**
* current segment starttime, RTMP pkt time.
*/
int64_t starttime;
/**
* current segment duration
*/
int64_t duration;
/**
* stream start time, to generate atc pts. abs time.
*/
int64_t stream_starttime;
/**
* stream duration, to generate atc segment.
*/
int64_t stream_duration;
/**
* previous stream RTMP pkt time, used to calc the duration.
* for the RTMP timestamp will overflow.
*/
int64_t stream_previous_pkt_time;
public:
SrsFlvSegment(SrsDvrPlan* p);
virtual ~SrsFlvSegment();
public:
/**
* initialize the segment.
*/
virtual int initialize(SrsRequest* r);
/**
* whether segment is overflow.
*/
virtual bool is_overflow(int64_t max_duration);
/**
* open new segment file, timestamp start at 0 for fresh flv file.
* @remark ignore when already open.
* @param use_tmp_file whether use tmp file if possible.
*/
virtual int open(bool use_tmp_file = true);
/**
* close current segment.
* @remark ignore when already closed.
*/
virtual int close();
/**
* write the metadata to segment.
*/
virtual int write_metadata(SrsSharedPtrMessage* metadata);
/**
* @param shared_audio, directly ptr, copy it if need to save it.
*/
virtual int write_audio(SrsSharedPtrMessage* shared_audio);
/**
* @param shared_video, directly ptr, copy it if need to save it.
*/
virtual int write_video(SrsSharedPtrMessage* shared_video);
/**
* update the flv metadata.
*/
virtual int update_flv_metadata();
/**
* get the current dvr path.
*/
virtual std::string get_path();
private:
/**
* generate the flv segment path.
*/
virtual std::string generate_path();
/**
* create flv jitter. load jitter when flv exists.
* @param loads_from_flv whether loads the jitter from exists flv file.
*/
virtual int create_jitter(bool loads_from_flv);
/**
* when update the duration of segment by rtmp msg.
*/
virtual int on_update_duration(SrsSharedPtrMessage* msg);
// interface ISrsReloadHandler
public:
virtual int on_reload_vhost_dvr(std::string vhost);
};
/**
* the dvr async call.
*/
class SrsDvrAsyncCallOnDvr : public ISrsAsyncCallTask
{
private:
int cid;
std::string path;
SrsRequest* req;
public:
SrsDvrAsyncCallOnDvr(int c, SrsRequest* r, std::string p);
virtual ~SrsDvrAsyncCallOnDvr();
public:
virtual int call();
virtual std::string to_string();
};
/**
* the plan for dvr.
* use to control the following dvr params:
* 1. filename: the filename for record file.
* 2. reap flv: when to reap the flv and start new piece.
*/
// TODO: FIXME: the plan is too fat, refine me.
class SrsDvrPlan
{
public:
friend class SrsFlvSegment;
public:
SrsRequest* req;
protected:
SrsFlvSegment* segment;
SrsAsyncCallWorker* async;
bool dvr_enabled;
public:
SrsDvrPlan();
virtual ~SrsDvrPlan();
public:
virtual int initialize(SrsRequest* r);
virtual int on_publish() = 0;
virtual void on_unpublish() = 0;
/**
* when got metadata.
*/
virtual int on_meta_data(SrsSharedPtrMessage* shared_metadata);
/**
* @param shared_audio, directly ptr, copy it if need to save it.
*/
virtual int on_audio(SrsSharedPtrMessage* shared_audio);
/**
* @param shared_video, directly ptr, copy it if need to save it.
*/
virtual int on_video(SrsSharedPtrMessage* shared_video);
protected:
virtual int on_reap_segment();
virtual int on_video_keyframe();
virtual int64_t filter_timestamp(int64_t timestamp);
public:
static SrsDvrPlan* create_plan(std::string vhost);
};
/**
* session plan: reap flv when session complete(unpublish)
*/
class SrsDvrSessionPlan : public SrsDvrPlan
{
public:
SrsDvrSessionPlan();
virtual ~SrsDvrSessionPlan();
public:
virtual int on_publish();
virtual void on_unpublish();
};
/**
* always append to flv file, never reap it.
*/
class SrsDvrAppendPlan : public SrsDvrPlan
{
private:
int64_t last_update_time;
public:
SrsDvrAppendPlan();
virtual ~SrsDvrAppendPlan();
public:
virtual int on_publish();
virtual void on_unpublish();
virtual int on_audio(SrsSharedPtrMessage* shared_audio);
virtual int on_video(SrsSharedPtrMessage* shared_video);
private:
virtual int update_duration(SrsSharedPtrMessage* msg);
};
/**
* segment plan: reap flv when duration exceed.
*/
class SrsDvrSegmentPlan : public SrsDvrPlan
{
private:
// in config, in ms
int segment_duration;
SrsSharedPtrMessage* sh_audio;
SrsSharedPtrMessage* sh_video;
SrsSharedPtrMessage* metadata;
public:
SrsDvrSegmentPlan();
virtual ~SrsDvrSegmentPlan();
public:
virtual int initialize(SrsRequest* req);
virtual int on_publish();
virtual void on_unpublish();
virtual int on_meta_data(SrsSharedPtrMessage* shared_metadata);
virtual int on_audio(SrsSharedPtrMessage* shared_audio);
virtual int on_video(SrsSharedPtrMessage* shared_video);
private:
virtual int update_duration(SrsSharedPtrMessage* msg);
};
/**
* dvr(digital video recorder) to record RTMP stream to flv file.
* TODO: FIXME: add utest for it.
*/
/*
数字录像机模块
将rtmp 流写入flv视频文件
*/
class SrsDvr
{
private:
SrsSource* source;
private:
SrsDvrPlan* plan;
public:
SrsDvr();
virtual ~SrsDvr();
public:
/**
* initialize dvr, create dvr plan.
* when system initialize(encoder publish at first time, or reload),
* initialize the dvr will reinitialize the plan, the whole dvr framework.
*/
virtual int initialize(SrsSource* s, SrsRequest* r);
/**
* publish stream event,
* when encoder start to publish RTMP stream.
*/
virtual int on_publish(SrsRequest* r);
/**
* the unpublish event.,
* when encoder stop(unpublish) to publish RTMP stream.
*/
virtual void on_unpublish();
/**
* get some information from metadata, it's optinal.
*/
virtual int on_meta_data(SrsOnMetaDataPacket* m);
/**
* mux the audio packets to dvr.
* @param shared_audio, directly ptr, copy it if need to save it.
*/
virtual int on_audio(SrsSharedPtrMessage* shared_audio);
/**
* mux the video packets to dvr.
* @param shared_video, directly ptr, copy it if need to save it.
*/
virtual int on_video(SrsSharedPtrMessage* shared_video);
};
#endif
#endif
| 9,003 | 3,010 |
class Solution {
public:
bool XXX(vector<int>& nums) {
int len = nums.size()-1;
int max = 0;
for(int i = 0;i<len;i++)
{
for(int j = i;j<=(i+nums[i]);j++)
{
max = (j+nums[j])>=(max+nums[max]) ? j : max ;
if(max!= len && nums[max]==0) return false;
if(max+nums[max]>=len) return true;
}
i = max-1;
}
return max>=len;
}
};
| 476 | 177 |
#include <iostream>
#include "Chapter1Helper.h"
#include "Chapter2Helper.h"
#include "Chapter3Helper.h"
#include "Chapter4Helper.h"
#include "Chapter5Helper.h"
#include "Chapter6Helper.h"
#include "Chapter7Helper.h"
#include "Chapter8Helper.h"
#include "Chapter9Helper.h"
#include "Chapter10Helper.h"
#include "Chapter11Helper.h"
#include "Chapter12Helper.h"
#include "Chapter13Helper.h"
#include "Chapter14Helper.h"
#include "Chapter15Helper.h"
#include "Chapter16Helper.h"
#include "Chapter17Helper.h"
#include "Chapter18Helper.h"
#include "Chapter19Helper.h"
#include "Chapter19Helper.h"
#include "Chapter20Helper.h"
using namespace std;
// Programming Exercises
int main()
{
Chapter1Helper chapter1;
Chapter2Helper chapter2;
Chapter3Helper chapter3;
Chapter4Helper chapter4;
Chapter5Helper chapter5;
Chapter6Helper chapter6;
Chapter7Helper chapter7;
Chapter8Helper chapter8;
Chapter9Helper chapter9;
Chapter10Helper chapter10;
Chapter11Helper chapter11;
Chapter12Helper chapter12;
Chapter13Helper chapter13;
Chapter14Helper chapter14;
Chapter15Helper chapter15;
Chapter16Helper chapter16;
Chapter17Helper chapter17;
Chapter18Helper chapter18;
Chapter19Helper chapter19;
Chapter20Helper chapter20;
chapter20.RunExercise8();
}
| 1,318 | 470 |
#include "CollisionManager.h"
#include <iostream>
CollisionManager::CollisionManager()
{
}
CollisionManager::~CollisionManager()
{
}
void CollisionManager::Update(float deltaTime)
{
for (int i = 0; i < _ObjectList.size(); i++)
{
GameObject* _Object = _ObjectList[i];
Collider* _FirstCollider = _Object->GetCollider();
for (int j = 0; j < _ObjectList.size(); j++)
{
GameObject* _OtherObject = _ObjectList[j];
Collider* _OtherCollider = _OtherObject->GetCollider();
if (!_OtherCollider)
continue;
if (i == j)
continue;
Vector2 _Min = _FirstCollider->GetMin();
Vector2 _Max = _FirstCollider->GetMax();
Vector2 _OtherMin = _OtherCollider->GetMin();
Vector2 _OtherMax = _OtherCollider->GetMax();
if (_Max.x > _OtherMin.x &&_Max.y > _OtherMin.y &&
_Min.x < _OtherMax.x &&_Min.y < _OtherMax.y)
{
if (_Object->GetName() == "Space_Ship" && _OtherObject->GetName() != "Bullet" )
_Object->OnCollision(_OtherObject);
if (_Object->GetName() == "Bullet" && _OtherObject->GetName() != "Space_Ship" && _OtherObject->GetName() != "Bullet")
_Object->OnCollision(_OtherObject);
}
}
}
}
void CollisionManager::Draw(aie::Renderer2D* renderer)
{
for (int i = 0; i < _ObjectList.size(); i++)
{
Collider* _collider = _ObjectList[i]->GetCollider();
Vector2 v2Min = _collider->GetMin();
Vector2 v2Max = _collider->GetMax();
renderer->drawLine(v2Min.x, v2Min.y, v2Min.x, v2Max.y);
renderer->drawLine(v2Min.x, v2Max.y, v2Max.x, v2Max.y);
renderer->drawLine(v2Max.x, v2Max.y, v2Max.x, v2Min.y);
renderer->drawLine(v2Max.x, v2Min.y, v2Min.x, v2Min.y);
if (_ObjectList[i]->HasCollider2())
{
Collider* _collider2 = _ObjectList[i]->GetCollider2();
Vector2 v2Min2 = _collider2->GetMin();
Vector2 v2Max2 = _collider2->GetMax();
renderer->drawLine(v2Min2.x, v2Min2.y, v2Min2.x, v2Max2.y);
renderer->drawLine(v2Min2.x, v2Max2.y, v2Max2.x, v2Max2.y);
renderer->drawLine(v2Max2.x, v2Max2.y, v2Max2.x, v2Min2.y);
renderer->drawLine(v2Max2.x, v2Min2.y, v2Min2.x, v2Min2.y);
}
}
}
void CollisionManager::AddObject(GameObject* object)
{
_ObjectList.push_back(object);
}
void CollisionManager::RemoveObject()
{
_ObjectList.pop_back();
}
GameObject* CollisionManager::GetObject()
{
return _ObjectList.back();
} | 2,402 | 1,063 |
// print-frac.cpp
// as of 2021-09-04 bw [bw.org]
#include <bwprint.h>
#include <string_view>
#include <string>
// support for std:: or fmt:: (reference implementation)
// see j.bw.org/fmt
#ifdef __cpp_lib_format
#define formatter std::formatter
#else
#define formatter fmt::formatter
#endif // __cpp_lib_format
using std::string_view;
using std::string;
using std::print;
struct Frac {
long n;
long d;
};
template<>
struct formatter<Frac> {
template<typename ParseContext>
constexpr auto parse(ParseContext& ctx) {
return ctx.begin();
}
template<typename FormatContext>
auto format(const Frac& f, FormatContext& ctx) {
return format_to(ctx.out(), "{0:d}/{1:d}", f.n, f.d);
}
};
int main() {
Frac f{ 5, 3 };
print("Frac: {}\n", f);
}
| 799 | 300 |
#include "math.h"
i64 pydiv(i64 a, i64 b) {
i64 result = a / b;
if ((a < 0) ^ (b < 0)) {
if (pymod(a, b) != 0) {
result -= 1;
}
}
return result;
}
i64 pymod(i64 a, i64 b) {
i64 result = a % b;
if (result < 0) {
result = b + result;
}
return result;
}
| 269 | 157 |
#pragma once
#include "ir/ir.hpp"
#include "ir/symbol_table.hpp"
enum class X86_Registers
{
EAX = 0,
EBX = 1,
ECX = 2,
EDX = 3,
ESI = 4,
EDI = 5,
EBP = 6,
ESP = 7
};
struct X86_IrRegisters
{
static constexpr Ir::Argument EAX = Ir::Argument::PinnedHardRegister(int(X86_Registers::EAX));
static constexpr Ir::Argument EBX = Ir::Argument::PinnedHardRegister(int(X86_Registers::EBX));
static constexpr Ir::Argument ECX = Ir::Argument::PinnedHardRegister(int(X86_Registers::ECX));
static constexpr Ir::Argument EDX = Ir::Argument::PinnedHardRegister(int(X86_Registers::EDX));
static constexpr Ir::Argument ESI = Ir::Argument::PinnedHardRegister(int(X86_Registers::ESI));
static constexpr Ir::Argument EDI = Ir::Argument::PinnedHardRegister(int(X86_Registers::EDI));
static constexpr Ir::Argument EBP = Ir::Argument::PinnedSpecialHardRegister(int(X86_Registers::EBP));
static constexpr Ir::Argument ESP = Ir::Argument::PinnedSpecialHardRegister(int(X86_Registers::ESP));
};
class Assembler
{
public:
std::string compile(const SymbolTable &symbolTable);
};
| 1,123 | 416 |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
#include "pch.h"
#include "BackEndAudioHelpers.h"
// release and zero out a possible NULL pointer. note this will
// do the release on a temp copy to avoid reentrancy issues that can result from
// callbacks durring the release
template <class T> void SafeRelease(__deref_inout_opt T **ppT)
{
T *pTTemp = *ppT; // temp copy
*ppT = nullptr; // zero the input
if (pTTemp)
{
pTTemp->Release();
}
}
// Begin of audio helpers
size_t inline GetWaveFormatSize(const WAVEFORMATEX& format)
{
return (sizeof WAVEFORMATEX) + (format.wFormatTag == WAVE_FORMAT_PCM ? 0 : format.cbSize);
}
void FillPcmFormat(WAVEFORMATEX& format, WORD wChannels, int nSampleRate, WORD wBits)
{
format.wFormatTag = WAVE_FORMAT_PCM;
format.nChannels = wChannels;
format.nSamplesPerSec = nSampleRate;
format.wBitsPerSample = wBits;
format.nBlockAlign = format.nChannels * (format.wBitsPerSample / 8);
format.nAvgBytesPerSec = format.nSamplesPerSec * format.nBlockAlign;
format.cbSize = 0;
}
size_t BytesFromDuration(int nDurationInMs, const WAVEFORMATEX& format)
{
return size_t(nDurationInMs * FLOAT(format.nAvgBytesPerSec) / 1000);
}
size_t SamplesFromDuration(int nDurationInMs, const WAVEFORMATEX& format)
{
return size_t(nDurationInMs * FLOAT(format.nSamplesPerSec) / 1000);
}
BOOL WaveFormatCompare(const WAVEFORMATEX& format1, const WAVEFORMATEX& format2)
{
size_t cbSizeFormat1 = GetWaveFormatSize(format1);
size_t cbSizeFormat2 = GetWaveFormatSize(format2);
return (cbSizeFormat1 == cbSizeFormat2) && (memcmp(&format1, &format2, cbSizeFormat1) == 0);
}
// End of audio helpers
| 2,187 | 794 |
#include "AncestralSeqNet.h"
#include "NetworkError.h"
#include <iostream>
#include <map>
#include <set>
using namespace std;
AncestralSeqNet::AncestralSeqNet(const vector <Sequence*> & seqvect, const vector<bool> & mask, unsigned epsilon, double alpha)
: /*AbstractMSN(seqvect, mask, epsilon), */HapNet(seqvect, mask), _seqsComputed(false), _alpha(alpha)
{
}
void AncestralSeqNet::computeGraph()
{
updateProgress(0);
map<const string, Vertex*> seq2Vert;
vector<unsigned> seqCount;
vector<unsigned> edgeCount;
for (unsigned i = 0; i < nseqs(); i++)
{
seq2Vert[seqSeq(i)] = newVertex(seqName(i), &seqSeq(i));
seqCount.push_back(0);
}
double progPerIter = 100./niter();
double prog;
for (unsigned i = 0; i < niter(); i++)
{
const list<pair<const string, const string> > edgelist = sampleEdge();
// for each edge, check to see if sequences are new. If neither new, check to see if already adjacent
list<pair<const string, const string> >::const_iterator edgeIt = edgelist.begin();
set<unsigned> verticesSeen;
set<unsigned> edgesSeen;
while (edgeIt != edgelist.end())
{
string seqFrom(edgeIt->first);
string seqTo(edgeIt->second);
bool seqFromNew = false;
bool seqToNew = false;
Vertex *u, *v;
map<const string, Vertex *>::iterator seqIt = seq2Vert.find(seqFrom);
if (seqIt != seq2Vert.end())
{
u = seqIt->second;
verticesSeen.insert(u->index());
}
else
{
u = newVertex("");
seq2Vert[seqFrom] = u;
verticesSeen.insert(u->index());
seqFromNew = true;
}
seqIt = seq2Vert.find(seqTo);
if (seqIt != seq2Vert.end())
{
v = seqIt->second;
verticesSeen.insert(v->index());
}
else
{
v = newVertex("");
seq2Vert[seqTo] = v;
verticesSeen.insert(v->index());
seqToNew = true;
}
if (seqToNew || seqFromNew)
{
double weight = pairwiseDistance(seqFrom, seqTo);
Edge *e = newEdge(u, v, weight);
edgesSeen.insert(e->index());
}
else if (u != v && ! v->isAdjacent(u))
{
double weight = pairwiseDistance(seqFrom, seqTo);
Edge *e = newEdge(u, v, weight);
edgesSeen.insert(e->index());
}
else if (u != v)
{
const Edge *e = v->sharedEdge(u);
edgesSeen.insert(e->index());
}
++edgeIt;
}
set<unsigned>::const_iterator idxIt = verticesSeen.begin();
while (idxIt != verticesSeen.end())
{
if (*idxIt >= seqCount.size())
seqCount.resize(*idxIt + 1, 0);
seqCount.at(*idxIt) += 1;
++idxIt;
}
idxIt = edgesSeen.begin();
while (idxIt != edgesSeen.end())
{
if (*idxIt >= edgeCount.size())
edgeCount.resize(*idxIt + 1, 0);
edgeCount.at(*idxIt) += 1;
++idxIt;
}
prog = (i + 1) * progPerIter;
updateProgress(prog);
}
//cout << *(dynamic_cast<Graph*>(this)) << endl;
priority_queue<pair<double, Edge*>, vector<pair<double, Edge*> >, greater<pair<double, Edge*> > > edgeQ;
for (unsigned i = 0; i < edgeCount.size(); i++)
{
double edgeFreq = (double)edgeCount.at(i)/niter();
if (edgeFreq < _alpha)
edgeQ.push(pair<double, Edge*>(edgeFreq, edge(i)));
}
while (! edgeQ.empty())
{
Edge *e = edgeQ.top().second;
double weight = e->weight();
Vertex *u = vertex(e->from()->index());
Vertex *v = vertex(e->to()->index());
//unsigned idx = e->index();
removeEdge(e->index());
if (! areConnected(u, v))
newEdge(u, v, weight);
edgeQ.pop();
}
for (unsigned i = seqCount.size(); i > nseqs(); i--)
{
if (vertex(i-1)->degree() <= 1)
{
removeVertex(i - 1);
}
}
updateProgress(100);
}
void AncestralSeqNet::setDistance(unsigned dist, unsigned i, unsigned j)
{
unsigned totalCount = nseqs() + ancestorCount();
if (i >= totalCount || j >= totalCount)
throw NetworkError("Invalid index.");
_distances.at(i).at(j) = dist;
}
unsigned AncestralSeqNet::distance(unsigned i, unsigned j) const
{
unsigned totalCount = nseqs() + ancestorCount();
if (i >= totalCount || j >= totalCount)
throw NetworkError("Invalid index.");
return _distances.at(i).at(j);
}
| 4,402 | 1,568 |
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef IROHA_SHARED_MODEL_PROTO_COMMAND_HPP
#define IROHA_SHARED_MODEL_PROTO_COMMAND_HPP
#include "interfaces/commands/command.hpp"
#include "commands.pb.h"
namespace shared_model {
namespace proto {
class Command final : public interface::Command {
public:
using TransportType = iroha::protocol::Command;
Command(const Command &o);
Command(Command &&o) noexcept;
explicit Command(const TransportType &ref);
explicit Command(TransportType &&ref);
~Command() override;
const CommandVariantType &get() const override;
protected:
Command *clone() const override;
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace proto
} // namespace shared_model
#endif // IROHA_SHARED_MODEL_PROTO_COMMAND_HPP
| 914 | 298 |
#include "prx/utilities/data_structures/tree.hpp"
PRX_SETTER(tree_t, vertex_id_counter)
PRX_GETTER(tree_t, vertex_id_counter)
void pyprx_utilities_data_structures_tree_py()
{
class_<prx::tree_node_t, std::shared_ptr<prx::tree_node_t>, bases<prx::abstract_node_t>>("tree_node", init<>())
.def("get_parent", &prx::tree_node_t::get_parent)
.def("get_index", &prx::tree_node_t::get_index)
.def("get_parent_edge", &prx::tree_node_t::get_parent_edge)
.def("get_children", &prx::tree_node_t::get_children, return_internal_reference<>())
;
class_<prx::tree_edge_t, std::shared_ptr<prx::tree_edge_t>, bases<prx::abstract_edge_t>, boost::noncopyable>("tree_edge", no_init)
.def("__init__", make_constructor(&init_as_ptr<prx::tree_edge_t>, default_call_policies()))
.def("get_index", &prx::tree_edge_t::get_index)
.def("get_source", &prx::tree_edge_t::get_source)
.def("get_target", &prx::tree_edge_t::get_target)
;
class_<prx::tree_t, std::shared_ptr<prx::tree_t>>("tree", init<>())
.def("allocate_memory", &prx::tree_t::allocate_memory<prx::tree_node_t, prx::tree_edge_t>)
.def("add_vertex", &prx::tree_t::add_vertex<prx::tree_node_t, prx::tree_edge_t>)
.def("get_vertex_as", &prx::tree_t::get_vertex_as<prx::tree_node_t>)
.def("get_edge_as", &prx::tree_t::get_edge_as<prx::tree_edge_t>)
.def("num_vertices", &prx::tree_t::num_vertices)
.def("num_edges", &prx::tree_t::num_edges)
.def("is_leaf", &prx::tree_t::is_leaf)
.def("edge", &prx::tree_t::edge)
.def("add_edge", &prx::tree_t::add_edge)
.def("add_safety_edge", &prx::tree_t::add_safety_edge)
.def("get_depth", &prx::tree_t::get_depth)
.def("remove_vertex", &prx::tree_t::remove_vertex)
.def("purge", &prx::tree_t::purge)
.def("clear", &prx::tree_t::clear)
.def("transplant", &prx::tree_t::transplant)
.add_property("vertex_id_counter", &get_tree_t_vertex_id_counter<unsigned>, &set_tree_t_vertex_id_counter<unsigned>)
// .def("", &prx::tree_t::)
;
} | 1,959 | 905 |
/**********************************************************************
AudMonkey: A Digital Audio Editor
@file ConfigInterface.cpp
**********************************************************************/
#include "ConfigInterface.h"
ConfigClientInterface::~ConfigClientInterface() = default;
| 300 | 61 |