hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
082bf53f1d88f591ebf74b485c0f627e0453b678
| 527
|
cpp
|
C++
|
Source/restrict.cpp
|
mikeeq/devilution-nx
|
d59170c5f1ab884b0539ec38bbfc8655ea9866b8
|
[
"Unlicense"
] | 878
|
2019-07-01T11:52:52.000Z
|
2022-02-20T21:31:45.000Z
|
Source/restrict.cpp
|
mikeeq/devilution-nx
|
d59170c5f1ab884b0539ec38bbfc8655ea9866b8
|
[
"Unlicense"
] | 29
|
2019-07-01T22:43:59.000Z
|
2021-12-06T09:32:17.000Z
|
Source/restrict.cpp
|
mikeeq/devilution-nx
|
d59170c5f1ab884b0539ec38bbfc8655ea9866b8
|
[
"Unlicense"
] | 79
|
2019-07-01T13:01:43.000Z
|
2021-12-06T08:52:52.000Z
|
#include "diablo.h"
DEVILUTION_BEGIN_NAMESPACE
BOOL SystemSupported()
{
return TRUE;
}
BOOL RestrictedTest()
{
#ifndef SWITCH
FILE *f;
char Buffer[MAX_PATH];
BOOL ret = FALSE;
if (SystemSupported() && GetWindowsDirectory(Buffer, sizeof(Buffer))) {
strcat(Buffer, "\\Diablo1RestrictedTest.foo");
f = fopen(Buffer, "wt");
if (f) {
fclose(f);
remove(Buffer);
} else {
ret = TRUE;
}
}
return ret;
#else
return TRUE;
#endif
}
BOOL ReadOnlyTest()
{
return false;
}
DEVILUTION_END_NAMESPACE
| 12.853659
| 72
| 0.664137
|
mikeeq
|
082ccc3a9c7bcc14fa687824a82bb5879e39d530
| 1,099
|
cpp
|
C++
|
pwiz/utility/bindings/SWIG/python_pwiz_RAMPAdapter.cpp
|
edyp-lab/pwiz-mzdb
|
d13ce17f4061596c7e3daf9cf5671167b5996831
|
[
"Apache-2.0"
] | 11
|
2015-01-08T08:33:44.000Z
|
2019-07-12T06:14:54.000Z
|
pwiz/utility/bindings/SWIG/python_pwiz_RAMPAdapter.cpp
|
edyp-lab/pwiz-mzdb
|
d13ce17f4061596c7e3daf9cf5671167b5996831
|
[
"Apache-2.0"
] | 61
|
2015-05-27T11:20:11.000Z
|
2019-12-20T15:06:21.000Z
|
pwiz/utility/bindings/SWIG/python_pwiz_RAMPAdapter.cpp
|
edyp-lab/pwiz-mzdb
|
d13ce17f4061596c7e3daf9cf5671167b5996831
|
[
"Apache-2.0"
] | 4
|
2016-02-03T09:41:16.000Z
|
2021-08-01T18:42:36.000Z
|
//
// python_pwiz_RAMPAdapter.cpp
//
// $Id: python_pwiz_RAMPAdapter.cpp 3300 2012-02-15 22:38:20Z chambm $
//
// a lightweight wrapper allowing SWIG to wrap some useful pwiz code
// Q: why a wrapper wrapper? A: SWIG can't handle namespaces
//
//
// Original author: Brian Pratt <Brian.Pratt@insilicos.com>
//
// Copyright 2011 Insilicos LLC All Rights Reserved
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// actually this is just here to make it easier to create an object file
// with different compile switches
#include "pwiz_RAMPAdapter.cpp"
| 35.451613
| 77
| 0.720655
|
edyp-lab
|
082e073c4a0e6203ee39e170ddc5f4e8270d6d2c
| 926
|
cpp
|
C++
|
Tareas/Tarea #2/Factura.cpp
|
JDaniel1010/cpp
|
ef067f3f0109812d7104cd8a21439d1ea5702afa
|
[
"MIT"
] | null | null | null |
Tareas/Tarea #2/Factura.cpp
|
JDaniel1010/cpp
|
ef067f3f0109812d7104cd8a21439d1ea5702afa
|
[
"MIT"
] | null | null | null |
Tareas/Tarea #2/Factura.cpp
|
JDaniel1010/cpp
|
ef067f3f0109812d7104cd8a21439d1ea5702afa
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
double subtotal = 0;
double total = 0;
double impuesto = 0.15;
int descuento = 0;
char facturaExenta;
double calculoDescuento = 0;
double calculoImpuesto = 0;
cout << " Ingrese el subtotal de la factura: ";
cin >> subtotal;
cout << " Ingrese el descuento (0, 10, 15, 20): ";
cin >> descuento;
cout << " La factura esta exenta? s/n ";
cin >> facturaExenta;
if ( facturaExenta == 's' || facturaExenta == 'S' )
{
calculoDescuento = (subtotal * descuento) / 100;
calculoImpuesto = 0;
}
else
{
calculoDescuento = (subtotal * descuento) / 100;
calculoImpuesto = (subtotal - calculoDescuento) * 0.15;
}
total = subtotal - calculoDescuento + calculoImpuesto;
cout << endl;
cout << " El total a pagar es: " << total;
return 0;
}
| 23.15
| 63
| 0.588553
|
JDaniel1010
|
0832797a2656e085e8c60dd8f647e1b5ca1e84c9
| 6,486
|
hxx
|
C++
|
include/itkRSHReconImageFilter.hxx
|
bloyl/DiffusionImagingTK
|
0516d32b7b0d41ed161134812746ef02aab000de
|
[
"Apache-2.0"
] | 4
|
2016-01-09T19:02:28.000Z
|
2017-07-31T19:41:32.000Z
|
include/itkRSHReconImageFilter.hxx
|
bloyl/DiffusionImagingTK
|
0516d32b7b0d41ed161134812746ef02aab000de
|
[
"Apache-2.0"
] | null | null | null |
include/itkRSHReconImageFilter.hxx
|
bloyl/DiffusionImagingTK
|
0516d32b7b0d41ed161134812746ef02aab000de
|
[
"Apache-2.0"
] | 2
|
2016-08-06T00:58:26.000Z
|
2019-02-18T01:03:13.000Z
|
/*=========================================================================
*
* Copyright Section of Biomedical Image Analysis
* University of Pennsylvania
*
* 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.txt
*
* 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 __itkRSHReconImageFilter_hxx_
#define __itkRSHReconImageFilter_hxx_
#include <cmath>
#include <itkImageRegionConstIterator.h>
#include <itkImageRegionConstIteratorWithIndex.h>
#include <itkImageRegionIterator.h>
#include <itkArray.h>
#include <vnl/vnl_vector.h>
#include <itkProgressReporter.h>
#include <itkRSHReconImageFilter.h>
namespace itk
{
template< class TDiffusionModelCalculator, unsigned int TImageDimension >
RSHReconImageFilter< TDiffusionModelCalculator, TImageDimension >
::RSHReconImageFilter()
{
// At least 1 inputs is necessary for a vector image.
// For images added one at a time we need at least six
this->SetNumberOfRequiredInputs( 1 );
m_ImageMask = NULL; //Must be suplied by the user
m_DiffusionModelCalculator = NULL; //Must be suplied by the user
m_ResidualImage = NULL;
m_CalculateResidualImage = false;
}
template< class TDiffusionModelCalculator, unsigned int TImageDimension >
void
RSHReconImageFilter< TDiffusionModelCalculator, TImageDimension >
::BeforeThreadedGenerateData()
{
itkDebugMacro( "RSHReconImageFilter::BeforeThreadedGenerateData ")
if ( m_DiffusionModelCalculator.IsNull() )
{
itkExceptionMacro( << "Diffusion Calculator Not Set" );
}
//Initialize the m_DiffusionModelCalculator
// m_DiffusionModelCalculator->InitializeTensorFitting();
m_DiffusionModelCalculator->InitializeRSHFitting();
/** Setup both fscores Image and residuals Image */
//Initialize the residualImage if we are going to calculate it.
if (m_CalculateResidualImage)
{
typename InputImageType::ConstPointer dwiImage =
static_cast< const InputImageType * >( this->ProcessObject::GetInput(0) );
m_ResidualImage = ResidualImageType::New();
m_ResidualImage->CopyInformation(this->ProcessObject::GetInput(0));
m_ResidualImage->SetRegions(m_ResidualImage->GetLargestPossibleRegion() );
m_ResidualImage->SetVectorLength( dwiImage->GetNumberOfComponentsPerPixel() );
m_ResidualImage->Allocate();
}
itkDebugMacro( "RSHReconImageFilter::BeforeThreadedGenerateData done")
}
template< class TDiffusionModelCalculator, unsigned int TImageDimension >
void
RSHReconImageFilter< TDiffusionModelCalculator, TImageDimension >
::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread,
ThreadIdType threadId)
{
itkDebugMacro( "RSHReconImageFilter::ThreadedGenerateData Begin")
//Get inputs and outputs
OutputImagePointer outputImage = static_cast< OutputImageType * >(this->ProcessObject::GetOutput(0));
InputImageConstPointer dwiImage = static_cast< const InputImageType * >( this->ProcessObject::GetInput(0) );
//Get the diffusion Calculator
DiffusionModelCalculatorConstPointer dtCalc = this->GetDiffusionModelCalculator();
ImageMaskConstPointer mask = this->GetImageMask();
//Generate iterators
ImageRegionConstIteratorWithIndex< InputImageType > git(dwiImage, outputRegionForThread );
ImageRegionIterator< OutputImageType > oit(outputImage, outputRegionForThread);
ImageRegionIterator< ResidualImageType > res_iter;
git.GoToBegin();
oit.GoToBegin();
const unsigned int numberOfGradientImages = dwiImage->GetNumberOfComponentsPerPixel();
//if we are calculateing the Residual set up an iterator...
if (m_CalculateResidualImage)
{
res_iter = ImageRegionIterator< ResidualImageType >( m_ResidualImage, outputRegionForThread);
res_iter.GoToBegin();
}
//Check is mask had been provided
bool hasMask = mask.IsNotNull();
// Support for progress methods/callbacks
ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels());
//Local variables to check supplied mask.
typename InputImageType::IndexType index;
typename InputImageType::PointType point;
OutputPixelType pixValue;
ResidualPixelType residualValue( numberOfGradientImages );
while( !git.IsAtEnd() )
{
//Check if the current location is outside of the mask
if (hasMask)
{
index = git.GetIndex();
dwiImage->TransformIndexToPhysicalPoint(index,point);
if ( not mask->IsInside(point) )
{
//don't compute anything for this pixel
oit.Set( NumericTraits<OutputPixelType>::Zero );
++oit;
if (m_CalculateResidualImage)
{
residualValue.Fill(NumericTraits<typename ResidualPixelType::ComponentType>::Zero);
res_iter.Set( residualValue );
++res_iter;
}
progress.CompletedPixel();
++git; // Gradient image iterator
}
}
//Grab the dwi
const InputPixelType dwi = static_cast<InputPixelType>(git.Get());
pixValue = dtCalc->ComputeRSH(dwi);
///TODO need to get this from dtCalc...
residualValue.Fill(NumericTraits<typename ResidualPixelType::ComponentType>::Zero);
oit.Set( pixValue );
++oit;
if (m_CalculateResidualImage)
{
res_iter.Set( residualValue );
++res_iter;
}
progress.CompletedPixel();
++git; // Gradient image iterator
}
itkDebugMacro( "RSHReconImageFilter::ThreadedGenerateData done")
}
template< class TDiffusionModelCalculator, unsigned int TImageDimension >
void
RSHReconImageFilter< TDiffusionModelCalculator, TImageDimension >
::PrintSelf(std::ostream& os, Indent indent) const
{
Superclass::PrintSelf(os,indent);
os << indent << "m_CalculateResidualImage: " << m_CalculateResidualImage << std::endl;
if (m_CalculateResidualImage)
{
os << indent << "m_ResidualImage: " << std::endl << indent << indent << m_ResidualImage << std::endl;
}
os << indent << "NEEDS MORE INFO" << std::endl;
}
} //end Itk namespace
#endif
| 34.136842
| 110
| 0.721708
|
bloyl
|
083b5eb371943035be1536423b5f9d70620737f3
| 2,133
|
cpp
|
C++
|
tools/export/export.cpp
|
paulhuggett/pstore2
|
a0c663d10a2e2713fdf39ecdae1f9c1e96041f5c
|
[
"Apache-2.0"
] | 11
|
2018-02-02T21:24:49.000Z
|
2020-12-11T04:06:03.000Z
|
tools/export/export.cpp
|
SNSystems/pstore
|
74e9dd960245d6bfc125af03ed964d8ad660a62d
|
[
"Apache-2.0"
] | 63
|
2018-02-05T17:24:59.000Z
|
2022-03-22T17:26:28.000Z
|
tools/export/export.cpp
|
paulhuggett/pstore
|
067be94d87c87fce524c8d76c6f47c347d8f1853
|
[
"Apache-2.0"
] | 5
|
2020-01-13T22:47:11.000Z
|
2021-05-14T09:31:15.000Z
|
//===- tools/export/export.cpp --------------------------------------------===//
//* _ *
//* _____ ___ __ ___ _ __| |_ *
//* / _ \ \/ / '_ \ / _ \| '__| __| *
//* | __/> <| |_) | (_) | | | |_ *
//* \___/_/\_\ .__/ \___/|_| \__| *
//* |_| *
//===----------------------------------------------------------------------===//
//
// Part of the pstore project, under the Apache License v2.0 with LLVM Exceptions.
// See https://github.com/SNSystems/pstore/blob/master/LICENSE.txt for license
// information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include <iostream>
#include "pstore/exchange/export.hpp"
#include "pstore/core/database.hpp"
#include "pstore/command_line/command_line.hpp"
using namespace pstore::command_line;
namespace {
opt<std::string> db_path{positional, usage{"repository"},
desc{"Path of the pstore repository to be exported."}, required};
opt<bool> no_comments{
"no-comments",
desc{"Disable embedded comments. (Required for output to be ECMA-404 compliant.)"},
init (false)};
} // end anonymous namespace.
#ifdef _WIN32
int _tmain (int argc, TCHAR const * argv[]) {
#else
int main (int argc, char * argv[]) {
#endif
int exit_code = EXIT_SUCCESS;
PSTORE_TRY {
parse_command_line_options (argc, argv, "pstore export utility\n");
pstore::exchange::export_ns::ostream os{stdout};
pstore::database db{db_path.get (), pstore::database::access_mode::read_only};
pstore::exchange::export_ns::emit_database (db, os, !no_comments);
os.flush ();
}
// clang-format off
PSTORE_CATCH (std::exception const & ex, { // clang-format on
std::cerr << "Error: " << ex.what () << '\n';
exit_code = EXIT_FAILURE;
})
// clang-format off
PSTORE_CATCH (..., { // clang-format on
std::cerr << "Error: an unknown error occurred\n";
exit_code = EXIT_FAILURE;
})
return exit_code;
}
| 33.857143
| 94
| 0.534459
|
paulhuggett
|
083c40e6225df441704e84f55c2af4808fcb9257
| 1,496
|
cpp
|
C++
|
legacy/tools/dtkDistributedServer/main.cpp
|
papadop/dtk
|
5d5bd7234987f01a23fbc6c7414a21c15e1455ab
|
[
"BSD-3-Clause"
] | null | null | null |
legacy/tools/dtkDistributedServer/main.cpp
|
papadop/dtk
|
5d5bd7234987f01a23fbc6c7414a21c15e1455ab
|
[
"BSD-3-Clause"
] | null | null | null |
legacy/tools/dtkDistributedServer/main.cpp
|
papadop/dtk
|
5d5bd7234987f01a23fbc6c7414a21c15e1455ab
|
[
"BSD-3-Clause"
] | 1
|
2020-04-21T14:41:52.000Z
|
2020-04-21T14:41:52.000Z
|
/* @(#)main.cpp ---
*
* Author: Nicolas Niclausse
* Copyright (C) 2012 - Nicolas Niclausse, Inria.
* Created: 2012/04/03 14:41:29
* Version: $Id$
* Last-Updated: mer. avril 25 13:08:30 2012 (+0200)
* By: Nicolas Niclausse
* Update #: 13
*/
/* Commentary:
*
*/
/* Change log:
*
*/
#include <dtkCore>
#include <dtkDistributed>
#include <dtkLog/dtkLog.h>
#include <QtCore>
int main(int argc, char **argv)
{
QCoreApplication application(argc, argv);
if(!dtkApplicationArgumentsContain(&application, "--torque")
&& !dtkApplicationArgumentsContain(&application, "--oar")
&& !dtkApplicationArgumentsContain(&application, "--ssh")) {
qDebug() << "Usage:" << argv[0] << " dtk://server:port [--oar || --torque || --ssh]";
return DTK_SUCCEED;
}
application.setApplicationName("dtkDistributedServer");
application.setApplicationVersion("0.0.1");
application.setOrganizationName("inria");
application.setOrganizationDomain("fr");
QSettings settings("inria", "dtk");
settings.beginGroup("server");
if (settings.contains("log_level"))
dtkLogger::instance().setLevel(settings.value("log_level").toString());
else
dtkLogger::instance().setLevel(dtkLog::Debug);
dtkLogger::instance().attachFile(dtkLogPath(&application));
dtkDistributedServer server(argc, argv);
qDebug() << "server started";
server.run();
int status = application.exec();
return status;
}
| 23.746032
| 93
| 0.644385
|
papadop
|
083eb282c9bfcfe896f58fd64a0b9a969b60addd
| 437
|
hpp
|
C++
|
AddinCfy/utils.hpp
|
eehlers/QuantLibAddin
|
bcbd9d1c0e7a4f4ce608470c6576d6e772305980
|
[
"BSD-3-Clause"
] | 5
|
2016-07-13T14:05:01.000Z
|
2022-01-24T15:15:17.000Z
|
AddinCfy/utils.hpp
|
eehlers/QuantLibAddin
|
bcbd9d1c0e7a4f4ce608470c6576d6e772305980
|
[
"BSD-3-Clause"
] | null | null | null |
AddinCfy/utils.hpp
|
eehlers/QuantLibAddin
|
bcbd9d1c0e7a4f4ce608470c6576d6e772305980
|
[
"BSD-3-Clause"
] | 12
|
2016-01-28T07:18:28.000Z
|
2021-11-15T03:48:52.000Z
|
#ifndef addincfy_utils_hpp
#define addincfy_utils_hpp
#include <vector>
#include "FlyLib/FlyLib_Types.h"
#include <rp/property.hpp>
namespace QuantLib {
class Date;
};
std::vector<bool> f6(FLYLIB_OPAQUE);
std::vector<long> f2(FLYLIB_OPAQUE);
std::vector<double> f1(FLYLIB_OPAQUE);
std::vector<std::string> f4(FLYLIB_OPAQUE);
std::vector<reposit::property_t> f3(FLYLIB_OPAQUE);
std::vector<QuantLib::Date> f5(FLYLIB_OPAQUE);
#endif
| 19.863636
| 51
| 0.764302
|
eehlers
|
083f7f46147b7fa40de49d41801d7fd0945af81a
| 1,481
|
hpp
|
C++
|
include/eschaton/eschaton.hpp
|
ortfero/eschaton
|
abc1ce77dd96105208a4563edba7550880ca8530
|
[
"MIT"
] | null | null | null |
include/eschaton/eschaton.hpp
|
ortfero/eschaton
|
abc1ce77dd96105208a4563edba7550880ca8530
|
[
"MIT"
] | null | null | null |
include/eschaton/eschaton.hpp
|
ortfero/eschaton
|
abc1ce77dd96105208a4563edba7550880ca8530
|
[
"MIT"
] | null | null | null |
#pragma once
#include <cstdint>
#include <chrono>
#include <tuple>
#ifndef HAS_UNCAUGHT_EXCEPTIONS
#define HAS_UNCAUGHT_EXCEPTIONS 1
#endif
#include <date/date.h>
namespace eschaton {
using system_time = std::chrono::system_clock::time_point;
using system_duration = std::chrono::system_clock::duration;
using time_of_day = date::hh_mm_ss<std::chrono::microseconds>;
template<typename D> std::int64_t to(system_time const& tp) noexcept {
return std::int64_t(std::chrono::floor<D>(tp.time_since_epoch()).count());
}
template<typename D> system_time from(std::int64_t units) noexcept {
return system_time{D{units}};
}
template<typename D> std::int64_t current() noexcept {
return to<D>(std::chrono::system_clock::now());
}
template<typename D> std::int64_t elapsed(std::int64_t from) noexcept {
return current<D>() - from;
}
template<class Rep, class Period> bool
is_occured(system_time const& tp, std::chrono::duration<Rep, Period> const& tod) noexcept {
namespace chr = std::chrono;
auto const daypoint = chr::floor<date::days>(tp);
return chr::floor<chr::duration<Rep, Period>>(tp - daypoint) == tod;
}
template<typename D> std::tuple<date::year_month_day, date::hh_mm_ss<D>>
to_ymd_hms(system_time const& tp) {
namespace chr = std::chrono;
namespace dt = date;
auto const dp = chr::floor<dt::days>(tp);
dt::year_month_day const ymd{dp};
dt::hh_mm_ss<D> const tod{chr::floor<D>(tp - dp)};
return {ymd, tod};
}
} // eschaton
| 25.534483
| 91
| 0.713032
|
ortfero
|
084279133dea1dbd01db23f8ca48ac8d9ac4b95a
| 3,075
|
cpp
|
C++
|
include/Lexer.cpp
|
Thomilist/math-converter
|
d0028f5096921fa34e9b4b1ddd086812ec5732f5
|
[
"MIT"
] | null | null | null |
include/Lexer.cpp
|
Thomilist/math-converter
|
d0028f5096921fa34e9b4b1ddd086812ec5732f5
|
[
"MIT"
] | null | null | null |
include/Lexer.cpp
|
Thomilist/math-converter
|
d0028f5096921fa34e9b4b1ddd086812ec5732f5
|
[
"MIT"
] | null | null | null |
#include "Lexer.hpp"
namespace mcon
{
Lexer::Lexer(
std::unique_ptr<CharacterStream> const &a_character_stream,
std::unique_ptr<CharacterSet> const &a_character_set
):
character_set(a_character_set),
character_stream(a_character_stream)
{
}
Lexer::~Lexer()
{ }
void Lexer::Scan()
{
// Create an initial token to mark the start of the token sequence
Token temp_token(TokenType::StartOfStream);
// Pair up the character sets and their corresponding token types for easy iteration
std::set<std::pair<TokenType, std::set<std::string>*>> character_sets = {
{TokenType::EndOfStream, &character_set->end_of_stream},
{TokenType::Whitespace, &character_set->whitespace},
{TokenType::Text, &character_set->letter},
{TokenType::Number, &character_set->number},
{TokenType::Symbol, &character_set->symbol}
};
// Main lexing loop
while (true)
{
// Variable to check if the character was appended and therefore recognised
bool character_appended = false;
// Obtain the current character
std::string current_character = character_stream->Peek(0);
// Iterate over the character sets
for (auto& set : character_sets)
{
// Attempt to find the current character in a set
if (set.second->find(current_character) != set.second->end())
{
// If the character type does not correspond to the current token type,
// or if the token is of "symbol" type, which should only hold one character,
// append the token to the token vector and create a new one of the correct type
if (temp_token.type != set.first || temp_token.type == TokenType::Symbol)
{
tokens.push_back(temp_token);
temp_token = Token(set.first);
}
// Append the current character to the current token
character_appended = temp_token.append(character_stream->Consume(0));
// If the current token marks the end of the stream, finish lexing
if (temp_token.type == TokenType::EndOfStream)
{
tokens.push_back(temp_token);
return;
}
}
}
// Check if the character was not found in any of the character sets
if (!character_appended)
{
// Ignore character and continue...
character_stream->Consume(0);
// ... or throw exception
// throw std::runtime_error("Unknown character.");
}
}
}
Token Lexer::Peek(uint8_t a_offset)
{
}
Token Lexer::Consume(uint8_t a_offset)
{
}
}
| 34.166667
| 100
| 0.541138
|
Thomilist
|
36b041859da7a7627fafaa9f402e464b40a6cd3e
| 744
|
hpp
|
C++
|
Sources/etwprof/OS/ETW/ETWSessionCommon.hpp
|
Donpedro13/etwprof
|
a9db371ef556d564529c5112c231157d3789292b
|
[
"MIT"
] | 38
|
2018-06-11T19:09:16.000Z
|
2022-03-17T04:15:15.000Z
|
Sources/etwprof/OS/ETW/ETWSessionCommon.hpp
|
Donpedro13/etwprof
|
a9db371ef556d564529c5112c231157d3789292b
|
[
"MIT"
] | 12
|
2018-06-12T20:24:05.000Z
|
2021-07-31T18:28:48.000Z
|
Sources/etwprof/OS/ETW/ETWSessionCommon.hpp
|
Donpedro13/etwprof
|
a9db371ef556d564529c5112c231157d3789292b
|
[
"MIT"
] | 5
|
2019-02-23T04:11:03.000Z
|
2022-03-17T04:15:18.000Z
|
#ifndef ETWP_ETW_SESSION_COMMON_HPP
#define ETWP_ETW_SESSION_COMMON_HPP
#include <windows.h>
#include <evntrace.h>
#include <memory>
#include <string>
namespace ETWP {
bool StopETWSession (TRACEHANDLE hSession, const std::wstring& name, PEVENT_TRACE_PROPERTIES pProperties);
bool StartRealTimeETWSession (const std::wstring& name,
ULONG logFileMode,
ULONG enableFlags,
PTRACEHANDLE pHandle,
std::unique_ptr<EVENT_TRACE_PROPERTIES>* pPropertiesOut);
bool EnableStackCachingForSession (TRACEHANDLE pSession, uint32_t cacheSize, uint32_t bucketCount);
} // namespace ETWP
#endif // #ifndef ETWP_ETW_SESSION_COMMON_HPP
| 32.347826
| 106
| 0.685484
|
Donpedro13
|
36b55ce1816fe3c54955cef0595b31d4653ca121
| 2,542
|
cpp
|
C++
|
apps/Quant/quantcontroller.cpp
|
ekoeppen/RDCL
|
bc8efd0577f8ee231ebdab1e330dde106ff92b15
|
[
"BSD-3-Clause"
] | 3
|
2016-01-09T11:40:36.000Z
|
2018-04-07T18:12:13.000Z
|
apps/Quant/quantcontroller.cpp
|
ekoeppen/RDCL
|
bc8efd0577f8ee231ebdab1e330dde106ff92b15
|
[
"BSD-3-Clause"
] | null | null | null |
apps/Quant/quantcontroller.cpp
|
ekoeppen/RDCL
|
bc8efd0577f8ee231ebdab1e330dde106ff92b15
|
[
"BSD-3-Clause"
] | null | null | null |
#include <QFileDialog>
#include <QDebug>
#include "mainwindow.h"
#include "quantcontroller.h"
#include "settingsdialog.h"
#ifdef Q_WS_WIN
#include "quantcontrollerwindows.h"
#else
#include "quantcontrollerposix.h"
#endif
QuantController *QuantController::controllerFactory(MainWindow *aMainWindow)
{
#ifdef Q_WS_WIN
return new QuantControllerWindows(aMainWindow);
#else
return new QuantControllerPosix(aMainWindow);
#endif
}
QuantController::QuantController(MainWindow *aMainWindow)
: mainWindow(aMainWindow), settings(NULL)
{
}
QuantController::~QuantController()
{
if (settings) {
delete settings;
settings = NULL;
}
}
QString QuantController::selectFile(void)
{
return QFileDialog::getOpenFileName(mainWindow, tr("Select Package File"));
}
void QuantController::getInfo(void)
{
mainWindow->clearOutput();
mainWindow->disableButtons();
QObject::connect(this, SIGNAL(gotNwtOutput(const QString&)), this, SLOT(infoData(const QString&)));
QObject::connect(this, SIGNAL(nwtCompleted()), this, SLOT(infoCompleted()));
launchNwt(QString("-n"));
}
void QuantController::install(void)
{
}
void QuantController::uninstall(void)
{
}
void QuantController::sync(void)
{
}
void QuantController::backup(void)
{
}
void QuantController::editSettings(void)
{
}
void QuantController::readSettings(void)
{
launchNwt(QString("--show-settings"));
}
void QuantController::saveSettings(const QString& settings)
{
QTemporaryFile* file = new QTemporaryFile();
QString cmd("--write-settings ");
file->open();
cmd += file->fileName();
file->write(settings.toAscii());
file->close();
tempFile = file;
QObject::connect(this, SIGNAL(nwtCompleted()), this, SLOT(saveSettingsCompleted()));
launchNwt(cmd);
}
void QuantController::launchSettingsDialog(void)
{
SettingsDialog settings(this);
settings.exec();
}
void QuantController::infoData(const QString& data)
{
mainWindow->addOutput(data);
qDebug() << data;
}
void QuantController::infoCompleted(void)
{
QObject::disconnect(this, SIGNAL(gotNwtOutput(const QString&)));
QObject::disconnect(this, SIGNAL(nwtCompleted()));
mainWindow->enableButtons();
}
void QuantController::cancel(void)
{
}
void QuantController::saveSettingsCompleted(void)
{
tempFile->remove();
delete tempFile;
QObject::disconnect(this, SLOT(saveSettingsCompleted()));
}
| 21.542373
| 104
| 0.684894
|
ekoeppen
|
36b8f1075415da3e489d32e067cffbcf25828afd
| 5,438
|
hpp
|
C++
|
src/rule/tile-type.hpp
|
drelatgithub/mahjong-calc
|
fee7a938ebbc4952ab703d95c628890a48d5125a
|
[
"MIT"
] | null | null | null |
src/rule/tile-type.hpp
|
drelatgithub/mahjong-calc
|
fee7a938ebbc4952ab703d95c628890a48d5125a
|
[
"MIT"
] | null | null | null |
src/rule/tile-type.hpp
|
drelatgithub/mahjong-calc
|
fee7a938ebbc4952ab703d95c628890a48d5125a
|
[
"MIT"
] | null | null | null |
#ifndef MAHJCALC_RULE_TILE_TYPE_HPP
#define MAHJCALC_RULE_TILE_TYPE_HPP
#include <cstdint>
#include <type_traits>
#include "common.hpp"
namespace mahjcalc {
constexpr size_t num_tile_types_total = 35; // Including Undefined
// Red Doras are not considered here
enum class TileType {
M1, M2, M3, M4, M5, M6, M7, M8, M9,
P1, P2, P3, P4, P5, P6, P7, P8, P9,
S1, S2, S3, S4, S5, S6, S7, S8, S9,
E, S, W, N,
Hk, Ht, Cn, // As in Haku, Hatsu, Chun
Undefined
};
constexpr auto underlying(TileType p) { return static_cast<std::underlying_type_t<TileType>>(p); }
constexpr const char* tile_type_name[] {
"1m", "2m", "3m", "4m", "5m", "6m", "7m", "8m", "9m",
"1p", "2p", "3p", "4p", "5p", "6p", "7p", "8p", "9p",
"1s", "2s", "3s", "4s", "5s", "6s", "7s", "8s", "9s",
"E ", "S ", "W ", "N ",
"Hk", "Ht", "Cn",
"Undefined"
};
constexpr auto name(TileType t) { return tile_type_name[underlying(t)]; }
enum class TileTypeCat {
Man, Pin, Sou, Kazehai, Sangenpai, Undefined
};
constexpr TileTypeCat category_of_tile_type[] {
// Man
TileTypeCat::Man, TileTypeCat::Man, TileTypeCat::Man,
TileTypeCat::Man, TileTypeCat::Man, TileTypeCat::Man,
TileTypeCat::Man, TileTypeCat::Man, TileTypeCat::Man,
// Pin
TileTypeCat::Pin, TileTypeCat::Pin, TileTypeCat::Pin,
TileTypeCat::Pin, TileTypeCat::Pin, TileTypeCat::Pin,
TileTypeCat::Pin, TileTypeCat::Pin, TileTypeCat::Pin,
// Sou
TileTypeCat::Sou, TileTypeCat::Sou, TileTypeCat::Sou,
TileTypeCat::Sou, TileTypeCat::Sou, TileTypeCat::Sou,
TileTypeCat::Sou, TileTypeCat::Sou, TileTypeCat::Sou,
// Kaze
TileTypeCat::Kazehai, TileTypeCat::Kazehai, TileTypeCat::Kazehai, TileTypeCat::Kazehai,
// Sangen
TileTypeCat::Sangenpai, TileTypeCat::Sangenpai, TileTypeCat::Sangenpai,
// Undefined
TileTypeCat::Undefined
};
constexpr TileTypeCat category(size_t tile_type_index) { return category_of_tile_type[tile_type_index]; }
constexpr TileTypeCat category(TileType p) { return category(underlying(p)); }
constexpr mc_uif8 number_of_tile_type[] {
/* Man */ 1, 2, 3, 4, 5, 6, 7, 8, 9,
/* Pin */ 1, 2, 3, 4, 5, 6, 7, 8, 9,
/* Sou */ 1, 2, 3, 4, 5, 6, 7, 8, 9,
/* Kaze */ 0, 0, 0, 0,
/* Sangen */ 0, 0, 0,
/* Undefined */ 0
};
constexpr mc_uif8 number(TileType p) { return number_of_tile_type[underlying(p)]; }
template< mc_uif8 num_players > struct CanStartShuntsu;
template<> struct CanStartShuntsu<4> {
static constexpr bool value[] {
// Man, Pin, Sou
true, true, true, true, true, true, true, false, false,
true, true, true, true, true, true, true, false, false,
true, true, true, true, true, true, true, false, false,
// Kaze
false, false, false, false,
// Sangen
false, false, false,
// Undefined
false
};
};
template<> struct CanStartShuntsu<3> {
static constexpr bool value[] {
// Man, Pin, Sou
false, false, false, false, false, false, false, false, false,
true, true, true, true, true, true, true, false, false,
true, true, true, true, true, true, true, false, false,
// Kaze
false, false, false, false,
// Sangen
false, false, false,
// Undefined
false
};
};
template< typename Rule >
constexpr bool can_start_shuntsu(size_t tile_type_index) {
return CanStartShuntsu<Rule::num_players>::value[tile_type_index];
}
template< typename Rule >
constexpr bool can_start_shuntsu(TileType t) {
return can_start_shuntsu<Rule>(underlying(t));
}
template< mc_uif8 num_players > struct DoraTileType;
template<> struct DoraTileType<4> {
static constexpr TileType value[] {
// Man
TileType::M2, TileType::M3, TileType::M4,
TileType::M5, TileType::M6, TileType::M7,
TileType::M8, TileType::M9, TileType::M1,
// Pin
TileType::P2, TileType::P3, TileType::P4,
TileType::P5, TileType::P6, TileType::P7,
TileType::P8, TileType::P9, TileType::P1,
// Sou
TileType::S2, TileType::S3, TileType::S4,
TileType::S5, TileType::S6, TileType::S7,
TileType::S8, TileType::S9, TileType::S1,
// Kaze
TileType::S, TileType::W, TileType::N, TileType::E,
// Sangen
TileType::Ht, TileType::Cn, TileType::Hk,
// Undefined
TileType::Undefined
};
};
template<> struct DoraTileType<3> {
static constexpr TileType value[] {
// Man
TileType::M9, TileType::Undefined, TileType::Undefined,
TileType::Undefined, TileType::Undefined, TileType::Undefined,
TileType::Undefined, TileType::Undefined, TileType::M1,
// Pin
TileType::P2, TileType::P3, TileType::P4,
TileType::P5, TileType::P6, TileType::P7,
TileType::P8, TileType::P9, TileType::P1,
// Sou
TileType::S2, TileType::S3, TileType::S4,
TileType::S5, TileType::S6, TileType::S7,
TileType::S8, TileType::S9, TileType::S1,
// Kaze
TileType::S, TileType::W, TileType::N, TileType::E,
// Sangen
TileType::Ht, TileType::Cn, TileType::Hk,
// Undefined
TileType::Undefined
};
};
template< typename Rule >
constexpr TileType get_dora_from_indicator(TileType p) {
return DoraTileType<Rule::num_players>::value[underlying(p)];
}
} // namespace mahjcalc
#endif
| 33.9875
| 105
| 0.622839
|
drelatgithub
|
36bc0edc5c1e7019d82cda76f0c173923b325d24
| 3,249
|
hh
|
C++
|
src/GroupDomain_cube.hh
|
lucjaulmes/FaultSim-A-Memory-Reliability-Simulator
|
fac1cee8780c5cb783f2ffcc25682b9e0172b11e
|
[
"BSD-3-Clause"
] | null | null | null |
src/GroupDomain_cube.hh
|
lucjaulmes/FaultSim-A-Memory-Reliability-Simulator
|
fac1cee8780c5cb783f2ffcc25682b9e0172b11e
|
[
"BSD-3-Clause"
] | null | null | null |
src/GroupDomain_cube.hh
|
lucjaulmes/FaultSim-A-Memory-Reliability-Simulator
|
fac1cee8780c5cb783f2ffcc25682b9e0172b11e
|
[
"BSD-3-Clause"
] | null | null | null |
/*
Copyright (c) 2015, Advanced Micro Devices, Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef GROUPDOMAIN_CUBE_HH_
#define GROUPDOMAIN_CUBE_HH_
#include <random>
#include "dram_common.hh"
#include "GroupDomain.hh"
class GroupDomain_cube : public GroupDomain
{
/** Total Chips in a DIMM */
const uint64_t m_chips;
/** Total Banks per Chip */
const uint64_t m_banks;
/** The burst length per access, this determines the number of TSVs */
const uint64_t m_burst_size;
// 3D memory variables
enum { HORIZONTAL, VERTICAL } cube_model;
uint64_t cube_data_tsv;
uint64_t enable_tsv;
bool *tsv_bitmap;
uint64_t *tsv_info;
/** Address Decoding Depth */
uint64_t m_cube_addr_dec_depth;
uint64_t cube_ecc_tsv;
uint64_t cube_redun_tsv;
uint64_t total_addr_tsv;
uint64_t total_tsv;
bool tsv_shared_accross_chips;
//Static Arrays for ISCA2014
uint64_t tsv_swapped_hc[9];
uint64_t tsv_swapped_vc[8];
uint64_t tsv_swapped_mc[9][8];
double tsv_transientFIT;
double tsv_permanentFIT;
uint64_t tsv_n_faults_transientFIT_class;
uint64_t tsv_n_faults_permanentFIT_class;
std::mt19937_64 gen;
std::uniform_int_distribution<uint64_t> tsv_dist;
void generateTSV(bool transient);
GroupDomain_cube(const std::string& name, unsigned cube_model, uint64_t chips, uint64_t banks, uint64_t burst_length,
uint64_t cube_addr_dec_depth, uint64_t cube_ecc_tsv, uint64_t cube_redun_tsv, bool enable_tsv);
public:
static GroupDomain_cube* genModule(Settings &settings, int module_id);
~GroupDomain_cube();
inline
void setFIT_TSV(bool isTransient_TSV, double FIT_TSV)
{
if (isTransient_TSV)
tsv_transientFIT = FIT_TSV;
else
tsv_permanentFIT = FIT_TSV;
}
inline
bool horizontalTSV()
{
return cube_model == HORIZONTAL;
}
void addDomain(FaultDomain *domain);
};
#endif /* GROUPDOMAIN_CUBE_HH_ */
| 33.153061
| 120
| 0.794398
|
lucjaulmes
|
36c244ea95072445e74ec096bb4a6e850690009c
| 1,704
|
cpp
|
C++
|
src/Viewer/tst/Segment2DSubsegments.unit.cpp
|
bakonyidani/Windows-CalcEngine
|
afa4c4a9f88199c6206af8bc994a073931fc8b91
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
src/Viewer/tst/Segment2DSubsegments.unit.cpp
|
bakonyidani/Windows-CalcEngine
|
afa4c4a9f88199c6206af8bc994a073931fc8b91
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
src/Viewer/tst/Segment2DSubsegments.unit.cpp
|
bakonyidani/Windows-CalcEngine
|
afa4c4a9f88199c6206af8bc994a073931fc8b91
|
[
"BSD-3-Clause-LBNL"
] | null | null | null |
#include <memory>
#include <gtest/gtest.h>
#include <memory>
#include <vector>
#include "WCEViewer.hpp"
using namespace Viewer;
class TestSegment2DSubsegments : public testing::Test {
protected:
virtual void SetUp() {
}
};
TEST_F( TestSegment2DSubsegments, Segment2DTest1 ) {
SCOPED_TRACE( "Begin Test: Segment 2D - subsegments creation." );
std::shared_ptr< CPoint2D > aStartPoint = std::make_shared< CPoint2D >( 0, 0 );
std::shared_ptr< CPoint2D > aEndPoint = std::make_shared< CPoint2D >( 10, 10 );
CViewSegment2D aSegment = CViewSegment2D( aStartPoint, aEndPoint );
std::shared_ptr< std::vector< std::shared_ptr< CViewSegment2D > > > aSubSegments = aSegment.subSegments( 4 );
std::vector< double > correctStartX = { 0, 2.5, 5, 7.5 };
std::vector< double > correctEndX = { 2.5, 5, 7.5, 10 };
std::vector< double > correctStartY = { 0, 2.5, 5, 7.5 };
std::vector< double > correctEndY = { 2.5, 5, 7.5, 10 };
size_t i = 0;
for ( std::shared_ptr< CViewSegment2D > aSubSegment : *aSubSegments ) {
double xStart = aSubSegment->startPoint()->x();
double xEnd = aSubSegment->endPoint()->x();
double yStart = aSubSegment->startPoint()->y();
double yEnd = aSubSegment->endPoint()->y();
EXPECT_NEAR( correctStartX[ i ], xStart, 1e-6 );
EXPECT_NEAR( correctEndX[ i ], xEnd, 1e-6 );
EXPECT_NEAR( correctStartY[ i ], yStart, 1e-6 );
EXPECT_NEAR( correctEndY[ i ], yEnd, 1e-6 );
++i;
}
// std::shared_ptr< CSegment2D > aNormal = aSegment.getNormal();
// std::shared_ptr< const CPoint2D > aNormalPoint = aNormal->endPoint();
// double x = aNormalPoint->x();
// double y = aNormalPoint->y();
//
// EXPECT_NEAR( 0, x, 1e-6 );
// EXPECT_NEAR( -1, y, 1e-6 );
}
| 27.934426
| 110
| 0.664906
|
bakonyidani
|
36c782d74d02e318d5d59adadd72f5184bddca75
| 1,782
|
cpp
|
C++
|
Upsolving/URI/1025.cpp
|
rodrigoAMF7/Notebook---Maratonas
|
06b38197a042bfbd27b20f707493e0a19fda7234
|
[
"MIT"
] | 4
|
2019-01-25T21:22:55.000Z
|
2019-03-20T18:04:01.000Z
|
Upsolving/URI/1025.cpp
|
rodrigoAMF/competitive-programming-notebook
|
06b38197a042bfbd27b20f707493e0a19fda7234
|
[
"MIT"
] | null | null | null |
Upsolving/URI/1025.cpp
|
rodrigoAMF/competitive-programming-notebook
|
06b38197a042bfbd27b20f707493e0a19fda7234
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
// Nome de Tipos
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
// Valores
#define INF 0x3F3F3F3F
#define LINF 0x3F3F3F3F3F3F3F3FLL
#define DINF (double)1e+30
#define EPS (double)1e-9
#define RAD(x) (double)(x*PI)/180.0
#define PCT(x,y) (double)x*100.0/y
// Atalhos
#define F first
#define S second
#define PB push_back
#define MP make_pair
#define forn(i, n) for ( int i = 0; i < (n); ++i )
using namespace std;
int binarySearch(vector<int> arr, int l, int r, int x)
{
if (r >= l)
{
int mid = l + (r - l)/2;
// If the element is present at the middle
// itself
if (arr.at(mid) == x)
return mid+1;
// If element is smaller than mid, then
// it can only be present in left subarray
if (arr.at(mid) > x)
return binarySearch(arr, l, mid-1, x);
// Else the element can only be present
// in right subarray
return binarySearch(arr, mid+1, r, x);
}
// We reach here when element is not
// present in array
return -1;
}
int linearSearch(vector<int> arr, int x){
forn(i, arr.size()){
if(arr.at(i) == x)
return i+1;
}
return -1;
}
int n, q;
int main(){
int contador = 1;
while(true){
cin >> n >> q;
if(n == q && n == 0) break;
cout << "CASE# " << contador << ":" << endl;
vector<int> numeros;
forn(i, n){
int aux;
cin >> aux;
numeros.push_back(aux);
}
sort(numeros.begin(), numeros.end());
forn(i, q){
int aux, resultado;
cin >> aux;
resultado = linearSearch(numeros, aux);
if(resultado != -1){
cout << aux << " found at " << resultado << endl;
}else{
cout << aux << " not found" << endl;
}
}
contador++;
}
return 0;
}
| 19.16129
| 54
| 0.570146
|
rodrigoAMF7
|
36cd25104f9088fa3393b26bea86e5da5d2075f7
| 329
|
cpp
|
C++
|
livro/cap_03 (finalizado)/02_ano_bissexto.cpp
|
sueyvid/Atividade_de_programacao_cpp
|
691941fc94125eddd4e5466862d5a1fe04dfb520
|
[
"MIT"
] | null | null | null |
livro/cap_03 (finalizado)/02_ano_bissexto.cpp
|
sueyvid/Atividade_de_programacao_cpp
|
691941fc94125eddd4e5466862d5a1fe04dfb520
|
[
"MIT"
] | null | null | null |
livro/cap_03 (finalizado)/02_ano_bissexto.cpp
|
sueyvid/Atividade_de_programacao_cpp
|
691941fc94125eddd4e5466862d5a1fe04dfb520
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int main()
{
int ano;
bool eh_bissexto;
cin >> ano;
eh_bissexto = ((ano%4 == 0 && !(ano%100 == 0)) || ano%400 == 0);
if(eh_bissexto){
cout << ano << " e um ano bissexto";
}
else{
cout << ano << " nao e um ano bissexto";
}
return 0;
}
| 17.315789
| 68
| 0.50152
|
sueyvid
|
36d33c3f56c0b85d99f4e4671415bd696e0d01d1
| 19,061
|
cpp
|
C++
|
source/loonyland/endgame.cpp
|
AutomaticFrenzy/HamSandwich
|
d991c840fd688cb2541806a33f152ba9aac41a1a
|
[
"MIT"
] | null | null | null |
source/loonyland/endgame.cpp
|
AutomaticFrenzy/HamSandwich
|
d991c840fd688cb2541806a33f152ba9aac41a1a
|
[
"MIT"
] | null | null | null |
source/loonyland/endgame.cpp
|
AutomaticFrenzy/HamSandwich
|
d991c840fd688cb2541806a33f152ba9aac41a1a
|
[
"MIT"
] | null | null | null |
#include "endgame.h"
#include "display.h"
#include "player.h"
#include "fireworks.h"
#include "badge.h"
#include "bossbash.h"
#include "highscore.h"
#include "log.h"
char rankText[][32]={
"Scalliwag",
"Cad",
"Ruffian",
"Weenie",
"Peon",
"Peasant",
"Citizen",
"Upper Crust",
"High Class",
"Knight",
"Baron",
"Duke",
"Lord",
"King",
"Emperor",
"Hero",
"Superhero",
"Ultrahero",
"Uberhero",
"Gyro Sandwich",
"Jamulio",
};
#define ST_NUM 0
#define ST_TIME 1
#define ST_PCT 2
#define ST_BASH 3 // bash power level
typedef struct stat_t
{
byte type;
char name[32];
int val;
char xtra[32];
int points;
int curPts;
byte visible;
} stat_t;
// `stat` is a thing that might already exist depending on header coincidences
#define stat loonystat
stat_t stat[16];
byte numStats;
byte curStat;
int totalScore;
void Commaize(char *s,int n)
{
char s2[8];
byte zero;
s[0]='\0';
zero=0;
if(n<0)
{
n=-n;
s[0]='-';
s[1]='\0';
}
if(n>=1000000)
{
zero=1;
sprintf(s2,"%d,",n/1000000);
strcat(s,s2);
}
if(n>=1000)
{
if(!zero)
sprintf(s2,"%d,",(n/1000)%1000);
else
sprintf(s2,"%03d,",(n/1000)%1000);
strcat(s,s2);
zero=1;
}
if(!zero)
sprintf(s2,"%d",n%1000);
else
sprintf(s2,"%03d",n%1000);
strcat(s,s2);
}
void ShowStat(byte w,int x,int y)
{
char s[88];
Print(x,y,stat[w].name,0,0);
switch(stat[w].type)
{
case ST_NUM:
// straight number
Commaize(s,stat[w].val);
RightPrint(x+210,y,s,0,0);
break;
case ST_TIME:
// time
sprintf(s,"%02d:%02d:%02d",
stat[w].val/(30*60*60),(stat[w].val/(30*60))%60,(stat[w].val/30)%60);
RightPrint(x+210,y,s,0,0);
break;
case ST_PCT:
// percent
sprintf(s,"%0.2f%%",(float)stat[w].val/10000);
RightPrint(x+210,y,s,0,0);
break;
case ST_BASH:
// bash power level
RightPrint(x+210,y,BashPowerName(stat[w].val),0,0);
break;
}
Print(x+220,y,stat[w].xtra,0,0);
Print(x+360,y,"=",0,0);
Commaize(s,stat[w].curPts);
RightPrint(x+500,y,s,0,0);
}
byte GetRank(int score)
{
if(score<0)
score=0;
score/=100000;
if(score>20)
score=20;
return (byte)score;
}
int GetTimePoints(dword time,dword best,dword bestScore,dword betterPts,dword worsePts)
{
int result;
if(time<=best)
{
result=bestScore+(betterPts*(best-time))/30;
}
else
{
result=bestScore-(worsePts*(time-best))/30;
}
return result;
}
void InitEndGame(void)
{
int i;
DBG("InitEndGame");
for(i=0;i<16;i++)
{
stat[i].curPts=0;
stat[i].type=ST_NUM;
stat[i].val=0;
stat[i].visible=0;
stat[i].xtra[0]='\0';
stat[i].name[0]='\0';
}
switch(player.worldNum)
{
case WORLD_NORMAL:
case WORLD_REMIX:
case WORLD_RANDOMIZER:
numStats=10;
// percent done
strcpy(stat[0].name,"Complete");
stat[0].val=(int)(CalcPercent(&player)*10000);
strcpy(stat[0].xtra,"x10,000");
stat[0].points=(int)(CalcPercent(&player)*10000);
stat[0].type=ST_PCT;
// time to finish
if((player.cheatsOn&PC_HARDCORE) && player.hearts==0)
{
strcpy(stat[1].name,"Time");
stat[1].val=player.timeToFinish;
stat[1].points=0;
stat[1].type=ST_TIME;
strcpy(stat[1].xtra,"(failed)");
}
else
{
strcpy(stat[1].name,"Time");
stat[1].val=player.timeToFinish;
stat[1].points=GetTimePoints(player.timeToFinish,30*60*60*8,1000000,200,200);
stat[1].type=ST_TIME;
strcpy(stat[1].xtra,"(8:00:00 par)");
}
// monster points
strcpy(stat[2].name,"Monster Pts");
stat[2].val=player.monsterPoints;
strcpy(stat[2].xtra,"x10");
stat[2].points=player.monsterPoints*10;
// gems collected
strcpy(stat[3].name,"Gems Obtained");
stat[3].val=player.gemsGotten;
strcpy(stat[3].xtra,"x10");
stat[3].points=player.gemsGotten*10;
// best combo
strcpy(stat[4].name,"Best Combo");
stat[4].val=player.bestCombo;
strcpy(stat[4].xtra,"x5,000");
stat[4].points=player.bestCombo*5000;
// badguys killed
strcpy(stat[5].name,"Badguys Slain");
stat[5].val=player.guysKilled;
strcpy(stat[5].xtra,"x5");
stat[5].points=player.guysKilled*5;
// shotsFired
strcpy(stat[6].name,"Shots Fired");
stat[6].val=player.shotsFired;
strcpy(stat[6].xtra,"x-10");
stat[6].points=player.shotsFired*-10;
// special shots fired
strcpy(stat[7].name,"Special Shots");
stat[7].val=player.specialShotsFired;
strcpy(stat[7].xtra,"x-10");
stat[7].points=player.specialShotsFired*-10;
// number of saves
strcpy(stat[8].name,"Saved Games");
stat[8].val=player.numSaves;
strcpy(stat[8].xtra,"x-5,000");
stat[8].points=player.numSaves*-5000;
// hits taken
strcpy(stat[9].name,"Hits Taken");
stat[9].val=player.hitsTaken;
strcpy(stat[9].xtra,"x-500");
stat[9].points=player.hitsTaken*-500;
break;
case WORLD_SURVIVAL:
numStats=9;
// level reached
strcpy(stat[0].name,"Level Passed");
stat[0].val=player.numSaves;
strcpy(stat[0].xtra,"x50,000");
stat[0].points=player.numSaves*50000;
if(player.cheatsOn&PC_INFSURV)
{
strcpy(stat[0].xtra,"x25,000");
stat[0].points=player.numSaves*25000;
}
// time to finish
if(player.cheatsOn&PC_INFSURV)
{
strcpy(stat[1].name,"Time");
stat[1].val=player.timeToFinish;
stat[1].points=0;
stat[1].type=ST_TIME;
strcpy(stat[1].xtra,"(no points)");
}
else
{
if(player.numSaves==25)
{
strcpy(stat[1].name,"Time");
stat[1].val=player.timeToFinish;
stat[1].points=GetTimePoints(player.timeToFinish,30*60*10,1000000,1000,1000);
stat[1].type=ST_TIME;
strcpy(stat[1].xtra,"(10:00 par)");
}
else
{
strcpy(stat[1].name,"Time");
stat[1].val=player.timeToFinish;
stat[1].points=-1000000;
stat[1].type=ST_TIME;
strcpy(stat[1].xtra,"(failed)");
}
}
// monster points
strcpy(stat[2].name,"Monster Pts");
stat[2].val=player.monsterPoints;
strcpy(stat[2].xtra,"x100");
stat[2].points=player.monsterPoints*100;
if(player.cheatsOn&PC_INFSURV)
{
stat[2].val=player.monsterPoints;
strcpy(stat[2].xtra,"x500");
stat[2].points=player.monsterPoints*500;
}
// gems collected
strcpy(stat[3].name,"Gems Obtained");
stat[3].val=player.gemsGotten;
strcpy(stat[3].xtra,"x100");
stat[3].points=player.gemsGotten*100;
// best combo
strcpy(stat[4].name,"Best Combo");
stat[4].val=player.bestCombo;
strcpy(stat[4].xtra,"x10,000");
stat[4].points=player.bestCombo*10000;
// badguys killed
strcpy(stat[5].name,"Badguys Slain");
stat[5].val=player.guysKilled;
strcpy(stat[5].xtra,"x500");
stat[5].points=player.guysKilled*500;
// shotsFired
strcpy(stat[6].name,"Shots Fired");
stat[6].val=player.shotsFired;
strcpy(stat[6].xtra,"x-500");
stat[6].points=player.shotsFired*-500;
// special shots fired
strcpy(stat[7].name,"Special Shots");
stat[7].val=player.specialShotsFired;
strcpy(stat[7].xtra,"x-200");
stat[7].points=player.specialShotsFired*-200;
// hits taken
strcpy(stat[8].name,"Hits Taken");
stat[8].val=player.hitsTaken;
strcpy(stat[8].xtra,"x-5000");
stat[8].points=player.hitsTaken*-5000;
if(player.cheatsOn&PC_INFSURV)
{
stat[8].val=player.hitsTaken;
strcpy(stat[8].xtra,"x-2000");
stat[8].points=player.hitsTaken*-2000;
}
break;
case WORLD_BOWLING:
numStats=5;
// points
strcpy(stat[0].name,"Points");
stat[0].val=player.monsterPoints;
strcpy(stat[0].xtra,"x10,000");
stat[0].points=player.monsterPoints*10000;
// strikes
strcpy(stat[1].name,"Strikes");
stat[1].val=player.gemsGotten;
strcpy(stat[1].xtra,"x100,000");
stat[1].points=player.gemsGotten*100000;
// gutterballs
strcpy(stat[2].name,"Gutterballs");
stat[2].val=player.specialShotsFired;
strcpy(stat[2].xtra,"x-50,000");
stat[2].points=player.specialShotsFired*-50000;
// used balls
strcpy(stat[3].name,"Balls Used");
stat[3].val=player.shotsFired;
strcpy(stat[3].xtra,"x-50,000");
stat[3].points=player.shotsFired*-50000;
// time
strcpy(stat[4].name,"Time");
stat[4].val=player.timeToFinish;
stat[4].points=GetTimePoints(player.timeToFinish,30*60*2,100000,5000,1000);
stat[4].type=ST_TIME;
strcpy(stat[4].xtra,"(2:00 par)");
break;
case WORLD_LOONYBALL:
numStats=5;
// points
strcpy(stat[0].name,"Points");
stat[0].val=(player.gemsGotten-5000);
strcpy(stat[0].xtra,"x100,000");
stat[0].points=(player.gemsGotten-5000)*100000;
// strikes
strcpy(stat[1].name,"Penalties");
stat[1].val=player.numSaves;
strcpy(stat[1].xtra,"x-100,000");
stat[1].points=player.numSaves*-100000;
// gutterballs
strcpy(stat[2].name,"Games Played");
stat[2].val=player.levelNum;
strcpy(stat[2].xtra,"x250,000");
stat[2].points=player.levelNum*250000;
// used balls
strcpy(stat[3].name,"Out Of Bounds");
player.guysKilled=player.oob;
stat[3].val=player.guysKilled;
strcpy(stat[3].xtra,"x-100,000");
stat[3].points=player.guysKilled*-100000;
// time
if(player.levelNum==5)
{
strcpy(stat[4].name,"Time");
stat[4].val=player.timeToFinish;
stat[4].points=GetTimePoints(player.timeToFinish,30*60*6,100000,10000,10000);
stat[4].type=ST_TIME;
strcpy(stat[4].xtra,"(6:00 par)");
}
else
{
strcpy(stat[4].name,"Time");
stat[4].val=player.timeToFinish;
stat[4].points=-100000;
stat[4].type=ST_TIME;
strcpy(stat[4].xtra,"(failed)");
}
break;
case WORLD_BOSSBASH:
DBG("BB-Setup");
numStats=3;
// time
DBG("BB1");
if(player.hearts>0)
{
DBG("BB2");
strcpy(stat[0].name,"Time");
stat[0].val=player.timeToFinish;
DBG("BB3");
i=player.numSaves-30*30*BashPower();
if(i<0)
i=10*30;
DBG("BB4");
stat[0].points=GetTimePoints(player.timeToFinish,i,2000000,40000,10000);
stat[0].type=ST_TIME;
DBG("BB5");
sprintf(stat[0].xtra,"(%d:%02d par)",i/(30*60),(i/30)%60);
}
else
{
strcpy(stat[0].name,"Time");
stat[0].val=player.timeToFinish;
stat[0].points=0;
stat[0].type=ST_TIME;
strcpy(stat[0].xtra,"(failed)");
}
DBG("BB6");
// power level
strcpy(stat[1].name,"Power");
stat[1].val=BashPower();
DBG("BB7");
strcpy(stat[1].xtra,"x-100,000");
stat[1].points=BashPower()*-100000;
stat[1].type=ST_BASH;
DBG("BB8");
// hits taken
strcpy(stat[2].name,"Hits Taken");
stat[2].val=player.hitsTaken;
DBG("BB9");
strcpy(stat[2].xtra,"x-100,000");
stat[2].points=player.hitsTaken*-100000;
DBG("BB10");
break;
}
DBG("BB-Setup2");
player.rank=0;
curStat=0;
totalScore=0;
GetDisplayMGL()->LastKeyPressed();
DBG("BB-Setup3");
GetTaps();
DBG("BB-Setup4");
InitFireworks();
DBG("BB-Setup5");
}
void RenderFinalScore(int x,int y,MGLDraw *mgl)
{
char s[48];
DrawBox(x,y,x+500,y+1,31);
RightPrint(x+340,y+5,"Total Score",0,0);
Commaize(s,totalScore);
RightPrint(x+500,y+5,s,0,0);
RightPrint(x+340,y+35,"Rank",0,0);
sprintf(s,"%s",rankText[player.rank]);
RightPrint(x+500,y+35,s,0,0);
}
void ShowHighScore(int x,int y,int score,byte on,byte col,MGLDraw *mgl)
{
char s[48];
Commaize(s,score);
if(on)
{
PrintGlow(x,y,s,0,0);
PrintGlow(x+120,y,rankText[GetRank(score)],0,0);
}
else
{
PrintColor(x,y,s,col,-10,0);
PrintColor(x+120,y,rankText[GetRank(score)],col,-10,0);
}
}
void ShowScoreStats(int x,int y,highScore_t *me,MGLDraw *mgl)
{
char s[32];
switch(me->mode)
{
case WORLD_NORMAL:
case WORLD_REMIX:
case WORLD_RANDOMIZER:
PrintGlow(x,y,"Percent Done",0,0);
sprintf(s,"%2.1f%%",(float)me->spclValue/FIXAMT);
RightPrintGlow(x+250,y,s,0,0);
PrintGlow(x,y+25,"Time",0,0);
sprintf(s,"%02d:%02d:%02d",
me->time/(30*60*60),(me->time/(30*60))%60,(me->time/30)%60);
RightPrintGlow(x+250,y+25,s,0,0);
PrintGlow(x,y+25*2,"Monster Pts",0,0);
sprintf(s,"%d",me->monsterPoints);
RightPrintGlow(x+250,y+25*2,s,0,0);
PrintGlow(x,y+25*3,"Gems Collected",0,0);
sprintf(s,"%d",me->gemsGotten);
RightPrintGlow(x+250,y+25*3,s,0,0);
PrintGlow(x,y+25*4,"Best Combo",0,0);
sprintf(s,"%d",me->bestCombo);
RightPrintGlow(x+250,y+25*4,s,0,0);
PrintGlow(x,y+25*5,"Badguys Slain",0,0);
sprintf(s,"%d",me->guysKilled);
RightPrintGlow(x+250,y+25*5,s,0,0);
PrintGlow(x,y+25*6,"Shots Fired",0,0);
sprintf(s,"%d",me->shotsFired);
RightPrintGlow(x+250,y+25*6,s,0,0);
PrintGlow(x,y+25*7,"Special Shots",0,0);
sprintf(s,"%d",me->specialShotsFired);
RightPrintGlow(x+250,y+25*7,s,0,0);
PrintGlow(x,y+25*8,"Saved Games",0,0);
sprintf(s,"%d",me->numSaves);
RightPrintGlow(x+250,y+25*8,s,0,0);
PrintGlow(x,y+25*9,"Hits Taken",0,0);
sprintf(s,"%d",me->hitsTaken);
RightPrintGlow(x+250,y+25*9,s,0,0);
break;
case WORLD_SURVIVAL:
case WORLD_INFSURV:
PrintGlow(x,y+25*0,"Level Passed",0,0);
sprintf(s,"%d",me->numSaves);
RightPrintGlow(x+250,y+25*0,s,0,0);
PrintGlow(x,y+25,"Time",0,0);
sprintf(s,"%02d:%02d:%02d",
me->time/(30*60*60),(me->time/(30*60))%60,(me->time/30)%60);
RightPrintGlow(x+250,y+25,s,0,0);
PrintGlow(x,y+25*2,"Monster Pts",0,0);
sprintf(s,"%d",me->monsterPoints);
RightPrintGlow(x+250,y+25*2,s,0,0);
PrintGlow(x,y+25*3,"Gems Collected",0,0);
sprintf(s,"%d",me->gemsGotten);
RightPrintGlow(x+250,y+25*3,s,0,0);
PrintGlow(x,y+25*4,"Best Combo",0,0);
sprintf(s,"%d",me->bestCombo);
RightPrintGlow(x+250,y+25*4,s,0,0);
PrintGlow(x,y+25*5,"Badguys Slain",0,0);
sprintf(s,"%d",me->guysKilled);
RightPrintGlow(x+250,y+25*5,s,0,0);
PrintGlow(x,y+25*6,"Shots Fired",0,0);
sprintf(s,"%d",me->shotsFired);
RightPrintGlow(x+250,y+25*6,s,0,0);
PrintGlow(x,y+25*7,"Special Shots",0,0);
sprintf(s,"%d",me->specialShotsFired);
RightPrintGlow(x+250,y+25*7,s,0,0);
PrintGlow(x,y+25*8,"Hits Taken",0,0);
sprintf(s,"%d",me->hitsTaken);
RightPrintGlow(x+250,y+25*8,s,0,0);
break;
case WORLD_BOWLING:
PrintGlow(x,y+25*0,"Points",0,0);
sprintf(s,"%d",me->monsterPoints);
RightPrintGlow(x+250,y+25*0,s,0,0);
PrintGlow(x,y+25*1,"Strikes",0,0);
sprintf(s,"%d",me->gemsGotten);
RightPrintGlow(x+250,y+25*1,s,0,0);
PrintGlow(x,y+25*2,"Gutterballs",0,0);
sprintf(s,"%d",me->specialShotsFired);
RightPrintGlow(x+250,y+25*2,s,0,0);
PrintGlow(x,y+25*3,"Balls Used",0,0);
sprintf(s,"%d",me->shotsFired);
RightPrintGlow(x+250,y+25*3,s,0,0);
PrintGlow(x,y+25*4,"Time",0,0);
sprintf(s,"%02d:%02d:%02d",
me->time/(30*60*60),(me->time/(30*60))%60,(me->time/30)%60);
RightPrintGlow(x+250,y+25*4,s,0,0);
break;
case WORLD_LOONYBALL:
PrintGlow(x,y+25*0,"Points",0,0);
sprintf(s,"%d",me->gemsGotten-5000);
RightPrintGlow(x+250,y+25*0,s,0,0);
PrintGlow(x,y+25*1,"Penalties",0,0);
sprintf(s,"%d",me->numSaves);
RightPrintGlow(x+250,y+25*1,s,0,0);
PrintGlow(x,y+25*2,"Games Played",0,0);
sprintf(s,"%d",me->bestCombo);
RightPrintGlow(x+250,y+25*2,s,0,0);
PrintGlow(x,y+25*3,"Out Of Bounds",0,0);
sprintf(s,"%d",me->guysKilled);
RightPrintGlow(x+250,y+25*3,s,0,0);
PrintGlow(x,y+25*4,"Time",0,0);
sprintf(s,"%02d:%02d:%02d",
me->time/(30*60*60),(me->time/(30*60))%60,(me->time/30)%60);
RightPrintGlow(x+250,y+25*4,s,0,0);
break;
case WORLD_BOSSBASH:
//PrintGlow(x,y,"Victim",0,0);
PrintGlow(x,y,BashLevelName(me->spclValue),0,0);
PrintGlow(x,y+25*1,"Time",0,0);
sprintf(s,"%02d:%02d:%02d",
me->time/(30*60*60),(me->time/(30*60))%60,(me->time/30)%60);
RightPrintGlow(x+250,y+25*1,s,0,0);
PrintGlow(x,y+25*2,"Power Level",0,0);
sprintf(s,"%d",me->gemsGotten);
RightPrintGlow(x+250,y+25*2,BashPowerName((byte)me->gemsGotten),0,0);
PrintGlow(x,y+25*3,"Hits Taken",0,0);
sprintf(s,"%d",me->hitsTaken);
RightPrintGlow(x+250,y+25*3,s,0,0);
break;
}
}
void RenderEndGame(MGLDraw *mgl)
{
int i,x,y;
DBG("RenderEndGame");
mgl->ClearScreen();
RenderFireworks(mgl);
CenterPrint(320,2,"Final Score",0,2);
x=75;
y=70;
i=0;
while(i<numStats)
{
if(stat[i].visible)
ShowStat(i,x,y);
y+=30;
i++;
}
y+=10;
RenderFinalScore(x,y,mgl);
}
byte UpdateEndGame(int *lastTime,MGLDraw *mgl)
{
int i;
char c;
byte t;
static byte fwClock;
DBG("UpdateEndGame");
if(*lastTime>TIME_PER_FRAME*30)
*lastTime=TIME_PER_FRAME*30;
while(*lastTime>=TIME_PER_FRAME)
{
c=mgl->LastKeyPressed();
t=GetTaps();
if(curStat<numStats)
{
MakeNormalSound(SND_MENUCLICK);
// make this stat visible
stat[curStat].visible=1;
// start cranking up the points
if(stat[curStat].curPts<stat[curStat].points)
{
if(stat[curStat].points-stat[curStat].curPts>100000)
{
stat[curStat].curPts+=10000;
totalScore+=10000;
}
else if(stat[curStat].points-stat[curStat].curPts>1000)
{
stat[curStat].curPts+=1000;
totalScore+=1000;
}
else if(stat[curStat].points-stat[curStat].curPts>100)
{
stat[curStat].curPts+=100;
totalScore+=100;
}
else if(stat[curStat].points-stat[curStat].curPts>10)
{
stat[curStat].curPts+=10;
totalScore+=10;
}
else
{
stat[curStat].curPts++;
totalScore++;
}
}
else if(stat[curStat].curPts>stat[curStat].points)
{
if(stat[curStat].points-stat[curStat].curPts<-100000)
{
stat[curStat].curPts-=10000;
totalScore-=10000;
}
else if(stat[curStat].points-stat[curStat].curPts<-1000)
{
stat[curStat].curPts-=1000;
totalScore-=1000;
}
else if(stat[curStat].points-stat[curStat].curPts<-100)
{
stat[curStat].curPts-=100;
totalScore-=100;
}
else if(stat[curStat].points-stat[curStat].curPts<-10)
{
stat[curStat].curPts-=10;
totalScore-=10;
}
else
{
stat[curStat].curPts--;
totalScore--;
}
}
else
curStat++;
if(c || t)
{
curStat=numStats;
totalScore=0;
for(i=0;i<numStats;i++)
{
stat[i].visible=1;
stat[i].curPts=stat[i].points;
totalScore+=stat[i].curPts;
}
}
}
else if(c || t)
{
return 0;
}
player.rank=GetRank(totalScore);
if(fwClock>0)
{
fwClock--;
if(fwClock==0)
{
if(Random(100)<player.rank)
LaunchShell(player.rank);
}
}
else
fwClock=10;
UpdateFireworks();
*lastTime-=TIME_PER_FRAME;
}
return 1;
}
TASK(void) EndGameTally(MGLDraw *mgl)
{
byte b;
int lastTime=1;
dword now,then,hangon;
highScore_t hs;
DBG("EndGameTally");
EndClock();
hangon=TimeLength();
now=timeGetTime();
InitEndGame();
DBG("SurvivedInitEndGame");
b=1;
while(b==1)
{
lastTime+=TimeLength();
StartClock();
b=UpdateEndGame(&lastTime,mgl);
RenderEndGame(mgl);
AWAIT mgl->Flip();
if(!mgl->Process())
{
CO_RETURN;
}
EndClock();
}
DBG("ExitEndGameTally1");
ExitFireworks();
DBG("ExitEndGameTally2");
then=timeGetTime();
ResetClock(hangon);
//AddGarbageTime(then-now);
MakeHighScore(&hs,totalScore);
AWAIT CheckForHighScore(hs);
if(totalScore>=10000000)
EarnBadge(BADGE_SCORE);
BadgeCheck(BE_ENDGAME,0,curMap);
DBG("ExitEndGameTally3");
}
| 23.132282
| 87
| 0.627826
|
AutomaticFrenzy
|
36d3addf468bd4ab1783ae5b617426e702dfe553
| 3,039
|
hh
|
C++
|
src/clang_tu.hh
|
SysRay/ccls
|
daac41a52be06822f2c93407bd5ff8384b0329f8
|
[
"Apache-2.0"
] | null | null | null |
src/clang_tu.hh
|
SysRay/ccls
|
daac41a52be06822f2c93407bd5ff8384b0329f8
|
[
"Apache-2.0"
] | null | null | null |
src/clang_tu.hh
|
SysRay/ccls
|
daac41a52be06822f2c93407bd5ff8384b0329f8
|
[
"Apache-2.0"
] | null | null | null |
/* Copyright 2017-2018 ccls Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#pragma once
#include "log.hh"
#include "position.hh"
#include "utils.hh"
#include <clang/Basic/FileManager.h>
#include <clang/Basic/LangOptions.h>
#include <clang/Basic/SourceManager.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Lex/PreprocessorOptions.h>
#include <mutex>
#include <unordered_map>
#if LLVM_VERSION_MAJOR < 8
// D52783 Lift VFS from clang to llvm
namespace llvm {
namespace vfs = clang::vfs;
}
#endif
namespace ccls {
std::string PathFromFileEntry(const clang::FileEntry &file);
Range FromCharSourceRange(const clang::SourceManager &SM,
const clang::LangOptions &LangOpts,
clang::CharSourceRange R,
llvm::sys::fs::UniqueID *UniqueID = nullptr);
Range FromCharRange(const clang::SourceManager &SM,
const clang::LangOptions &LangOpts, clang::SourceRange R,
llvm::sys::fs::UniqueID *UniqueID = nullptr);
Range FromTokenRange(const clang::SourceManager &SM,
const clang::LangOptions &LangOpts, clang::SourceRange R,
llvm::sys::fs::UniqueID *UniqueID = nullptr);
Range FromTokenRangeDefaulted(const clang::SourceManager &SM,
const clang::LangOptions &Lang,
clang::SourceRange R, const clang::FileEntry *FE,
Range range);
std::unique_ptr<clang::CompilerInvocation>
BuildCompilerInvocation(const std::string &main, std::vector<const char *> args,
llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS);
class SystemFileCacher {
std::unordered_map<std::string, std::string> files;
std::mutex m_mtx;
public:
void addFile(std::string const &path) {
std::unique_lock lock(m_mtx);
if (files.find(path) == files.end()) {
auto file = ccls::ReadContent(path);
if (file) {
files.emplace(std::make_pair(path, *file));
}
}
}
void remapFiles(clang::CompilerInvocation* CI ) {
std::unique_lock lock(m_mtx);
for (auto &item : files) {
CI->getPreprocessorOpts().addRemappedFile(
item.first, llvm::MemoryBuffer::getMemBuffer(item.second).release());
}
}
static SystemFileCacher &getInstance() {
static SystemFileCacher inst;
return inst;
}
private:
};
const char *ClangBuiltinTypeName(int);
} // namespace ccls
| 32.677419
| 80
| 0.654163
|
SysRay
|
36d5280e189a823721c5bd19846b120eb11d98ba
| 12,656
|
cc
|
C++
|
src/game/Strategic/QuestText.cc
|
FluffyQuack/ja2-stracciatella
|
59781890986dc5360ed4b148b83836c029121d5f
|
[
"BSD-Source-Code"
] | 346
|
2016-02-16T11:17:25.000Z
|
2022-03-28T18:18:14.000Z
|
src/game/Strategic/QuestText.cc
|
FluffyQuack/ja2-stracciatella
|
59781890986dc5360ed4b148b83836c029121d5f
|
[
"BSD-Source-Code"
] | 1,119
|
2016-02-14T23:19:56.000Z
|
2022-03-31T21:57:58.000Z
|
src/game/Strategic/QuestText.cc
|
FluffyQuack/ja2-stracciatella
|
59781890986dc5360ed4b148b83836c029121d5f
|
[
"BSD-Source-Code"
] | 90
|
2016-02-17T22:17:11.000Z
|
2022-03-12T11:59:56.000Z
|
#include "Types.h"
#include "QuestText.h"
#include "Quests.h"
const ST::string QuestDescText[] =
{
"Deliver Letter",
"Food Route",
"Terrorists",
"Kingpin Chalice",
"Kingpin Money",
"Runaway Joey",
"Rescue Maria",
"Chitzena Chalice",
"Held in Alma",
"Interogation",
"Hillbilly Problem", //10
"Find Scientist",
"Deliver Video Camera",
"Blood Cats",
"Find Hermit",
"Creatures",
"Find Chopper Pilot",
"Escort SkyRider",
"Free Dynamo",
"Escort Tourists",
"Doreen", //20
"Leather Shop Dream",
"Escort Shank",
"No 23 Yet",
"No 24 Yet",
"Kill Deidranna",
"No 26 Yet",
"No 27 Yet",
"No 28 Yet",
"No 29 Yet",
};
const ST::string FactDescText[] =
{
"Omerta Liberated",
"Drassen Liberated",
"Sanmona Liberated",
"Cambria Liberated",
"Alma Liberated",
"Grumm Liberated",
"Tixa Liberated",
"Chitzena Liberated",
"Estoni Liberated",
"Balime Liberated",
"Orta Liberated", //10
"Meduna Liberated",
"Pacos approched",
"Fatima Read note",
"Fatima Walked away from player",
"Dimitri (#60) is dead",
"Fatima responded to Dimitri's supprise",
"Carlo's exclaimed 'no one moves'",
"Fatima described note",
"Fatima arrives at final dest",
"Dimitri said Fatima has proof", //20
"Miguel overheard conversation",
"Miguel asked for letter",
"Miguel read note",
"Ira comment on Miguel reading note",
"Rebels are enemies",
"Fatima spoken to before given note",
"Start Drassen quest",
"Miguel offered Ira",
"Pacos hurt/Killed",
"Pacos is in A10", //30
"Current Sector is safe",
"Bobby R Shpmnt in transit",
"Bobby R Shpmnt in Drassen",
"33 is TRUE and it arrived within 2 hours",
"33 is TRUE 34 is false more then 2 hours",
"Player has realized part of shipment is missing",
"36 is TRUE and Pablo was injured by player",
"Pablo admitted theft",
"Pablo returned goods, set 37 false",
"Miguel will join team", //40
"Gave some cash to Pablo",
"Skyrider is currently under escort",
"Skyrider is close to his chopper in Drassen",
"Skyrider explained deal",
"Player has clicked on Heli in Mapscreen at least once",
"NPC is owed money",
"Npc is wounded",
"Npc was wounded by Player",
"Father J.Walker was told of food shortage",
"Ira is not in sector", //50
"Ira is doing the talking",
"Food quest over",
"Pablo stole something from last shpmnt",
"Last shipment crashed",
"Last shipment went to wrong airport",
"24 hours elapsed since notified that shpment went to wrong airport",
"Lost package arrived with damaged goods. 56 to False",
"Lost package is lost permanently. Turn 56 False",
"Next package can (random) be lost",
"Next package can(random) be delayed", //60
"Package is medium sized",
"Package is largesized",
"Doreen has conscience",
"Player Spoke to Gordon",
"Ira is still npc and in A10-2(hasnt joined)",
"Dynamo asked for first aid",
"Dynamo can be recruited",
"Npc is bleeding",
"Shank wnts to join",
"NPC is bleeding", //70
"Player Team has head & Carmen in San Mona",
"Player Team has head & Carmen in Cambria",
"Player Team has head & Carmen in Drassen",
"Father is drunk",
"Player has wounded mercs within 8 tiles of NPC",
"1 & only 1 merc wounded within 8 tiles of NPC",
"More then 1 wounded merc within 8 tiles of NPC",
"Brenda is in the store ",
"Brenda is Dead",
"Brenda is at home", //80
"NPC is an enemy",
"Speaker Strength >= 84 and < 3 males present",
"Speaker Strength >= 84 and at least 3 males present",
"Hans lets you see Tony",
"Hans is standing on 13523",
"Tony isnt available Today",
"Female is speaking to NPC",
"Player has enjoyed the Brothel",
"Carla is available",
"Cindy is available", //90
"Bambi is available",
"No girls is available",
"Player waited for girls",
"Player paid right amount of money",
"Mercs walked by goon",
"More thean 1 merc present within 3 tiles of NPC",
"At least 1 merc present withing 3 tiles of NPC",
"Kingping expectingh visit from player",
"Darren expecting money from player",
"Player within 5 tiles and NPC is visible", // 100
"Carmen is in San Mona",
"Player Spoke to Carmen",
"KingPin knows about stolen money",
"Player gave money back to KingPin",
"Frank was given the money ( not to buy booze )",
"Player was told about KingPin watching fights",
"Past club closing time and Darren warned Player. (reset every day)",
"Joey is EPC",
"Joey is in C5",
"Joey is within 5 tiles of Martha(109) in sector G8", //110
"Joey is Dead!",
"At least one player merc within 5 tiles of Martha",
"Spike is occuping tile 9817",
"Angel offered vest",
"Angel sold vest",
"Maria is EPC",
"Maria is EPC and inside leather Shop",
"Player wants to buy vest",
"Maria rescue was noticed by KingPin goons and Kingpin now enemy",
"Angel left deed on counter", //120
"Maria quest over",
"Player bandaged NPC today",
"Doreen revealed allegiance to Queen",
"Pablo should not steal from player",
"Player shipment arrived but loyalty to low, so it left",
"Helicopter is in working condition",
"Player is giving amount of money >= $1000",
"Player is giving amount less than $1000",
"Waldo agreed to fix helicopter( heli is damaged )",
"Helicopter was destroyed", //130
"Waldo told us about heli pilot",
"Father told us about Deidranna killing sick people",
"Father told us about Chivaldori family",
"Father told us about creatures",
"Loyalty is OK",
"Loyalty is Low",
"Loyalty is High",
"Player doing poorly",
"Player gave valid head to Carmen",
"Current sector is G9(Cambria)", //140
"Current sector is C5(SanMona)",
"Current sector is C13(Drassen",
"Carmen has at least $10,000 on him",
"Player has Slay on team for over 48 hours",
"Carmen is suspicous about slay",
"Slay is in current sector",
"Carmen gave us final warning",
"Vince has explained that he has to charge",
"Vince is expecting cash (reset everyday)",
"Player stole some medical supplies once", //150
"Player stole some medical supplies again",
"Vince can be recruited",
"Vince is currently doctoring",
"Vince was recruited",
"Slay offered deal",
"All terrorists killed",
"",
"Maria left in wrong sector",
"Skyrider left in wrong sector",
"Joey left in wrong sector", //160
"John left in wrong sector",
"Mary left in wrong sector",
"Walter was bribed",
"Shank(67) is part of squad but not speaker",
"Maddog spoken to",
"Jake told us about shank",
"Shank(67) is not in secotr",
"Bloodcat quest on for more than 2 days",
"Effective threat made to Armand",
"Queen is DEAD!", //170
"Speaker is with Aim or Aim person on squad within 10 tiles",
"Current mine is empty",
"Current mine is running out",
"Loyalty low in affiliated town (low mine production)",
"Creatures invaded current mine",
"Player LOST current mine",
"Current mine is at FULL production",
"Dynamo(66) is Speaker or within 10 tiles of speaker",
"Fred told us about creatures",
"Matt told us about creatures", //180
"Oswald told us about creatures",
"Calvin told us about creatures",
"Carl told us about creatures",
"Chalice stolen from museam",
"John(118) is EPC",
"Mary(119) and John (118) are EPC's",
"Mary(119) is alive",
"Mary(119)is EPC",
"Mary(119) is bleeding",
"John(118) is alive", //190
"John(118) is bleeding",
"John or Mary close to airport in Drassen(B13)",
"Mary is Dead",
"Miners placed",
"Krott planning to shoot player",
"Madlab explained his situation",
"Madlab expecting a firearm",
"Madlab expecting a video camera.",
"Item condition is < 70 ",
"Madlab complained about bad firearm.", //200
"Madlab complained about bad video camera.",
"Robot is ready to go!",
"First robot destroyed.",
"Madlab given a good camera.",
"Robot is ready to go a second time!",
"Second robot destroyed.",
"Mines explained to player.",
"Dynamo (#66) is in sector J9.",
"Dynamo (#66) is alive.",
"One PC hasn't fought, but is able, and less than 3 fights have occured", //210
"Player receiving mine income from Drassen, Cambria, Alma & Chitzena",
"Player has been to K4_b1",
"Brewster got to talk while Warden was alive",
"Warden (#103) is dead.",
"Ernest gave us the guns",
"This is the first bartender",
"This is the second bartender",
"This is the third bartender",
"This is the fourth bartender",
"Manny is a bartender.", //220
"Nothing is repaired yet (some stuff being worked on, nothing to give player right now)",
"Player made purchase from Howard (#125)",
"Dave sold vehicle",
"Dave's vehicle ready",
"Dave expecting cash for car",
"Dave has gas. (randomized daily)",
"Vehicle is present",
"First battle won by player",
"Robot recruited and moved",
"No club fighting allowed", //230
"Player already fought 3 fights today",
"Hans mentioned Joey",
"Player is doing better than 50% (Alex's function)",
"Player is doing very well (better than 80%)",
"Father is drunk and sci-fi option is on",
"Micky (#96) is drunk",
"Player has attempted to force their way into brothel",
"Rat effectively threatened 3 times",
"Player paid for two people to enter brothel",
"", //240
"",
"Player owns 2 towns including omerta",
"Player owns 3 towns including omerta",// 243
"Player owns 4 towns including omerta",// 244
"",
"",
"",
"Fact male speaking female present",
"Fact hicks married player merc",// 249
"Fact museum open",// 250
"Fact brothel open",// 251
"Fact club open",// 252
"Fact first battle fought",// 253
"Fact first battle being fought",// 254
"Fact kingpin introduced self",// 255
"Fact kingpin not in office",// 256
"Fact dont owe kingpin money",// 257
"Fact pc marrying daryl is flo",// 258
"",
"", //260
"Fact npc cowering", // 261,
"",
"",
"Fact top and bottom levels cleared",
"Fact top level cleared",// 265
"Fact bottom level cleared",// 266
"Fact need to speak nicely",// 267
"Fact attached item before",// 268
"Fact skyrider ever escorted",// 269
"Fact npc not under fire",// 270
"Fact willis heard about joey rescue",// 271
"Fact willis gives discount",// 272
"Fact hillbillies killed",// 273
"Fact keith out of business", // 274
"Fact mike available to army",// 275
"Fact kingpin can send assassins",// 276
"Fact estoni refuelling possible",// 277
"Fact museum alarm went off",// 278
"",
"Fact maddog is speaker", //280,
"",
"Fact angel mentioned deed", // 282,
"Fact iggy available to army",// 283
"Fact pc has conrads recruit opinion",// 284
"",
"",
"",
"",
"Fact npc hostile or pissed off", //289,
"", //290
"Fact tony in building", //291,
"Fact shank speaking", // 292,
"Fact doreen alive",// 293
"Fact waldo alive",// 294
"Fact perko alive",// 295
"Fact tony alive",// 296
"",
"Fact vince alive",// 298,
"Fact jenny alive",// 299
"", //300
"",
"Fact arnold alive",// 302,
"",
"Fact rocket rifle exists",// 304,
"",
"",
"",
"",
"",
"", //310
"",
"",
"",
"",
"",
"",
"",
"",
"",
"", //320
"",
"",
"",
"",
"",
"",
"",
"",
"",
"", //330
"",
"",
"",
"",
"",
"",
"",
"",
"",
"", //340
"",
"",
"",
"",
"",
"",
"",
"",
"",
"", //350
"",
"",
"",
"",
"",
"",
"",
"",
"",
"", //360
"",
"",
"",
"",
"",
"",
"",
"",
"",
"", //370
"",
"",
"",
"",
"",
"",
"",
"",
"",
"", //380
"",
"",
"",
"",
"",
"",
"",
"",
"",
"", //390
"",
"",
"",
"",
"",
"",
"",
"",
"",
"", //400
"",
"",
"",
"",
"",
"",
"",
"",
"",
"", //410
"",
"",
"",
"",
"",
"",
"",
"",
"",
"", //420
"",
"",
"",
"",
"",
"",
"",
"",
"",
"", //430
"",
"",
"",
"",
"",
"",
"",
"",
"",
"", //440
"",
"",
"",
"",
"",
"",
"",
"",
"",
"", //450
"",
"",
"",
"",
"",
"",
"",
"",
"",
"", //460
"",
"",
"",
"",
"",
"",
"",
"",
"",
"", //470
"",
"",
"",
"",
"",
"",
"",
"",
"",
"", //480
"",
"",
"",
"",
"",
"",
"",
"",
"",
"", //490
"",
"",
"",
"",
"",
"",
"",
"",
"",
"", //500
};
| 21.093333
| 90
| 0.591182
|
FluffyQuack
|
36d89906b5ba9e66ffcae5b71fc944eb4c5a5d4a
| 28,876
|
cpp
|
C++
|
third_party/occmapping/src/robustoctree.cpp
|
SRI-IPS/general-tools
|
b3113cbcf83c3a430c630d050d1b96e722dfb043
|
[
"BSD-3-Clause"
] | null | null | null |
third_party/occmapping/src/robustoctree.cpp
|
SRI-IPS/general-tools
|
b3113cbcf83c3a430c630d050d1b96e722dfb043
|
[
"BSD-3-Clause"
] | null | null | null |
third_party/occmapping/src/robustoctree.cpp
|
SRI-IPS/general-tools
|
b3113cbcf83c3a430c630d050d1b96e722dfb043
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright (c) 2013-2014, Konstantin Schauwecker
*
* This code is based on the original OctoMap implementation. The original
* copyright notice and source code license are as follows:
*
* Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg
* All rights reserved.
* License: New BSD
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the University of Freiburg nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <cmath>
#include <chrono>
#include <iostream>
#include <exception>
#include <list>
#include "robustoctree.h"
#define MODEL_Z_ERROR // remove this constant if depth error should not be modeled
// #define this to enable debugging the calcVisibilities() graph traversal logic.
#undef OCC_DEBUG_CALC_VISIBILITIES
#undef OCC_PROFILE_CALC_VISIBILITIES
#undef OCC_PROFILE_COMPUTE_UPDATE
#undef OCC_PROFILE_INSERT_POINT_CLOUD
namespace occmapping {
// A dummy value we use to represent the root key of a ray.
octomap::OcTreeKey RobustOcTree::ROOT_KEY(0xFFFF, 0xFFFF, 0xFFFF);
RobustOcTree::StaticMemberInitializer RobustOcTree::ocTreeMemberInit;
RobustOcTree::RobustOcTree() : Base(RobustOcTreeParameters().octreeResolution) {
initFromParameters();
}
RobustOcTree::RobustOcTree(const RobustOcTreeParameters& parameters)
: Base(parameters.octreeResolution), parameters(parameters) {
initFromParameters();
}
RobustOcTree::~RobustOcTree() { delete lookup; }
void RobustOcTree::initFromParameters() {
// We keep the inverse probabilities too
probMissIfOccupied = 1.0 - parameters.probHitIfOccupied;
probMissIfNotOccupied = 1.0 - parameters.probHitIfNotOccupied;
probMissIfNotVisible = 1.0 - parameters.probHitIfNotVisible;
// Convert minimum and maximum height to octree keys
octomap::OcTreeKey key;
if (!coordToKeyChecked(0, 0, parameters.minHeight, key))
minZKey = 0;
else
minZKey = key[2];
if (!coordToKeyChecked(0, 0, parameters.maxHeight, key))
maxZKey = 0xFFFF;
else
maxZKey = key[2];
// Generate probability look-up table.
// Some parameters are hard coded here, but you propability don't want to change them anyway.
lookup = new ProbabilityLookup(parameters.octreeResolution, parameters.depthErrorResolution, 0.1,
parameters.maxRange, 0, 1, 0.05, parameters.depthErrorScale);
// Hopefully makes accesses to the hash faster
voxelUpdateCache.max_load_factor(0.75);
voxelUpdateCache.rehash(1000);
}
void RobustOcTree::insertPointCloud(const octomap::Pointcloud& scan,
const octomap::point3d& sensor_origin,
const octomap::point3d& forwardVec, bool lazy_eval) {
#ifdef OCC_PROFILE_INSERT_POINT_CLOUD
static auto max_calc_vis_t = 0;
static auto calc_vis_t_sum = 0;
static auto calc_vis_count = 0;
++calc_vis_count;
auto t0 = std::chrono::high_resolution_clock::now();
#endif
// Do ray casting stuff
computeUpdate(scan, sensor_origin, forwardVec);
#ifdef OCC_PROFILE_INSERT_POINT_CLOUD
auto t1 = std::chrono::high_resolution_clock::now();
#endif
// Calculate a visibility for all voxels that will be updated
calcVisibilities(sensor_origin);
#ifdef OCC_PROFILE_INSERT_POINT_CLOUD
auto t2 = std::chrono::high_resolution_clock::now();
auto calc_vis_t = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count();
calc_vis_t_sum += calc_vis_t;
if (calc_vis_t > max_calc_vis_t) {
max_calc_vis_t = calc_vis_t;
}
#endif
// Perform update
for (OccPrevKeySet::iterator it = voxelUpdateCache.begin(); it != voxelUpdateCache.end(); it++) {
float visibility = visibilities[it->key];
if (visibility >= parameters.visibilityClampingMin)
updateNode(it->key, visibility, it->occupancy, lazy_eval);
}
#ifdef OCC_PROFILE_INSERT_POINT_CLOUD
auto t3 = std::chrono::high_resolution_clock::now();
std::cerr << "InsertPointCloud: computeUpdate: "
<< std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0).count()
<< " ms, calcVisibilities: " << calc_vis_t << " ms (max: " << max_calc_vis_t
<< " ms, avg: " << calc_vis_t_sum / calc_vis_count << " ms),"
<< " updateNode(s): "
<< std::chrono::duration_cast<std::chrono::milliseconds>(t3 - t2).count() << " ms"
<< std::endl;
#endif
}
void RobustOcTree::calcKeyVisibility(const OccPrevKey& key, const octomap::OcTreeKey& originKey) {
KeyVisMap::iterator visIter = visibilities.find(key.prevKey);
if (visIter == visibilities.end()) {
assert(false && "visIter not found");
OCTOMAP_WARNING_STR("visIter not found!!!");
return;
}
// Find occupancies for the three neighbor nodes bordering
// the visible faces
octomap::OcTreeKey currKey = key.key;
int step[3] = {currKey[0] > originKey[0] ? 1 : -1, currKey[1] > originKey[1] ? 1 : -1,
currKey[2] > originKey[2] ? 1 : -1};
octomap::OcTreeKey neighborKeys[3] = {
octomap::OcTreeKey(currKey[0] - step[0], currKey[1], currKey[2]),
octomap::OcTreeKey(currKey[0], currKey[1] - step[1], currKey[2]),
octomap::OcTreeKey(currKey[0], currKey[1], currKey[2] - step[2])};
float occupancies[3] = {0.5F, 0.5F, 0.5F};
for (unsigned int i = 0; i < 3; i++) {
RobustOcTreeNode* neighborNode = search(neighborKeys[i]);
if (neighborNode != NULL) {
occupancies[i] = neighborNode->getOccupancy();
if (occupancies[i] <= parameters.clampingThresholdMin) occupancies[i] = 0;
}
}
// Get the probabilities that the current voxel is occluded by its neighbors
float occlusionProb = std::min(occupancies[0], std::min(occupancies[1], occupancies[2]));
float visibility =
visIter->second * (parameters.probVisibleIfOccluded * occlusionProb +
parameters.probVisibleIfNotOccluded * (1.0F - occlusionProb));
// clamp visibility
if (visibility > parameters.visibilityClampingMax) visibility = 1.0F;
visibilities[currKey] = visibility;
}
void RobustOcTree::calcVisibilities(const octomap::point3d& sensor_origin) {
#ifdef OCC_PROFILE_CALC_VISIBILITIES
auto voxel_update_cache_size = voxelUpdateCache.size();
#endif
#ifdef OCC_DEBUG_CALC_VISIBILITIES
std::cerr << "voxelUpdateCache size: " << voxelUpdateCache.size() << std::endl;
#endif
// Find the origin key
octomap::OcTreeKey originKey;
if (!coordToKeyChecked(sensor_origin, originKey)) {
OCTOMAP_WARNING_STR("origin coordinates ( " << sensor_origin
<< ") out of bounds in calcVisibilities");
return;
}
visibilities.clear();
visibilities[ROOT_KEY] = 1.0;
keyGraph.clear();
#ifdef OCC_PROFILE_CALC_VISIBILITIES
auto t0 = std::chrono::high_resolution_clock::now();
#endif
// Stores the parent's iterator and the child iterator that is currently being processed.
auto parentStack = std::stack<
std::pair<KeyGraphMap::iterator, std::list<const OccPrevKey *>::iterator>>{};
auto visitedKeys = std::unordered_set<octomap::OcTreeKey, octomap::OcTreeKey::KeyHash>{};
for (const auto& cacheKey : voxelUpdateCache) {
keyGraph[cacheKey.prevKey].push_back(&cacheKey);
}
#ifdef OCC_PROFILE_CALC_VISIBILITIES
auto t1 = std::chrono::high_resolution_clock::now();
auto create_key_graph_t = std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0).count();
#endif
#ifdef OCC_PROFILE_CALC_VISIBILITIES
auto key_graph_size = keyGraph.size();
#endif
#ifdef OCC_DEBUG_CALC_VISIBILITIES
std::cerr << "keyGraph size: " << keyGraph.size() << std::endl;
#endif
#ifdef OCC_PROFILE_CALC_VISIBILITIES
auto calc_key_visibilities_count = 0;
auto calc_key_visibilities_t_sum = 0;
t0 = std::chrono::high_resolution_clock::now();
#endif
auto currNode = keyGraph.find(ROOT_KEY);
if (currNode == keyGraph.end()) {
OCTOMAP_WARNING_STR("Empty key graph in calcVisibilities");
return;
}
visitedKeys.insert(currNode->first);
auto childIt = currNode->second.begin();
while (true) {
if (childIt == currNode->second.end()) {
if (parentStack.empty()) {
// We are done!
break;
}
#ifdef OCC_DEBUG_CALC_VISIBILITIES
std::cerr << "Leaving child " << *childIt << std::endl;
#endif
// Advance to the next child of the parent.
currNode = parentStack.top().first;
childIt = parentStack.top().second;
parentStack.pop();
++childIt;
continue;
}
#ifdef OCC_DEBUG_CALC_VISIBILITIES
std::cerr << "Updating visibility for child " << *childIt << std::endl;
#endif
#ifdef OCC_PROFILE_CALC_VISIBILITIES
++calc_key_visibilities_count;
auto calc_key_visibility_t0 = std::chrono::high_resolution_clock::now();
#endif
calcKeyVisibility(**childIt, originKey);
#ifdef OCC_PROFILE_CALC_VISIBILITIES
auto calc_key_visibility_t1 = std::chrono::high_resolution_clock::now();
calc_key_visibilities_t_sum += std::chrono::duration_cast<std::chrono::nanoseconds>(
calc_key_visibility_t1 - calc_key_visibility_t0)
.count();
#endif
auto childNode = keyGraph.find((*childIt)->key);
if (childNode == keyGraph.end()) {
// This child has no sub-children to recurse to, so just advance to the next child.
++childIt;
#ifdef OCC_DEBUG_CALC_VISIBILITIES
std::cerr << "Child has no children, advancing to child " << *childIt << std::endl;
#endif
continue;
}
if (visitedKeys.count(childNode->first)) {
// TODO(kgreenek): Verify whether this can actually happen.
assert(false && "Cycle detected in key graph");
OCTOMAP_WARNING_STR("Cycle detected in key graph");
++childIt;
continue;
}
#ifdef OCC_DEBUG_CALC_VISIBILITIES
std::cerr << "Recursing into child " << *childIt << std::endl;
#endif
// Recurse down into the childNode.
parentStack.push({currNode, childIt});
currNode = childNode;
visitedKeys.insert(currNode->first);
childIt = currNode->second.begin();
}
#ifdef OCC_PROFILE_CALC_VISIBILITIES
t1 = std::chrono::high_resolution_clock::now();
auto key_graph_traversal_t =
std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0).count();
std::cerr << "calcVisibilities:\n"
<< " voxelUpdateCache size: " << voxel_update_cache_size << "\n"
<< " keyGraph size: " << key_graph_size << ", create_t: " << create_key_graph_t
<< " ms\n"
<< " key_graph_traversal_t: " << key_graph_traversal_t << "\n"
<< " calcKeyVisibility: count: " << calc_key_visibilities_count
<< ", total_t: " << calc_key_visibilities_t_sum / 1000000
<< " ms, avg_t: " << calc_key_visibilities_t_sum / calc_key_visibilities_count / 1000
<< " us" << std::endl;
#endif
}
void RobustOcTree::insertPointCloud(const octomap::Pointcloud& pc,
const octomap::point3d& sensor_origin,
const octomap::pose6d& frame_origin, bool lazy_eval) {
// performs transformation to data and sensor origin first
octomap::Pointcloud transformed_scan(pc);
transformed_scan.transform(frame_origin);
octomap::point3d transformed_sensor_origin = frame_origin.transform(sensor_origin);
octomap::point3d forwardVec =
frame_origin.transform(sensor_origin + octomap::point3d(0, 1.0, 0.0)) -
transformed_sensor_origin;
// Process transformed point cloud
insertPointCloud(transformed_scan, transformed_sensor_origin, forwardVec, lazy_eval);
}
void RobustOcTree::computeUpdate(const octomap::Pointcloud& scan, const octomap::point3d& origin,
const octomap::point3d& forwardVec) {
voxelUpdateCache.clear();
prevKeyray.reset();
#ifdef OCC_PROFILE_COMPUTE_UPDATE
auto compute_ray_keys_sum = 0;
auto compute_ray_keys_count = 0;
auto update_cache_sum = 0;
auto update_cache_count = 0;
#endif
for (int i = 0; i < (int)scan.size(); ++i) {
// Compute a new ray
const octomap::point3d& p = scan[i];
#ifdef OCC_PROFILE_COMPUTE_UPDATE
auto t0 = std::chrono::high_resolution_clock::now();
#endif
computeRayKeys(origin, p, forwardVec);
#ifdef OCC_PROFILE_COMPUTE_UPDATE
auto t1 = std::chrono::high_resolution_clock::now();
compute_ray_keys_sum += std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0).count();
++compute_ray_keys_count;
#endif
// Insert cells into the update cache if they haven't been
// part of a previous ray, or if their occupancy is higher than
// for any previous ray.
// First perform lookup against previous ray
OccPrevKeyRay::iterator currIt = keyray.begin();
OccPrevKeyRay::iterator currEnd =
prevKeyray.size() > keyray.size() ? keyray.end() : keyray.begin() + prevKeyray.size();
for (OccPrevKeyRay::iterator prevIt = prevKeyray.begin(); currIt != currEnd;
currIt++, prevIt++) {
if (currIt->key == prevIt->key) {
// Cell already exists in previous ray
if (currIt->occupancy > prevIt->occupancy) {
OccPrevKeySet::iterator updateIter = voxelUpdateCache.find(*currIt);
OccPrevKeySet::iterator insertHint = voxelUpdateCache.erase(updateIter);
voxelUpdateCache.insert(insertHint, *currIt);
} else {
currIt->occupancy = prevIt->occupancy; // Keep best occupancy for next ray
}
} else {
// Perform full lookup against hash map
OccPrevKeySet::iterator updateIter = voxelUpdateCache.find(*currIt);
if (updateIter == voxelUpdateCache.end()) {
voxelUpdateCache.insert(*currIt);
} else if (currIt->occupancy > updateIter->occupancy) {
OccPrevKeySet::iterator insertHint = voxelUpdateCache.erase(updateIter);
voxelUpdateCache.insert(insertHint, *currIt);
} else {
currIt->occupancy = updateIter->occupancy; // Keep best occupancy for next ray
}
}
}
#ifdef OCC_PROFILE_COMPUTE_UPDATE
auto t2 = std::chrono::high_resolution_clock::now();
#endif
// Lookup remaining cells against hash map
for (; currIt != keyray.end(); currIt++) {
OccPrevKeySet::iterator updateIter = voxelUpdateCache.find(*currIt);
if (updateIter == voxelUpdateCache.end()) {
voxelUpdateCache.insert(*currIt);
} else if (currIt->occupancy > updateIter->occupancy) {
OccPrevKeySet::iterator insertHint = voxelUpdateCache.erase(updateIter);
voxelUpdateCache.insert(insertHint, *currIt);
} else {
currIt->occupancy = updateIter->occupancy; // Keep best occupancy for next ray
}
}
#ifdef OCC_PROFILE_COMPUTE_UPDATE
auto t3 = std::chrono::high_resolution_clock::now();
update_cache_sum += std::chrono::duration_cast<std::chrono::nanoseconds>(t3 - t2).count();
++update_cache_count;
#endif
keyray.swap(prevKeyray);
}
#ifdef OCC_PROFILE_COMPUTE_UPDATE
std::cerr << "computeUpdate: computeRayKeys: " << compute_ray_keys_sum / 1000000
<< " ms, voxelUpdateCache: " << update_cache_sum / 1000000 << " ms"
<< std::endl;
#endif
}
void RobustOcTree::computeRayKeys(const octomap::point3d& origin, const octomap::point3d& end,
const octomap::point3d& forwardVec) {
// see "A Faster Voxel Traversal Algorithm for Ray Tracing" by Amanatides & Woo
// basically: DDA in 3D
keyray.reset();
octomap::point3d direction = (end - origin);
double length = direction.norm();
direction /= length; // normalize vector
octomap::OcTreeKey key_origin, key_end;
if (!coordToKeyChecked(origin, key_origin)) {
OCTOMAP_WARNING_STR("origin coordinates ( " << origin << " -> " << end
<< ") out of bounds in computeRayKeys");
return;
}
if (!coordToKeyChecked(end, key_end) &&
!coordToKeyChecked(origin + direction * (2.0 * parameters.maxRange), key_end)) {
OCTOMAP_WARNING_STR("end coordinates ( " << origin << " -> " << end
<< ") out of bounds in computeRayKeys");
return;
}
// Initialization phase -------------------------------------------------------
int step[3];
double tMax[3];
double tDelta[3];
octomap::OcTreeKey prev_key = ROOT_KEY;
octomap::OcTreeKey current_key = key_origin;
for (unsigned int i = 0; i < 3; ++i) {
// compute step direction
if (direction(i) > 0.0)
step[i] = 1;
else if (direction(i) < 0.0)
step[i] = -1;
else
step[i] = 0;
// compute tMax, tDelta
if (step[i] != 0) {
// corner point of voxel (in direction of ray)
double voxelBorder = keyToCoord(current_key[i]);
voxelBorder += step[i] * resolution * 0.5;
tMax[i] = (voxelBorder - origin(i)) / direction(i);
tDelta[i] = this->resolution / fabs(direction(i));
} else {
tMax[i] = std::numeric_limits<double>::max();
tDelta[i] = std::numeric_limits<double>::max();
}
}
// for speedup:
octomap::point3d origin_scaled = origin;
origin_scaled /= resolution;
double length_to_key = (keyToCoord(key_end) - origin).norm();
double length_scaled = (std::min(length_to_key, parameters.maxRange)) / resolution;
length_scaled = length_scaled * length_scaled;
double maxrange_scaled = parameters.maxRange / resolution;
maxrange_scaled *= maxrange_scaled;
// Conversion factor from length to depth (length of one z-step)
double lengthToDepth = forwardVec.x() * direction.x() + forwardVec.y() * direction.y() +
forwardVec.z() * forwardVec.z();
double depth = length / lengthToDepth;
double probApproxMaxDistScaled, probApproxMaxDist;
std::vector<float>* lookupEntry = lookup->lookupEntry(depth);
if (lookupEntry == NULL) {
probApproxMaxDist = std::numeric_limits<double>::max();
probApproxMaxDistScaled = maxrange_scaled;
} else {
probApproxMaxDist =
lengthToDepth * (depth - (lookupEntry->size() / 2.0) * parameters.depthErrorResolution);
probApproxMaxDistScaled = probApproxMaxDist / resolution;
probApproxMaxDistScaled =
std::min(probApproxMaxDistScaled * probApproxMaxDistScaled, maxrange_scaled);
}
double treeMax05 = tree_max_val - 0.5F;
// Incremental phase ---------------------------------------------------------
unsigned int dim = 0;
double squareDistFromOrigVec[3] = {(current_key[0] - treeMax05 - origin_scaled(0)) *
(current_key[0] - treeMax05 - origin_scaled(0)),
(current_key[1] - treeMax05 - origin_scaled(1)) *
(current_key[1] - treeMax05 - origin_scaled(1)),
(current_key[2] - treeMax05 - origin_scaled(2)) *
(current_key[2] - treeMax05 - origin_scaled(2))};
while (true) {
// Calculate distance from origin
double squareDistFromOrig =
squareDistFromOrigVec[0] + squareDistFromOrigVec[1] + squareDistFromOrigVec[2];
#ifdef MODEL_Z_ERROR
if (squareDistFromOrig < probApproxMaxDistScaled) {
// Use approximate probabilities
keyray.addOccPrevKey(0.0, current_key, prev_key);
} else if (squareDistFromOrig >= maxrange_scaled) {
// The point is too far away. Lets stop.
break;
} else {
// Detailed calculation
int index = int((sqrt(squareDistFromOrig) * resolution - probApproxMaxDist) /
(parameters.depthErrorResolution * lengthToDepth) +
0.5);
double occupancyFactor = 1.0;
bool done = false;
if (index >= (int)lookupEntry->size()) {
done = true;
// Continue to make sure we integrate one full hit
} else {
occupancyFactor = (*lookupEntry)[index];
}
keyray.addOccPrevKey(occupancyFactor, current_key, prev_key);
if (done) break;
}
#else
// reached endpoint?
if (current_key == key_end) {
keyray.addOccPrevKey(1.0, current_key, prev_key);
break;
} else if (squareDistFromOrig >= length_scaled) {
// We missed it :-(
if (length_to_key < parameters.maxRange) keyray.addOccPrevKey(1.0, key_end, prev_key);
break;
} else {
keyray.addOccPrevKey(0.0, current_key, prev_key);
}
#endif
// find minimum tMax:
if (tMax[0] < tMax[1]) {
if (tMax[0] < tMax[2])
dim = 0;
else
dim = 2;
} else {
if (tMax[1] < tMax[2])
dim = 1;
else
dim = 2;
}
// advance in direction "dim"
prev_key = current_key;
current_key[dim] += step[dim];
tMax[dim] += tDelta[dim];
squareDistFromOrigVec[dim] = current_key[dim] - treeMax05 - origin_scaled(dim);
squareDistFromOrigVec[dim] *= squareDistFromOrigVec[dim];
assert(current_key[dim] < 2 * this->tree_max_val);
if (current_key[2] < minZKey || current_key[2] > maxZKey) break; // Exceeded min or max height
// TODO(kgreenek): Re-enable this assert once a17hq/a17#150 is fixed. This assert is being
// triggered for some datasets, when it shouldn't be.
#if 0
assert(keyray.size() < keyray.sizeMax() - 1);
#else
if (keyray.size() >= keyray.sizeMax() - 1) {
std::cerr << "WARNING: keyraw.size >= keyraw.sizeMax(). Skipping scan..." << std::endl;
break;
}
#endif
}
}
RobustOcTreeNode* RobustOcTree::updateNode(const octomap::OcTreeKey& key, float visibility,
float occupancy, bool lazy_eval) {
// early abort (no change will happen).
// may cause an overhead in some configuration, but more often helps
RobustOcTreeNode* leaf = this->search(key);
// no change: node already at minimum threshold
if (leaf != NULL && occupancy == 0.0F && leaf->getOccupancy() <= parameters.clampingThresholdMin)
return leaf;
bool createdRoot = false;
if (this->root == NULL) {
this->root = new RobustOcTreeNode();
this->tree_size++;
createdRoot = true;
}
return updateNodeRecurs(this->root, visibility, createdRoot, key, 0, occupancy, lazy_eval);
}
RobustOcTreeNode* RobustOcTree::updateNodeRecurs(RobustOcTreeNode* node, float visibility,
bool node_just_created,
const octomap::OcTreeKey& key, unsigned int depth,
float occupancy, bool lazy_eval) {
// Differences to OccupancyOcTreeBase implementation: only cosmetic
unsigned int pos = computeChildIdx(key, this->tree_depth - 1 - depth);
bool created_node = false;
assert(node);
// follow down to last level
if (depth < this->tree_depth) {
if (!nodeChildExists(node, pos)) {
// child does not exist, but maybe it's a pruned node?
if ((!nodeHasChildren(node)) && !node_just_created) {
// current node does not have children AND it is not a new node
// -> expand pruned node
expandNode(node);
this->tree_size += 8;
this->size_changed = true;
} else {
// not a pruned node, create requested child
createNodeChild(node, pos);
this->tree_size++;
this->size_changed = true;
created_node = true;
}
}
if (lazy_eval)
return updateNodeRecurs(getNodeChild(node, pos), visibility, created_node, key, depth + 1,
occupancy, lazy_eval);
else {
RobustOcTreeNode* retval = updateNodeRecurs(getNodeChild(node, pos), visibility, created_node,
key, depth + 1, occupancy, lazy_eval);
// prune node if possible, otherwise set own probability
// note: combining both did not lead to a speedup!
if (pruneNode(node))
this->tree_size -= 8;
else
node->updateOccupancyChildren();
return retval;
}
}
// at last level, update node, end of recursion
else {
if (use_change_detection) {
bool occBefore = this->isNodeOccupied(node);
updateNodeOccupancy(node, visibility, occupancy);
if (node_just_created) { // new node
changed_keys.insert(std::pair<octomap::OcTreeKey, bool>(key, true));
} else if (occBefore != this->isNodeOccupied(node)) { // occupancy changed, track it
auto it = changed_keys.find(key);
if (it == changed_keys.end()) {
changed_keys.insert(std::pair<octomap::OcTreeKey, bool>(key, false));
} else if (it->second == false) {
// This happens when the value changes back to what it was, so we can just remove it,
// because it has no longer changed since the last time changed_keys was cleared.
changed_keys.erase(it);
}
}
} else {
updateNodeOccupancy(node, visibility, occupancy);
}
return node;
}
}
void RobustOcTree::updateNodeOccupancy(RobustOcTreeNode* occupancyNode, float probVisible,
float occupancy) {
float probOccupied = occupancyNode->getOccupancy();
// Decide which update procedure to perform
if (occupancy == 0.0F) {
// Perform update for certainly free voxels
float probMiss = calcOccupiedProbability(probOccupied, probVisible, probMissIfOccupied,
probMissIfNotOccupied, probMissIfNotVisible);
occupancyNode->setOccupancy(
probMiss > parameters.clampingThresholdMin ? probMiss : parameters.clampingThresholdMin);
} else {
float probHit =
calcOccupiedProbability(probOccupied, probVisible, parameters.probHitIfOccupied,
parameters.probHitIfNotOccupied, parameters.probHitIfNotVisible);
if (occupancy == 1.0F) {
// Perform update for certainly occupied voxels
occupancyNode->setOccupancy(
probHit < parameters.clampingThresholdMax ? probHit : parameters.clampingThresholdMax);
} else {
// We are not certain, but we know the occupancy probability.
// Lets interpolate between the update for free and occupied voxels.
float probMiss =
calcOccupiedProbability(probOccupied, probVisible, probMissIfOccupied,
probMissIfNotOccupied, parameters.probHitIfNotVisible);
occupancyNode->setOccupancy(occupancy * probHit + (1.0F - occupancy) * probMiss);
// Perform probability clamping
if (occupancyNode->getOccupancy() < parameters.clampingThresholdMin)
occupancyNode->setOccupancy(parameters.clampingThresholdMin);
else if (occupancyNode->getOccupancy() > parameters.clampingThresholdMax)
occupancyNode->setOccupancy(parameters.clampingThresholdMax);
}
}
}
float RobustOcTree::calcOccupiedProbability(float probOccupied, float probVisible,
float probMeasIfOccupied, float probMeasIfNotOccupied,
float probMeasNotVisible) {
// This is our update equation. See our paper for a derivation of this formula (Eq. 4 - 6).
return (probMeasIfOccupied * probVisible * probOccupied +
probMeasNotVisible * (1.0F - probVisible) * probOccupied) /
(probMeasIfOccupied * probVisible * probOccupied +
probMeasIfNotOccupied * probVisible * (1.0F - probOccupied) +
probMeasNotVisible * (1.0F - probVisible));
}
} // namespace occmapping
| 38.968961
| 100
| 0.659717
|
SRI-IPS
|
36d964a0571b9bdec37447907b20634637c26a4f
| 862
|
cpp
|
C++
|
cse419/CodeForces/349A/22273399_AC_218ms_8kB.cpp
|
cosmicray001/academic
|
6aa142baeba4bb1ad73b8669e37305ca0b5102a7
|
[
"MIT"
] | 2
|
2020-09-02T12:07:47.000Z
|
2020-11-17T11:17:16.000Z
|
cse419/CodeForces/349A/22273399_AC_218ms_8kB.cpp
|
cosmicray001/academic
|
6aa142baeba4bb1ad73b8669e37305ca0b5102a7
|
[
"MIT"
] | null | null | null |
cse419/CodeForces/349A/22273399_AC_218ms_8kB.cpp
|
cosmicray001/academic
|
6aa142baeba4bb1ad73b8669e37305ca0b5102a7
|
[
"MIT"
] | 4
|
2020-08-11T14:23:34.000Z
|
2020-11-17T10:52:31.000Z
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
map<int,int>t;
bool check = true;
int n,v;
cin>>n;
for(int i=0;i<n;i++){
cin>>v;
if(v==100){
if(t[50]>=1 && t[25]>=1){
t[50]--;
t[25]--;
}
else if(t[25]>=3){
t[25]-=3;
}
else{
cout<<"NO"<<endl;
check=false;
break;
}
}
else if(v==50){
if(t[25]>=1){
t[50]++;
t[25]--;
}
else{
cout<<"NO"<<"\n";
check=false;
break;
}
}
else{
t[25]++;
}
}
if(check){
cout<<"YES"<<endl;
}
return 0;
}
| 18.73913
| 37
| 0.267981
|
cosmicray001
|
36dfd3e497e94478162e3edbe06481d562332f35
| 4,189
|
cpp
|
C++
|
src/ui/VKUMainForm.cpp
|
igorglotov/tizen-vk-client
|
de213ede7185818285f78abad36592bc864f76cc
|
[
"Unlicense"
] | null | null | null |
src/ui/VKUMainForm.cpp
|
igorglotov/tizen-vk-client
|
de213ede7185818285f78abad36592bc864f76cc
|
[
"Unlicense"
] | null | null | null |
src/ui/VKUMainForm.cpp
|
igorglotov/tizen-vk-client
|
de213ede7185818285f78abad36592bc864f76cc
|
[
"Unlicense"
] | null | null | null |
#include "VKUMainForm.h"
#include "AppResourceId.h"
#include "SceneRegister.h"
#include "VKUColors.h"
#include "VKUContactsPanel.h"
#include "VKUApi.h"
#include "JsonParseUtils.h"
#include "ObjectCounter.h"
using namespace Tizen::Base;
using namespace Tizen::App;
using namespace Tizen::Ui;
using namespace Tizen::Ui::Controls;
using namespace Tizen::Ui::Scenes;
using namespace Tizen::Graphics;
using namespace Tizen::Web::Json;
VKUMainForm::VKUMainForm(void) {
CONSTRUCT(L"VKUMainForm");
}
VKUMainForm::~VKUMainForm(void) {
DESTRUCT(L"VKUMainForm");
}
bool VKUMainForm::Initialize(void) {
Construct(IDF_MAIN);
return true;
}
result VKUMainForm::OnInitializing(void) {
result r = E_SUCCESS;
Color headerColor(HEADER_BG_COLOR, false);
// TODO:
// Add your initialization code here
Header* pHeader = GetHeader();
if (pHeader) {
pHeader->AddActionEventListener(*this);
pHeader->SetColor(headerColor);
}
// Setup back event listener
SetFormBackEventListener(this);
return r;
}
result VKUMainForm::OnTerminating(void) {
result r = E_SUCCESS;
// TODO:
// Add your termination code here
return r;
}
void VKUMainForm::OnActionPerformed(const Tizen::Ui::Control& source,
int actionId) {
SceneManager* pSceneManager = SceneManager::GetInstance();
AppAssert(pSceneManager);
UpdateCounters();
switch (actionId) {
case ID_HEADER_MESSAGES:
pSceneManager->GoForward(ForwardSceneTransition(SCENE_MAIN_DIALOGS));
break;
case ID_HEADER_CONTACTS:
pSceneManager->GoForward(ForwardSceneTransition(SCENE_MAIN_CONTACTS));
break;
case ID_HEADER_SEARCH:
pSceneManager->GoForward(ForwardSceneTransition(SCENE_MAIN_SEARCH));
break;
case ID_HEADER_SETTINGS:
pSceneManager->GoForward(ForwardSceneTransition(SCENE_MAIN_SETTINGS));
break;
default:
break;
}
}
void VKUMainForm::OnFormBackRequested(Tizen::Ui::Controls::Form& source) {
AppLog("Back requested. Finishing app");
UiApp* pApp = UiApp::GetInstance();
AppAssert(pApp);
pApp->Terminate();
}
void VKUMainForm::OnSceneActivatedN(
const Tizen::Ui::Scenes::SceneId& previousSceneId,
const Tizen::Ui::Scenes::SceneId& currentSceneId,
Tizen::Base::Collection::IList* pArgs) {
// TODO: Add your implementation codes here
UpdateCounters();
}
void VKUMainForm::OnSceneDeactivated(
const Tizen::Ui::Scenes::SceneId& currentSceneId,
const Tizen::Ui::Scenes::SceneId& nextSceneId) {
// TODO: Add your implementation codes here
}
/*
void VKUMainForm::ClearContacts() {
//Frame* frame = VKUApp::GetInstance()->GetFrame(FRAME_NAME);
//Form* form = frame->GetCurrentForm();
//if (form->GetName() == IDF_MAIN) {
VKUContactsPanel* contactsPanel = static_cast<VKUContactsPanel*>(GetControl(IDC_PANEL_CONTACTS));
if (contactsPanel != null) {
contactsPanel->ClearItems();
}
//}
}
*/
void VKUMainForm::UpdateCounters() {
VKUApi::GetInstance().CreateRequest("account.getCounters", this)->Put(L"filter", L"messages,friends")->Submit(REQUEST_COUNTERS);
}
void VKUMainForm::OnResponseN(RequestId requestId, JsonObject *object) {
result r;
if(requestId != REQUEST_COUNTERS) {
return;
}
JsonObject *response;
int messages, friends;
Header *header = GetHeader();
r = JsonParseUtils::GetObject(object, L"response", response);
if(r != E_SUCCESS) { return; }
r = JsonParseUtils::GetInteger(*response, L"messages", messages);
if(r == E_SUCCESS) {
header->SetItemNumberedBadgeIcon(0, messages);
Tizen::Shell::NotificationRequest notificationBadge;
notificationBadge.SetBadgeNumber(messages);
Tizen::Shell::NotificationManager notificationManager;
notificationManager.Construct();
notificationManager.NotifyByAppId(L"iEl2RaVlnG.VKU", notificationBadge);
} else {
header->SetItemNumberedBadgeIcon(0, 0);
Tizen::Shell::NotificationRequest notificationBadge;
notificationBadge.SetBadgeNumber(0);
Tizen::Shell::NotificationManager notificationManager;
notificationManager.Construct();
notificationManager.NotifyByAppId(L"iEl2RaVlnG.VKU", notificationBadge);
}
r = JsonParseUtils::GetInteger(*response, L"friends", friends);
if(r == E_SUCCESS) {
header->SetItemNumberedBadgeIcon(2, friends);
} else {
header->SetItemNumberedBadgeIcon(2, 0);
}
}
| 25.387879
| 129
| 0.752208
|
igorglotov
|
36e1ba9d1e4a83cd1fdbe3e9dbda6d6a2ca76b1c
| 3,145
|
cpp
|
C++
|
Signal Flow Simulation/truetime-2.0/kernel/matlab/ttCreateTask.cpp
|
raulest50/MicroGrid_GITCoD
|
885001242c8e581a6998afb4be2ae1c0b923e9c4
|
[
"MIT"
] | 1
|
2019-08-31T08:06:48.000Z
|
2019-08-31T08:06:48.000Z
|
Signal Flow Simulation/truetime-2.0/kernel/matlab/ttCreateTask.cpp
|
raulest50/MicroGrid_GITCoD
|
885001242c8e581a6998afb4be2ae1c0b923e9c4
|
[
"MIT"
] | null | null | null |
Signal Flow Simulation/truetime-2.0/kernel/matlab/ttCreateTask.cpp
|
raulest50/MicroGrid_GITCoD
|
885001242c8e581a6998afb4be2ae1c0b923e9c4
|
[
"MIT"
] | 1
|
2020-01-07T10:46:23.000Z
|
2020-01-07T10:46:23.000Z
|
/*
* Copyright (c) 2016 Lund University
*
* Written by Anton Cervin, Dan Henriksson and Martin Ohlin,
* Department of Automatic Control LTH, Lund University, Sweden.
*
* This file is part of TrueTime 2.0.
*
* TrueTime 2.0 is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* TrueTime 2.0 is distributed in the hope that it will be useful, but
* without any warranty; without even the implied warranty of
* merchantability or fitness for a particular purpose. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with TrueTime 2.0. If not, see <http://www.gnu.org/licenses/>
*/
#define KERNEL_MATLAB
#include "../ttkernel.h"
#include "../createtask.cpp"
#include "getrtsys.cpp"
#include "../checkinputargs.cpp"
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[] )
{
rtsys = getrtsys() ; // Get pointer to rtsys
if (rtsys==NULL) {
return;
}
/* Check and parse input arguments */
char name[MAXCHARS];
double starttime;
double deadline;
char codeFcn[MAXCHARS];
const mxArray *data;
if (checkinputargs(nrhs,prhs,TT_STRING,TT_SCALAR,TT_STRING)) {
mxGetString(prhs[0], name, MAXCHARS);
deadline = *mxGetPr(prhs[1]);
mxGetString(prhs[2], codeFcn, MAXCHARS);
starttime = -1.0;
data = NULL;
} else if (checkinputargs(nrhs,prhs,TT_STRING,TT_SCALAR,TT_STRING,TT_STRUCT)) {
mxGetString(prhs[0], name, MAXCHARS);
deadline = *mxGetPr(prhs[1]);
mxGetString(prhs[2], codeFcn, MAXCHARS);
data = prhs[3];
starttime = -1.0;
} else if (checkinputargs(nrhs,prhs,TT_STRING,TT_SCALAR,TT_SCALAR,TT_STRING)) {
mxGetString(prhs[0], name, MAXCHARS);
starttime = *mxGetPr(prhs[1]);
deadline = *mxGetPr(prhs[2]);
mxGetString(prhs[3], codeFcn, MAXCHARS);
data = NULL;
} else if (checkinputargs(nrhs,prhs,TT_STRING,TT_SCALAR,TT_SCALAR,TT_STRING,TT_STRUCT)) {
mxGetString(prhs[0], name, MAXCHARS);
starttime = *mxGetPr(prhs[1]);
deadline = *mxGetPr(prhs[2]);
mxGetString(prhs[3], codeFcn, MAXCHARS);
data = prhs[4];
} else {
TT_MEX_ERROR("ttCreateTask: Wrong input arguments!\n"
"Usage: ttCreateTask(name, deadline, codeFcn)\n"
" ttCreateTask(name, deadline, codeFcn, data)\n"
" ttCreateTask(name, starttime, deadline, codeFcn)\n"
" ttCreateTask(name, starttime, deadline, codeFcn, data)");
return;
}
/* Check that the code function exists */
mxArray *lhs[1], *rhs[1];
rhs[0] = mxCreateString(codeFcn);
mexCallMATLAB(1, lhs, 1, rhs, "exist");
int number = (int) *mxGetPr(lhs[0]);
if (number != 2) {
char buf[MAXERRBUF];
sprintf(buf, "ttCreateTask: codeFcn '%s.m' not in path! Task '%s' not created!", codeFcn, name);
TT_MEX_ERROR(buf);
return;
}
ttCreateTaskMATLAB(name, starttime, -1.0, deadline, codeFcn, data);
}
| 29.392523
| 100
| 0.66868
|
raulest50
|
36e70d0faa5b99e46248dc857d0fba598422590b
| 1,764
|
cpp
|
C++
|
src/mbgl/shaders/collision_box.cpp
|
sp0n-7/mapbox-gl-native
|
0df37421faeaffb83564a81a469faa099434b767
|
[
"BSL-1.0",
"Apache-2.0"
] | 2
|
2018-11-28T21:38:52.000Z
|
2019-04-04T19:17:05.000Z
|
src/mbgl/shaders/collision_box.cpp
|
sp0n-7/mapbox-gl-native
|
0df37421faeaffb83564a81a469faa099434b767
|
[
"BSL-1.0",
"Apache-2.0"
] | null | null | null |
src/mbgl/shaders/collision_box.cpp
|
sp0n-7/mapbox-gl-native
|
0df37421faeaffb83564a81a469faa099434b767
|
[
"BSL-1.0",
"Apache-2.0"
] | 1
|
2020-12-26T06:09:50.000Z
|
2020-12-26T06:09:50.000Z
|
// NOTE: DO NOT CHANGE THIS FILE. IT IS AUTOMATICALLY GENERATED.
#include <mbgl/shaders/collision_box.hpp>
#include <mbgl/shaders/source.hpp>
namespace mbgl {
namespace shaders {
const char* collision_box::name = "collision_box";
const char* collision_box::vertexSource = source() + 14428;
const char* collision_box::fragmentSource = source() + 15252;
// Uncompressed source of collision_box.vertex.glsl:
/*
attribute vec2 a_pos;
attribute vec2 a_anchor_pos;
attribute vec2 a_extrude;
attribute vec2 a_placed;
uniform mat4 u_matrix;
uniform vec2 u_extrude_scale;
uniform float u_camera_to_center_distance;
varying float v_placed;
varying float v_notUsed;
void main() {
vec4 projectedPoint = u_matrix * vec4(a_anchor_pos, 0, 1);
highp float camera_to_anchor_distance = projectedPoint.w;
highp float collision_perspective_ratio = clamp(
0.5 + 0.5 * (u_camera_to_center_distance / camera_to_anchor_distance),
0.0, // Prevents oversized near-field boxes in pitched/overzoomed tiles
4.0);
gl_Position = u_matrix * vec4(a_pos, 0.0, 1.0);
gl_Position.xy += a_extrude * u_extrude_scale * gl_Position.w * collision_perspective_ratio;
v_placed = a_placed.x;
v_notUsed = a_placed.y;
}
*/
// Uncompressed source of collision_box.fragment.glsl:
/*
varying float v_placed;
varying float v_notUsed;
void main() {
float alpha = 0.5;
// Red = collision, hide label
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0) * alpha;
// Blue = no collision, label is showing
if (v_placed > 0.5) {
gl_FragColor = vec4(0.0, 0.0, 1.0, 0.5) * alpha;
}
if (v_notUsed > 0.5) {
// This box not used, fade it out
gl_FragColor *= .1;
}
}
*/
} // namespace shaders
} // namespace mbgl
| 24.84507
| 96
| 0.697279
|
sp0n-7
|
36e74399e6af9a3055b96e2b58bf83365a6611c2
| 3,314
|
hpp
|
C++
|
PlayRho/Common/Real.hpp
|
Hexlord/PlayRho
|
a3a91554cf9b267894d06a996c5799a0479c5b5f
|
[
"Zlib"
] | 88
|
2017-07-13T18:12:40.000Z
|
2022-03-23T03:43:11.000Z
|
PlayRho/Common/Real.hpp
|
Hexlord/PlayRho
|
a3a91554cf9b267894d06a996c5799a0479c5b5f
|
[
"Zlib"
] | 388
|
2017-07-13T04:32:09.000Z
|
2021-11-10T20:59:23.000Z
|
PlayRho/Common/Real.hpp
|
Hexlord/PlayRho
|
a3a91554cf9b267894d06a996c5799a0479c5b5f
|
[
"Zlib"
] | 18
|
2017-07-20T16:14:57.000Z
|
2021-06-20T07:17:23.000Z
|
/*
* Copyright (c) 2021 Louis Langholtz https://github.com/louis-langholtz/PlayRho
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
/**
* @file
* @brief Real number definition file.
* @details This file may have been autogenerated from the Real.hpp.in file.
*/
#ifndef PLAYRHO_COMMON_REAL_HPP
#define PLAYRHO_COMMON_REAL_HPP
#include <PlayRho/Common/Fixed.hpp>
#include <PlayRho/Common/FixedMath.hpp>
#include <PlayRho/Common/FixedLimits.hpp>
namespace playrho {
/// @brief Real-number type.
///
/// @details This is the number type underlying numerical calculations conceptually involving
/// real-numbers. Ideally the implementation of this type doesn't suffer from things like:
/// catastrophic cancellation, catastrophic division, overflows, nor underflows.
///
/// @note This can be implemented using any of the fundamental floating point types (
/// <code>float</code>, <code>double</code>, or <code>long double</code>).
/// @note This can also be implemented using a <code>LiteralType</code> that has the necessary
/// support: all common mathematical functions, support for infinity and NaN, and a
/// specialization of the <code>std::numeric_limits</code> class template for it.
/// @note At present, the <code>Fixed32</code> and <code>Fixed64</code> aliases of the
/// <code>Fixed</code> template type are provided as examples of qualifying literal types
/// though the usability of these are limited and their use is discouraged.
///
/// @note Regarding division:
/// - While dividing 1 by a real, caching the result, and then doing multiplications with the
/// result may well be faster (than repeatedly dividing), dividing 1 by the real can also
/// result in an underflow situation that's then compounded every time it's multiplied with
/// other values.
/// - Meanwhile, dividing every time by a real isolates any underflows to the particular
/// division where underflow occurs.
///
/// @warning Using <code>Fixed32</code> is not advised as its numerical limitations are more
/// likely to result in problems like overflows or underflows.
/// @warning The note regarding division applies even more so when using a fixed-point type
/// (for <code>Real</code>).
///
/// @see https://en.cppreference.com/w/cpp/language/types
/// @see https://en.cppreference.com/w/cpp/types/is_floating_point
/// @see https://en.cppreference.com/w/cpp/named_req/LiteralType
///
using Real = float;
} // namespace playrho
#endif // PLAYRHO_COMMON_REAL_HPP
| 45.39726
| 94
| 0.742004
|
Hexlord
|
36e750b9077beed22edab1cb202f2df8794fb31d
| 1,000
|
cpp
|
C++
|
codeforces/A - Fancy Fence/Accepted.cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | 1
|
2022-02-11T16:55:36.000Z
|
2022-02-11T16:55:36.000Z
|
codeforces/A - Fancy Fence/Accepted.cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | null | null | null |
codeforces/A - Fancy Fence/Accepted.cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | null | null | null |
/****************************************************************************************
* @author: kzvd4729 created: Oct/09/2017 21:27
* solution_verdict: Accepted language: GNU C++14
* run_time: 0 ms memory_used: 0 KB
* problem: https://codeforces.com/contest/270/problem/A
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
long t,a,vis[200];
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin>>t;
while(t--)
{
for(long i=3;i<=1000;i++)
{
long x=(i-2)*180;
if(x%i==0)vis[x/i]=1;
}
cin>>a;
if(vis[a])cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
return 0;
}
| 33.333333
| 111
| 0.337
|
kzvd4729
|
36e76fa676db29ff8af7e32fd96821479a2873e4
| 1,038
|
cpp
|
C++
|
Miscellaneous/Dynamic Programming/wildcard.cpp
|
chirag-singhal/-Data-Structures-and-Algorithms
|
9f01b5cc0f382ed59bcd74444a0be1c3aa6cd1a3
|
[
"MIT"
] | 24
|
2021-02-09T17:59:54.000Z
|
2022-03-11T07:30:38.000Z
|
Miscellaneous/Dynamic Programming/wildcard.cpp
|
chirag-singhal/-Data-Structures-and-Algorithms
|
9f01b5cc0f382ed59bcd74444a0be1c3aa6cd1a3
|
[
"MIT"
] | null | null | null |
Miscellaneous/Dynamic Programming/wildcard.cpp
|
chirag-singhal/-Data-Structures-and-Algorithms
|
9f01b5cc0f382ed59bcd74444a0be1c3aa6cd1a3
|
[
"MIT"
] | 3
|
2021-06-22T03:09:49.000Z
|
2022-03-09T18:25:14.000Z
|
#include <iostream>
int main() {
int n, m;
std::cout<<"Enter length of string : ";
std::cin>>n;
char str[n + 1];
std::cout<<"Enter string : ";
std::cin>>str;
std::cout<<"Enter length of pattern : ";
std::cin>>m;
char pat[m + 1];
std::cout<<"Enter pattern : ";
std::cin>>pat;
bool arr[n + 1][m + 1];
for(int i = 0; i <= n; i++)
for(int j = 0; j <=m; j++)
arr[i][j] = false;
arr[0][0] = true;
for(int i = 1; i <= m; i++)
if(pat[i - 1] == '*')
arr[0][i] = arr[0][i - 1];
for(int i = 0; i <= n; i++) {
for(int j = 0; j <=m; j++) {
if(pat[j - 1] == '*')
arr[i][j] = arr[i - 1][j] || arr[i][j - 1];
else if(pat[j - 1] == '?' || pat[j - 1] == str[i - 1])
arr[i][j] = arr[i - 1][j - 1];
else arr[i][j] = false;
}
}
if(arr[n][m])
std::cout<<"TRUE"<<std::endl;
else
std::cout<<"FALSE"<<std::endl;
return 0;
}
| 22.085106
| 66
| 0.381503
|
chirag-singhal
|
36e84838eea8780afe1b2e460e0675b0a94a633f
| 1,661
|
cpp
|
C++
|
Source/Magneto/Magnet/Magnet.cpp
|
AlecLafita/Magneto
|
8b7f1aab34572e9991717ffb7484b45ccecabe20
|
[
"MIT"
] | null | null | null |
Source/Magneto/Magnet/Magnet.cpp
|
AlecLafita/Magneto
|
8b7f1aab34572e9991717ffb7484b45ccecabe20
|
[
"MIT"
] | null | null | null |
Source/Magneto/Magnet/Magnet.cpp
|
AlecLafita/Magneto
|
8b7f1aab34572e9991717ffb7484b45ccecabe20
|
[
"MIT"
] | null | null | null |
#include "Magnet.h"
#include "MagnetRay.h"
#include "Components/StaticMeshComponent.h"
#include "Components/InputComponent.h"
#include "GameFramework/PlayerController.h"
#include "Kismet/KismetMathLibrary.h"
AMagnet::AMagnet()
{
PrimaryActorTick.bCanEverTick = true;
mMeshComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh"));
RootComponent = mMeshComponent;
}
void AMagnet::BeginPlay()
{
Super::BeginPlay();
}
void AMagnet::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
void AMagnet::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
}
void AMagnet::PostInitProperties()
{
Super::PostInitProperties();
UWorld* World = GetWorld();
if (mRayClass != nullptr && World != nullptr)
{
FActorSpawnParameters SpawnParams;
SpawnParams.Owner = this;
mRay = World->SpawnActor<AMagnetRay>(mRayClass, SpawnParams);
mRay->AttachToActor(this, FAttachmentTransformRules::KeepRelativeTransform);
mRay->SetActorHiddenInGame(true);
}
}
void AMagnet::Fire(const FVector& aDestinationPoint)
{
mRay->SetActorHiddenInGame(false);
RestartRay();
FRotator LookAt = UKismetMathLibrary::FindLookAtRotation(mRay->GetActorLocation(), aDestinationPoint);
mRay->SetActorRotation(LookAt);
mRay->FireInDirection(LookAt.Vector());
}
void AMagnet::StopFire()
{
mRay->SetActorHiddenInGame(true);
mRay->StopFire();
}
void AMagnet::RestartRay()
{
FVector Origin;
FVector BoxExtent;
GetActorBounds(true, Origin, BoxExtent);
//TODO add projectile size. Also this does not get the magnet size at all
mRay->SetActorRelativeLocation(FVector(BoxExtent.X, 0.0f, 0.0f));
}
| 24.791045
| 103
| 0.771222
|
AlecLafita
|
36ed6a0238d1d1e593ef14937f6cb965cbe08ebc
| 247
|
cpp
|
C++
|
kontrolnya-rabota-1/task2/task2.cpp
|
MuKaTiR/orazbaev-timur-2021
|
2e44f1d336fbe87a0d096e0d9f56cfef6b98104f
|
[
"Apache-2.0"
] | null | null | null |
kontrolnya-rabota-1/task2/task2.cpp
|
MuKaTiR/orazbaev-timur-2021
|
2e44f1d336fbe87a0d096e0d9f56cfef6b98104f
|
[
"Apache-2.0"
] | null | null | null |
kontrolnya-rabota-1/task2/task2.cpp
|
MuKaTiR/orazbaev-timur-2021
|
2e44f1d336fbe87a0d096e0d9f56cfef6b98104f
|
[
"Apache-2.0"
] | null | null | null |
#include<iostream>
using namespace std;
main()
{
int x, max, min, i = 2;
cin >> min >> max;
while (cin >> x)
{
i++;
if (i % 2)
{
if (x < min)
{
min = x;
}
}
else if (x > max)
{
max = x;
}
}
cout << max + min;
}
| 10.73913
| 24
| 0.425101
|
MuKaTiR
|
36fa294236a47a5d466d1326caf0c40ee7ff8f93
| 1,372
|
cpp
|
C++
|
GripPoints/DbDgnUnderlayGripPoints.cpp
|
terry-texas-us/Eo
|
5652b68468c0bacd8e8da732befa2374360a4bbd
|
[
"MIT"
] | 1
|
2020-09-07T07:06:19.000Z
|
2020-09-07T07:06:19.000Z
|
GripPoints/DbDgnUnderlayGripPoints.cpp
|
terry-texas-us/Eo
|
5652b68468c0bacd8e8da732befa2374360a4bbd
|
[
"MIT"
] | null | null | null |
GripPoints/DbDgnUnderlayGripPoints.cpp
|
terry-texas-us/Eo
|
5652b68468c0bacd8e8da732befa2374360a4bbd
|
[
"MIT"
] | 2
|
2019-10-24T00:36:58.000Z
|
2020-09-30T16:45:56.000Z
|
#include <OdaCommon.h>
#include "DbDgnUnderlayGripPoints.h"
#include <DbUnderlayReference.h>
#include <DbUnderlayDefinition.h>
#include <Gi/GiDummyGeometry.h>
#include <Ge/GeNurbCurve3d.h>
OdResult OdDbDgnUnderlayGripPointsPE::getOsnapPoints(const OdDbEntity* entity, const OdDb::OsnapMode objectSnapMode, const OdGsMarker selectionMarker, const OdGePoint3d& pickPoint, const OdGePoint3d& lastPoint, const OdGeMatrix3d& worldToEyeTransform, OdGePoint3dArray& snapPoints) const {
const auto DgnGripPointsModule {odrxDynamicLinker()->loadModule(ExDgnGripPointsModuleName)};
if (DgnGripPointsModule.isNull()) {
return eTxError;
}
const auto Result {OdDbUnderlayGripPointsPE::getOsnapPoints(entity, objectSnapMode, selectionMarker, pickPoint, lastPoint, worldToEyeTransform, snapPoints)};
if (eOk == Result) {
auto UnderlayReference {OdDbUnderlayReference::cast(entity)};
OdDbUnderlayDefinitionPtr UnderlayDefinition {UnderlayReference->definitionId().openObject()};
auto UnderlayItem {UnderlayDefinition->getUnderlayItem()};
OdIntArray GeometryIds;
// NB: last parameter of this call needs to be changed to last parameter of this function
return UnderlayItem->getOsnapPoints(UnderlayReference->transform(), objectSnapMode, selectionMarker, pickPoint, lastPoint, worldToEyeTransform, OdGeMatrix3d::kIdentity, snapPoints, GeometryIds);
}
return Result;
}
| 57.166667
| 289
| 0.815598
|
terry-texas-us
|
3c02a882093d7ce5efc1f9f88864a71c28d87af1
| 14,382
|
cpp
|
C++
|
APEX_1.4/shared/general/PxUserProfilerCallback/src/PsUserProfilerPVD.cpp
|
DoubleTT-Changan/0715
|
acbd071531ca4f3e2a82525b92f60824178c39fa
|
[
"Unlicense"
] | null | null | null |
APEX_1.4/shared/general/PxUserProfilerCallback/src/PsUserProfilerPVD.cpp
|
DoubleTT-Changan/0715
|
acbd071531ca4f3e2a82525b92f60824178c39fa
|
[
"Unlicense"
] | null | null | null |
APEX_1.4/shared/general/PxUserProfilerCallback/src/PsUserProfilerPVD.cpp
|
DoubleTT-Changan/0715
|
acbd071531ca4f3e2a82525b92f60824178c39fa
|
[
"Unlicense"
] | null | null | null |
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2019 NVIDIA Corporation. All rights reserved.
#include <assert.h>
#include <stdio.h>
#include <new>
#include <windows.h>
#include <PxAllocatorCallback.h>
#include <PxErrorCallback.h>
#include <PsFoundation.h>
#include "PxUserProfilerCallback.h"
#include "PxSimpleTypes.h"
#include "PsHashMap.h"
#include "SimpleHash.h"
#include "PsMutex.h"
#include "PxUserProfilerParent.h"
namespace physx
{
using namespace pubfnd;
using namespace shdfnd;
};
#include "MemTracker.h"
#include "PxProfileZone.h"
#include "PxProfileZoneManager.h"
#include "PxProfileEventSystem.h"
#include "PxProfileEventHandler.h"
#include "PxProfileEventNames.h"
#include "PxProfileZone.h"
#include "PxProfileScopedEvent.h"
#include "PxProfileCompileTimeEventFilter.h"
#include "PxProfileScopedEvent.h"
#include "PVDBinding.h"
#include "PvdConnectionType.h"
#include "PVDBindingUserAllocator.h"
#include "PVDBindingErrorStream.h"
//#pragma comment(lib,"PhysXProfileSDK.lib")
namespace PVD
{
struct SLocalFoundation
{
static PVDBindingUserAllocator sAllocator;
physx::profile::PVDBindingErrorStream mErrorStream;
SLocalFoundation()
{
using namespace physx::shdfnd;
Foundation::createInstance(PX_PUBLIC_FOUNDATION_VERSION, mErrorStream, sAllocator);
}
~SLocalFoundation()
{
using namespace physx::shdfnd;
Foundation::destroyInstance();
}
};
PVDBindingUserAllocator SLocalFoundation::sAllocator("");
}
namespace physx
{
using namespace physx::pubfnd3;
};
#ifdef WIN32
#include <windows.h>
#endif
#pragma warning(disable:4100 4996)
using namespace physx;
namespace PX_USER_PROFILER_CALLBACK
{
typedef SimpleHash< PxU16 > EventPVDMap;
class PxUserProfilerCallbackPVD;
class PxUserProfilerCallbackPVD : public PxUserProfilerCallback, public UserAllocated
{
public:
PxUserProfilerCallbackPVD(PxUserProfilerParent *parent,const PxUserProfilerCallback::Desc &desc)
{
mActive = desc.profilerActive;
mParent = parent;
mOwnsPvdBinding = false;
if ( desc.useMemTracker )
{
mMemTracker = createMemTracker();
mMemTracker->setLogLevel(desc.logEveryAllocation,desc.logEveryFrame,desc.verifySingleThreaded);
}
else
{
mMemTracker = NULL;
}
mPvdBinding = desc.pvdBinding;
if ( desc.createProfilerContext )
{
// TODO: Create PVD binding here!
mPvdBinding = &PVD::PvdBinding::create( false );
//Attempt to connect automatically to pvd.
mPvdBinding->connect( "localhost", DEFAULT_PVD_BINDING_PORT, DEFAULT_PVD_BINDING_TIMEOUT_MS, PVD::PvdConnectionType::Profile | PVD::PvdConnectionType::Memory );
mOwnsPvdBinding = true;
}
mProfileZone = NULL;
if ( mPvdBinding )
{
mProfileZone = &mPvdBinding->getProfileManager().createProfileZone("PxUserProfilerCallback",PxProfileNames(),0x4000);
}
}
virtual ~PxUserProfilerCallbackPVD(void)
{
if ( mMemTracker )
{
releaseMemTracker(mMemTracker);
}
releaseProfiler();
}
void releaseProfiler(void)
{
if ( mProfileZone )
{
mProfileZone->release();
mProfileZone = NULL;
}
if ( mPvdBinding && mOwnsPvdBinding )
{
mPvdBinding->release();
mPvdBinding = NULL;
mOwnsPvdBinding = false;
}
}
virtual bool trackInfo(const void *mem,TrackInfo &info)
{
bool ret = false;
if ( mMemTracker )
{
mMemMutex.lock();
ret = mMemTracker->trackInfo(mem,info);
mMemMutex.unlock();
}
return ret;
}
virtual void trackAlloc(void *mem,size_t size,MemoryType type,const char *context,const char *className,const char *fileName,physx::PxU32 lineno)
{
if ( mMemTracker )
{
mMemMutex.lock();
mMemTracker->trackAlloc( getCurrentThreadId(),
mem,
size,
type,
context,
className,
fileName,
lineno);
mMemMutex.unlock();
}
}
virtual void trackRealloc(void *oldMem,
void *newMem,
size_t newSize,
const char *context,
const char *className,
const char *fileName,
physx::PxU32 lineno)
{
if ( mMemTracker )
{
mMemMutex.lock();
mMemTracker->trackRealloc( getCurrentThreadId(),
oldMem,
newMem,
newSize,
context,
className,
fileName,
lineno);
mMemMutex.unlock();
}
}
virtual void trackFree(void *mem,MemoryType type,const char *context,const char *fileName,physx::PxU32 lineno)
{
if ( mMemTracker )
{
mMemMutex.lock();
mMemTracker->trackFree(getCurrentThreadId(),
mem,
type,
context,
fileName,
lineno);
mMemMutex.unlock();
}
}
virtual const char * trackValidateFree(void *mem,MemoryType type,const char *context,const char *fileName,physx::PxU32 lineno)
{
const char *ret = NULL;
if ( mMemTracker )
{
mMemMutex.lock();
ret = mMemTracker->trackValidateFree(getCurrentThreadId(),
mem,
type,
context,
fileName,
lineno);
mMemMutex.unlock();
}
return ret;
}
size_t getCurrentThreadId(void)
{
size_t ret = 0;
#ifdef WIN32
ret = GetCurrentThreadId();
#endif
return ret;
}
virtual bool memoryReport(MemoryReportFormat format,const char *fname,bool reportAllLeaks) // detect memory leaks and, if any, write out a report to the filename specified.
{
bool ret = false;
if ( mMemTracker )
{
mMemMutex.lock();
size_t leakCount;
size_t leaked = mMemTracker->detectLeaks(leakCount);
if ( leaked )
{
physx::PxU32 dataLen;
void *mem = mMemTracker->generateReport(format,fname,dataLen,reportAllLeaks);
if ( mem )
{
FILE *fph = fopen(fname,"wb");
fwrite(mem,dataLen,1,fph);
fclose(fph);
mMemTracker->releaseReportMemory(mem);
}
ret = true; // it leaked memory!
}
mMemMutex.unlock();
}
return ret;
}
/**
\brief This method is used to generate a memory usage report in memory. If it returns NULL then no active memory blocks are registered. (i.e. no leaks on application exit.
*/
virtual const void * memoryReport(MemoryReportFormat format, // The format to output the report in.
const char *reportName, // The name of the report.
bool reportAllLeaks, // Whether or not to output every single memory leak. *WARNING* Only enable this if you know you wish to identify a specific limited number of memory leaks.
physx::PxU32 &reportSize) // The size of the output report.
{
const void *ret = NULL;
if ( mMemTracker )
{
mMemMutex.lock();
size_t leakCount;
size_t leaked = mMemTracker->detectLeaks(leakCount);
if ( leaked )
{
physx::PxU32 dataLen;
void *mem = mMemTracker->generateReport(format,reportName,dataLen,reportAllLeaks);
if ( mem )
{
ret = mem;
reportSize = dataLen;
}
}
mMemMutex.unlock();
}
return ret;
}
/**
\brief Releases the memory allocated for a previous memory report.
*/
virtual void releaseMemoryReport(const void *reportData)
{
if ( mMemTracker )
{
mMemMutex.lock();
mMemTracker->releaseReportMemory((void *)reportData);
mMemMutex.unlock();
}
}
virtual void profileStat(const char *statName, // The descriptive name of this statistic
PxU64 context, // The context of this statistic. Data is presented 'in context' by PVD. This parameter is ignored by other profiler tools.
physx::PxI64 statValue, // Up to a 16 bit signed integer value for the statistic.
const char *fileName, // The source code file name where this statistic event was generated.
physx::PxU32 lineno) // The source code line number where this statistic event was generated.
{
if ( mProfileZone )
{
PxU16 eventId = mProfileZone->getEventIdForName(statName);
mProfileZone->eventValue(eventId,context,statValue);
}
}
// Mark the beginning of a profile zone.
virtual void profileBegin(const char *str,physx::pubfnd3::PxU64 context,const char *fileName,physx::PxU32 lineno)
{
if ( mProfileZone )
{
PxU16 eventId = mProfileZone->getEventIdForName(str);
mProfileZone->startEvent(eventId,context);
}
}
virtual void profileBegin(const char *str,physx::pubfnd3::PxU64 context,physx::pubfnd3::PxU32 threadId,const char *fileName,physx::PxU32 lineno)
{
if ( mProfileZone )
{
PxU16 eventId = mProfileZone->getEventIdForName(str);
mProfileZone->startEvent(eventId,context,threadId);
}
}
// Mark the end of a profile zone
virtual void profileEnd(const char *event,physx::pubfnd3::PxU64 context)
{
if ( mProfileZone )
{
PxU16 eventId = mProfileZone->getEventIdForName(event);
mProfileZone->stopEvent(eventId,context);
}
}
virtual void profileEnd(const char *event,physx::pubfnd3::PxU64 context,physx::pubfnd3::PxU32 threadId)
{
if ( mProfileZone )
{
PxU16 eventId = mProfileZone->getEventIdForName(event);
mProfileZone->stopEvent(eventId,context,threadId);
}
}
void profileMessageChannel(MessageChannelType type,const char *channel,const char *message,...)
{
}
virtual void profileSectionName(const char *fmt,...)
{
}
virtual void profileFrame(void)
{
mMemMutex.lock();
if ( mMemTracker )
{
mMemTracker->trackFrame();
mMemTracker->plotStats();
}
mMemMutex.unlock();
//If we don't own the pvd binding then apex or physx will be providing frame markers
if ( mOwnsPvdBinding )
{
PxU64 instPtr = static_cast<PxU64>( reinterpret_cast<size_t>( this ) );
mPvdBinding->endFrame( instPtr );
mPvdBinding->beginFrame( instPtr );
}
}
virtual void release(void)
{
PxUserProfilerParent *parent = mParent;
delete this;
parent->release();
}
virtual void objectInit(void *mem,const char *object,const char *fileName,physx::PxU32 lineno)
{
}
virtual void objectKill(void *mem,const char *fileName,physx::PxU32 lineno)
{
}
virtual void objectInitArray(void *mem,size_t objectSize,size_t arraySize,const char *object,const char *fileName,physx::PxU32 lineno)
{
}
virtual void objectKillArray(void *mem,const char *fileName,physx::PxU32 lineno)
{
}
virtual void setProfilerHandle(Type type,void *context)
{
if ( type == PT_PVD )
{
releaseProfiler();
{
mPvdBinding = (PVD::PvdBinding *)context;
if ( mPvdBinding )
mProfileZone = &mPvdBinding->getProfileManager().createProfileZone("PxUserProfilerCallback",PxProfileNames(),0x4000);
}
}
}
virtual void *getProfilerHandle(void)
{
return mPvdBinding;
}
/**
\brief Reports the 'Type' of 3rd party profiler SDK being used.
*/
virtual Type getProfilerType(void)
{
return PT_PVD;
}
virtual void setProfilerActive(bool state)
{
mActive = state;
}
virtual bool getProfilerActive(void) const
{
return mActive;
}
/**
\brief Processes a single data point to be plotted by the profiler.
*/
virtual void profilePlot(PlotType type, // How to display/format the data.
physx::PxF32 value, // The data value to plot.
const char *name) // The name of the data item.
{
}
/**
\brief Processes a single data point to be plotted by the profiler.
*/
virtual void profilePlot(PlotType type, // How to display/format the data.
physx::PxF64 value, // The data value to plot.
const char *name) // The name of the data item.
{
}
/**
\brief Processes a single data point to be plotted by the profiler.
*/
virtual void profilePlot(PlotType type, // How to display/format the data.
PxU64 value, // The data value to plot.
const char *name) // The name of the data item.
{
}
/**
\brief Processes a single data point to be plotted by the profiler.
*/
virtual void profilePlot(PlotType type, // How to display/format the data.
physx::PxI64 value, // The data value to plot.
const char *name) // The name of the data item.
{
}
/**
\brief Processes a single data point to be plotted by the profiler.
*/
virtual void profilePlot(PlotType type, // How to display/format the data.
physx::PxU32 value, // The data value to plot.
const char *name) // The name of the data item.
{
}
/**
\brief Processes a single data point to be plotted by the profiler.
*/
virtual void profilePlot(PlotType type, // How to display/format the data.
physx::PxI32 value, // The data value to plot.
const char *name) // The name of the data item.
{
}
private:
bool mActive;
MemTracker *mMemTracker;
PVD::PvdBinding *mPvdBinding;
physx::PxProfileZone *mProfileZone;
physx::Mutex mMemMutex;
PxUserProfilerParent *mParent;
bool mOwnsPvdBinding;
};
PxUserProfilerCallback * createPxUserProfilerCallbackPVD(PxUserProfilerParent *parent,const PxUserProfilerCallback::Desc &desc)
{
PxUserProfilerCallbackPVD *ret = PX_NEW(PxUserProfilerCallbackPVD)(parent,desc);
return static_cast<PxUserProfilerCallback *>(ret);
}
};
| 25.913514
| 190
| 0.697052
|
DoubleTT-Changan
|
3c040770e78affea2ff73870cff5f6f02a5cf003
| 4,909
|
hpp
|
C++
|
src/physics/thermal_conduction.hpp
|
joshessman-llnl/serac
|
1365a8f9ca372f0c50008b4b8f5f718955e4b80c
|
[
"BSD-3-Clause"
] | null | null | null |
src/physics/thermal_conduction.hpp
|
joshessman-llnl/serac
|
1365a8f9ca372f0c50008b4b8f5f718955e4b80c
|
[
"BSD-3-Clause"
] | null | null | null |
src/physics/thermal_conduction.hpp
|
joshessman-llnl/serac
|
1365a8f9ca372f0c50008b4b8f5f718955e4b80c
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright (c) 2019-2020, Lawrence Livermore National Security, LLC and
// other Serac Project Developers. See the top-level LICENSE file for
// details.
//
// SPDX-License-Identifier: (BSD-3-Clause)
/**
* @file thermal_solver.hpp
*
* @brief An object containing the solver for a thermal conduction PDE
*/
#ifndef THERMAL_CONDUCTION
#define THERMAL_CONDUCTION
#include "mfem.hpp"
#include "physics/base_physics.hpp"
#include "physics/operators/thermal_operators.hpp"
namespace serac {
/**
* @brief An object containing the solver for a thermal conduction PDE
*
* This is a generic linear thermal diffusion oeprator of the form
*
* M du/dt = -kappa Ku + f
*
* where M is a mass matrix, K is a stiffness matrix, and f is a
* thermal load vector.
*/
class ThermalConduction : public BasePhysics {
public:
/**
* @brief Construct a new Thermal Solver object
*
* @param[in] order The order of the thermal field discretization
* @param[in] mesh The MFEM parallel mesh to solve the PDE on
*/
ThermalConduction(int order, std::shared_ptr<mfem::ParMesh> mesh);
/**
* @brief Set essential temperature boundary conditions (strongly enforced)
*
* @param[in] temp_bdr The boundary attributes on which to enforce a temperature
* @param[in] temp_bdr_coef The prescribed boundary temperature
*/
void setTemperatureBCs(const std::set<int>& temp_bdr, std::shared_ptr<mfem::Coefficient> temp_bdr_coef);
/**
* @brief Set flux boundary conditions (weakly enforced)
*
* @param[in] flux_bdr The boundary attributes on which to enforce a heat flux (weakly enforced)
* @param[in] flux_bdr_coef The prescribed boundary heat flux
*/
void setFluxBCs(const std::set<int>& flux_bdr, std::shared_ptr<mfem::Coefficient> flux_bdr_coef);
/**
* @brief Advance the timestep
*
* @param[inout] dt The timestep to advance. For adaptive time integration methods, the actual timestep is returned.
*/
void advanceTimestep(double& dt) override;
/**
* @brief Set the thermal conductivity
*
* @param[in] kappa The thermal conductivity
*/
void setConductivity(std::unique_ptr<mfem::Coefficient>&& kappa);
/**
* @brief Set the temperature state vector from a coefficient
*
* @param[in] temp The temperature coefficient
*/
void setTemperature(mfem::Coefficient& temp);
/**
* @brief Set the thermal body source from a coefficient
*
* @param[in] source The source function coefficient
*/
void setSource(std::unique_ptr<mfem::Coefficient>&& source);
/**
* @brief Get the temperature state
*
* @return A pointer to the current temperature finite element state
*/
std::shared_ptr<serac::FiniteElementState> temperature() { return temperature_; };
/**
* @brief Complete the initialization and allocation of the data structures.
*
* This must be called before StaticSolve() or AdvanceTimestep(). If allow_dynamic
* = false, do not allocate the mass matrix or dynamic operator
*/
void completeSetup() override;
/**
* @brief Set the linear solver parameters for both the M and K matrices
*
* @param[in] params The linear solver parameters
*/
void setLinearSolverParameters(const serac::LinearSolverParameters& params);
/**
* @brief Destroy the Thermal Solver object
*/
virtual ~ThermalConduction() = default;
protected:
/**
* @brief The temperature finite element state
*/
std::shared_ptr<serac::FiniteElementState> temperature_;
/**
* @brief Mass bilinear form object
*/
std::unique_ptr<mfem::ParBilinearForm> M_form_;
/**
* @brief Stiffness bilinear form object
*/
std::unique_ptr<mfem::ParBilinearForm> K_form_;
/**
* @brief Assembled mass matrix
*/
std::unique_ptr<mfem::HypreParMatrix> M_mat_;
/**
* @brief Assembled stiffness matrix
*/
std::unique_ptr<mfem::HypreParMatrix> K_mat_;
/**
* @brief Thermal load linear form
*/
std::unique_ptr<mfem::ParLinearForm> l_form_;
/**
* @brief Assembled BC load vector
*/
std::unique_ptr<mfem::HypreParVector> bc_rhs_;
/**
* @brief Assembled RHS vector
*/
std::unique_ptr<mfem::HypreParVector> rhs_;
/**
* @brief Linear solver for the K operator
*/
std::unique_ptr<mfem::CGSolver> K_solver_;
/**
* @brief Preconditioner for the K operator
*/
std::unique_ptr<mfem::HypreSmoother> K_prec_;
/**
* @brief Conduction coefficient
*/
std::unique_ptr<mfem::Coefficient> kappa_;
/**
* @brief Body source coefficient
*/
std::unique_ptr<mfem::Coefficient> source_;
/**
* @brief Time integration operator
*/
std::unique_ptr<DynamicConductionOperator> dyn_oper_;
/**
* @brief Linear solver parameters
*/
serac::LinearSolverParameters lin_params_;
/**
* @brief Solve the Quasi-static operator
*/
void quasiStaticSolve();
};
} // namespace serac
#endif
| 25.435233
| 118
| 0.693013
|
joshessman-llnl
|
3c072513e9cc8f1ca894d5db59629249bf10f939
| 3,411
|
hh
|
C++
|
src/ros_tf_listener.hh
|
MaximilienNaveau/dynamic_graph_bridge
|
6dafe58f9e72263fd361efa824c26ac49b96276d
|
[
"BSD-2-Clause"
] | null | null | null |
src/ros_tf_listener.hh
|
MaximilienNaveau/dynamic_graph_bridge
|
6dafe58f9e72263fd361efa824c26ac49b96276d
|
[
"BSD-2-Clause"
] | null | null | null |
src/ros_tf_listener.hh
|
MaximilienNaveau/dynamic_graph_bridge
|
6dafe58f9e72263fd361efa824c26ac49b96276d
|
[
"BSD-2-Clause"
] | 1
|
2021-11-29T16:46:35.000Z
|
2021-11-29T16:46:35.000Z
|
#ifndef DYNAMIC_GRAPH_ROS_TF_LISTENER_HH
# define DYNAMIC_GRAPH_ROS_TF_LISTENER_HH
# include <boost/bind.hpp>
# include <tf/transform_listener.h>
# include <dynamic-graph/entity.h>
# include <dynamic-graph/signal.h>
# include <dynamic-graph/command-bind.h>
# include <sot/core/matrix-geometry.hh>
namespace dynamicgraph {
class RosTfListener;
namespace internal
{
struct TransformListenerData {
typedef Signal<sot::MatrixHomogeneous, int> signal_t;
tf::TransformListener& listener;
const std::string toFrame, fromFrame;
tf::StampedTransform transform;
signal_t signal;
TransformListenerData (tf::TransformListener& l,
const std::string& to, const std::string& from,
const std::string& signame)
: listener (l)
, toFrame (to)
, fromFrame (from)
, signal (signame)
{
signal.setFunction (boost::bind(&TransformListenerData::getTransform, this, _1, _2));
}
sot::MatrixHomogeneous& getTransform (sot::MatrixHomogeneous& res, int time)
{
static const ros::Time rosTime(0);
try {
listener.lookupTransform (toFrame, fromFrame, rosTime, transform);
} catch (const tf::TransformException& ex) {
res.setIdentity();
ROS_ERROR("Enable to get transform at time %i: %s",time,ex.what());
return res;
}
for (sot::MatrixHomogeneous::Index r = 0; r < 3; ++r) {
for (sot::MatrixHomogeneous::Index c = 0; c < 3; ++c)
res.linear ()(r,c) = transform.getBasis().getRow(r)[c];
res.translation()[r] = transform.getOrigin()[r];
}
return res;
}
};
} // end of internal namespace.
class RosTfListener : public Entity
{
DYNAMIC_GRAPH_ENTITY_DECL();
public:
typedef internal::TransformListenerData TransformListenerData;
RosTfListener (const std::string& name) : Entity (name)
{
std::string docstring =
"\n"
" Add a signal containing the transform between two frames.\n"
"\n"
" Input:\n"
" - to : frame name\n"
" - from: frame name,\n"
" - signalName: the signal name in dynamic-graph"
"\n";
addCommand ("add",
command::makeCommandVoid3(*this, &RosTfListener::add, docstring));
}
~RosTfListener ()
{
for (Map_t::const_iterator _it = listenerDatas.begin(); _it != listenerDatas.end(); ++_it)
delete _it->second;
}
void add (const std::string& to, const std::string& from, const std::string& signame)
{
if (listenerDatas.find(signame) != listenerDatas.end())
throw std::invalid_argument ("A signal " + signame
+ " already exists in RosTfListener " + getName());
boost::format signalName ("RosTfListener(%1%)::output(MatrixHomo)::%2%");
signalName % getName () % signame;
TransformListenerData* tld = new TransformListenerData (
listener, to, from, signalName.str());
signalRegistration (tld->signal);
listenerDatas[signame] = tld;
}
private:
typedef std::map<std::string, TransformListenerData*> Map_t;
Map_t listenerDatas;
tf::TransformListener listener;
};
} // end of namespace dynamicgraph.
#endif // DYNAMIC_GRAPH_ROS_TF_LISTENER_HH
| 31.293578
| 98
| 0.609792
|
MaximilienNaveau
|
3c0980f7da1a152303ec234ac70fba4b60892112
| 1,035
|
cpp
|
C++
|
Applied/CCore/src/ToMemBase.cpp
|
SergeyStrukov/CCore-2-xx
|
118aa4011ee7cc587298d6373b6587540e044a83
|
[
"BSL-1.0"
] | null | null | null |
Applied/CCore/src/ToMemBase.cpp
|
SergeyStrukov/CCore-2-xx
|
118aa4011ee7cc587298d6373b6587540e044a83
|
[
"BSL-1.0"
] | null | null | null |
Applied/CCore/src/ToMemBase.cpp
|
SergeyStrukov/CCore-2-xx
|
118aa4011ee7cc587298d6373b6587540e044a83
|
[
"BSL-1.0"
] | null | null | null |
/* ToMemBase.cpp */
//----------------------------------------------------------------------------------------
//
// Project: CCore 2.00
//
// Tag: Applied Mini
//
// License: Boost Software License - Version 1.0 - August 17th, 2003
//
// see http://www.boost.org/LICENSE_1_0.txt or the local copy
//
// Copyright (c) 2015 Sergey Strukov. All rights reserved.
//
//----------------------------------------------------------------------------------------
#include <CCore/inc/ToMemBase.h>
#include <CCore/inc/MemBase.h>
namespace CCore {
/* class ToMemBase */
uint8 * ToMemBase::alloc(ulen len_)
{
ptr=static_cast<uint8 *>(MemAlloc(len_));
len=len_;
return ptr;
}
ToMemBase::ToMemBase()
{
ptr=0;
len=0;
}
ToMemBase::~ToMemBase()
{
MemFree(ptr);
}
ToMemBase & ToMemBase::operator = (ToMemBase &&obj) noexcept
{
if( this!=&obj )
{
uint8 *todel=Replace(ptr,Replace_null(obj.ptr));
len=Replace_null(obj.len);
MemFree(todel);
}
return *this;
}
} // namespace CCore
| 17.25
| 90
| 0.516908
|
SergeyStrukov
|
3c121eb334096ff2c91a202bd462c2666a5b976f
| 758
|
hpp
|
C++
|
code/modules/data/AddListItemModule.hpp
|
TU-Berlin-CVRS/uipf
|
57f4afcfdece904e82624453a938aafdfde8df41
|
[
"BSD-2-Clause"
] | 8
|
2015-07-07T16:38:38.000Z
|
2020-11-26T13:52:18.000Z
|
code/modules/data/AddListItemModule.hpp
|
TU-Berlin-CVRS/uipf
|
57f4afcfdece904e82624453a938aafdfde8df41
|
[
"BSD-2-Clause"
] | 129
|
2015-07-14T19:06:30.000Z
|
2019-05-29T20:40:00.000Z
|
code/modules/data/AddListItemModule.hpp
|
TU-Berlin-CVRS/uipf
|
57f4afcfdece904e82624453a938aafdfde8df41
|
[
"BSD-2-Clause"
] | 6
|
2015-08-20T19:00:07.000Z
|
2020-11-26T13:52:19.000Z
|
#ifndef _ADDLISTITEMMODULE_
#define _ADDLISTITEMMODULE_
#include "../../framework/ModuleInterface.hpp"
#include "../../framework/ModuleBase.hpp"
namespace uipf{
// Create an empty list
class AddListItemModule : public QObject, ModuleBase
{
Q_OBJECT
Q_PLUGIN_METADATA(IID "org.tu-berlin.uipf.ModuleInterface" )
Q_INTERFACES(uipf::ModuleInterface)
public:
// constructor tells ModuleBase our name so we don't need to implement name()
AddListItemModule(void): ModuleBase("addListItem"){};
// destructor needs to be virtual otherwise it not called due polymorphism
virtual ~AddListItemModule(void){};
void run( DataManager& data ) const Q_DECL_OVERRIDE;
uipf::MetaData getMetaData() const Q_DECL_OVERRIDE;
};
}
#endif //AddListItemModule
| 23.6875
| 79
| 0.766491
|
TU-Berlin-CVRS
|
3c1398ed48d4bdd319bbdb28b953104965bcf0ca
| 6,390
|
cpp
|
C++
|
update-client-hub/modules/lwm2m-mbed/source/lwm2m-monitor.cpp
|
marcuschangarm/mbed-cloud-client
|
d7edc529ed3722c811ff401440ef58ea980bf543
|
[
"Apache-2.0"
] | 27
|
2018-04-04T12:06:23.000Z
|
2020-10-16T08:58:38.000Z
|
update-client-hub/modules/lwm2m-mbed/source/lwm2m-monitor.cpp
|
marcuschangarm/mbed-cloud-client
|
d7edc529ed3722c811ff401440ef58ea980bf543
|
[
"Apache-2.0"
] | 41
|
2018-07-12T08:09:39.000Z
|
2020-11-06T13:47:43.000Z
|
update-client-hub/modules/lwm2m-mbed/source/lwm2m-monitor.cpp
|
marcuschangarm/mbed-cloud-client
|
d7edc529ed3722c811ff401440ef58ea980bf543
|
[
"Apache-2.0"
] | 53
|
2018-04-16T08:36:25.000Z
|
2020-11-02T15:50:43.000Z
|
// ----------------------------------------------------------------------------
// Copyright 2016-2019 ARM Ltd.
//
// SPDX-License-Identifier: Apache-2.0
//
// 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 "update-client-common/arm_uc_config.h"
#if defined(ARM_UC_ENABLE) && (ARM_UC_ENABLE == 1)
#include "update-lwm2m-mbed-apis.h"
#include "update-client-lwm2m/lwm2m-monitor.h"
#include "update-client-lwm2m/FirmwareUpdateResource.h"
#include "update-client-lwm2m/DeviceMetadataResource.h"
/**
* @brief Get driver version.
* @return Driver version.
*/
uint32_t ARM_UCS_LWM2M_MONITOR_GetVersion(void)
{
return 0;
}
/**
* @brief Get Source capabilities.
* @return Struct containing capabilites. See definition above.
*/
ARM_MONITOR_CAPABILITIES ARM_UCS_LWM2M_MONITOR_GetCapabilities(void)
{
ARM_MONITOR_CAPABILITIES result;
result.state = 1;
result.result = 1;
result.version = 1;
result.reserved = 30;
return result;
}
/**
* @brief Initialize Monitor.
* @return Error code.
*/
arm_uc_error_t ARM_UCS_LWM2M_MONITOR_Initialize(void (*notification_handler)(void))
{
ARM_UC_INIT_ERROR(retval, ERR_NONE);
FirmwareUpdateResource::Initialize();
FirmwareUpdateResource::addNotificationCallback(notification_handler);
DeviceMetadataResource::Initialize();
return retval;
}
/**
* @brief Uninitialized Monitor.
* @return Error code.
*/
arm_uc_error_t ARM_UCS_LWM2M_MONITOR_Uninitialize(void)
{
ARM_UC_INIT_ERROR(retval, ERR_NONE);
return retval;
}
/**
* @brief Send Update Client state.
* @details From the OMA LWM2M Technical Specification:
*
* Indicates current state with respect to this firmware update.
* This value is set by the LWM2M Client in accordance with state
* and arm_uc_monitor_state_t type.
*
* @return Error code.
*/
arm_uc_error_t ARM_UCS_LWM2M_MONITOR_SendState(arm_uc_monitor_state_t an_update_state)
{
ARM_UC_INIT_ERROR(result, ERR_NONE);
// If out of range of a legitimate update-state, return an "invalid-parameter" error to the caller,
// otherwise try send the new state to the monitor.
if (!ARM_UC_IsValidState(an_update_state)) {
ARM_UC_SET_ERROR(result, ERR_INVALID_PARAMETER);
} else {
FirmwareUpdateResource::arm_ucs_lwm2m_state_t state =
(FirmwareUpdateResource::arm_ucs_lwm2m_state_t)an_update_state;
if (FirmwareUpdateResource::sendState(state) != 0) {
ARM_UC_SET_ERROR(result, ERR_UNSPECIFIED);
}
}
return result;
}
arm_uc_monitor_state_t ARM_UCS_LWM2M_MONITOR_GetState()
{
return (arm_uc_monitor_state_t)FirmwareUpdateResource::getState();
}
/**
* @brief Send update result.
* @details From the OMA LWM2M Technical Specification:
* Contains the result of downloading or updating the firmware
* This Resource MAY be reported by sending Observe operation.
*
* @return Error code.
*/
arm_uc_error_t ARM_UCS_LWM2M_MONITOR_SendUpdateResult(arm_uc_monitor_result_t an_update_result)
{
ARM_UC_INIT_ERROR(result, ERR_NONE);
// If out of range of a legitimate update-result, send an "unspecified-error" result.
if (!ARM_UC_IsValidResult(an_update_result)) {
ARM_UC_SET_ERROR(result, ERR_INVALID_PARAMETER);
} else {
// Cast the arm_uc_monitor_result_t to a arm_ucs_lwm2m_result_t, and send it.
FirmwareUpdateResource::arm_ucs_lwm2m_result_t code =
(FirmwareUpdateResource::arm_ucs_lwm2m_result_t)an_update_result;
if (FirmwareUpdateResource::sendUpdateResult(code) != 0) {
ARM_UC_SET_ERROR(result, ERR_UNSPECIFIED);
}
}
return result;
}
/**
* @brief Send current firmware name.
* @details The firmware name is the SHA256 hash.
* @param name Pointer to buffer struct. Hash is stored as byte array.
* @return Error code.
*/
arm_uc_error_t ARM_UCS_LWM2M_MONITOR_SendName(arm_uc_buffer_t *name)
{
ARM_UC_INIT_ERROR(result, ERR_NONE);
if (!name || !name->ptr) {
ARM_UC_SET_ERROR(result, ERR_INVALID_PARAMETER);
} else if (FirmwareUpdateResource::sendPkgName(name->ptr, name->size) != 0) {
ARM_UC_SET_ERROR(result, ERR_UNSPECIFIED);
}
return result;
}
/**
* @brief Send current firmware version.
* @details The firmware version is the timestamp from the manifest that
* authorized the firmware.
* @param version Timestamp, 64 bit unsigned integer.
* @return Error code.
*/
arm_uc_error_t ARM_UCS_LWM2M_MONITOR_SendVersion(uint64_t version)
{
ARM_UC_INIT_ERROR(result, ERR_NONE);
if (FirmwareUpdateResource::sendPkgVersion(version) != 0) {
ARM_UC_SET_ERROR(result, ERR_UNSPECIFIED);
}
return result;
}
/**
* @brief Set the bootloader hash.
* @details The bootloader hash is a hash of the bootloader. This is
* used for tracking the version of the bootloader used.
* @param name Pointer to buffer struct. Hash is stored as byte array.
* @return Error code.
*/
arm_uc_error_t ARM_UCS_LWM2M_MONITOR_SetBootloaderHash(arm_uc_buffer_t *hash)
{
ARM_UC_INIT_ERROR(result, ERR_NONE);
if (DeviceMetadataResource::setBootloaderHash(hash) != 0) {
ARM_UC_SET_ERROR(result, ERR_UNSPECIFIED);
}
return result;
}
/**
* @brief Set the OEM bootloader hash.
* @details If the end-user has modified the bootloader the hash of the
* modified bootloader can be set here.
* @param name Pointer to buffer struct. Hash is stored as byte array.
* @return Error code.
*/
arm_uc_error_t ARM_UCS_LWM2M_MONITOR_SetOEMBootloaderHash(arm_uc_buffer_t *hash)
{
ARM_UC_INIT_ERROR(result, ERR_NONE);
if (DeviceMetadataResource::setOEMBootloaderHash(hash) != 0) {
ARM_UC_SET_ERROR(result, ERR_UNSPECIFIED);
}
return result;
}
#endif
| 31.477833
| 103
| 0.707042
|
marcuschangarm
|
3c1c58b0c647d3925e2cb2cb3232b4a8e84ef37c
| 872
|
cpp
|
C++
|
Pearly/src/Pearly/Renderer/Texture.cpp
|
JumpyLionnn/Pearly
|
2dce5f54144980cecd998a325422e56bff6c4c83
|
[
"Apache-2.0"
] | null | null | null |
Pearly/src/Pearly/Renderer/Texture.cpp
|
JumpyLionnn/Pearly
|
2dce5f54144980cecd998a325422e56bff6c4c83
|
[
"Apache-2.0"
] | null | null | null |
Pearly/src/Pearly/Renderer/Texture.cpp
|
JumpyLionnn/Pearly
|
2dce5f54144980cecd998a325422e56bff6c4c83
|
[
"Apache-2.0"
] | null | null | null |
#include "prpch.h"
#include "Texture.h"
#include "Renderer.h"
#include "Platform/OpenGL/OpenGLTexture.h"
namespace Pearly {
Ref<Texture2D> Texture2D::Create(uint32 width, uint32 height)
{
switch (Renderer::GetAPI())
{
case RendererAPI::API::None: PR_CORE_ASSERT(false, "Renderer API None is currently not supported!"); return nullptr;
case RendererAPI::API::OpenGL: return CreateRef<OpenGLTexture2D>(width, height);
}
PR_CORE_ASSERT(false, "Unknown Renderer API!");
return nullptr;
}
Ref<Texture2D> Texture2D::Create(const std::string& path)
{
switch (Renderer::GetAPI())
{
case RendererAPI::API::None: PR_CORE_ASSERT(false, "Renderer API None is currently not supported!"); return nullptr;
case RendererAPI::API::OpenGL: return CreateRef<OpenGLTexture2D>(path);
}
PR_CORE_ASSERT(false, "Unknown Renderer API!");
return nullptr;
}
}
| 27.25
| 118
| 0.729358
|
JumpyLionnn
|
3c1f396558e74f120b6cc10dc576dad44e7bce4f
| 3,048
|
cpp
|
C++
|
src/rtsp/RtpSink.cpp
|
7956968/miniRtspServer
|
1de66d613941cd036d63ef32e7284ed68cb4b8a4
|
[
"MIT"
] | 10
|
2020-07-28T01:14:49.000Z
|
2021-08-19T04:33:49.000Z
|
src/rtsp/RtpSink.cpp
|
TaoistLuo/miniRtspServer
|
1de66d613941cd036d63ef32e7284ed68cb4b8a4
|
[
"MIT"
] | null | null | null |
src/rtsp/RtpSink.cpp
|
TaoistLuo/miniRtspServer
|
1de66d613941cd036d63ef32e7284ed68cb4b8a4
|
[
"MIT"
] | 3
|
2020-09-15T11:14:55.000Z
|
2020-09-30T08:39:45.000Z
|
/*************************************************************************
Copyright (c) 2020 Taoist Luo
Create by: Taoist Luo
CSDN:https://blog.csdn.net/daichanzhang9734/article/details/107549026
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 <arpa/inet.h>
#include "RtpSink.h"
#include "Mylog.h"
RtpSink::RtpSink(Env* env,MediaSource* mediaSource, int payloadType) :
mMediaSource(mediaSource),
mSendPacketCallback(NULL),
mCsrcLen(0),
mExtension(0),
mPadding(0),
mVersion(RTP_VESION),
mPayloadType(payloadType),
mMarker(0),
mSeq(0),
mTimestamp(0),
mEnv(env)
{
uint32_t frameTime = 1000/(mMediaSource->getFps());
mEnv->addTimer(timeoutCallback,frameTime,true,this);
mSSRC = rand();
}
RtpSink::~RtpSink()
{
delete mTimerEvent;
}
void RtpSink::setSendFrameCallback(SendPacketCallback cb, void* arg1, void* arg2)
{
mSendPacketCallback = cb;
mArg1 = arg1;
mArg2 = arg2;
}
void RtpSink::sendRtpPacket(RtpPacket* packet)
{
RtpHeader* rtpHead = packet->mRtpHeadr;
rtpHead->csrcLen = mCsrcLen;
rtpHead->extension = mExtension;
rtpHead->padding = mPadding;
rtpHead->version = mVersion;
rtpHead->payloadType = mPayloadType;
rtpHead->marker = mMarker;
rtpHead->seq = htons(mSeq);
rtpHead->timestamp = htonl(mTimestamp);
rtpHead->ssrc = htonl(mSSRC);
packet->mSize += RTP_HEADER_SIZE;
if(mSendPacketCallback)
mSendPacketCallback(mArg1, mArg2, packet);
}
void RtpSink::timeoutCallback(void* arg)
{
RtpSink* rtpSink = (RtpSink*)arg;
AVFrame* frame = rtpSink->mMediaSource->getFrame();
if(!frame)
{
LOGI("get frame was NULL\n");
return;
}
rtpSink->handleFrame(frame);
rtpSink->mMediaSource->putFrame(frame);
}
void RtpSink::start(int ms)
{
//mTimerEvent->setTimeout((uint32_t)ms);
mTimerEvent->start(ms*1000,true);
}
void RtpSink::stop()
{
//mEnv->scheduler()->removeTimedEvent(mTimerId);
}
| 29.882353
| 81
| 0.682415
|
7956968
|
3c1fa063e155984fd3faf5cd2db03ea607393732
| 22,608
|
cpp
|
C++
|
olp-cpp-sdk-core/tests/client/PendingUrlRequestsTest.cpp
|
OstapKL/here-data-sdk-cpp
|
0f7e9078fd1b273d868337d4f859512ffd1782fb
|
[
"Apache-2.0"
] | 21
|
2019-07-03T07:26:52.000Z
|
2019-09-04T08:35:07.000Z
|
olp-cpp-sdk-core/tests/client/PendingUrlRequestsTest.cpp
|
OstapKL/here-data-sdk-cpp
|
0f7e9078fd1b273d868337d4f859512ffd1782fb
|
[
"Apache-2.0"
] | 639
|
2019-09-13T17:14:24.000Z
|
2020-05-13T11:49:14.000Z
|
olp-cpp-sdk-core/tests/client/PendingUrlRequestsTest.cpp
|
OstapKL/here-data-sdk-cpp
|
0f7e9078fd1b273d868337d4f859512ffd1782fb
|
[
"Apache-2.0"
] | 21
|
2020-05-14T15:32:28.000Z
|
2022-03-15T13:52:33.000Z
|
/*
* Copyright (C) 2020 HERE Europe B.V.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
* License-Filename: LICENSE
*/
#include <chrono>
#include <future>
#include <queue>
#include <sstream>
#include <string>
#include <thread>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <olp/core/client/ApiError.h>
#include <olp/core/client/OlpClient.h>
#include <olp/core/http/Network.h>
#include <olp/core/logging/Log.h>
#include "client/PendingUrlRequests.h"
namespace {
using olp::client::HttpResponse;
using olp::http::ErrorCode;
using ::testing::_;
namespace client = olp::client;
namespace http = olp::http;
static const std::string kGoodResponse = "Response1234";
static const std::string kBadResponse = "Cancelled";
constexpr int kCancelledStatus =
static_cast<int>(http::ErrorCode::CANCELLED_ERROR);
constexpr http::RequestId kRequestId = 1234u;
constexpr auto kSleepFor = std::chrono::seconds(1);
constexpr auto kWaitFor = std::chrono::seconds(5);
client::HttpResponse GetHttpResponse(ErrorCode error, std::string status) {
return client::HttpResponse(static_cast<int>(error), status);
}
client::HttpResponse GetHttpResponse(int http_status, std::string status,
http::Headers headers = {}) {
std::stringstream stream;
stream.str(std::move(status));
return client::HttpResponse(http_status, std::move(stream),
std::move(headers));
}
client::HttpResponse GetCancelledResponse() {
return {kCancelledStatus, "Operation cancelled"};
}
TEST(HttpResponseTest, Copy) {
{
SCOPED_TRACE("Error response");
auto response = GetHttpResponse(ErrorCode::CANCELLED_ERROR, kBadResponse);
auto copy_response = response;
std::string status;
std::string copy_status;
response.GetResponse(status);
copy_response.GetResponse(copy_status);
EXPECT_FALSE(status.empty());
EXPECT_FALSE(copy_status.empty());
EXPECT_TRUE(response.GetHeaders().empty());
EXPECT_TRUE(copy_response.GetHeaders().empty());
EXPECT_EQ(kBadResponse, status);
EXPECT_EQ(response.GetStatus(),
static_cast<int>(ErrorCode::CANCELLED_ERROR));
EXPECT_EQ(copy_response.GetStatus(), response.GetStatus());
EXPECT_EQ(status, copy_status);
}
{
SCOPED_TRACE("Valid response");
http::Headers headers = {{"header1", "value1"}, {"header2", "value2"}};
auto response =
GetHttpResponse(http::HttpStatusCode::OK, kGoodResponse, headers);
auto copy_response = response;
std::string status;
std::string copy_status;
response.GetResponse(status);
copy_response.GetResponse(copy_status);
EXPECT_FALSE(status.empty());
EXPECT_FALSE(copy_status.empty());
EXPECT_EQ(response.GetHeaders(), headers);
EXPECT_EQ(copy_response.GetHeaders(), headers);
EXPECT_EQ(kGoodResponse, status);
EXPECT_EQ(response.GetStatus(), http::HttpStatusCode::OK);
EXPECT_EQ(copy_response.GetStatus(), response.GetStatus());
EXPECT_EQ(status, copy_status);
}
}
TEST(HttpResponseTest, Move) {
{
SCOPED_TRACE("Error response");
auto response = GetHttpResponse(ErrorCode::CANCELLED_ERROR, kBadResponse);
auto copy_response = std::move(response);
std::string status;
std::string copy_status;
response.GetResponse(status);
copy_response.GetResponse(copy_status);
EXPECT_TRUE(status.empty());
EXPECT_FALSE(copy_status.empty());
EXPECT_TRUE(response.GetHeaders().empty());
EXPECT_TRUE(copy_response.GetHeaders().empty());
EXPECT_EQ(kBadResponse, copy_status);
EXPECT_EQ(copy_response.GetStatus(),
static_cast<int>(ErrorCode::CANCELLED_ERROR));
}
{
SCOPED_TRACE("Valid response");
http::Headers headers = {{"header1", "value1"}, {"header2", "value2"}};
auto response =
GetHttpResponse(http::HttpStatusCode::OK, kGoodResponse, headers);
auto copy_response = std::move(response);
std::string status;
std::string copy_status;
response.GetResponse(status);
copy_response.GetResponse(copy_status);
EXPECT_TRUE(status.empty());
EXPECT_FALSE(copy_status.empty());
EXPECT_TRUE(response.GetHeaders().empty());
EXPECT_EQ(copy_response.GetHeaders(), headers);
EXPECT_EQ(kGoodResponse, copy_status);
EXPECT_EQ(copy_response.GetStatus(), http::HttpStatusCode::OK);
}
}
void CheckHttResponse(client::HttpResponse& in, int status,
const std::string& response,
const http::Headers& headers) {
std::string response_in;
in.GetResponse(response_in);
EXPECT_EQ(response_in, response);
EXPECT_EQ(in.GetHeaders(), headers);
EXPECT_EQ(in.GetStatus(), status);
}
TEST(PendingUrlRequestsTest, IsCancelled) {
client::PendingUrlRequests pending_requests;
const std::string url1 = "url1";
const std::string url2 = "url2";
auto check_cancelled = [&](client::HttpResponse response) {
ASSERT_EQ(response.GetStatus(), kCancelledStatus);
};
auto check_not_cancelled = [&](client::HttpResponse response) {
ASSERT_NE(response.GetStatus(), kCancelledStatus);
};
auto complete_call = [&](http::RequestId request_id, const std::string& url) {
std::this_thread::sleep_for(kSleepFor);
pending_requests.OnRequestCompleted(
request_id, url,
GetHttpResponse(http::HttpStatusCode::OK, kGoodResponse,
{{"header1", "value1"}, {"header2", "value2"}}));
};
{
SCOPED_TRACE("Cancel one request");
auto request_valid = pending_requests[url1];
auto request_cancelled = pending_requests[url2];
ASSERT_TRUE(request_valid && request_cancelled);
request_valid->Append(check_not_cancelled);
auto request_id = request_cancelled->Append(check_cancelled);
ASSERT_FALSE(request_valid->IsCancelled());
ASSERT_FALSE(request_cancelled->IsCancelled());
std::future<void> future1, future2;
request_valid->ExecuteOrCancelled([&](http::RequestId& id) {
id = kRequestId;
future1 = std::async(std::launch::async, complete_call, id, url1);
return client::CancellationToken([] {
// Should not be called
EXPECT_TRUE(false) << "Cancellation called on not cancelled request";
});
});
request_cancelled->ExecuteOrCancelled([&](http::RequestId& id) {
id = kRequestId + 1;
return client::CancellationToken([&] {
future2 = std::async(std::launch::async, complete_call, id, url2);
});
});
EXPECT_TRUE(pending_requests.Cancel(url2, request_id));
EXPECT_FALSE(request_valid->IsCancelled());
EXPECT_TRUE(request_cancelled->IsCancelled());
ASSERT_EQ(future1.wait_for(kWaitFor), std::future_status::ready);
ASSERT_EQ(future2.wait_for(kWaitFor), std::future_status::ready);
// Cancell all and wait to leave a clean state for the next scope
ASSERT_TRUE(pending_requests.CancelAllAndWait());
}
{
SCOPED_TRACE("Cancel all requests");
auto request1 = pending_requests[url1];
auto request2 = pending_requests[url2];
ASSERT_TRUE(request1 && request2);
request1->Append(check_cancelled);
request2->Append(check_cancelled);
ASSERT_FALSE(request1->IsCancelled());
ASSERT_FALSE(request2->IsCancelled());
std::future<void> future1, future2;
request1->ExecuteOrCancelled([&](http::RequestId& id) {
id = kRequestId;
return client::CancellationToken([&] {
future1 = std::async(std::launch::async, complete_call, id, url1);
});
});
request2->ExecuteOrCancelled([&](http::RequestId& id) {
id = kRequestId + 1;
return client::CancellationToken([&] {
future2 = std::async(std::launch::async, complete_call, id, url2);
});
});
EXPECT_TRUE(pending_requests.CancelAll());
EXPECT_TRUE(request1->IsCancelled());
EXPECT_TRUE(request2->IsCancelled());
ASSERT_EQ(future1.wait_for(kWaitFor), std::future_status::ready);
ASSERT_EQ(future2.wait_for(kWaitFor), std::future_status::ready);
}
}
TEST(PendingUrlRequestsTest, CancelAllAndWait) {
client::PendingUrlRequests pending_requests;
const std::string url1 = "url1";
const std::string url2 = "url2";
auto request1 = pending_requests[url1];
auto request2 = pending_requests[url2];
ASSERT_TRUE(request1 && request2);
auto check_cancelled = [&](client::HttpResponse response) {
ASSERT_EQ(response.GetStatus(), kCancelledStatus);
};
request1->Append(check_cancelled);
request2->Append(check_cancelled);
auto cancel_call = [&](http::RequestId request_id, const std::string& url) {
std::this_thread::sleep_for(std::chrono::seconds(1));
pending_requests.OnRequestCompleted(request_id, url,
GetCancelledResponse());
};
const http::RequestId request_id = 1234;
std::future<void> future1, future2;
request1->ExecuteOrCancelled([&](http::RequestId& id) {
id = request_id;
return client::CancellationToken([&] {
future1 = std::async(std::launch::async, cancel_call, id, url1);
});
});
request2->ExecuteOrCancelled([&](http::RequestId& id) {
id = request_id + 1;
return client::CancellationToken([&] {
future2 = std::async(std::launch::async, cancel_call, id, url2);
});
});
// Once CancelAllAndWait is called, it should wait for all responses else we
// face crashes
ASSERT_TRUE(pending_requests.CancelAllAndWait());
ASSERT_EQ(future1.wait_for(std::chrono::milliseconds(1)),
std::future_status::ready);
ASSERT_EQ(future2.wait_for(std::chrono::milliseconds(1)),
std::future_status::ready);
}
TEST(PendingUrlRequestsTest, ExecuteOrCancelled) {
client::PendingUrlRequests pending_requests;
const std::string url = "url";
auto check_cancelled = [&](client::HttpResponse response) {
ASSERT_EQ(response.GetStatus(), kCancelledStatus);
};
// Check that ExecuteOrCancelled is behaving correctly
auto request_ptr = pending_requests[url];
ASSERT_TRUE(request_ptr);
ASSERT_FALSE(request_ptr->IsCancelled());
ASSERT_EQ(request_ptr.use_count(), 2);
request_ptr->Append(check_cancelled);
bool is_cancelled = false;
bool cancel_func_called = false;
std::future<void> future;
// Set request Id
request_ptr->ExecuteOrCancelled(
[&](http::RequestId& id) {
return client::CancellationToken([&] {
is_cancelled = true;
id = kRequestId;
future = std::async(
std::launch::async,
[&](http::RequestId request_id, const std::string& url) {
std::this_thread::sleep_for(kSleepFor);
pending_requests.OnRequestCompleted(
request_id, url,
GetHttpResponse(
http::HttpStatusCode::OK, kGoodResponse,
{{"header1", "value1"}, {"header2", "value2"}}));
},
id, url);
});
},
[] { EXPECT_TRUE(false) << "Cancel function should not be called!"; });
// Now cancel request and call again
request_ptr->CancelOperation();
request_ptr->ExecuteOrCancelled(
[](http::RequestId&) {
EXPECT_TRUE(false) << "Execute function should not be called!";
return client::CancellationToken();
},
[&] { cancel_func_called = true; });
EXPECT_TRUE(is_cancelled);
EXPECT_TRUE(cancel_func_called);
ASSERT_EQ(future.wait_for(kWaitFor), std::future_status::ready);
}
TEST(PendingUrlRequestsTest, SameUrlAfterCancel) {
// This test covers the use-case were you have a cancelled request which is in
// the process of waiting for the network cancel answer and afterwards a new
// request with the same URL. In this case both should exist at the same time,
// one in the pending request list the other in the cancelled list.
client::PendingUrlRequests pending_requests;
const std::string url = "url1";
std::future<void> future_cancelled, future_valid;
auto check_cancelled = [&](client::HttpResponse response) {
ASSERT_EQ(response.GetStatus(), kCancelledStatus);
};
auto check_not_cancelled = [&](client::HttpResponse response) {
ASSERT_NE(response.GetStatus(), kCancelledStatus);
};
// Add request to be cancelled
auto request_ptr = pending_requests[url];
ASSERT_TRUE(request_ptr);
ASSERT_FALSE(request_ptr->IsCancelled());
ASSERT_EQ(request_ptr.use_count(), 2);
auto cancel_id = request_ptr->Append(check_cancelled);
request_ptr->ExecuteOrCancelled([&](http::RequestId& id) {
id = kRequestId;
return client::CancellationToken([&] {
future_cancelled =
std::async(std::launch::async,
[&](http::RequestId request_id, const std::string& url) {
std::this_thread::sleep_for(kSleepFor);
pending_requests.OnRequestCompleted(
request_id, url,
GetHttpResponse(
http::HttpStatusCode::OK, kGoodResponse,
{{"header1", "value1"}, {"header2", "value2"}}));
},
id, url);
});
});
// Now cancel the request
EXPECT_TRUE(pending_requests.Cancel(url, cancel_id));
ASSERT_TRUE(request_ptr->IsCancelled());
// Add second request with the same url
auto new_request_ptr = pending_requests[url];
ASSERT_TRUE(new_request_ptr);
ASSERT_FALSE(new_request_ptr->IsCancelled());
ASSERT_EQ(new_request_ptr.use_count(), 2);
ASSERT_FALSE(new_request_ptr == request_ptr);
new_request_ptr->Append(check_not_cancelled);
new_request_ptr->ExecuteOrCancelled([&](http::RequestId& id) {
id = kRequestId + 1;
future_valid = std::async(
std::launch::async,
[&](http::RequestId request_id, const std::string& url) {
std::this_thread::sleep_for(kSleepFor);
pending_requests.OnRequestCompleted(
request_id, url,
GetHttpResponse(http::HttpStatusCode::OK, kGoodResponse,
{{"header1", "value1"}, {"header2", "value2"}}));
},
id, url);
return client::CancellationToken();
});
ASSERT_EQ(future_cancelled.wait_for(kWaitFor), std::future_status::ready);
ASSERT_EQ(future_valid.wait_for(kWaitFor), std::future_status::ready);
}
TEST(PendingUrlRequestsTest, CallbackCalled) {
client::PendingUrlRequests pending_requests;
const std::string url = "url1";
{
SCOPED_TRACE("Single callback");
auto request_ptr = pending_requests[url];
ASSERT_TRUE(request_ptr);
ASSERT_FALSE(request_ptr->IsCancelled());
ASSERT_EQ(request_ptr.use_count(), 2);
// Add one callback and check that it is triggered
client::HttpResponse response_out;
EXPECT_EQ(0u, request_ptr->Append([&](client::HttpResponse response) {
response_out = std::move(response);
}));
// Set request Id
const http::RequestId request_id = 1234;
request_ptr->ExecuteOrCancelled(
[&](http::RequestId& id) {
id = request_id;
return client::CancellationToken();
},
[] { EXPECT_TRUE(false) << "Cancel function should not be called!"; });
// Relese the pending request from local var to make sure we don't have
// any issues there.
request_ptr.reset();
// Now mark the request as completed and expect the callback to be called
http::Headers headers = {{"header1", "value1"}, {"header2", "value2"}};
const auto response_in =
GetHttpResponse(http::HttpStatusCode::OK, kGoodResponse, headers);
pending_requests.OnRequestCompleted(request_id, url, response_in);
EXPECT_NO_FATAL_FAILURE(CheckHttResponse(
response_out, response_in.GetStatus(), kGoodResponse, headers));
ASSERT_EQ(pending_requests.Size(), 0u)
<< "Pending requests should be empty";
}
{
SCOPED_TRACE("Multiple callbacks");
auto request_ptr = pending_requests[url];
ASSERT_TRUE(request_ptr);
ASSERT_FALSE(request_ptr->IsCancelled());
ASSERT_EQ(request_ptr.use_count(), 2);
// Add one callback and check that it is triggered
client::HttpResponse response_out_1, response_out_2;
EXPECT_EQ(0u, request_ptr->Append([&](client::HttpResponse response) {
response_out_1 = std::move(response);
}));
EXPECT_EQ(1u, request_ptr->Append([&](client::HttpResponse response) {
response_out_2 = std::move(response);
}));
// Set request Id
const http::RequestId request_id = 1234;
request_ptr->ExecuteOrCancelled(
[&](http::RequestId& id) {
id = request_id;
return client::CancellationToken();
},
[] { EXPECT_TRUE(false) << "Cancel function should not be called!"; });
// Relese the pending request from local var to make sure we don't have
// any issues there.
request_ptr.reset();
// Now mark the request as completed and expect the callback to be called
http::Headers headers = {{"header1", "value1"}, {"header2", "value2"}};
pending_requests.OnRequestCompleted(
request_id, url,
GetHttpResponse(http::HttpStatusCode::OK, kGoodResponse, headers));
EXPECT_NO_FATAL_FAILURE(CheckHttResponse(
response_out_1, http::HttpStatusCode::OK, kGoodResponse, headers));
EXPECT_NO_FATAL_FAILURE(CheckHttResponse(
response_out_2, http::HttpStatusCode::OK, kGoodResponse, headers));
ASSERT_EQ(pending_requests.Size(), 0u)
<< "Pending requests should be empty";
}
{
SCOPED_TRACE("Multiple callbacks, one cancelled");
auto request_ptr = pending_requests[url];
ASSERT_TRUE(request_ptr);
ASSERT_FALSE(request_ptr->IsCancelled());
ASSERT_EQ(request_ptr.use_count(), 2);
client::HttpResponse response_good, response_cancelled;
EXPECT_EQ(0u, request_ptr->Append([&](client::HttpResponse response) {
response_good = std::move(response);
}));
auto callback_id = request_ptr->Append([&](client::HttpResponse response) {
response_cancelled = std::move(response);
});
EXPECT_EQ(callback_id, 1u);
// Set request Id
const http::RequestId request_id = 1234;
request_ptr->ExecuteOrCancelled(
[&](http::RequestId& id) {
id = request_id;
return client::CancellationToken();
},
[] { EXPECT_TRUE(false) << "Cancel function should not be called!"; });
// Cancel second request and check that request is not cancelled fully
pending_requests.Cancel(url, callback_id);
ASSERT_FALSE(request_ptr->IsCancelled());
http::Headers headers = {{"header1", "value1"}, {"header2", "value2"}};
pending_requests.OnRequestCompleted(
request_id, url,
GetHttpResponse(http::HttpStatusCode::OK, kGoodResponse, headers));
EXPECT_NO_FATAL_FAILURE(CheckHttResponse(
response_good, http::HttpStatusCode::OK, kGoodResponse, headers));
std::string cancelled_response;
auto cancelled_expected = GetCancelledResponse();
cancelled_expected.GetResponse(cancelled_response);
EXPECT_NO_FATAL_FAILURE(CheckHttResponse(response_cancelled,
cancelled_expected.GetStatus(),
cancelled_response, {}));
}
}
TEST(PendingUrlRequestsTest, CancelCallback) {
client::PendingUrlRequests pending_requests;
const std::string url1 = "url1", url2 = "url2", url3 = "url3";
http::RequestId request_id = 1234;
auto response_call = [&](http::RequestId request_id, const std::string& url) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
pending_requests.OnRequestCompleted(
request_id, url,
GetHttpResponse(http::HttpStatusCode::OK, kGoodResponse));
};
{
SCOPED_TRACE("Single callback cancelled");
auto request_ptr = pending_requests[url1];
ASSERT_TRUE(request_ptr);
// Add one callback and check that it is triggered and it is cancelled
auto callback_id = request_ptr->Append([&](client::HttpResponse response) {
ASSERT_EQ(response.GetStatus(), kCancelledStatus);
});
request_ptr->ExecuteOrCancelled([&](http::RequestId& id) {
id = ++request_id;
return client::CancellationToken();
});
EXPECT_TRUE(pending_requests.Cancel(url1, callback_id));
// Trigger and wait for response
std::async(std::launch::async, response_call, request_id, url1).get();
}
{
SCOPED_TRACE("Multiple callbacks, one cancelled");
auto request_ptr = pending_requests[url1];
ASSERT_TRUE(request_ptr);
// Add one callback and check that it is triggered and it is cancelled
request_ptr->Append([&](client::HttpResponse response) {
ASSERT_NE(response.GetStatus(), kCancelledStatus);
});
request_ptr->ExecuteOrCancelled([&](http::RequestId& id) {
id = ++request_id;
return client::CancellationToken();
});
auto callback_id = request_ptr->Append([&](client::HttpResponse response) {
ASSERT_EQ(response.GetStatus(), kCancelledStatus);
});
EXPECT_TRUE(pending_requests.Cancel(url1, callback_id));
// Trigger and wait for response
std::async(std::launch::async, response_call, request_id, url1).get();
}
{
SCOPED_TRACE("Multiple callbacks, unknown cancelled");
auto request_ptr = pending_requests[url1];
ASSERT_TRUE(request_ptr);
// Add one callback and check that it is triggered and it is cancelled
request_ptr->Append([&](client::HttpResponse response) {
ASSERT_NE(response.GetStatus(), kCancelledStatus);
});
auto callback_id = request_ptr->Append([&](client::HttpResponse response) {
ASSERT_NE(response.GetStatus(), kCancelledStatus);
});
request_ptr->ExecuteOrCancelled([&](http::RequestId& id) {
id = ++request_id;
return client::CancellationToken();
});
EXPECT_FALSE(pending_requests.Cancel(url1, callback_id + 15));
// Trigger and wait for response
std::async(std::launch::async, response_call, request_id, url1).get();
}
}
} // namespace
| 33.394387
| 80
| 0.675159
|
OstapKL
|
3c212a755a5bb5e9b921802faf3207fc8dd6b63f
| 2,448
|
cpp
|
C++
|
android-31/android/inputmethodservice/AbstractInputMethodService.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 12
|
2020-03-26T02:38:56.000Z
|
2022-03-14T08:17:26.000Z
|
android-31/android/inputmethodservice/AbstractInputMethodService.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 1
|
2021-01-27T06:07:45.000Z
|
2021-11-13T19:19:43.000Z
|
android-31/android/inputmethodservice/AbstractInputMethodService.cpp
|
YJBeetle/QtAndroidAPI
|
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
|
[
"Apache-2.0"
] | 3
|
2021-02-02T12:34:55.000Z
|
2022-03-08T07:45:57.000Z
|
#include "../../JArray.hpp"
#include "../content/Intent.hpp"
#include "./AbstractInputMethodService_AbstractInputMethodImpl.hpp"
#include "./AbstractInputMethodService_AbstractInputMethodSessionImpl.hpp"
#include "../view/KeyEvent_DispatcherState.hpp"
#include "../view/MotionEvent.hpp"
#include "../../java/io/FileDescriptor.hpp"
#include "../../java/io/PrintWriter.hpp"
#include "./AbstractInputMethodService.hpp"
namespace android::inputmethodservice
{
// Fields
// QJniObject forward
AbstractInputMethodService::AbstractInputMethodService(QJniObject obj) : android::app::Service(obj) {}
// Constructors
AbstractInputMethodService::AbstractInputMethodService()
: android::app::Service(
"android.inputmethodservice.AbstractInputMethodService",
"()V"
) {}
// Methods
android::view::KeyEvent_DispatcherState AbstractInputMethodService::getKeyDispatcherState() const
{
return callObjectMethod(
"getKeyDispatcherState",
"()Landroid/view/KeyEvent$DispatcherState;"
);
}
jboolean AbstractInputMethodService::isUiContext() const
{
return callMethod<jboolean>(
"isUiContext",
"()Z"
);
}
JObject AbstractInputMethodService::onBind(android::content::Intent arg0) const
{
return callObjectMethod(
"onBind",
"(Landroid/content/Intent;)Landroid/os/IBinder;",
arg0.object()
);
}
android::inputmethodservice::AbstractInputMethodService_AbstractInputMethodImpl AbstractInputMethodService::onCreateInputMethodInterface() const
{
return callObjectMethod(
"onCreateInputMethodInterface",
"()Landroid/inputmethodservice/AbstractInputMethodService$AbstractInputMethodImpl;"
);
}
android::inputmethodservice::AbstractInputMethodService_AbstractInputMethodSessionImpl AbstractInputMethodService::onCreateInputMethodSessionInterface() const
{
return callObjectMethod(
"onCreateInputMethodSessionInterface",
"()Landroid/inputmethodservice/AbstractInputMethodService$AbstractInputMethodSessionImpl;"
);
}
jboolean AbstractInputMethodService::onGenericMotionEvent(android::view::MotionEvent arg0) const
{
return callMethod<jboolean>(
"onGenericMotionEvent",
"(Landroid/view/MotionEvent;)Z",
arg0.object()
);
}
jboolean AbstractInputMethodService::onTrackballEvent(android::view::MotionEvent arg0) const
{
return callMethod<jboolean>(
"onTrackballEvent",
"(Landroid/view/MotionEvent;)Z",
arg0.object()
);
}
} // namespace android::inputmethodservice
| 30.6
| 159
| 0.774918
|
YJBeetle
|
3c21ffb618f6158cc3d225adc5e6ead2a878075f
| 396
|
cpp
|
C++
|
ds3runtime/scripts/sync_call_script.cpp
|
tremwil/DS3RuntimeScripting
|
50508bbf9295f87c459722ea3bea015c85a36de5
|
[
"MIT"
] | 8
|
2021-06-05T21:59:53.000Z
|
2022-02-03T10:00:09.000Z
|
ds3runtime/scripts/sync_call_script.cpp
|
tremwil/DS3RuntimeScripting
|
50508bbf9295f87c459722ea3bea015c85a36de5
|
[
"MIT"
] | null | null | null |
ds3runtime/scripts/sync_call_script.cpp
|
tremwil/DS3RuntimeScripting
|
50508bbf9295f87c459722ea3bea015c85a36de5
|
[
"MIT"
] | 5
|
2021-05-17T19:49:29.000Z
|
2022-02-26T11:00:29.000Z
|
/*
* DS3RuntimeScripting
* Contributers: Amir
*/
#pragma once
#include "pch.h"
#include "sync_call_script.h"
#include "ds3runtime/ds3runtime.h"
namespace ds3runtime {
void SyncCallScript::execute()
{
for (auto bulletSpawn : syncBullets) bulletSpawn.launch();
syncBullets.clear();
}
void SyncCallScript::launchBulletSync(BulletSpawn bulletSpawn) {
syncBullets.push_back(bulletSpawn);
}
}
| 17.217391
| 64
| 0.760101
|
tremwil
|
3c228ea65f934c84c768568390d6b2a66ab56a81
| 1,250
|
cpp
|
C++
|
LeetCode/SwapNodesInPairs.cpp
|
Michael-Ma/Coding-Practice
|
6ab3d76ae1cd3a97046b399c59d6bf2b135d7b5f
|
[
"MIT"
] | null | null | null |
LeetCode/SwapNodesInPairs.cpp
|
Michael-Ma/Coding-Practice
|
6ab3d76ae1cd3a97046b399c59d6bf2b135d7b5f
|
[
"MIT"
] | null | null | null |
LeetCode/SwapNodesInPairs.cpp
|
Michael-Ma/Coding-Practice
|
6ab3d76ae1cd3a97046b399c59d6bf2b135d7b5f
|
[
"MIT"
] | null | null | null |
#include <sstream>
#include <stdio.h>
#include <string>
#include <cstring>
#include <iostream>
#include <vector>
#include <map>
#include <stack>
#include <queue>
#include <set>
#include <cmath>
#include <algorithm>
#include <cfloat>
#include <climits>
//#include <unordered_set>
//#include <unordered_map>
using namespace std;
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
/*
Time Complexity : O(n)
Space Complexity : O(1)
Trick:
Special Cases :
Summary:
using dummy head is pretty neat!
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head==NULL || head->next==NULL){
return head;
}
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* cur = head->next;
ListNode* pre = dummyHead;
while(cur != NULL){
pre->next->next = cur->next;
cur->next = pre->next;
pre->next = cur;
cur = cur->next->next;
if(cur!=NULL){
cur = cur->next;
pre = pre->next->next;
}
}
return dummyHead->next;
}
};
| 21.186441
| 46
| 0.5528
|
Michael-Ma
|
3c2343c690bdbd2d26b2f2643ed7bff7572a6670
| 11,419
|
cpp
|
C++
|
src/task_jump_2.cpp
|
RPGP1/task-draft
|
5459ea24b717c690d00909b77a76f599828f3566
|
[
"Unlicense"
] | null | null | null |
src/task_jump_2.cpp
|
RPGP1/task-draft
|
5459ea24b717c690d00909b77a76f599828f3566
|
[
"Unlicense"
] | null | null | null |
src/task_jump_2.cpp
|
RPGP1/task-draft
|
5459ea24b717c690d00909b77a76f599828f3566
|
[
"Unlicense"
] | null | null | null |
#include "task_jump.hpp"
namespace TaskManager
{
namespace Expr
{
Jump::JumpManager::JumpManagerOperator::JumpManagerOperator(const std::shared_ptr<JumpManager>& _jump_manager, const std::shared_ptr<TaskSet>& _taskset) noexcept
: JumpIf{_jump_manager, _taskset},
JumpBackIf{_jump_manager, _taskset}
{
}
Jump::JumpManager::JumpManagerOperator::JumpManagerOperator(std::shared_ptr<JumpManager>&& _jump_manager, std::shared_ptr<TaskSet>&& _taskset) noexcept
: JumpIf{_jump_manager, _taskset},
JumpBackIf{std::move(_jump_manager), std::move(_taskset)}
{
}
Jump::JumpManager::JumpManagerOperator::JumpIfCondition::JumpIfCondition(const std::shared_ptr<JumpManager>& _jump_manager, int _priority, const std::function<bool()>& _func, const std::shared_ptr<TaskSet>& _taskset) noexcept
: m_jump_manager{_jump_manager},
m_priority{_priority},
m_func{_func},
m_taskset{_taskset}
{
}
Jump::JumpManager::JumpManagerOperator::JumpIfCondition::JumpIfCondition(const std::shared_ptr<JumpManager>& _jump_manager, int _priority, std::function<bool()>&& _func, const std::shared_ptr<TaskSet>& _taskset) noexcept
: m_jump_manager{_jump_manager},
m_priority{_priority},
m_func{std::move(_func)},
m_taskset{_taskset}
{
}
Jump::JumpManager::JumpManagerOperator::JumpIfCondition::JumpIfCondition(std::shared_ptr<JumpManager>&& _jump_manager, int _priority, const std::function<bool()>& _func, std::shared_ptr<TaskSet>&& _taskset) noexcept
: m_jump_manager{std::move(_jump_manager)},
m_priority{_priority},
m_func{_func},
m_taskset{std::move(_taskset)}
{
}
Jump::JumpManager::JumpManagerOperator::JumpIfCondition::JumpIfCondition(std::shared_ptr<JumpManager>&& _jump_manager, int _priority, std::function<bool()>&& _func, std::shared_ptr<TaskSet>&& _taskset) noexcept
: m_jump_manager{_jump_manager},
m_priority{_priority},
m_func{std::move(_func)},
m_taskset{std::move(_taskset)}
{
}
Jump Jump::JumpManager::JumpManagerOperator::JumpIfCondition::operator()(std::nullptr_t) const& noexcept
{
if (m_jump_manager) {
if (auto& jump_list = m_jump_manager->m_jump_list) {
(*jump_list)[m_priority].emplace_back(m_func, JumpType::OneWay, nullptr);
}
}
return {m_taskset, m_jump_manager};
}
Jump Jump::JumpManager::JumpManagerOperator::JumpIfCondition::operator()(std::nullptr_t) && noexcept
{
if (m_jump_manager) {
if (auto& jump_list = m_jump_manager->m_jump_list) {
(*jump_list)[m_priority].emplace_back(std::move(m_func), JumpType::OneWay, nullptr);
}
}
return {std::move(m_taskset), std::move(m_jump_manager)};
}
Jump::JumpManager::JumpManagerOperator::JumpIfClass::JumpIfClass(const std::shared_ptr<JumpManager>& _jump_manager, const std::shared_ptr<TaskSet>& _taskset) noexcept
: m_jump_manager{_jump_manager},
m_taskset{_taskset}
{
}
Jump::JumpManager::JumpManagerOperator::JumpIfClass Jump::JumpManager::JumpManagerOperator::JumpIfClass::operator[](int _priority) const& noexcept
{
JumpIfClass tmp{*this};
tmp.m_priority = _priority;
return tmp;
}
Jump::JumpManager::JumpManagerOperator::JumpIfClass Jump::JumpManager::JumpManagerOperator::JumpIfClass::operator[](int _priority) && noexcept
{
JumpIfClass tmp{std::move(*this)};
tmp.m_priority = _priority;
return tmp;
}
Jump::JumpManager::JumpManagerOperator::JumpIfCondition Jump::JumpManager::JumpManagerOperator::JumpIfClass::operator[](const std::function<bool()>& _func) const& noexcept
{
return {m_jump_manager, m_priority, _func, m_taskset};
}
Jump::JumpManager::JumpManagerOperator::JumpIfCondition Jump::JumpManager::JumpManagerOperator::JumpIfClass::operator[](std::function<bool()>&& _func) const& noexcept
{
return {m_jump_manager, m_priority, std::move(_func), m_taskset};
}
Jump::JumpManager::JumpManagerOperator::JumpIfCondition Jump::JumpManager::JumpManagerOperator::JumpIfClass::operator()(const std::function<bool()>& _func) const& noexcept
{
return {m_jump_manager, m_priority, _func, m_taskset};
}
Jump::JumpManager::JumpManagerOperator::JumpIfCondition Jump::JumpManager::JumpManagerOperator::JumpIfClass::operator()(std::function<bool()>&& _func) const& noexcept
{
return {m_jump_manager, m_priority, std::move(_func), m_taskset};
}
Jump::JumpManager::JumpManagerOperator::JumpIfCondition Jump::JumpManager::JumpManagerOperator::JumpIfClass::operator[](const std::function<bool()>& _func) && noexcept
{
return {std::move(m_jump_manager), m_priority, _func, std::move(m_taskset)};
}
Jump::JumpManager::JumpManagerOperator::JumpIfCondition Jump::JumpManager::JumpManagerOperator::JumpIfClass::operator[](std::function<bool()>&& _func) && noexcept
{
return {std::move(m_jump_manager), m_priority, std::move(_func), std::move(m_taskset)};
}
Jump::JumpManager::JumpManagerOperator::JumpIfCondition Jump::JumpManager::JumpManagerOperator::JumpIfClass::operator()(const std::function<bool()>& _func) && noexcept
{
return {std::move(m_jump_manager), m_priority, _func, std::move(m_taskset)};
}
Jump::JumpManager::JumpManagerOperator::JumpIfCondition Jump::JumpManager::JumpManagerOperator::JumpIfClass::operator()(std::function<bool()>&& _func) && noexcept
{
return {std::move(m_jump_manager), m_priority, std::move(_func), std::move(m_taskset)};
}
Jump::JumpManager::JumpManagerOperator::JumpBackIfCondition::JumpBackIfCondition(const std::shared_ptr<JumpManager>& _jump_manager, int _priority, const std::function<bool()>& _func, const std::shared_ptr<TaskSet>& _taskset) noexcept
: m_jump_manager{_jump_manager},
m_priority{_priority},
m_func{_func},
m_taskset{_taskset}
{
}
Jump::JumpManager::JumpManagerOperator::JumpBackIfCondition::JumpBackIfCondition(const std::shared_ptr<JumpManager>& _jump_manager, int _priority, std::function<bool()>&& _func, const std::shared_ptr<TaskSet>& _taskset) noexcept
: m_jump_manager{_jump_manager},
m_priority{_priority},
m_func{std::move(_func)},
m_taskset{_taskset}
{
}
Jump::JumpManager::JumpManagerOperator::JumpBackIfCondition::JumpBackIfCondition(std::shared_ptr<JumpManager>&& _jump_manager, int _priority, const std::function<bool()>& _func, std::shared_ptr<TaskSet>&& _taskset) noexcept
: m_jump_manager{std::move(_jump_manager)},
m_priority{_priority},
m_func{_func},
m_taskset{std::move(_taskset)}
{
}
Jump::JumpManager::JumpManagerOperator::JumpBackIfCondition::JumpBackIfCondition(std::shared_ptr<JumpManager>&& _jump_manager, int _priority, std::function<bool()>&& _func, std::shared_ptr<TaskSet>&& _taskset) noexcept
: m_jump_manager{std::move(_jump_manager)},
m_priority{_priority},
m_func{std::move(_func)},
m_taskset{std::move(_taskset)}
{
}
Jump Jump::JumpManager::JumpManagerOperator::JumpBackIfCondition::operator()(std::nullptr_t) const& noexcept
{
if (m_jump_manager) {
if (auto& jump_list = m_jump_manager->m_jump_list) {
(*jump_list)[m_priority].emplace_back(m_func, JumpType::ReturnBack, nullptr);
}
}
return {m_taskset, m_jump_manager};
}
Jump Jump::JumpManager::JumpManagerOperator::JumpBackIfCondition::operator()(std::nullptr_t) && noexcept
{
if (m_jump_manager) {
if (auto& jump_list = m_jump_manager->m_jump_list) {
(*jump_list)[m_priority].emplace_back(std::move(m_func), JumpType::ReturnBack, nullptr);
}
}
return {std::move(m_taskset), std::move(m_jump_manager)};
}
Jump::JumpManager::JumpManagerOperator::JumpBackIfClass::JumpBackIfClass(const std::shared_ptr<JumpManager>& _jump_manager, const std::shared_ptr<TaskSet>& _taskset) noexcept
: m_jump_manager{_jump_manager},
m_taskset{_taskset}
{
}
Jump::JumpManager::JumpManagerOperator::JumpBackIfClass::JumpBackIfClass(std::shared_ptr<JumpManager>&& _jump_manager, std::shared_ptr<TaskSet>&& _taskset) noexcept
: m_jump_manager{std::move(_jump_manager)},
m_taskset{std::move(_taskset)}
{
}
Jump::JumpManager::JumpManagerOperator::JumpBackIfClass Jump::JumpManager::JumpManagerOperator::JumpBackIfClass::operator[](int _priority) const& noexcept
{
JumpBackIfClass tmp{*this};
tmp.m_priority = _priority;
return tmp;
}
Jump::JumpManager::JumpManagerOperator::JumpBackIfClass Jump::JumpManager::JumpManagerOperator::JumpBackIfClass::operator[](int _priority) && noexcept
{
JumpBackIfClass tmp{std::move(*this)};
tmp.m_priority = _priority;
return tmp;
}
Jump::JumpManager::JumpManagerOperator::JumpBackIfCondition Jump::JumpManager::JumpManagerOperator::JumpBackIfClass::operator[](const std::function<bool()>& _func) const& noexcept
{
return {m_jump_manager, m_priority, _func, m_taskset};
}
Jump::JumpManager::JumpManagerOperator::JumpBackIfCondition Jump::JumpManager::JumpManagerOperator::JumpBackIfClass::operator[](std::function<bool()>&& _func) const& noexcept
{
return {m_jump_manager, m_priority, std::move(_func), m_taskset};
}
Jump::JumpManager::JumpManagerOperator::JumpBackIfCondition Jump::JumpManager::JumpManagerOperator::JumpBackIfClass::operator()(const std::function<bool()>& _func) const& noexcept
{
return {m_jump_manager, m_priority, _func, m_taskset};
}
Jump::JumpManager::JumpManagerOperator::JumpBackIfCondition Jump::JumpManager::JumpManagerOperator::JumpBackIfClass::operator()(std::function<bool()>&& _func) const& noexcept
{
return {m_jump_manager, m_priority, std::move(_func), m_taskset};
}
Jump::JumpManager::JumpManagerOperator::JumpBackIfCondition Jump::JumpManager::JumpManagerOperator::JumpBackIfClass::operator[](const std::function<bool()>& _func) && noexcept
{
return {std::move(m_jump_manager), m_priority, _func, std::move(m_taskset)};
}
Jump::JumpManager::JumpManagerOperator::JumpBackIfCondition Jump::JumpManager::JumpManagerOperator::JumpBackIfClass::operator[](std::function<bool()>&& _func) && noexcept
{
return {std::move(m_jump_manager), m_priority, std::move(_func), std::move(m_taskset)};
}
Jump::JumpManager::JumpManagerOperator::JumpBackIfCondition Jump::JumpManager::JumpManagerOperator::JumpBackIfClass::operator()(const std::function<bool()>& _func) && noexcept
{
return {std::move(m_jump_manager), m_priority, _func, std::move(m_taskset)};
}
Jump::JumpManager::JumpManagerOperator::JumpBackIfCondition Jump::JumpManager::JumpManagerOperator::JumpBackIfClass::operator()(std::function<bool()>&& _func) && noexcept
{
return {std::move(m_jump_manager), m_priority, std::move(_func), std::move(m_taskset)};
}
} //namespace Expr
} //namespace TaskManager
| 47.978992
| 237
| 0.694894
|
RPGP1
|
3c2501530d7d4246a772f5c0f774edcf08c6e9dc
| 3,857
|
cpp
|
C++
|
libraries/wallet/cache.cpp
|
siwelo/bitshares-2
|
03561bfcf97801b44863bd51c400aae3ba51e3b0
|
[
"MIT"
] | null | null | null |
libraries/wallet/cache.cpp
|
siwelo/bitshares-2
|
03561bfcf97801b44863bd51c400aae3ba51e3b0
|
[
"MIT"
] | null | null | null |
libraries/wallet/cache.cpp
|
siwelo/bitshares-2
|
03561bfcf97801b44863bd51c400aae3ba51e3b0
|
[
"MIT"
] | null | null | null |
/*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
* 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. Any modified source or binaries are used only with the BitShares network.
*
* 2. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 3. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <graphene/chain/account_object.hpp>
#include <graphene/chain/asset_object.hpp>
#include <graphene/chain/committee_member_object.hpp>
#include <graphene/chain/witness_object.hpp>
#include <graphene/chain/market_evaluator.hpp>
#include <graphene/chain/proposal_object.hpp>
#include <graphene/chain/operation_history_object.hpp>
#include <graphene/chain/withdraw_permission_object.hpp>
using namespace fc;
using namespace graphene::chain;
namespace graphene { namespace wallet {
template< typename ObjectType >
object* create_object_of_type( const variant& v )
{
return new ObjectType( v.as<ObjectType>() );
}
object* create_object( const variant& v )
{
const variant_object& obj = v.get_object();
object_id_type obj_id = obj["id"].as< object_id_type >();
FC_ASSERT( obj_id.type() == protocol_ids );
//
// Sufficiently clever template metaprogramming might
// be able to convince the compiler to emit this switch
// instead of creating it explicitly.
//
switch( obj_id.space() )
{
/*
case null_object_type:
return nullptr;
case base_object_type:
return create_object_of_type< base_object >( v );
*/
case account_object_type:
return create_object_of_type< account_object >( v );
case asset_object_type:
return create_object_of_type< asset_object >( v );
case force_settlement_object_type:
return create_object_of_type< force_settlement_object >( v );
case committee_member_object_type:
return create_object_of_type< committee_member_object >( v );
case witness_object_type:
return create_object_of_type< witness_object >( v );
case limit_order_object_type:
return create_object_of_type< limit_order_object >( v );
case call_order_object_type:
return create_object_of_type< call_order_object >( v );
/*
case custom_object_type:
return create_object_of_type< custom_object >( v );
*/
case proposal_object_type:
return create_object_of_type< proposal_object >( v );
case operation_history_object_type:
return create_object_of_type< operation_history_object >( v );
case withdraw_permission_object_type:
return create_object_of_type< withdraw_permission_object >( v );
default:
;
}
FC_ASSERT( false, "unknown type_id" );
}
} }
| 41.473118
| 208
| 0.736064
|
siwelo
|
3c298f4a5eaab9ef894d24e30415b6742ef64ff5
| 1,116
|
cpp
|
C++
|
Session_05/2019/00_Particle/src/ofApp.cpp
|
SAIC-ATS/ARTTECH3135
|
179805d373601ac92dcdbb51ddc4925fc65f7c22
|
[
"MIT"
] | 26
|
2015-09-23T12:31:16.000Z
|
2020-12-14T03:19:19.000Z
|
Session_05/2019/00_Particle/src/ofApp.cpp
|
SAIC-ATS/ARTTECH3135
|
179805d373601ac92dcdbb51ddc4925fc65f7c22
|
[
"MIT"
] | 2
|
2017-07-05T18:14:52.000Z
|
2017-10-31T00:04:13.000Z
|
Session_05/2019/00_Particle/src/ofApp.cpp
|
SAIC-ATS/ARTTECH3135
|
179805d373601ac92dcdbb51ddc4925fc65f7c22
|
[
"MIT"
] | 37
|
2015-09-19T22:10:32.000Z
|
2019-12-07T19:35:55.000Z
|
#include "ofApp.h"
void ofApp::setup()
{
// ofSetFrameRate(1)
ofBackground(80);
position.x = ofGetWidth() / 2;
position.y = 0;
position.z = 0;
// Alternative syntax.
velocity = { 0, 0, 0 };
// Acceleration due to gravity.
// We only accelerate in the +y direction (down on screen).
acceleration = { 0, .5, 0 };
}
void ofApp::update()
{
// position.x = position.x + velocity.x;
// position.y = position.y + velocity.y;
// position.z = position.z + velocity.z;
// is ...
// position = position + velocity;
// is ...
velocity += acceleration;
position += velocity;
// "Bounce on the bottom condition."
if (position.y + ballRadius > ofGetHeight())
{
// Change its direction!
velocity.y = velocity.y * -1;
// Steal some of its velocity.
velocity.y = velocity.y * 0.90;
// Reset the ball to the "correct" position.
position.y = ofGetHeight() - ballRadius;
}
}
void ofApp::draw()
{
ofDrawCircle(position, ballRadius);
}
| 19.241379
| 63
| 0.545699
|
SAIC-ATS
|
3c2a85dfd511265cc1c722cc0044f23ef623185f
| 1,245
|
cpp
|
C++
|
source/tracer/GlobalTrace.cpp
|
xzrunner/raytracing
|
c130691a92fab2cc9605f04534f42ca9b99e6fde
|
[
"MIT"
] | null | null | null |
source/tracer/GlobalTrace.cpp
|
xzrunner/raytracing
|
c130691a92fab2cc9605f04534f42ca9b99e6fde
|
[
"MIT"
] | null | null | null |
source/tracer/GlobalTrace.cpp
|
xzrunner/raytracing
|
c130691a92fab2cc9605f04534f42ca9b99e6fde
|
[
"MIT"
] | null | null | null |
#include "raytracing/tracer/GlobalTrace.h"
#include "raytracing/world/World.h"
#include "raytracing/material/Material.h"
#include "raytracing/utilities/ShadeRec.h"
#include "raytracing/utilities/Constants.h"
namespace rt
{
GlobalTrace::GlobalTrace(const World& world)
: Tracer(world)
{
}
RGBColor GlobalTrace::TraceRay(const Ray& ray, int depth) const
{
if (depth > m_world.GetViewPlane().GetMaxDepth())
{
// return BLACK;
return WHITE;
}
else
{
ShadeRec sr(m_world.HitObjects(ray));
if (sr.hit_an_object) {
sr.depth = depth;
sr.ray = ray;
return sr.material->GlobalShade(sr);
} else {
return m_world.GetBackgroundColor();
}
}
}
RGBColor GlobalTrace::TraceRay(const Ray& ray, double& tmin, int depth) const
{
if (depth > m_world.GetViewPlane().GetMaxDepth())
{
tmin = HUGE_VALUE;
// return BLACK;
return WHITE;
}
else
{
ShadeRec sr(m_world.HitObjects(ray));
if (sr.hit_an_object)
{
sr.depth = depth;
sr.ray = ray;
tmin = sr.t; // required for colored transparency
return sr.material->GlobalShade(sr);
}
else
{
tmin = HUGE_VALUE;
return m_world.GetBackgroundColor();
}
}
}
}
| 19.453125
| 77
| 0.636145
|
xzrunner
|
3c2ea94823802909038a93a49ee82226fd5f3c2f
| 1,966
|
hpp
|
C++
|
lkCommon/include/lkCommon/Utils/StaticStack.hpp
|
lookeypl/lkCommon
|
efd08396f2b151a320e103bd8111b745246b44e8
|
[
"WTFPL"
] | 1
|
2020-11-11T20:05:19.000Z
|
2020-11-11T20:05:19.000Z
|
lkCommon/include/lkCommon/Utils/StaticStack.hpp
|
lookeypl/lkCommon
|
efd08396f2b151a320e103bd8111b745246b44e8
|
[
"WTFPL"
] | null | null | null |
lkCommon/include/lkCommon/Utils/StaticStack.hpp
|
lookeypl/lkCommon
|
efd08396f2b151a320e103bd8111b745246b44e8
|
[
"WTFPL"
] | null | null | null |
#pragma once
#define _LKCOMMON_UTILS_STATIC_STACK_HPP_
#include "lkCommon/lkCommon.hpp"
#include <stddef.h>
namespace lkCommon {
namespace Utils {
/**
* A lightweight LIFO stack implementation with zero dynamic allocations.
*
* @warning For performance, this stack does not perform any checks on
* Release code. All error checks are done with asserts.
*/
template <typename T, size_t N>
class StaticStack
{
T mStack[N];
size_t mStackPointer;
public:
/**
* Constructs and initializes stack.
*/
StaticStack();
/**
* Default destructor.
*/
~StaticStack() = default;
/**
* Push existing element on top of stack.
*
* @p[in] element Element to be pushed on top of stack.
*
* @note Exceptional situations (like exceeding stack's size) are detected
* only with debug assertions.
*/
void Push(const T& element);
/**
* Construct in-place element on top of stack.
*
* @p[in] args Arguments passed to element's constructor.
*
* @note Exceptional situations (like exceeding stack's size) are detected
* only with debug assertions.
*/
template <typename... Args>
void Emplace(Args&&... args);
/**
* Get stack element on top.
*
* @return Top element from stack. Element is considered as non-existent
* on stack after this call (meaning, subsequent Push calls can
* overwrite it).
*
* @note Popping on an empty stack is detected with assertion only in Debug
* build.
*/
T Pop();
/**
* Acquire stack's max possible size.
*/
constexpr size_t Capacity() const
{
return N;
}
/**
* Acquire amount of elements already on Stack.
*/
LKCOMMON_INLINE size_t Size() const
{
return mStackPointer;
}
};
} // namespace Utils
} // namespace lkCommon
#include "StaticStackImpl.hpp"
| 22.340909
| 79
| 0.614954
|
lookeypl
|
3c367342b0ae3cec2e0d19dc53bc66c2d47489e8
| 440
|
cpp
|
C++
|
src/tibb/src/TabbedScene.cpp
|
ssaracut/titanium_mobile_blackberry
|
952a8100086dcc625584e33abc2dc03340cbb219
|
[
"Apache-2.0"
] | 3
|
2015-03-07T15:41:18.000Z
|
2015-11-05T05:07:45.000Z
|
src/tibb/src/TabbedScene.cpp
|
ssaracut/titanium_mobile_blackberry
|
952a8100086dcc625584e33abc2dc03340cbb219
|
[
"Apache-2.0"
] | 1
|
2015-04-12T11:50:33.000Z
|
2015-04-12T21:13:19.000Z
|
src/tibb/src/TabbedScene.cpp
|
ssaracut/titanium_mobile_blackberry
|
952a8100086dcc625584e33abc2dc03340cbb219
|
[
"Apache-2.0"
] | 5
|
2015-01-13T17:14:41.000Z
|
2015-05-25T16:54:26.000Z
|
/**
* Appcelerator Titanium Mobile
* Copyright (c) 2012-2013 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
#include "TabbedScene.h"
#include <bb/cascades/TabbedPane>
using namespace bb::cascades;
namespace titanium {
TabbedScene::TabbedScene()
: Scene(new TabbedPane()) {
}
} // namespace titanium
| 20
| 70
| 0.736364
|
ssaracut
|
3c426f062de1b588cf562c6fb8184caeb0d0aa15
| 3,238
|
cpp
|
C++
|
src/gui/profile_list_model.cpp
|
adam-currie/fannn
|
b8433b9cc223b98a976590796986a2b0a1e68a68
|
[
"MIT"
] | 2
|
2021-10-16T01:43:03.000Z
|
2021-12-12T20:28:43.000Z
|
src/gui/profile_list_model.cpp
|
adam-currie/fannn
|
b8433b9cc223b98a976590796986a2b0a1e68a68
|
[
"MIT"
] | null | null | null |
src/gui/profile_list_model.cpp
|
adam-currie/fannn
|
b8433b9cc223b98a976590796986a2b0a1e68a68
|
[
"MIT"
] | null | null | null |
#include "profile_list_model.h"
#include "profile_persister.h"
#include <algorithm>
#include <stdexcept>
#include <string>
#include "containers_util.h"
using std::string;
using Fannn::Util::contains;
ProfileListModel::ProfileListModel(QObject *parent) : QAbstractListModel(parent) {
auto persister = Fannn::ProfilePersister(Fannn::ProfilePersister::getActiveProfileName());
persister.load();
setCurrentProfile(new ProfileModel(this, persister));
}
void ProfileListModel::setCurrentProfile(ProfileModel *value) {
if(_currentProfile != value){
//todo: delete old profile model?
_currentProfile = value;
emit currentProfileChanged(value);
loadProfileNames();
}
}
QVariant ProfileListModel::data(const QModelIndex &index, int role) const {
if (!index.isValid())
return QVariant();
return QString::fromStdString(profileNames.at(index.row()));
}
Qt::ItemFlags ProfileListModel::flags(const QModelIndex &index) const {
//todo
return Qt::NoItemFlags;
}
int ProfileListModel::rowCount(const QModelIndex &parent) const {
return profileNames.size();
}
void ProfileListModel::loadProfileNames() {
auto newNames = Fannn::ProfilePersister::getProfileNames();
if (_currentProfile) {
//put at front
//and make sure it's on the list even if not read from disk, cause we can just save it anyway
string curName = _currentProfile->name().toStdString();
for (auto iter = newNames.begin(); iter != newNames.end(); ++iter) {
if (*iter == curName) {
newNames.erase(iter);
break;
}
}
newNames.insert(newNames.begin(), curName);
}
if (newNames != profileNames) {
beginResetModel();
profileNames = newNames;
endResetModel();
}
}
int ProfileListModel::indexOf(QString profileName) {
for(int i=0; i<profileNames.size(); i++)
if (profileNames[i] == profileName.toStdString())
return i;
throw std::out_of_range("'" + profileName.toStdString() + "' not found");
}
void ProfileListModel::createAndSwitchTo() {
//we want this to be up to date
auto latestProfileNames = Fannn::ProfilePersister::getProfileNames();
string name = "profile1";
for (int i=2; latestProfileNames>>contains(name); ++i)
name = "profile" + std::to_string(i);
Fannn::ProfilePersister pp(name);
pp.save(); //need to mark our territory
setCurrentProfile(new ProfileModel(this, pp));
}
void ProfileListModel::loadProfile(QString name) {
Fannn::ProfilePersister persister(name.toStdString());
persister.load();//todo: LoadError
setCurrentProfile(new ProfileModel(this, persister));
}
void ProfileListModel::setActiveProfileName(QString profileName) {
string newName = profileName.toStdString();
string oldName = Fannn::ProfilePersister::getActiveProfileName();
if (newName != oldName) {
Fannn::ProfilePersister::setActiveProfileName(newName);
emit activeProfileNameChanged(QString::fromStdString(newName));
}
}
QString ProfileListModel::activeProfileName() const {
return QString::fromStdString(Fannn::ProfilePersister::getActiveProfileName());
}
| 31.436893
| 101
| 0.684064
|
adam-currie
|
3c43bf70da25fd81b8ba016b6ce73a5c16e7f0d8
| 19,774
|
cxx
|
C++
|
resip/recon/UserAgent.cxx
|
dulton/reSipServer
|
ac4241df81c1e3eef2e678271ffef4dda1fc6747
|
[
"Apache-2.0"
] | 1
|
2019-04-15T14:10:58.000Z
|
2019-04-15T14:10:58.000Z
|
resip/recon/UserAgent.cxx
|
dulton/reSipServer
|
ac4241df81c1e3eef2e678271ffef4dda1fc6747
|
[
"Apache-2.0"
] | null | null | null |
resip/recon/UserAgent.cxx
|
dulton/reSipServer
|
ac4241df81c1e3eef2e678271ffef4dda1fc6747
|
[
"Apache-2.0"
] | 2
|
2019-10-31T09:11:09.000Z
|
2021-09-17T01:00:49.000Z
|
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "UserAgent.hxx"
#include "UserAgentDialogSetFactory.hxx"
#include "UserAgentCmds.hxx"
#include "UserAgentServerAuthManager.hxx"
#include "UserAgentClientSubscription.hxx"
#include "UserAgentRegistration.hxx"
#include "ReconSubsystem.hxx"
#include "reflow/FlowManagerSubsystem.hxx"
#include <reTurn/ReTurnSubsystem.hxx>
#include <rutil/Log.hxx>
#include <rutil/Logger.hxx>
#include <resip/dum/ClientAuthManager.hxx>
#include <resip/dum/ClientSubscription.hxx>
#include <resip/dum/ServerSubscription.hxx>
#include <resip/dum/ClientRegistration.hxx>
#include <resip/dum/KeepAliveManager.hxx>
#include <resip/dum/AppDialogSet.hxx>
#if defined(USE_SSL)
#include <resip/stack/ssl/Security.hxx>
#endif
#include <rutil/WinLeakCheck.hxx>
using namespace recon;
using namespace resip;
using namespace std;
#define RESIPROCATE_SUBSYSTEM ReconSubsystem::RECON
UserAgent::UserAgent(ConversationManager* conversationManager, SharedPtr<UserAgentMasterProfile> profile, AfterSocketCreationFuncPtr socketFunc) :
mCurrentSubscriptionHandle(1),
mCurrentConversationProfileHandle(1),
mDefaultOutgoingConversationProfileHandle(0),
mConversationManager(conversationManager),
mProfile(profile),
#if defined(USE_SSL)
mSecurity(new Security(profile->certPath())),
#else
mSecurity(0),
#endif
mStack(mSecurity, profile->getAdditionalDnsServers(), &mSelectInterruptor, false /* stateless */, socketFunc),
mDum(mStack),
mStackThread(mStack, mSelectInterruptor),
mDumShutdown(false)
{
assert(mConversationManager);
mConversationManager->setUserAgent(this);
addTransports();
// Set Enum Suffixes
mStack.setEnumSuffixes(profile->getEnumSuffixes());
// Enable/Disable Statistics Manager
mStack.statisticsManagerEnabled() = profile->statisticsManagerEnabled();
// Install Handlers
mDum.setMasterProfile(mProfile);
mDum.setClientRegistrationHandler(this);
mDum.setClientAuthManager(std::auto_ptr<ClientAuthManager>(new ClientAuthManager));
mDum.setKeepAliveManager(std::auto_ptr<KeepAliveManager>(new KeepAliveManager));
mDum.setRedirectHandler(mConversationManager);
mDum.setInviteSessionHandler(mConversationManager);
mDum.setDialogSetHandler(mConversationManager);
mDum.addOutOfDialogHandler(OPTIONS, mConversationManager);
mDum.addOutOfDialogHandler(REFER, mConversationManager);
mDum.addClientSubscriptionHandler("refer", mConversationManager);
mDum.addServerSubscriptionHandler("refer", mConversationManager);
//mDum.addClientSubscriptionHandler(Symbols::Presence, this);
//mDum.addClientPublicationHandler(Symbols::Presence, this);
//mDum.addOutOfDialogHandler(NOTIFY, this);
//mDum.addServerSubscriptionHandler("message-summary", this);
// Set AppDialogSetFactory
auto_ptr<AppDialogSetFactory> dsf(new UserAgentDialogSetFactory(*mConversationManager));
mDum.setAppDialogSetFactory(dsf);
// Set UserAgentServerAuthManager
SharedPtr<ServerAuthManager> uasAuth( new UserAgentServerAuthManager(*this));
mDum.setServerAuthManager(uasAuth);
}
UserAgent::~UserAgent()
{
shutdown();
}
void
UserAgent::startup()
{
mStackThread.run();
}
SubscriptionHandle
UserAgent::getNewSubscriptionHandle()
{
Lock lock(mSubscriptionHandleMutex);
return mCurrentSubscriptionHandle++;
}
void
UserAgent::registerSubscription(UserAgentClientSubscription *subscription)
{
mSubscriptions[subscription->getSubscriptionHandle()] = subscription;
}
void
UserAgent::unregisterSubscription(UserAgentClientSubscription *subscription)
{
mSubscriptions.erase(subscription->getSubscriptionHandle());
}
ConversationProfileHandle
UserAgent::getNewConversationProfileHandle()
{
Lock lock(mConversationProfileHandleMutex);
return mCurrentConversationProfileHandle++;
}
void
UserAgent::registerRegistration(UserAgentRegistration *registration)
{
mRegistrations[registration->getConversationProfileHandle()] = registration;
}
void
UserAgent::unregisterRegistration(UserAgentRegistration *registration)
{
mRegistrations.erase(registration->getConversationProfileHandle());
}
void
UserAgent::process(int timeoutMs)
{
mDum.process(timeoutMs);
}
void
UserAgent::shutdown()
{
UserAgentShutdownCmd* cmd = new UserAgentShutdownCmd(this);
mDum.post(cmd);
// Wait for Dum to shutdown
while(!mDumShutdown)
{
process(100);
}
mStackThread.shutdown();
mStackThread.join();
}
void
UserAgent::logDnsCache()
{
mStack.logDnsCache();
}
void
UserAgent::clearDnsCache()
{
mStack.clearDnsCache();
}
void
UserAgent::post(ApplicationMessage& message, unsigned int ms)
{
if(ms > 0)
{
mStack.postMS(message, ms, &mDum);
}
else
{
mDum.post(&message);
}
}
void
UserAgent::setLogLevel(Log::Level level, LoggingSubsystem subsystem)
{
switch(subsystem)
{
case SubsystemAll:
Log::setLevel(level);
break;
case SubsystemContents:
Log::setLevel(level, Subsystem::CONTENTS);
break;
case SubsystemDns:
Log::setLevel(level, Subsystem::DNS);
break;
case SubsystemDum:
Log::setLevel(level, Subsystem::DUM);
break;
case SubsystemSdp:
Log::setLevel(level, Subsystem::SDP);
break;
case SubsystemSip:
Log::setLevel(level, Subsystem::SIP);
break;
case SubsystemTransaction:
Log::setLevel(level, Subsystem::TRANSACTION);
break;
case SubsystemTransport:
Log::setLevel(level, Subsystem::TRANSPORT);
break;
case SubsystemStats:
Log::setLevel(level, Subsystem::STATS);
break;
case SubsystemRecon:
Log::setLevel(level, ReconSubsystem::RECON);
break;
case SubsystemFlowManager:
Log::setLevel(level, FlowManagerSubsystem::FLOWMANAGER);
break;
case SubsystemReTurn:
Log::setLevel(level, ReTurnSubsystem::RETURN);
break;
}
}
ConversationProfileHandle
UserAgent::addConversationProfile(SharedPtr<ConversationProfile> conversationProfile, bool defaultOutgoing)
{
ConversationProfileHandle handle = getNewConversationProfileHandle();
AddConversationProfileCmd* cmd = new AddConversationProfileCmd(this, handle, conversationProfile, defaultOutgoing);
mDum.post(cmd);
return handle;
}
void
UserAgent::setDefaultOutgoingConversationProfile(ConversationProfileHandle handle)
{
SetDefaultOutgoingConversationProfileCmd* cmd = new SetDefaultOutgoingConversationProfileCmd(this, handle);
mDum.post(cmd);
}
void
UserAgent::destroyConversationProfile(ConversationProfileHandle handle)
{
DestroyConversationProfileCmd* cmd = new DestroyConversationProfileCmd(this, handle);
mDum.post(cmd);
}
SubscriptionHandle
UserAgent::createSubscription(const Data& eventType, const NameAddr& target, unsigned int subscriptionTime, const Mime& mimeType)
{
SubscriptionHandle handle = getNewSubscriptionHandle();
CreateSubscriptionCmd* cmd = new CreateSubscriptionCmd(this, handle, eventType, target, subscriptionTime, mimeType);
mDum.post(cmd);
return handle;
}
void
UserAgent::destroySubscription(SubscriptionHandle handle)
{
DestroySubscriptionCmd* cmd = new DestroySubscriptionCmd(this, handle);
mDum.post(cmd);
}
SharedPtr<ConversationProfile>
UserAgent::getDefaultOutgoingConversationProfile()
{
if(mDefaultOutgoingConversationProfileHandle != 0)
{
return mConversationProfiles[mDefaultOutgoingConversationProfileHandle];
}
else
{
assert(false);
ErrLog( << "getDefaultOutgoingConversationProfile: something is wrong - no profiles to return");
return SharedPtr<ConversationProfile>((ConversationProfile*)0);
}
}
SharedPtr<ConversationProfile>
UserAgent::getIncomingConversationProfile(const SipMessage& msg)
{
assert(msg.isRequest());
// Examine the sip message, and select the most appropriate conversation profile
// Check if request uri matches registration contact
const Uri& requestUri = msg.header(h_RequestLine).uri();
RegistrationMap::iterator regIt;
for(regIt = mRegistrations.begin(); regIt != mRegistrations.end(); regIt++)
{
const NameAddrs& contacts = regIt->second->getContactAddresses();
NameAddrs::const_iterator naIt;
for(naIt = contacts.begin(); naIt != contacts.end(); naIt++)
{
InfoLog( << "getIncomingConversationProfile: comparing requestUri=" << requestUri << " to contactUri=" << (*naIt).uri());
if((*naIt).uri() == requestUri)
{
ConversationProfileMap::iterator conIt = mConversationProfiles.find(regIt->first);
if(conIt != mConversationProfiles.end())
{
return conIt->second;
}
}
}
}
// Check if To header matches default from
Data toAor = msg.header(h_To).uri().getAor();
ConversationProfileMap::iterator conIt;
for(conIt = mConversationProfiles.begin(); conIt != mConversationProfiles.end(); conIt++)
{
InfoLog( << "getIncomingConversationProfile: comparing toAor=" << toAor << " to defaultFromAor=" << conIt->second->getDefaultFrom().uri().getAor());
if(isEqualNoCase(toAor, conIt->second->getDefaultFrom().uri().getAor()))
{
return conIt->second;
}
}
// If can't find any matches, then return the default outgoing profile
InfoLog( << "getIncomingConversationProfile: no matching profile found, falling back to default outgoing profile");
return getDefaultOutgoingConversationProfile();
}
SharedPtr<UserAgentMasterProfile>
UserAgent::getUserAgentMasterProfile()
{
return mProfile;
}
DialogUsageManager&
UserAgent::getDialogUsageManager()
{
return mDum;
}
ConversationManager*
UserAgent::getConversationManager()
{
return mConversationManager;
}
void
UserAgent::onDumCanBeDeleted()
{
mDumShutdown = true;
}
void
UserAgent::addTransports()
{
const std::vector<UserAgentMasterProfile::TransportInfo>& transports = mProfile->getTransports();
std::vector<UserAgentMasterProfile::TransportInfo>::const_iterator i;
for(i = transports.begin(); i != transports.end(); i++)
{
try
{
switch((*i).mProtocol)
{
#ifdef USE_SSL
case TLS:
#ifdef USE_DTLS
case DTLS:
#endif
mDum.addTransport((*i).mProtocol, (*i).mPort, (*i).mIPVersion, (*i).mIPInterface, (*i).mSipDomainname, Data::Empty, (*i).mSslType);
break;
#endif
case UDP:
case TCP:
mDum.addTransport((*i).mProtocol, (*i).mPort, (*i).mIPVersion, (*i).mIPInterface);
break;
default:
WarningLog (<< "Failed to add " << Tuple::toData((*i).mProtocol) << " transport - unsupported type");
}
}
catch (BaseException& e)
{
WarningLog (<< "Caught: " << e);
WarningLog (<< "Failed to add " << Tuple::toData((*i).mProtocol) << " transport on " << (*i).mPort);
}
}
}
void
UserAgent::startApplicationTimer(unsigned int timerId, unsigned int durationMs, unsigned int seqNumber)
{
UserAgentTimeout t(*this, timerId, durationMs, seqNumber);
post(t, durationMs);
}
void
UserAgent::onApplicationTimer(unsigned int timerId, unsigned int durationMs, unsigned int seqNumber)
{
// Default implementation is to do nothing - application should override this
}
void
UserAgent::onSubscriptionTerminated(SubscriptionHandle handle, unsigned int statusCode)
{
// Default implementation is to do nothing - application should override this
}
void
UserAgent::onSubscriptionNotify(SubscriptionHandle handle, const Data& notifyData)
{
// Default implementation is to do nothing - application should override this
}
void
UserAgent::shutdownImpl()
{
mDum.shutdown(this);
// End all subscriptions
SubscriptionMap tempSubs = mSubscriptions; // Create copy for safety, since ending Subscriptions can immediately remove themselves from map
SubscriptionMap::iterator i;
for(i = tempSubs.begin(); i != tempSubs.end(); i++)
{
i->second->end();
}
// Unregister all registrations
RegistrationMap tempRegs = mRegistrations; // Create copy for safety, since ending can immediately remove themselves from map
RegistrationMap::iterator j;
for(j = tempRegs.begin(); j != tempRegs.end(); j++)
{
j->second->end();
}
mConversationManager->shutdown();
}
void
UserAgent::addConversationProfileImpl(ConversationProfileHandle handle, SharedPtr<ConversationProfile> conversationProfile, bool defaultOutgoing)
{
// Store new profile
mConversationProfiles[handle] = conversationProfile;
conversationProfile->setHandle(handle);
#ifdef USE_SSL
// If this is the first profile ever set - then use the aor defined in it as the aor used in
// the DTLS certificate for the DtlsFactory - TODO - improve this sometime so that we can change the aor in
// the cert at runtime to equal the aor in the default conversation profile
if(!mDefaultOutgoingConversationProfileHandle)
{
mConversationManager->getFlowManager().initializeDtlsFactory(conversationProfile->getDefaultFrom().uri().getAor().c_str());
}
#endif
// Set the default outgoing if requested to do so, or we don't have one yet
if(defaultOutgoing || mDefaultOutgoingConversationProfileHandle == 0)
{
setDefaultOutgoingConversationProfileImpl(handle);
}
// Register new profile
if(conversationProfile->getDefaultRegistrationTime() != 0)
{
UserAgentRegistration *registration = new UserAgentRegistration(*this, mDum, handle);
mDum.send(mDum.makeRegistration(conversationProfile->getDefaultFrom(), conversationProfile, registration));
}
}
void
UserAgent::setDefaultOutgoingConversationProfileImpl(ConversationProfileHandle handle)
{
mDefaultOutgoingConversationProfileHandle = handle;
}
void
UserAgent::destroyConversationProfileImpl(ConversationProfileHandle handle)
{
// Remove matching registration if found
RegistrationMap::iterator it = mRegistrations.find(handle);
if(it != mRegistrations.end())
{
it->second->end();
}
// Remove from ConversationProfile map
mConversationProfiles.erase(handle);
// If this Conversation Profile was the default - select the first item in the map as the new default
if(handle == mDefaultOutgoingConversationProfileHandle)
{
ConversationProfileMap::iterator it = mConversationProfiles.begin();
if(it != mConversationProfiles.end())
{
setDefaultOutgoingConversationProfileImpl(it->first);
}
else
{
setDefaultOutgoingConversationProfileImpl(0);
}
}
}
void
UserAgent::createSubscriptionImpl(SubscriptionHandle handle, const Data& eventType, const NameAddr& target, unsigned int subscriptionTime, const Mime& mimeType)
{
// Ensure we have a client subscription handler for this event type
if(!mDum.getClientSubscriptionHandler(eventType))
{
mDum.addClientSubscriptionHandler(eventType, this);
}
// Ensure that the request Mime type is supported in the dum profile
if(!mProfile->isMimeTypeSupported(NOTIFY, mimeType))
{
mProfile->addSupportedMimeType(NOTIFY, mimeType);
}
UserAgentClientSubscription *subscription = new UserAgentClientSubscription(*this, mDum, handle);
mDum.send(mDum.makeSubscription(target, getDefaultOutgoingConversationProfile(), eventType, subscriptionTime, subscription));
}
void
UserAgent::destroySubscriptionImpl(SubscriptionHandle handle)
{
SubscriptionMap::iterator it = mSubscriptions.find(handle);
if(it != mSubscriptions.end())
{
it->second->end();
}
}
////////////////////////////////////////////////////////////////////////////////
// Registration Handler ////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void
UserAgent::onSuccess(ClientRegistrationHandle h, const SipMessage& msg)
{
dynamic_cast<UserAgentRegistration *>(h->getAppDialogSet().get())->onSuccess(h, msg);
}
void
UserAgent::onFailure(ClientRegistrationHandle h, const SipMessage& msg)
{
dynamic_cast<UserAgentRegistration *>(h->getAppDialogSet().get())->onFailure(h, msg);
}
void
UserAgent::onRemoved(ClientRegistrationHandle h, const SipMessage&msg)
{
dynamic_cast<UserAgentRegistration *>(h->getAppDialogSet().get())->onRemoved(h, msg);
}
int
UserAgent::onRequestRetry(ClientRegistrationHandle h, int retryMinimum, const SipMessage& msg)
{
return dynamic_cast<UserAgentRegistration *>(h->getAppDialogSet().get())->onRequestRetry(h, retryMinimum, msg);
}
////////////////////////////////////////////////////////////////////////////////
// ClientSubscriptionHandler ///////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
void
UserAgent::onUpdatePending(ClientSubscriptionHandle h, const SipMessage& msg, bool outOfOrder)
{
dynamic_cast<UserAgentClientSubscription *>(h->getAppDialogSet().get())->onUpdatePending(h, msg, outOfOrder);
}
void
UserAgent::onUpdateActive(ClientSubscriptionHandle h, const SipMessage& msg, bool outOfOrder)
{
dynamic_cast<UserAgentClientSubscription *>(h->getAppDialogSet().get())->onUpdateActive(h, msg, outOfOrder);
}
void
UserAgent::onUpdateExtension(ClientSubscriptionHandle h, const SipMessage& msg, bool outOfOrder)
{
dynamic_cast<UserAgentClientSubscription *>(h->getAppDialogSet().get())->onUpdateExtension(h, msg, outOfOrder);
}
void
UserAgent::onTerminated(ClientSubscriptionHandle h, const SipMessage* msg)
{
dynamic_cast<UserAgentClientSubscription *>(h->getAppDialogSet().get())->onTerminated(h, msg);
}
void
UserAgent::onNewSubscription(ClientSubscriptionHandle h, const SipMessage& msg)
{
dynamic_cast<UserAgentClientSubscription *>(h->getAppDialogSet().get())->onNewSubscription(h, msg);
}
int
UserAgent::onRequestRetry(ClientSubscriptionHandle h, int retryMinimum, const SipMessage& msg)
{
return dynamic_cast<UserAgentClientSubscription *>(h->getAppDialogSet().get())->onRequestRetry(h, retryMinimum, msg);
}
/* ====================================================================
Copyright (c) 2007-2008, Plantronics, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
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 Plantronics nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
==================================================================== */
| 31.337559
| 160
| 0.720239
|
dulton
|
3c47704ffffe4ef4c955177924b541d952ea6157
| 46,864
|
cpp
|
C++
|
src/updater.cpp
|
smarttowel/AppImageUpdate
|
ac5376d70e55bb9d4684a5bede555f0bbcbfb249
|
[
"MIT"
] | null | null | null |
src/updater.cpp
|
smarttowel/AppImageUpdate
|
ac5376d70e55bb9d4684a5bede555f0bbcbfb249
|
[
"MIT"
] | null | null | null |
src/updater.cpp
|
smarttowel/AppImageUpdate
|
ac5376d70e55bb9d4684a5bede555f0bbcbfb249
|
[
"MIT"
] | null | null | null |
// system headers+
#include <algorithm>
#include <chrono>
#include <deque>
#include <fnmatch.h>
#include <fstream>
#include <iostream>
#include <libgen.h>
#include <mutex>
#include <sstream>
#include <thread>
#include <unistd.h>
// library headers
#include <zsclient.h>
#include <hashlib/sha256.h>
#include <cpr/cpr.h>
#include <ftw.h>
// local headers
#include "appimage/update.h"
#include "util.h"
#include "update_methods/pling_v1_zsync.h"
// convenience declaration
typedef std::lock_guard<std::mutex> lock_guard;
namespace appimage {
namespace update {
class Updater::Private {
public:
Private() : state(INITIALIZED),
pathToAppImage(),
zSyncClient(nullptr),
thread(nullptr),
mutex(),
overwrite(false)
{};
~Private() {
delete zSyncClient;
}
public:
// data
std::string pathToAppImage;
// state
State state;
// ZSync client -- will be instantiated only if necessary
zsync2::ZSyncClient* zSyncClient;
// threading
std::thread* thread;
std::mutex mutex;
// status messages
std::deque<std::string> statusMessages;
// defines whether to overwrite original file
bool overwrite;
public:
enum UpdateInformationType {
INVALID = -1,
ZSYNC_GENERIC = 0,
ZSYNC_GITHUB_RELEASES,
ZSYNC_BINTRAY,
ZSYNC_PLING_V1,
};
struct AppImage {
std::string filename;
int appImageVersion;
std::string rawUpdateInformation;
UpdateInformationType updateInformationType;
std::string zsyncUrl;
std::string signature;
AppImage() : appImageVersion(-1), updateInformationType(INVALID) {};
};
typedef struct AppImage AppImage;
public:
void issueStatusMessage(const std::string& message) {
statusMessages.push_back(message);
}
static const std::string readAppImageSignature(const std::string& pathToAppImage) {
return readElfSection(pathToAppImage, ".sha256_sig");
}
static const std::string hashAppImage(const std::string& pathToAppImage) {
// read offset and length of signature section to skip it later
unsigned long sigOffset = 0, sigLength = 0;
unsigned long keyOffset = 0, keyLength = 0;
if (!appimage_get_elf_section_offset_and_length(pathToAppImage.c_str(), ".sha256_sig", &sigOffset, &sigLength))
return "";
if (!appimage_get_elf_section_offset_and_length(pathToAppImage.c_str(), ".sig_key", &keyOffset, &keyLength))
return "";
std::ifstream ifs(pathToAppImage);
if (!ifs)
return "";
SHA256 digest;
// validate.c uses "offset" as chunk size, but that value might be quite high, and therefore uses
// a lot of memory
// TODO: use a smaller value (maybe use a prime factorization and use the biggest prime factor?)
const ssize_t chunkSize = 4096;
std::vector<char> buffer(chunkSize, 0);
ssize_t totalBytesRead = 0;
// bytes that should be skipped when reading the next chunk
// when e.g., a section that must be ignored spans over more than one chunk, this amount of bytes is
// being nulled & skipped before reading data from the file again
std::streamsize bytesToSkip = 0;
ifs.seekg(0, ifs.end);
const ssize_t fileSize = ifs.tellg();
ifs.seekg(0, ifs.beg);
while (ifs) {
ssize_t bytesRead = 0;
auto bytesLeftInChunk = std::min(chunkSize, (fileSize - totalBytesRead));
if (bytesLeftInChunk <= 0)
break;
auto skipBytes = [&bytesRead, &bytesLeftInChunk, &buffer, &ifs, &totalBytesRead](ssize_t count) {
if (count <= 0)
return;
const auto start = buffer.begin() + bytesRead;
std::fill_n(start, count, '\0');
bytesRead += count;
totalBytesRead += count;
bytesLeftInChunk -= count;
ifs.seekg(count, std::ios::cur);
};
auto readBytes = [&bytesRead, &bytesLeftInChunk, &buffer, &ifs, &totalBytesRead](ssize_t count) {
if (count <= 0)
return;
ifs.read(buffer.data() + bytesRead, count);
bytesRead += ifs.gcount();
totalBytesRead += count;
bytesLeftInChunk -= bytesRead;
};
auto checkSkipSection = [&](const ssize_t sectionOffset, const ssize_t sectionLength) {
// check whether signature starts in current chunk
const ssize_t sectionOffsetDelta = sectionOffset - totalBytesRead;
if (sectionOffsetDelta >= 0 && sectionOffsetDelta < bytesLeftInChunk) {
// read until section begins
readBytes(sectionOffsetDelta);
// calculate how many bytes must be nulled in this chunk
// the rest will be nulled in the following chunk(s)
auto bytesLeft = sectionLength;
const auto bytesToNullInCurrentChunk = std::min(bytesLeftInChunk, bytesLeft);
// null these bytes
skipBytes(bytesToNullInCurrentChunk);
// calculate how many bytes must be nulled in future chunks
bytesLeft -= bytesToNullInCurrentChunk;
bytesToSkip = bytesLeft;
}
};
// check whether bytes must be skipped from previous sections
if (bytesToSkip > 0) {
auto bytesToSkipInCurrentChunk = std::min(chunkSize, bytesToSkip);
skipBytes(bytesToSkipInCurrentChunk);
bytesToSkip -= bytesToSkipInCurrentChunk;
}
// check whether one of the sections that must be skipped are in the current chunk, and if they
// are, skip those sections in the current and future sections
checkSkipSection(sigOffset, sigLength);
checkSkipSection(keyOffset, keyLength);
// read remaining bytes in chunk, given the file has still data to be read
if (ifs && bytesLeftInChunk > 0) {
readBytes(bytesLeftInChunk);
}
// update hash with data from buffer
digest.add(buffer.data(), static_cast<size_t>(bytesRead));
}
return digest.getHash();
}
const AppImage* readAppImage(const std::string& pathToAppImage) {
// error state: empty AppImage path
if (pathToAppImage.empty()) {
issueStatusMessage("Path to AppImage must not be empty.");
return nullptr;
}
// check whether file exists
std::ifstream ifs(pathToAppImage);
// if file can't be opened, it's an error
if (!ifs || !ifs.good()) {
issueStatusMessage("Failed to access AppImage file: " + pathToAppImage);
return nullptr;
}
// read magic number
ifs.seekg(8, std::ios::beg);
std::vector<char> magicByte(4, '\0');
ifs.read(magicByte.data(), 3);
// validate first two bytes are A and I
if (magicByte[0] != 'A' && magicByte[1] != 'I') {
std::ostringstream oss;
oss << "Invalid magic bytes: " << (int) magicByte[0] << (int) magicByte[1];
issueStatusMessage(oss.str());
}
int appImageType = -1;
// the third byte contains the version
switch (magicByte[2]) {
case '\x01':
appImageType = 1;
break;
case '\x02':
appImageType = 2;
break;
default:
// see fallback in the final else block in the next if construct
break;
}
// read update information in the file
std::string updateInformation;
// also read signature in the file
std::string signature;
if (appImageType == 1) {
// update information is always at the same position, and has a fixed length
static constexpr auto position = 0x8373;
static constexpr auto length = 512;
ifs.seekg(position);
std::vector<char> rawUpdateInformation(length, 0);
ifs.read(rawUpdateInformation.data(), length);
updateInformation = rawUpdateInformation.data();
} else if (appImageType == 2) {
// try to read ELF section .upd_info
updateInformation = readElfSection(pathToAppImage, ".upd_info");
// type 2 supports signatures, so we can extract it here, too
signature = readAppImageSignature(pathToAppImage);
} else {
// final try: type 1 AppImages do not have to set the magic bytes, although they should
// if the file is both an ELF and an ISO9660 file, we'll suspect it to be a type 1 AppImage, and
// proceed with a warning
static constexpr int elfMagicPos = 1;
static const std::string elfMagicValue = "ELF";
static constexpr int isoMagicPos = 32769;
static const std::string isoMagicValue = "CD001";
ifs.seekg(elfMagicPos);
std::vector<char> elfMagicPosData(elfMagicValue.size() + 1, '\0');
ifs.read(elfMagicPosData.data(), elfMagicValue.size());
auto elfMagicAvailable = (elfMagicPosData.data() == elfMagicValue);
ifs.seekg(isoMagicPos);
std::vector<char> isoMagicPosData(isoMagicValue.size() + 1, '\0');
ifs.read(isoMagicPosData.data(), isoMagicValue.size());
auto isoMagicAvailable = (isoMagicPosData.data() == isoMagicValue);
if (isoMagicAvailable) {
issueStatusMessage("Guessing AppImage type 1 or ISO");
appImageType = 1;
} else {
// all possible methods attempted, ultimately fail here
issueStatusMessage("No such AppImage type: " + std::to_string(magicByte[2]));
return nullptr;
}
}
UpdateInformationType uiType = INVALID;
std::string zsyncUrl;
// parse update information
auto uiParts = split(updateInformation, '|');
// make sure uiParts isn't empty
if (!uiParts.empty()) {
// TODO: GitHub releases type should consider pre-releases when there's no other types of releases
if (uiParts[0] == "gh-releases-zsync") {
// validate update information
if (uiParts.size() != 5) {
std::ostringstream oss;
oss << "Update information has invalid parameter count. Please contact the author of "
<< "the AppImage and ask them to revise the update information. They should consult "
<< "the AppImage specification, there might have been changes to the update"
<< "information.";
issueStatusMessage(oss.str());
} else {
uiType = ZSYNC_GITHUB_RELEASES;
auto username = uiParts[1];
auto repository = uiParts[2];
auto tag = uiParts[3];
auto filename = uiParts[4];
std::stringstream url;
url << "https://api.github.com/repos/" << username << "/" << repository << "/releases/";
if (tag.find("latest") != std::string::npos) {
issueStatusMessage("Fetching latest release information from GitHub API");
url << "latest";
} else {
std::ostringstream oss;
oss << "Fetching release information for tag \"" << tag << "\" from GitHub API.";
issueStatusMessage(oss.str());
url << "tags/" << tag;
}
auto response = cpr::Get(url.str());
// counter that will be evaluated later to give some meaningful feedback why parsing API
// response might have failed
int downloadUrlLines = 0;
int matchingUrls = 0;
// continue only if HTTP status is good
if (response.status_code >= 200 && response.status_code < 300) {
// in contrary to the original implementation, instead of converting wildcards into
// all-matching regular expressions, we have the power of fnmatch() available, a real wildcard
// implementation
// unfortunately, this is still hoping for GitHub's JSON API to return a pretty printed
// response which can be parsed like this
std::stringstream responseText(response.text);
std::string currentLine;
// not ideal, but allows for returning a match for the entire line
auto pattern = "*" + filename + "*";
// iterate through all lines to find a possible download URL and compare it to the pattern
while (std::getline(responseText, currentLine)) {
if (currentLine.find("browser_download_url") != std::string::npos) {
downloadUrlLines++;
if (fnmatch(pattern.c_str(), currentLine.c_str(), 0) == 0) {
matchingUrls++;
auto parts = split(currentLine, '"');
zsyncUrl = parts.back();
break;
}
}
}
} else {
issueStatusMessage("GitHub API request failed!");
}
if (downloadUrlLines <= 0) {
std::ostringstream oss;
oss << "Could not find any artifacts in release data. "
<< "Please contact the author of the AppImage and tell them the files are missing "
<< "on the releases page.";
issueStatusMessage(oss.str());
} else if (matchingUrls <= 0) {
std::ostringstream oss;
oss << "None of the artifacts matched the pattern in the update information. "
<< "The pattern is most likely invalid, e.g., due to changes in the filenames of "
<< "the AppImages. Please contact the author of the AppImage and ask them to "
<< "revise the update information.";
issueStatusMessage(oss.str());
} else if (zsyncUrl.empty()) {
// unlike that this code will ever be reached, the other two messages should cover all
// cases in which a ZSync URL is missing
// if it does, however, it's most likely that GitHub's API didn't return a URL
issueStatusMessage("Failed to parse GitHub's response.");
}
}
} else if (uiParts[0] == "bintray-zsync") {
// TODO: better error handling
if (uiParts.size() == 5) {
uiType = ZSYNC_BINTRAY;
auto username = uiParts[1];
auto repository = uiParts[2];
auto packageName = uiParts[3];
auto filename = uiParts[4];
std::stringstream downloadUrl;
downloadUrl << "https://dl.bintray.com/" << username << "/" << repository << "/"
<< filename;
if (downloadUrl.str().find("_latestVersion") == std::string::npos) {
zsyncUrl = downloadUrl.str();
} else {
std::stringstream redirectorUrl;
redirectorUrl << "https://bintray.com/" << username << "/" << repository << "/"
<< packageName << "/_latestVersion";
auto versionResponse = cpr::Head(redirectorUrl.str());
// this request is supposed to be redirected
// due to how cpr works, we can't check for a redirection status, as we get the response for
// the redirected request
// therefore, we check for a 2xx response, and then can inspect and compare the redirected URL
if (versionResponse.status_code >= 200 && versionResponse.status_code < 400) {
auto redirectedUrl = versionResponse.url;
// if they're different, it's probably been successful
if (redirectorUrl.str() != redirectedUrl) {
// the last part will contain the current version
auto packageVersion = static_cast<std::string>(split(redirectedUrl, '/').back());
auto urlTemplate = downloadUrl.str();
// split by _latestVersion, insert correct value, compose final value
auto pos = urlTemplate.find("_latestVersion");
auto firstPart = urlTemplate.substr(0, pos);
auto secondPart = urlTemplate.substr(pos + std::string("_latestVersion").length());
zsyncUrl = firstPart + packageVersion + secondPart;
}
}
}
}
} else if (uiParts[0] == "zsync") {
// validate update information
if (uiParts.size() == 2) {
uiType = ZSYNC_GENERIC;
zsyncUrl = uiParts.back();
} else {
std::ostringstream oss;
oss << "Update information has invalid parameter count. Please contact the author of "
<< "the AppImage and ask them to revise the update information. They should consult "
<< "the AppImage specification, there might have been changes to the update"
<< "information.";
issueStatusMessage(oss.str());
}
} else if (methods::PlingV1Zsync::isUpdateStringAccepted(uiParts)) {
uiType = ZSYNC_PLING_V1;
auto updateMethod = methods::PlingV1Zsync(uiParts);
auto availableDownloads = updateMethod.getAvailableDownloads();
auto latestReleaseUrl = updateMethod.findLatestRelease(availableDownloads);
zsyncUrl = updateMethod.resolveZsyncUrl(latestReleaseUrl);
} else {
// unknown type
}
}
auto* appImage = new AppImage();
appImage->filename = pathToAppImage;
appImage->appImageVersion = appImageType;
appImage->rawUpdateInformation = updateInformation;
appImage->updateInformationType = uiType;
appImage->zsyncUrl = zsyncUrl;
appImage->signature = signature;
return appImage;
}
bool validateAppImage(AppImage const* appImage) {
// a null pointer is clearly a sign
if (appImage == nullptr) {
std::ostringstream oss;
oss << "Parsing AppImage failed. See previous message for details. "
<< "Are you sure the file is an AppImage?";
issueStatusMessage(oss.str());
return false;
}
// first check whether there's update information at all
if (appImage->rawUpdateInformation.empty()) {
std::ostringstream oss;
oss << "Could not find update information in the AppImage. "
<< "Please contact the author of the AppImage and ask them to embed update information.";
issueStatusMessage(oss.str());
return false;
}
// now check whether a ZSync URL could be composed by readAppImage
// this is the only supported update type at the moment
if (appImage->zsyncUrl.empty()) {
std::ostringstream oss;
oss << "ZSync URL not available. See previous messages for details.";
issueStatusMessage(oss.str());
return false;
}
// check whether update information is available
if (appImage->updateInformationType == INVALID) {
std::stringstream oss;
oss << "Could not detect update information type."
<< "Please contact the author of the AppImage and ask them whether the update information "
<< "is correct.";
issueStatusMessage(oss.str());
return false;
}
return true;
}
// thread runner
void runUpdate() {
// initialization
{
lock_guard guard(mutex);
// make sure it runs only once at a time
// should never occur, but you never know
if (state != INITIALIZED)
return;
// if there is a ZSync client (e.g., because an update check has been run), clean it up
// this ensures that a fresh instance will be used for the update run
if (zSyncClient != nullptr) {
delete zSyncClient;
zSyncClient = nullptr;
}
// WARNING: if you don't want to shoot yourself in the foot, make sure to read in the AppImage
// while locking the mutex and/or before the RUNNING state to make sure readAppImage() finishes
// before progress() and such can be called! Otherwise, progress() etc. will return an error state,
// causing e.g., main(), to interrupt the thread and finish.
auto* appImage = readAppImage(pathToAppImage);
if (!validateAppImage(appImage)) {
// cleanup
delete appImage;
state = ERROR;
return;
}
if (appImage->updateInformationType == ZSYNC_BINTRAY) {
issueStatusMessage("Updating from Bintray via ZSync");
} else if (appImage->updateInformationType == ZSYNC_GITHUB_RELEASES) {
issueStatusMessage("Updating from GitHub Releases via ZSync");
} else if (appImage->updateInformationType == ZSYNC_GENERIC) {
issueStatusMessage("Updating from generic server via ZSync");
}
if (appImage->updateInformationType == ZSYNC_GITHUB_RELEASES ||
appImage->updateInformationType == ZSYNC_BINTRAY ||
appImage->updateInformationType == ZSYNC_PLING_V1 ||
appImage->updateInformationType == ZSYNC_GENERIC) {
// doesn't matter which type it is exactly, they all work like the same
zSyncClient = new zsync2::ZSyncClient(appImage->zsyncUrl, pathToAppImage, overwrite);
// enable ranges optimizations
zSyncClient->setRangesOptimizationThreshold(64 * 4096);
// make sure the new AppImage goes into the same directory as the old one
// unfortunately, to be able to use dirname(), one has to copy the C string first
auto* path = strdup(appImage->filename.c_str());
std::string dirPath = dirname(path);
free(path);
zSyncClient->setCwd(dirPath);
} else {
// error unsupported type
issueStatusMessage("Error: update method not implemented");
// cleanup
delete appImage;
state = ERROR;
return;
}
// cleanup
delete appImage;
state = RUNNING;
}
// keep state -- by default, an error (false) is assumed
bool result = false;
// run phase
{
// check whether it's a zsync operation
if (zSyncClient != nullptr) {
result = zSyncClient->run();
}
}
// end phase
{
lock_guard guard(mutex);
if (result) {
state = SUCCESS;
} else {
state = ERROR;
}
}
}
bool checkForChanges(bool& updateAvailable, const unsigned int method = 0) {
lock_guard guard(mutex);
if (state != INITIALIZED)
return false;
// TODO: this code is somewhat duplicated in run()
// should probably be extracted to separate function
auto* appImage = readAppImage(pathToAppImage);
// validate AppImage
if(!validateAppImage(appImage))
return false;
if (appImage->updateInformationType == ZSYNC_GITHUB_RELEASES ||
appImage->updateInformationType == ZSYNC_BINTRAY ||
appImage->updateInformationType == ZSYNC_PLING_V1 ||
appImage->updateInformationType == ZSYNC_GENERIC ) {
zSyncClient = new zsync2::ZSyncClient(appImage->zsyncUrl, pathToAppImage);
return zSyncClient->checkForChanges(updateAvailable, method);
}
zSyncClient = nullptr;
// return error in case of unknown update information
issueStatusMessage("Unknown update information type, aborting.");
return false;
}
};
Updater::Updater(const std::string& pathToAppImage, bool overwrite) {
// initialize data class
d = new Updater::Private();
// workaround for AppImageLauncher filesystem
d->pathToAppImage = ailfsRealpath(pathToAppImage);
d->overwrite = overwrite;
// check whether file exists, otherwise throw exception
std::ifstream f(d->pathToAppImage);
if(!f || !f.good()) {
auto errorMessage = std::strerror(errno);
throw std::invalid_argument(errorMessage + std::string(": ") + d->pathToAppImage);
}
}
Updater::~Updater() {
delete d;
}
void Updater::runUpdate() {
// alias for private function
return d->runUpdate();
}
bool Updater::start() {
// lock mutex
lock_guard guard(d->mutex);
// prevent multiple start calls
if(d->state != INITIALIZED)
return false;
// if there's a thread managed by this class already, should not start another one and lose access to
// this one
if(d->thread)
return false;
// create thread
d->thread = new std::thread(&Updater::runUpdate, this);
return true;
}
bool Updater::isDone() {
lock_guard guard(d->mutex);
return d->state != INITIALIZED && d->state != RUNNING && d->state != STOPPING;
}
bool Updater::hasError() {
lock_guard guard(d->mutex);
return d->state == ERROR;
}
bool Updater::progress(double& progress) {
lock_guard guard(d->mutex);
if (d->state == INITIALIZED) {
// this protects update checks from returning progress, which would only occur when using method 0
progress = 0;
return true;
} else if (d->state == SUCCESS || d->state == ERROR) {
progress = 1;
return true;
}
if (d->zSyncClient != nullptr) {
progress = d->zSyncClient->progress();
return true;
}
return false;
}
bool Updater::stop() {
throw std::runtime_error("not implemented");
}
bool Updater::nextStatusMessage(std::string& message) {
// first, check own message queue
if (!d->statusMessages.empty()) {
message = d->statusMessages.front();
d->statusMessages.pop_front();
return true;
}
// next, check zsync client for a message
if (d->zSyncClient != nullptr) {
std::string zsyncMessage;
if (!d->zSyncClient->nextStatusMessage(zsyncMessage))
return false;
// show that the message is coming from zsync2
message = "zsync2: " + zsyncMessage;
return true;
}
return false;
}
Updater::State Updater::state() {
return d->state;
}
bool Updater::checkForChanges(bool &updateAvailable, const unsigned int method) {
return d->checkForChanges(updateAvailable, method);
}
bool Updater::describeAppImage(std::string& description) const {
std::ostringstream oss;
auto* appImage = d->readAppImage(d->pathToAppImage);
if (appImage == nullptr)
return false;
oss << "Parsing file: " << appImage->filename << std::endl;
oss << "AppImage type: " << appImage->appImageVersion << std::endl;
oss << "Raw update information: ";
if (appImage->rawUpdateInformation.empty())
oss << "<empty>";
else
oss << appImage->rawUpdateInformation;
oss << std::endl;
oss << "Update information type: ";
if (appImage->updateInformationType == d->ZSYNC_GENERIC)
oss << "Generic ZSync URL";
else if (appImage->updateInformationType == d->ZSYNC_BINTRAY)
oss << "ZSync via Bintray";
else if (appImage->updateInformationType == d->ZSYNC_GITHUB_RELEASES)
oss << "ZSync via GitHub Releases";
else if (appImage->updateInformationType == d->ZSYNC_PLING_V1)
oss << "ZSync via OCS";
else if (appImage->updateInformationType == d->INVALID)
oss << "Invalid (parsing failed/no update information available)";
else
oss << "Unknown error";
oss << std::endl;
if (!appImage->zsyncUrl.empty())
oss << "Assembled ZSync URL: " << appImage->zsyncUrl << std::endl;
else
oss << "Failed to assemble ZSync URL. AppImageUpdate can not be used with this AppImage.";
description = oss.str();
return true;
}
bool Updater::pathToNewFile(std::string& path) const {
// only available update method is via ZSync
if (d->zSyncClient)
return d->zSyncClient->pathToNewFile(path);
return false;
}
bool Updater::remoteFileSize(off_t& fileSize) const {
// only available update method is via ZSync
if (d->zSyncClient != nullptr)
return d->zSyncClient->remoteFileSize(fileSize);
return false;
}
Updater::ValidationState Updater::validateSignature() {
std::string pathToNewAppImage;
if (!this->pathToNewFile(pathToNewAppImage)) {
// return generic error
return VALIDATION_FAILED;
}
auto pathToOldAppImage = abspath(d->pathToAppImage);
if (pathToOldAppImage == pathToNewAppImage) {
pathToOldAppImage = pathToNewAppImage + ".zs-old";
}
auto oldSignature = d->readAppImageSignature(pathToOldAppImage);
auto newSignature = d->readAppImageSignature(pathToNewAppImage);
// remove any spaces and/or newline characters there might be on the left or right of the payload
zsync2::trim(oldSignature, '\n');
zsync2::trim(newSignature, '\n');
zsync2::trim(oldSignature);
zsync2::trim(newSignature);
auto oldSigned = !oldSignature.empty();
auto newSigned = !newSignature.empty();
auto oldDigest = d->hashAppImage(pathToOldAppImage);
auto newDigest = d->hashAppImage(pathToNewAppImage);
auto oldDigestOrig = readElfSection(pathToOldAppImage, ".sha256_sig");
auto newDigestOrig = readElfSection(pathToNewAppImage, ".sha256_sig");
std::string tempDir;
{
char* buffer;
char* pattern = strdup("/tmp/AppImageUpdate-XXXXXX");
if ((buffer = mkdtemp(pattern)) == nullptr) {
d->issueStatusMessage("Failed to create temporary directory");
return VALIDATION_TEMPDIR_CREATION_FAILED;
}
tempDir = buffer;
free(pattern);
}
auto tempFile = [&tempDir](const std::string& filename, const std::string& contents) {
std::stringstream path;
path << tempDir << "/" << filename;
auto x = path.str();
std::ofstream ofs(path.str());
ofs.write(contents.c_str(), contents.size());
return path.str();
};
if (!oldSigned && !newSigned)
return VALIDATION_NOT_SIGNED;
else if (oldSigned && !newSigned)
return VALIDATION_NO_LONGER_SIGNED;
// store digests and signatures in files so they can be passed to gpg2
auto oldDigestFilename = tempFile("old-digest", oldDigest);
auto newDigestFilename = tempFile("new-digest", newDigest);
auto oldSignatureFilename = tempFile("old-signature", oldSignature);
auto newSignatureFilename = tempFile("new-signature", newSignature);
auto cleanup = [&tempDir]() {
// cleanup
auto unlinkCb = [](const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf) {
int rv = remove(fpath);
if (rv)
perror(fpath);
return rv;
};
nftw(tempDir.c_str(), unlinkCb, 64, FTW_DEPTH | FTW_PHYS);
rmdir(tempDir.c_str());
};
// find gpg2 binary
auto gpg2Path = findInPATH("gpg2");
if (gpg2Path.empty()) {
cleanup();
return VALIDATION_GPG2_MISSING;
}
const auto tempKeyRingPath = tempDir + "/keyring";
// create keyring file, otherwise GPG will complain
std::ofstream ofs(tempKeyRingPath);
ofs.close();
auto importKeyFromAppImage = [&tempKeyRingPath, &gpg2Path](const std::string& path) {
auto key = readElfSection(path, ".sig_key");
if (key.empty())
return false;
std::ostringstream oss;
oss << "'" << gpg2Path << "' "
<< "--no-default-keyring --keyring '" << tempKeyRingPath << "' --import";
auto command = oss.str();
auto proc = popen(oss.str().c_str(), "w");
fwrite(key.c_str(), key.size(), sizeof(char), proc);
auto retval = pclose(proc);
return retval == 0;
};
importKeyFromAppImage(pathToOldAppImage);
importKeyFromAppImage(pathToNewAppImage);
auto verifySignature = [this, &gpg2Path, &tempKeyRingPath](
const std::string& signatureFile, const std::string& digestFile,
bool& keyFound, bool& goodSignature,
std::string& keyID, std::string& keyOwner
) {
std::ostringstream oss;
oss << "'" << gpg2Path << "'"
<< " --keyring '" << tempKeyRingPath << "'"
<< " --verify '" << signatureFile << "' '" << digestFile << "' 2>&1";
auto command = oss.str();
// make sure output is in English
setenv("LANGUAGE", "C", 1);
setenv("LANG", "C", 1);
setenv("LC_ALL", "C", 1);
auto* proc = popen(command.c_str(), "r");
if (proc == nullptr)
return false;
char* currentLine = nullptr;
size_t lineSize = 0;
keyFound = true;
goodSignature = false;
while (getline(¤tLine, &lineSize, proc) != -1) {
std::string line = currentLine;
trim(line, '\n');
trim(line);
d->issueStatusMessage(std::string("gpg2: ") + line);
auto splitOwner = [&line]() {
auto parts = split(line, '"');
if (parts.size() < 2)
return std::string();
auto skip = parts[0].length();
return line.substr(skip + 1, line.length() - skip - 2);
};
if (stringStartsWith(line, "gpg: Signature made")) {
// extract key
auto parts = split(line);
if (*(parts.end() - 3) == "key" && *(parts.end() - 2) == "ID")
keyID = parts.back();
} else if (stringStartsWith(line, "gpg: Good signature from")) {
goodSignature = true;
keyOwner = splitOwner();
} else if (stringStartsWith(line, "gpg: BAD signature from")) {
goodSignature = false;
keyOwner = splitOwner();
} else if (stringStartsWith(line, "gpg: Can't check signature: No public key")) {
keyFound = false;
}
}
auto rv = pclose(proc);
return true;
};
bool oldKeyFound = false, newKeyFound = false, oldSignatureGood = false, newSignatureGood = false;
std::string oldKeyID, newKeyID, oldKeyOwner, newKeyOwner;
if (oldSigned) {
if (!verifySignature(oldSignatureFilename, oldDigestFilename, oldKeyFound, oldSignatureGood, oldKeyID, oldKeyOwner)) {
cleanup();
return VALIDATION_GPG2_CALL_FAILED;
}
}
if (newSigned) {
if (!verifySignature(newSignatureFilename, newDigestFilename, newKeyFound, newSignatureGood, newKeyID, newKeyOwner)) {
cleanup();
return VALIDATION_GPG2_CALL_FAILED;
}
}
if (!oldKeyFound || !newKeyFound) {
// if the keys haven't been embedded in the AppImages, we treat them as not signed
// see https://github.com/AppImage/AppImageUpdate/issues/16#issuecomment-370932698 for details
cleanup();
return VALIDATION_NOT_SIGNED;
}
if (!oldSignatureGood || !newSignatureGood) {
cleanup();
return VALIDATION_BAD_SIGNATURE;
}
if (oldSigned && newSigned) {
if (oldKeyID != newKeyID) {
cleanup();
return VALIDATION_KEY_CHANGED;
}
}
cleanup();
return VALIDATION_PASSED;
}
std::string Updater::signatureValidationMessage(const Updater::ValidationState& state) {
static const std::map<ValidationState, std::string> validationMessages = {
{VALIDATION_PASSED, "Signature validation successful"},
// warning states
{VALIDATION_WARNING, "Signature validation warning"},
{VALIDATION_NOT_SIGNED, "AppImage not signed"},
{VALIDATION_GPG2_MISSING, "gpg2 command not found, please install"},
// error states
{VALIDATION_FAILED, "Signature validation failed"},
{VALIDATION_GPG2_CALL_FAILED, "Call to gpg2 failed"},
{VALIDATION_TEMPDIR_CREATION_FAILED, "Failed to create temporary directory"},
{VALIDATION_NO_LONGER_SIGNED, "AppImage no longer comes with signature"},
{VALIDATION_BAD_SIGNATURE, "Bad signature"},
{VALIDATION_KEY_CHANGED, "Key changed for signing AppImages"},
};
if (validationMessages.count(state) > 0) {
return validationMessages.at(state);
}
return "Unknown validation state";
}
std::string Updater::updateInformation() const {
const auto* appImage = d->readAppImage(d->pathToAppImage);
if (appImage == nullptr)
throw std::runtime_error("Failed to parse AppImage");
return appImage->rawUpdateInformation;
}
bool Updater::restoreOriginalFile() {
std::string newFilePath;
if (!pathToNewFile(newFilePath)) {
throw std::runtime_error("Failed to get path to new file");
}
// make sure to compare absolute, resolved paths
newFilePath = abspath(newFilePath);
const auto& oldFilePath = abspath(d->pathToAppImage);
// restore original file
std::remove(newFilePath.c_str());
if (oldFilePath == newFilePath) {
std::rename((newFilePath + ".zs-old").c_str(), newFilePath.c_str());
}
}
void Updater::copyPermissionsToNewFile() {
std::string oldFilePath = abspath(d->pathToAppImage);
std::string newFilePath;
if (!pathToNewFile(newFilePath)) {
throw std::runtime_error("Failed to get path to new file");
}
// make sure to compare absolute, resolved paths
newFilePath = abspath(newFilePath);
appimage::update::copyPermissions(oldFilePath, newFilePath);
}
}
}
| 41.88025
| 134
| 0.485959
|
smarttowel
|
3c48c916165d83ea1649606af974f6d4ae2b10e1
| 21,267
|
cpp
|
C++
|
bebop_driver/src/bebop.cpp
|
itssme/bebop_autonomy
|
f061c8a2c45526eb79c1ba0aaa09618bbd9408d0
|
[
"BSD-3-Clause"
] | 2
|
2019-02-12T14:55:21.000Z
|
2021-02-15T23:32:36.000Z
|
bebop_driver/src/bebop.cpp
|
itssme/bebop_autonomy
|
f061c8a2c45526eb79c1ba0aaa09618bbd9408d0
|
[
"BSD-3-Clause"
] | null | null | null |
bebop_driver/src/bebop.cpp
|
itssme/bebop_autonomy
|
f061c8a2c45526eb79c1ba0aaa09618bbd9408d0
|
[
"BSD-3-Clause"
] | null | null | null |
/**
Software License Agreement (BSD)
\file bebop.cpp
\authors Mani Monajjemi <mmonajje@sfu.ca>
\copyright Copyright (c) 2015, Autonomy Lab (Simon Fraser University), 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 Autonomy Lab 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 WAR-
RANTIES, 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, IN-
DIRECT, 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 <stdexcept>
#include <cmath>
#include <string>
#include <algorithm>
#include <vector>
#include <boost/bind.hpp>
#include <boost/thread/locks.hpp>
#include <boost/make_shared.hpp>
extern "C"
{
#include "libARCommands/ARCommands.h"
#include "libARDiscovery/ARDiscovery.h"
#include <libARController/ARController.h>
}
#include <bebop_driver/bebop.h>
#include "bebop_driver/BebopArdrone3Config.h"
#include "bebop_driver/bebop_video_decoder.h"
// include all callback wrappers
#include "bebop_driver/autogenerated/ardrone3_state_callbacks.h"
#include "bebop_driver/autogenerated/common_state_callbacks.h"
#include "bebop_driver/autogenerated/ardrone3_setting_callbacks.h"
/*
* Bebop coordinate systems
*
* Velocities:
*
* +x : East
* +y : South
* +z : Down
*
* Attitude:
*
* +x : forward
* +y : right
* +z : down
* +yaw : CW
*
* ROS coordinate system (REP 105)
*
* +x : forward
* +y : left
* +z : up
* +yaw : CCW
*
* Move function (setPilotingPCMD, conforms with Attiude, except for gaz)
*
* +roll : right
* +pitch : forward
* +gaz : up
* +yaw : CW
*
*/
namespace bebop_driver
{
const char* Bebop::LOG_TAG = "BebopSDK";
void Bebop::StateChangedCallback(eARCONTROLLER_DEVICE_STATE new_state, eARCONTROLLER_ERROR error, void *bebop_void_ptr)
{
// TODO(mani-monaj): Log error
Bebop* bebop_ptr_ = static_cast<Bebop*>(bebop_void_ptr);
switch (new_state)
{
case ARCONTROLLER_DEVICE_STATE_STOPPED:
ARSAL_Sem_Post(&(bebop_ptr_->state_sem_));
break;
case ARCONTROLLER_DEVICE_STATE_RUNNING:
ARSAL_Sem_Post(&(bebop_ptr_->state_sem_));
break;
}
}
void Bebop::CommandReceivedCallback(eARCONTROLLER_DICTIONARY_KEY cmd_key,
ARCONTROLLER_DICTIONARY_ELEMENT_t *element_dict_ptr,
void *bebop_void_ptr)
{
static long int lwp_id = util::GetLWPId();
static bool lwp_id_printed = false;
if (!lwp_id_printed)
{
ARSAL_PRINT(ARSAL_PRINT_INFO, LOG_TAG, "Command Received Callback LWP id is: %ld", lwp_id);
lwp_id_printed = true;
}
Bebop* bebop_ptr = static_cast<Bebop*>(bebop_void_ptr);
if (!bebop_ptr->IsConnected()) return;
ARCONTROLLER_DICTIONARY_ELEMENT_t *single_element_ptr = NULL;
if (element_dict_ptr)
{
// We are only interested in single key dictionaries
HASH_FIND_STR(element_dict_ptr, ARCONTROLLER_DICTIONARY_SINGLE_KEY, single_element_ptr);
if (single_element_ptr)
{
callback_map_t::iterator it = bebop_ptr->callback_map_.find(cmd_key);
if (it != bebop_ptr->callback_map_.end())
{
// TODO(mani-monaj): Check if we can find the time from the packets
it->second->Update(element_dict_ptr->arguments, ros::Time::now());
}
}
}
}
// This callback is called within the same context as FrameReceivedCallback()
eARCONTROLLER_ERROR Bebop::DecoderConfigCallback(ARCONTROLLER_Stream_Codec_t codec, void *bebop_void_ptr)
{
Bebop* bebop_ptr = static_cast<Bebop*>(bebop_void_ptr);
if (codec.type == ARCONTROLLER_STREAM_CODEC_TYPE_H264)
{
ARSAL_PRINT(ARSAL_PRINT_INFO, LOG_TAG, "H264 configuration packet received: #SPS: %d #PPS: %d (MP4? %d)",
codec.parameters.h264parameters.spsSize,
codec.parameters.h264parameters.ppsSize,
codec.parameters.h264parameters.isMP4Compliant);
if (!bebop_ptr->video_decoder_ptr_->SetH264Params(
codec.parameters.h264parameters.spsBuffer,
codec.parameters.h264parameters.spsSize,
codec.parameters.h264parameters.ppsBuffer,
codec.parameters.h264parameters.ppsSize))
{
return ARCONTROLLER_ERROR;
}
}
else
{
ARSAL_PRINT(ARSAL_PRINT_WARNING, LOG_TAG, "Codec type is not H264");
return ARCONTROLLER_ERROR;
}
return ARCONTROLLER_OK;
}
// This Callback runs in ARCONTROLLER_Stream_ReaderThreadRun context and blocks it until it returns
eARCONTROLLER_ERROR Bebop::FrameReceivedCallback(ARCONTROLLER_Frame_t *frame, void *bebop_void_ptr)
{
static long int lwp_id = util::GetLWPId();
static bool lwp_id_printed = false;
if (!lwp_id_printed)
{
ARSAL_PRINT(ARSAL_PRINT_INFO, LOG_TAG, "Frame Recv & Decode LWP id: %ld", lwp_id);
lwp_id_printed = true;
}
if (!frame)
{
ARSAL_PRINT(ARSAL_PRINT_WARNING, LOG_TAG, "Received frame is NULL");
return ARCONTROLLER_ERROR_NO_VIDEO;
}
Bebop* bebop_ptr = static_cast<Bebop*>(bebop_void_ptr);
if (!bebop_ptr->IsConnected()) return ARCONTROLLER_ERROR;
{
boost::unique_lock<boost::mutex> lock(bebop_ptr->frame_avail_mutex_);
if (bebop_ptr->is_frame_avail_)
{
ARSAL_PRINT(ARSAL_PRINT_WARNING, LOG_TAG, "Previous frame might have been missed.");
}
if (!bebop_ptr->video_decoder_ptr_->Decode(frame))
{
ARSAL_PRINT(ARSAL_PRINT_ERROR, LOG_TAG, "Video decode failed");
}
else
{
bebop_ptr->is_frame_avail_ = true;
// ARSAL_PRINT(ARSAL_PRINT_INFO, LOG_TAG, "FRAME IS READY");
bebop_ptr->frame_avail_cond_.notify_one();
}
}
return ARCONTROLLER_OK;
}
Bebop::Bebop(ARSAL_Print_Callback_t custom_print_callback):
is_connected_(false),
is_streaming_started_(false),
device_ptr_(NULL),
device_controller_ptr_(NULL),
error_(ARCONTROLLER_OK),
device_state_(ARCONTROLLER_DEVICE_STATE_MAX),
video_decoder_ptr_(new bebop_driver::VideoDecoder()),
is_frame_avail_(false)
// out_file("/tmp/ts.txt")
{
// Redirect all calls to AR_PRINT_* to this function if provided
if (custom_print_callback)
ARSAL_Print_SetCallback(custom_print_callback);
ARSAL_PRINT(ARSAL_PRINT_INFO, LOG_TAG, "Bebop Cnstr()");
}
Bebop::~Bebop()
{
// This is the last resort, the program must run Cleanup() fo
// proper disconnection and free
if (device_ptr_) ARDISCOVERY_Device_Delete(&device_ptr_);
if (device_controller_ptr_) ARCONTROLLER_Device_Delete(&device_controller_ptr_);
}
void Bebop::Connect(ros::NodeHandle& nh, ros::NodeHandle& priv_nh, const std::string& bebop_ip)
{
try
{
if (is_connected_) throw std::runtime_error("Already inited");
// TODO(mani-monaj): Error checking;
ARSAL_Sem_Init(&state_sem_, 0, 0);
eARDISCOVERY_ERROR error_discovery = ARDISCOVERY_OK;
device_ptr_ = ARDISCOVERY_Device_New(&error_discovery);
if (error_discovery != ARDISCOVERY_OK)
{
throw std::runtime_error("Discovery failed: " + std::string(ARDISCOVERY_Error_ToString(error_discovery)));
}
// set/save ip
bebop_ip_ = bebop_ip;
// TODO(mani-monaj): Make ip and port params
error_discovery = ARDISCOVERY_Device_InitWifi(device_ptr_,
ARDISCOVERY_PRODUCT_ARDRONE, "Bebop",
bebop_ip_.c_str(), 44444);
if (error_discovery != ARDISCOVERY_OK)
{
throw std::runtime_error("Discovery failed: " + std::string(ARDISCOVERY_Error_ToString(error_discovery)));
}
device_controller_ptr_ = ARCONTROLLER_Device_New(device_ptr_, &error_);
ThrowOnCtrlError(error_, "Creation of device controller failed: ");
ARDISCOVERY_Device_Delete(&device_ptr_);
// callback_map is not being modified after this initial update
#define UPDTAE_CALLBACK_MAP
#include "bebop_driver/autogenerated/ardrone3_state_callback_includes.h"
#include "bebop_driver/autogenerated/common_state_callback_includes.h"
#include "bebop_driver/autogenerated/ardrone3_setting_callback_includes.h"
#undef UPDTAE_CALLBACK_MAP
ThrowOnCtrlError(ARCONTROLLER_Device_Start(device_controller_ptr_), "Controller device start failed");
ThrowOnCtrlError(
ARCONTROLLER_Device_AddStateChangedCallback(
device_controller_ptr_, Bebop::StateChangedCallback, reinterpret_cast<void*>(this)),
"Registering state callback failed");
ThrowOnCtrlError(
ARCONTROLLER_Device_AddCommandReceivedCallback(
device_controller_ptr_, Bebop::CommandReceivedCallback, reinterpret_cast<void*>(this)),
"Registering command callback failed");
// ThrowOnCtrlError(
// ARCONTROLLER_Device_SetVideoStreamMP4Compliant(
// device_controller_ptr_, 1),
// "Enforcing MP4 compliancy failed");
// The forth argument is frame timeout callback
ThrowOnCtrlError(
ARCONTROLLER_Device_SetVideoStreamCallbacks(
device_controller_ptr_, Bebop::DecoderConfigCallback, Bebop::FrameReceivedCallback,
NULL , reinterpret_cast<void*>(this)),
"Registering video callback failed");
// This semaphore is touched inside the StateCallback
ARSAL_Sem_Wait(&state_sem_);
device_state_ = ARCONTROLLER_Device_GetState(device_controller_ptr_, &error_);
if ((error_ != ARCONTROLLER_OK) || (device_state_ != ARCONTROLLER_DEVICE_STATE_RUNNING))
{
throw std::runtime_error("Waiting for device failed: " + std::string(ARCONTROLLER_Error_ToString(error_)));
}
// Enforce termination of video streaming ... (use Start/Stop streaming to enable/disable this)
ThrowOnCtrlError(device_controller_ptr_->aRDrone3->sendMediaStreamingVideoEnable(
device_controller_ptr_->aRDrone3, 0), "Stopping video stream failed.");
}
catch (const std::runtime_error& e)
{
Cleanup();
throw e;
}
is_connected_ = true;
ARSAL_PRINT(ARSAL_PRINT_INFO, LOG_TAG, "BebopSDK inited, lwp_id: %ld", util::GetLWPId());
}
void Bebop::Cleanup()
{
ARSAL_PRINT(ARSAL_PRINT_INFO, LOG_TAG, "Bebop Cleanup()");
if (device_controller_ptr_)
{
device_state_ = ARCONTROLLER_Device_GetState(device_controller_ptr_, &error_);
if ((error_ == ARCONTROLLER_OK) && (device_state_ != ARCONTROLLER_DEVICE_STATE_STOPPED))
{
ARSAL_PRINT(ARSAL_PRINT_INFO, LOG_TAG, "Disconnecting ...");
error_ = ARCONTROLLER_Device_Stop(device_controller_ptr_);
if (error_ == ARCONTROLLER_OK)
{
ARSAL_Sem_Wait(&state_sem_);
}
}
ARCONTROLLER_Device_Delete(&device_controller_ptr_);
}
is_connected_ = false;
ARSAL_Sem_Destroy(&state_sem_);
}
void Bebop::StartStreaming()
{
if (is_streaming_started_)
{
ARSAL_PRINT(ARSAL_PRINT_WARNING, LOG_TAG, "Video streaming is already started ...");
return;
}
try
{
ThrowOnInternalError("Starting video stream failed");
// Start video streaming
ThrowOnCtrlError(device_controller_ptr_->aRDrone3->sendMediaStreamingVideoEnable(
device_controller_ptr_->aRDrone3, 1), "Starting video stream failed.");
is_streaming_started_ = true;
ARSAL_PRINT(ARSAL_PRINT_WARNING, LOG_TAG, "Video streaming started ...");
}
catch (const std::runtime_error& e)
{
ARSAL_PRINT(ARSAL_PRINT_INFO, LOG_TAG, "Failed to start video streaming ...");
is_streaming_started_ = false;
throw e;
}
}
void Bebop::StopStreaming()
{
if (!is_streaming_started_) return;
try
{
ThrowOnInternalError("Stopping video stream failed");
// Stop video streaming
ThrowOnCtrlError(device_controller_ptr_->aRDrone3->sendMediaStreamingVideoEnable(
device_controller_ptr_->aRDrone3, 0), "Stopping video stream failed.");
is_streaming_started_ = false;
}
catch (const std::runtime_error& e)
{
ARSAL_PRINT(ARSAL_PRINT_ERROR, LOG_TAG, "Failed to stop video streaming ...");
}
}
void Bebop::Disconnect()
{
if (!is_connected_) return;
if (is_streaming_started_) StopStreaming();
Cleanup();
ARSAL_PRINT(ARSAL_PRINT_INFO, LOG_TAG, "Disconnected from Bebop ...");
}
void Bebop::SetDate(const std::string &date)
{
ThrowOnInternalError("Setting Date Failed");
ThrowOnCtrlError(
device_controller_ptr_->common->sendCommonCurrentDate(device_controller_ptr_->common, const_cast<char*>(date.c_str())),
"Setting Date Failed");
}
void Bebop::RequestAllSettings()
{
ThrowOnInternalError("Request Settings Failed");
ThrowOnCtrlError(
device_controller_ptr_->common->sendSettingsAllSettings(device_controller_ptr_->common),
"Request Settings Failed");
}
void Bebop::ResetAllSettings()
{
ThrowOnInternalError("Reset Settings Failed");
ThrowOnCtrlError(
device_controller_ptr_->common->sendSettingsReset(device_controller_ptr_->common),
"Reset Settings Failed");
ARSAL_PRINT(ARSAL_PRINT_INFO, LOG_TAG, "All settings of the drone have been reset to default values.");
}
void Bebop::UpdateSettings(const BebopArdrone3Config &config)
{
ThrowOnInternalError("Update Settings Failed");
// For all callback_map members
// 1) Check if they are derived from AbstractSetting type
// 1.1) Pass the config objects to them
// boost::lock_guard<boost::mutex> lock(callback_map_mutex_);
for (callback_map_t::iterator it = callback_map_.begin(); it != callback_map_.end(); it++)
{
// Convert the base class pointer (AbstractCommand) to the derived class pointer (AbstractSetting)
// In case of State classes, do nothing
boost::shared_ptr<cb::AbstractSetting> setting_ptr = boost::dynamic_pointer_cast<cb::AbstractSetting>(it->second);
if (setting_ptr)
{
setting_ptr->UpdateBebopFromROS(config, device_controller_ptr_);
}
}
}
void Bebop::Takeoff()
{
ThrowOnInternalError("Takeoff failed");
ThrowOnCtrlError(
device_controller_ptr_->aRDrone3->sendPilotingTakeOff(device_controller_ptr_->aRDrone3),
"Takeoff failed");
}
void Bebop::Land()
{
ThrowOnInternalError("Land failed");
ThrowOnCtrlError(
device_controller_ptr_->aRDrone3->sendPilotingLanding(device_controller_ptr_->aRDrone3),
"Land failed");
}
void Bebop::Emergency()
{
ThrowOnInternalError("Emergency failed");
ThrowOnCtrlError(
device_controller_ptr_->aRDrone3->sendPilotingEmergency(device_controller_ptr_->aRDrone3),
"Emergency failed");
}
void Bebop::FlatTrim()
{
ThrowOnInternalError("FlatTrim failed");
ThrowOnCtrlError(
device_controller_ptr_->aRDrone3->sendPilotingFlatTrim(device_controller_ptr_->aRDrone3),
"FlatTrim failed");
}
void Bebop::NavigateHome(const bool &start_stop)
{
ThrowOnInternalError("Navigate home failed");
ThrowOnCtrlError(
device_controller_ptr_->aRDrone3->sendPilotingNavigateHome(
device_controller_ptr_->aRDrone3, start_stop ? 1 : 0),
"Navigate home failed");
}
void Bebop::StartAutonomousFlight(const std::string &filepath)
{
ThrowOnInternalError("Start autonomous flight failed");
ThrowOnCtrlError(
device_controller_ptr_->common->sendMavlinkStart(device_controller_ptr_->common, const_cast<char*>(filepath.c_str()), (eARCOMMANDS_COMMON_MAVLINK_START_TYPE)0),
"Start autonomous flight failed");
}
void Bebop::PauseAutonomousFlight()
{
ThrowOnInternalError("Pause autonomous flight failed");
ThrowOnCtrlError(
device_controller_ptr_->common->sendMavlinkPause(device_controller_ptr_->common),
"Pause autonomous flight failed");
}
void Bebop::StopAutonomousFlight()
{
ThrowOnInternalError("Stop autonomous flight failed");
ThrowOnCtrlError(
device_controller_ptr_->common->sendMavlinkStop(device_controller_ptr_->common),
"Stop autonomous flight failed");
}
void Bebop::AnimationFlip(const uint8_t &anim_id)
{
ThrowOnInternalError("Animation failed");
if (anim_id >= ARCOMMANDS_ARDRONE3_ANIMATIONS_FLIP_DIRECTION_MAX)
{
throw std::runtime_error("Inavlid animation id");
}
ThrowOnCtrlError(
device_controller_ptr_->aRDrone3->sendAnimationsFlip(
device_controller_ptr_->aRDrone3, static_cast<eARCOMMANDS_ARDRONE3_ANIMATIONS_FLIP_DIRECTION>(
anim_id % ARCOMMANDS_ARDRONE3_ANIMATIONS_FLIP_DIRECTION_MAX)),
"Navigate home failed");
}
void Bebop::Move(const double &roll, const double &pitch, const double &gaz_speed, const double &yaw_speed)
{
// TODO(mani-monaj): Bound check
ThrowOnInternalError("Move failure");
// If roll or pitch value are non-zero, enabel roll/pitch flag
const bool do_rp = !((fabs(roll) < 0.001) && (fabs(pitch) < 0.001));
// If all values are zero, hover
const bool do_hover = !do_rp && (fabs(yaw_speed) < 0.001) && (fabs(gaz_speed) < 0.001);
if (do_hover)
{
ARSAL_PRINT(ARSAL_PRINT_DEBUG, LOG_TAG, "STOP");
ThrowOnCtrlError(
device_controller_ptr_->aRDrone3->setPilotingPCMD(
device_controller_ptr_->aRDrone3,
0, 0, 0, 0, 0, 0));
}
else
{
ThrowOnCtrlError(
device_controller_ptr_->aRDrone3->setPilotingPCMD(
device_controller_ptr_->aRDrone3,
do_rp,
static_cast<int8_t>(roll * 100.0),
static_cast<int8_t>(pitch * 100.0),
static_cast<int8_t>(yaw_speed * 100.0),
static_cast<int8_t>(gaz_speed * 100.0),
0));
}
}
// in degrees
void Bebop::MoveCamera(const double &tilt, const double &pan)
{
ThrowOnInternalError("Camera Move Failure");
ThrowOnCtrlError(device_controller_ptr_->aRDrone3->setCameraOrientationV2(
device_controller_ptr_->aRDrone3,
static_cast<float>(tilt),
static_cast<float>(pan)));
}
uint32_t Bebop::GetFrontCameraFrameWidth() const
{
return video_decoder_ptr_->GetFrameWidth();
}
uint32_t Bebop::GetFrontCameraFrameHeight() const
{
return video_decoder_ptr_->GetFrameHeight();
}
bool Bebop::GetFrontCameraFrame(std::vector<uint8_t> &buffer, uint32_t& width, uint32_t& height) const
{
boost::unique_lock<boost::mutex> lock(frame_avail_mutex_);
ARSAL_PRINT(ARSAL_PRINT_DEBUG, LOG_TAG, "Waiting for frame to become available ...");
while (!is_frame_avail_)
{
frame_avail_cond_.wait(lock);
}
// ARSAL_PRINT(ARSAL_PRINT_INFO, LOG_TAG, "COPY STARTED");
const uint32_t num_bytes = video_decoder_ptr_->GetFrameWidth() * video_decoder_ptr_->GetFrameHeight() * 3;
if (num_bytes == 0)
{
ARSAL_PRINT(ARSAL_PRINT_WARNING, LOG_TAG, "No picture size");
return false;
}
buffer.resize(num_bytes);
// New frame is ready
std::copy(video_decoder_ptr_->GetFrameRGBRawCstPtr(),
video_decoder_ptr_->GetFrameRGBRawCstPtr() + num_bytes,
buffer.begin());
width = video_decoder_ptr_->GetFrameWidth();
height = video_decoder_ptr_->GetFrameHeight();
is_frame_avail_ = false;
// ARSAL_PRINT(ARSAL_PRINT_INFO, LOG_TAG, "COPY ENDED");
return true;
}
void Bebop::TakeSnapshot()
{
ThrowOnInternalError("Snapshot Failure");
ThrowOnCtrlError(
device_controller_ptr_->aRDrone3->sendMediaRecordPictureV2(
device_controller_ptr_->aRDrone3));
}
void Bebop::SetExposure(const float& exposure)
{
ThrowOnInternalError("Failed to set exposure");
// TODO fairf4x: Check bounds ?
ThrowOnCtrlError(
device_controller_ptr_->aRDrone3->sendPictureSettingsExpositionSelection(device_controller_ptr_->aRDrone3, (float)exposure)
);
}
void Bebop::ToggleVideoRecording(const bool start)
{
ThrowOnInternalError("Video Toggle Failure");
ThrowOnCtrlError(device_controller_ptr_->aRDrone3->sendMediaRecordVideoV2(
device_controller_ptr_->aRDrone3,
start ? ARCOMMANDS_ARDRONE3_MEDIARECORD_VIDEOV2_RECORD_START :
ARCOMMANDS_ARDRONE3_MEDIARECORD_VIDEOV2_RECORD_STOP));
}
void Bebop::ThrowOnInternalError(const std::string &message)
{
if (!is_connected_ || !device_controller_ptr_)
{
throw std::runtime_error(message);
}
}
void Bebop::ThrowOnCtrlError(const eARCONTROLLER_ERROR &error, const std::string &message)
{
if (error != ARCONTROLLER_OK)
{
throw std::runtime_error(message + std::string(ARCONTROLLER_Error_ToString(error)));
}
}
} // namespace bebop_driver
| 32.972093
| 168
| 0.723045
|
itssme
|
3c511c5a89914a48912e42920f3246b389530021
| 2,662
|
hpp
|
C++
|
include/utility/persistent_container/container_config.hpp
|
SakuraLife/utility
|
b9bf26198917b6dc415520f74eb3eebf8aa8195e
|
[
"Unlicense"
] | 2
|
2017-12-10T10:59:48.000Z
|
2017-12-13T04:11:14.000Z
|
include/utility/persistent_container/container_config.hpp
|
SakuraLife/utility
|
b9bf26198917b6dc415520f74eb3eebf8aa8195e
|
[
"Unlicense"
] | null | null | null |
include/utility/persistent_container/container_config.hpp
|
SakuraLife/utility
|
b9bf26198917b6dc415520f74eb3eebf8aa8195e
|
[
"Unlicense"
] | null | null | null |
#ifndef ___UTILITY__PERSISTENT__CONTAINER__CONFIG___
#define ___UTILITY__PERSISTENT__CONTAINER__CONFIG___
#include<utility/config/utility_config.hpp>
namespace utility
{
namespace persistent_container
{
namespace config
{
struct cache_config
{
public:
typedef unsigned short counter_type;
public:
constexpr static size_t max_record = 65535UL;
public:
UTILITY_ALWAYS_INLINE
static inline counter_type init_state(counter_type __now) noexcept
{ return 0;}
UTILITY_ALWAYS_INLINE
static inline counter_type discard_state(counter_type __now) noexcept
{ return __now;}
UTILITY_ALWAYS_INLINE
static inline void update_state(counter_type& __now) noexcept
{ ++__now;}
public:
UTILITY_ALWAYS_INLINE
static inline bool is_vaild(
counter_type __init, counter_type __discard
) noexcept
{ return __discard == 0;}
UTILITY_ALWAYS_INLINE
static inline bool is_vaild(
counter_type __need, counter_type __init, counter_type __discard
) noexcept
{ return __need <= __discard && __need > __init;}
UTILITY_ALWAYS_INLINE
static inline bool is_invaild(
counter_type __init, counter_type __discard
) noexcept
{ return __discard != 0;}
UTILITY_ALWAYS_INLINE
static inline bool is_invaild(
counter_type __need, counter_type __init, counter_type __discard
) noexcept
{ return !is_vaild(__need, __discard, __init);}
UTILITY_ALWAYS_INLINE
static inline bool is_reserved(
counter_type __need, counter_type __init
)
{ return __need > __init;}
public:
UTILITY_ALWAYS_INLINE
static inline size_t steps(counter_type __now) noexcept
{ return __now-1;}
UTILITY_ALWAYS_INLINE
static inline size_t next(counter_type __now, size_t __len) noexcept
{ return __now+__len;}
static inline size_t prev(counter_type __now, size_t __len) noexcept
{ return __now-__len;}
};
typedef cache_config base_cache_sg;
}
using config::base_cache_sg;
}
namespace p_container
{
namespace config
{
using persistent_container::config::base_cache_sg;
}
using persistent_container::config::base_cache_sg;
}
}
#endif // ! ___UTILITY__PERSISTENT__CONTAINER__CONFIG___
| 30.597701
| 80
| 0.624718
|
SakuraLife
|
3c5627ae8d7edb3d1b23dfb28c9c6b5da0a91d5b
| 6,818
|
cxx
|
C++
|
Podd/THaBPM.cxx
|
leadmocha/analyzer
|
ab26d755dbe816975e4165479c9fbefc4c4ca069
|
[
"BSD-3-Clause"
] | null | null | null |
Podd/THaBPM.cxx
|
leadmocha/analyzer
|
ab26d755dbe816975e4165479c9fbefc4c4ca069
|
[
"BSD-3-Clause"
] | null | null | null |
Podd/THaBPM.cxx
|
leadmocha/analyzer
|
ab26d755dbe816975e4165479c9fbefc4c4ca069
|
[
"BSD-3-Clause"
] | null | null | null |
///////////////////////////////////////////////////////////////////////////////
// //
// THaBPM //
// //
// Class for a BPM //
// measuring signals from four antennas //
// and the position at the BPM (without phase correction) //
// works with standard ADCs (lecroy like types) //
// is good for unrastered beam, or to get average positions //
// //
///////////////////////////////////////////////////////////////////////////////
#include "THaBPM.h"
#include "THaEvData.h"
#include "THaDetMap.h"
#include "VarDef.h"
#include "VarType.h"
#include "TMath.h"
#include <vector>
static const UInt_t NCHAN = 4;
using namespace std;
//_____________________________________________________________________________
THaBPM::THaBPM( const char* name, const char* description,
THaApparatus* apparatus ) :
THaBeamDet(name,description,apparatus),
fRawSignal(NCHAN),fPedestals(NCHAN),fCorSignal(NCHAN),fRotPos(NCHAN/2),
fRot2HCSPos(NCHAN/2,NCHAN/2), fCalibRot(0)
{
// Constructor
}
//_____________________________________________________________________________
Int_t THaBPM::ReadDatabase( const TDatime& date )
{
// ReadDatabase: if detectors cant be added to detmap
// or entry for bpms is missing -> kInitError
// otherwise -> kOk
const char* const here = "ReadDatabase";
vector<Int_t> detmap;
Double_t pedestals[NCHAN], rotations[NCHAN], offsets[2];
FILE* file = OpenFile( date );
if( !file )
return kInitError;
fOrigin.SetXYZ(0,0,0);
Int_t err = ReadGeometry( file, date );
if( !err ) {
// Read configuration parameters
DBRequest config_request[] = {
{ "detmap", &detmap, kIntV },
{ nullptr }
};
err = LoadDB( file, date, config_request, fPrefix );
}
UInt_t flags = THaDetMap::kFillLogicalChannel | THaDetMap::kFillModel;
if( !err && FillDetMap(detmap, flags, here) <= 0 ) {
err = kInitError; // Error already printed by FillDetMap
}
if( !err ) {
memset( pedestals, 0, sizeof(pedestals) );
memset( rotations, 0, sizeof(rotations) );
memset( offsets , 0, sizeof( offsets ) );
DBRequest calib_request[] = {
{ "calib_rot", &fCalibRot },
{ "pedestals", pedestals, kDouble, NCHAN, true },
{ "rotmatrix", rotations, kDouble, NCHAN, true },
{ "offsets" , offsets, kDouble, 2 , true },
{ nullptr }
};
err = LoadDB( file, date, calib_request, fPrefix );
}
fclose(file);
if( err )
return err;
fOffset(0) = offsets[0];
fOffset(1) = offsets[1];
fPedestals.SetElements( pedestals );
fRot2HCSPos(0,0) = rotations[0];
fRot2HCSPos(0,1) = rotations[1];
fRot2HCSPos(1,0) = rotations[2];
fRot2HCSPos(1,1) = rotations[3];
return kOK;
}
//_____________________________________________________________________________
Int_t THaBPM::DefineVariables( EMode mode )
{
// Initialize global variables and lookup table for decoder
if( mode == kDefine && fIsSetup ) return kOK;
fIsSetup = ( mode == kDefine );
// Register variables in global list
RVarDef vars[] = {
{ "rawcur.1", "current in antenna 1", "GetRawSignal0()"},
{ "rawcur.2", "current in antenna 2", "GetRawSignal1()"},
{ "rawcur.3", "current in antenna 3", "GetRawSignal2()"},
{ "rawcur.4", "current in antenna 4", "GetRawSignal3()"},
{ "x", "reconstructed x-position", "fPosition.fX"},
{ "y", "reconstructed y-position", "fPosition.fY"},
{ "z", "reconstructed z-position", "fPosition.fZ"},
{ "rotpos1", "position in bpm system","GetRotPosX()"},
{ "rotpos2", "position in bpm system","GetRotPosY()"},
{ nullptr }
};
return DefineVarsFromList( vars, mode );
}
//_____________________________________________________________________________
THaBPM::~THaBPM()
{
// Destructor. Remove variables from global list.
if( fIsSetup )
RemoveVariables();
}
//_____________________________________________________________________________
void THaBPM::Clear( Option_t* opt )
{
// Reset per-event data.
THaBeamDet::Clear(opt);
fPosition.SetXYZ(0.,0.,-10000.);
fDirection.SetXYZ(0.,0.,1.);
for( UInt_t k=0; k<NCHAN; ++k ) {
fRawSignal(k)=-1;
fCorSignal(k)=-1;
}
fRotPos(0) = fRotPos(1) = 0.0;
}
//_____________________________________________________________________________
Int_t THaBPM::Decode( const THaEvData& evdata )
{
// clears the event structure
// loops over all modules defined in the detector map
// copies raw data into local variables
// performs pedestal subtraction
const char* const here = "Decode()";
UInt_t nfired = 0;
for (Int_t i = 0; i < fDetMap->GetSize(); i++ ){
THaDetMap::Module* d = fDetMap->GetModule( i );
for (Int_t j=0; j< evdata.GetNumChan( d->crate, d->slot ); j++) {
Int_t chan = evdata.GetNextChan( d->crate, d->slot, j);
if ((chan>=d->lo)&&(chan<=d->hi)) {
Int_t data = evdata.GetData( d->crate, d->slot, chan, 0 );
UInt_t k = d->first + ((d->reverse) ? d->hi - chan : chan - d->lo) -1;
if ((k<NCHAN)&&(fRawSignal(k)==-1)) {
fRawSignal(k)= data;
nfired++;
}
else {
Warning( Here(here), "Illegal detector channel: %d", k );
}
}
}
}
if (nfired!=NCHAN) {
Warning( Here(here), "Number of fired Channels out of range. "
"Setting beam position to nominal values");
}
else {
fCorSignal=fRawSignal;
fCorSignal-=fPedestals;
}
return 0;
}
//____________________________________________________
//
Int_t THaBPM::Process( )
{
// called by the beam apparatus
// uses the pedestal subtracted signals from the antennas
// to get the position in the bpm coordinate system
// and uses the transformation matrix defined in the database
// to transform it into the HCS
// directions are not calculated, they are always set parallel to z
for( UInt_t k = 0; k < NCHAN; k += 2 ) {
Double_t ap = fCorSignal(k);
Double_t am = fCorSignal(k + 1);
if( ap + am != 0.0 ) {
fRotPos(k / 2) = fCalibRot * (ap - am) / (ap + am);
} else {
fRotPos(k / 2) = 0.0;
}
}
TVectorD dum(fRotPos);
dum *= fRot2HCSPos;
fPosition.SetXYZ(
dum(0)+fOrigin(0)+fOffset(0),
dum(1)+fOrigin(1)+fOffset(1),
fOrigin(2)
);
return 0;
}
////////////////////////////////////////////////////////////////////////////////
ClassImp(THaBPM)
| 29.903509
| 80
| 0.579642
|
leadmocha
|
3c5db36a85222d394f0cd4ceb37fc551de360fd0
| 453
|
hpp
|
C++
|
src/engine/window/Surface.hpp
|
Lothav/volkano
|
b345091e4066727ca5cf72111453c0f6a82285a3
|
[
"MIT"
] | null | null | null |
src/engine/window/Surface.hpp
|
Lothav/volkano
|
b345091e4066727ca5cf72111453c0f6a82285a3
|
[
"MIT"
] | null | null | null |
src/engine/window/Surface.hpp
|
Lothav/volkano
|
b345091e4066727ca5cf72111453c0f6a82285a3
|
[
"MIT"
] | null | null | null |
//
// Created by luiz0tavio on 8/30/18.
//
#ifndef VOLKANO_SURFACE_HPP
#define VOLKANO_SURFACE_HPP
#include <cstdint>
#include <vulkan/vulkan.h>
namespace vkn
{
class Surface
{
private:
static uint16_t width;
static uint16_t height;
static VkSurfaceKHR surface;
public:
Surface() = delete;
static void init();
static void destroy();
};
}
#endif //VOLKANO_SURFACE_HPP
| 13.727273
| 36
| 0.615894
|
Lothav
|
3c6b9e29ecbcfa8cb09c1a52a24adc71ac377dfc
| 507
|
cpp
|
C++
|
AIC/AIC'20 - Level 1 Training/Sheet #3/E.cpp
|
MaGnsio/CP-Problems
|
a7f518a20ba470f554b6d54a414b84043bf209c5
|
[
"Unlicense"
] | 3
|
2020-11-01T06:31:30.000Z
|
2022-02-21T20:37:51.000Z
|
AIC/AIC'20 - Level 1 Training/Sheet #3/E.cpp
|
MaGnsio/CP-Problems
|
a7f518a20ba470f554b6d54a414b84043bf209c5
|
[
"Unlicense"
] | null | null | null |
AIC/AIC'20 - Level 1 Training/Sheet #3/E.cpp
|
MaGnsio/CP-Problems
|
a7f518a20ba470f554b6d54a414b84043bf209c5
|
[
"Unlicense"
] | 1
|
2021-05-05T18:56:31.000Z
|
2021-05-05T18:56:31.000Z
|
//https://codeforces.com/group/Rv2Qzg0DgK/contest/272491/problem/E
#include <bits/stdc++.h>
using namespace std;
#define F first
#define S second
typedef long long ll;
typedef long double ld;
ll mod = 1e9 + 7;
int main ()
{
ios_base::sync_with_stdio (0); cin.tie (0); cout.tie (0);
int n;
cin >> n;
vector<int> v(n);
for (auto& elem : v) cin >> elem;
int mi = *(min_element (v.begin (), v.end ()));
int idx = distance (v.begin (), find (v.begin (), v.end (), mi));
cout << mi << " " << idx + 1;
}
| 24.142857
| 66
| 0.617357
|
MaGnsio
|
3c721e2350479e5bd1ad28f3110b34e6313463bf
| 47,440
|
inl
|
C++
|
include/bolt/cl/detail/transform.inl
|
jayavanth/Bolt
|
ea1045126efc060c56f43eef926d65490bca7375
|
[
"BSL-1.0"
] | 1
|
2016-11-29T21:03:54.000Z
|
2016-11-29T21:03:54.000Z
|
include/bolt/cl/detail/transform.inl
|
jayavanth/Bolt
|
ea1045126efc060c56f43eef926d65490bca7375
|
[
"BSL-1.0"
] | null | null | null |
include/bolt/cl/detail/transform.inl
|
jayavanth/Bolt
|
ea1045126efc060c56f43eef926d65490bca7375
|
[
"BSL-1.0"
] | null | null | null |
/***************************************************************************
* Copyright 2012 - 2013 Advanced Micro Devices, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
***************************************************************************/
#pragma once
#if !defined( BOLT_CL_TRANSFORM_INL )
#define BOLT_CL_TRANSFORM_INL
#define WAVEFRONT_SIZE 64
#define TRANSFORM_ENABLE_PROFILING 0
#include <type_traits>
#ifdef ENABLE_TBB
#include "bolt/btbb/transform.h"
#endif
#include "bolt/cl/bolt.h"
#include "bolt/cl/device_vector.h"
#include "bolt/cl/iterator/iterator_traits.h"
namespace bolt {
namespace cl {
namespace detail {
enum TransformTypes {transform_iType1, transform_DVInputIterator1, transform_iType2, transform_DVInputIterator2,
transform_oTypeB,transform_DVOutputIteratorB, transform_BinaryFunction, transform_endB };
enum TransformUnaryTypes {transform_iType, transform_DVInputIterator, transform_oTypeU,
transform_DVOutputIteratorU, transform_UnaryFunction, transform_endU };
class Transform_KernelTemplateSpecializer : public KernelTemplateSpecializer
{
public:
Transform_KernelTemplateSpecializer() : KernelTemplateSpecializer()
{
addKernelName("transformTemplate");
addKernelName("transformNoBoundsCheckTemplate");
}
const ::std::string operator() ( const ::std::vector< ::std::string>& binaryTransformKernels ) const
{
const std::string templateSpecializationString =
"// Host generates this instantiation string with user-specified value type and functor\n"
"template __attribute__((mangled_name("+name(0)+"Instantiated)))\n"
"kernel void "+name(0)+"(\n"
"global " + binaryTransformKernels[transform_iType1] + "* A_ptr,\n"
+ binaryTransformKernels[transform_DVInputIterator1] + " A_iter,\n"
"global " + binaryTransformKernels[transform_iType2] + "* B_ptr,\n"
+ binaryTransformKernels[transform_DVInputIterator2] + " B_iter,\n"
"global " + binaryTransformKernels[transform_oTypeB] + "* Z_ptr,\n"
+ binaryTransformKernels[transform_DVOutputIteratorB] + " Z_iter,\n"
"const uint length,\n"
"global " + binaryTransformKernels[transform_BinaryFunction] + "* userFunctor);\n\n"
"// Host generates this instantiation string with user-specified value type and functor\n"
"template __attribute__((mangled_name("+name(1)+"Instantiated)))\n"
"kernel void "+name(1)+"(\n"
"global " + binaryTransformKernels[transform_iType1] + "* A_ptr,\n"
+ binaryTransformKernels[transform_DVInputIterator1] + " A_iter,\n"
"global " + binaryTransformKernels[transform_iType2] + "* B_ptr,\n"
+ binaryTransformKernels[transform_DVInputIterator2] + " B_iter,\n"
"global " + binaryTransformKernels[transform_oTypeB] + "* Z_ptr,\n"
+ binaryTransformKernels[transform_DVOutputIteratorB] + " Z_iter,\n"
"const uint length,\n"
"global " + binaryTransformKernels[transform_BinaryFunction] + "* userFunctor);\n\n";
return templateSpecializationString;
}
};
class TransformUnary_KernelTemplateSpecializer : public KernelTemplateSpecializer
{
public:
TransformUnary_KernelTemplateSpecializer() : KernelTemplateSpecializer()
{
addKernelName("unaryTransformTemplate");
addKernelName("unaryTransformNoBoundsCheckTemplate");
}
const ::std::string operator() ( const ::std::vector< ::std::string>& unaryTransformKernels ) const
{
const std::string templateSpecializationString =
"// Host generates this instantiation string with user-specified value type and functor\n"
"template __attribute__((mangled_name("+name( 0 )+"Instantiated)))\n"
"kernel void unaryTransformTemplate(\n"
"global " + unaryTransformKernels[transform_iType] + "* A,\n"
+ unaryTransformKernels[transform_DVInputIterator] + " A_iter,\n"
"global " + unaryTransformKernels[transform_oTypeU] + "* Z,\n"
+ unaryTransformKernels[transform_DVOutputIteratorU] + " Z_iter,\n"
"const uint length,\n"
"global " + unaryTransformKernels[transform_UnaryFunction] + "* userFunctor);\n\n"
"// Host generates this instantiation string with user-specified value type and functor\n"
"template __attribute__((mangled_name("+name(1)+"Instantiated)))\n"
"kernel void unaryTransformNoBoundsCheckTemplate(\n"
"global " + unaryTransformKernels[transform_iType] + "* A,\n"
+ unaryTransformKernels[transform_DVInputIterator] + " A_iter,\n"
"global " + unaryTransformKernels[transform_oTypeU] + "* Z,\n"
+ unaryTransformKernels[transform_DVOutputIteratorU] + " Z_iter,\n"
"const uint length,\n"
"global " +unaryTransformKernels[transform_UnaryFunction] + "* userFunctor);\n\n";
return templateSpecializationString;
}
};
template<typename DVInputIterator1, typename DVInputIterator2, typename DVOutputIterator, typename BinaryFunction>
void transform_enqueue( bolt::cl::control &ctl, const DVInputIterator1& first1, const DVInputIterator1& last1,
const DVInputIterator2& first2, const DVOutputIterator& result,
const BinaryFunction& f, const std::string& cl_code)
{
typedef typename std::iterator_traits<DVInputIterator1>::value_type iType1;
typedef typename std::iterator_traits<DVInputIterator2>::value_type iType2;
typedef typename std::iterator_traits<DVOutputIterator>::value_type oType;
cl_uint distVec = static_cast< cl_uint >( first1.distance_to(last1) );
if( distVec == 0 )
return;
const size_t numComputeUnits = ctl.getDevice( ).getInfo< CL_DEVICE_MAX_COMPUTE_UNITS >( );
const size_t numWorkGroupsPerComputeUnit = ctl.getWGPerComputeUnit( );
size_t numWorkGroups = numComputeUnits * numWorkGroupsPerComputeUnit;
/**********************************************************************************
* Type Names - used in KernelTemplateSpecializer
*********************************************************************************/
std::vector<std::string> binaryTransformKernels(transform_endB);
binaryTransformKernels[transform_iType1] = TypeName< iType1 >::get( );
binaryTransformKernels[transform_iType2] = TypeName< iType2 >::get( );
binaryTransformKernels[transform_DVInputIterator1] = TypeName< DVInputIterator1 >::get( );
binaryTransformKernels[transform_DVInputIterator2] = TypeName< DVInputIterator2 >::get( );
binaryTransformKernels[transform_oTypeB] = TypeName< oType >::get( );
binaryTransformKernels[transform_DVOutputIteratorB] = TypeName< DVOutputIterator >::get( );
binaryTransformKernels[transform_BinaryFunction] = TypeName< BinaryFunction >::get();
/**********************************************************************************
* Type Definitions - directrly concatenated into kernel string
*********************************************************************************/
// For user-defined types, the user must create a TypeName trait which returns the name of the
//class - note use of TypeName<>::get to retrieve the name here.
std::vector<std::string> typeDefinitions;
PUSH_BACK_UNIQUE( typeDefinitions, cl_code)
PUSH_BACK_UNIQUE( typeDefinitions, ClCode< iType1 >::get() )
PUSH_BACK_UNIQUE( typeDefinitions, ClCode< DVInputIterator1 >::get() )
PUSH_BACK_UNIQUE( typeDefinitions, ClCode< DVInputIterator2 >::get() )
PUSH_BACK_UNIQUE( typeDefinitions, ClCode< oType >::get() )
PUSH_BACK_UNIQUE( typeDefinitions, ClCode< DVOutputIterator >::get() )
PUSH_BACK_UNIQUE( typeDefinitions, ClCode< BinaryFunction >::get() )
/**********************************************************************************
* Calculate WG Size
*********************************************************************************/
cl_int l_Error = CL_SUCCESS;
const size_t wgSize = WAVEFRONT_SIZE;
V_OPENCL( l_Error, "Error querying kernel for CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE" );
assert( (wgSize & (wgSize-1) ) == 0 ); // The bitwise &,~ logic below requires wgSize to be a power of 2
int boundsCheck = 0;
size_t wgMultiple = distVec;
size_t lowerBits = ( distVec & (wgSize-1) );
if( lowerBits )
{
// Bump the workitem count to the next multiple of wgSize
wgMultiple &= ~lowerBits;
wgMultiple += wgSize;
}
else
{
boundsCheck = 1;
}
if (wgMultiple/wgSize < numWorkGroups)
numWorkGroups = wgMultiple/wgSize;
/**********************************************************************************
* Compile Options
*********************************************************************************/
bool cpuDevice = ctl.getDevice().getInfo<CL_DEVICE_TYPE>() == CL_DEVICE_TYPE_CPU;
//std::cout << "Device is CPU: " << (cpuDevice?"TRUE":"FALSE") << std::endl;
const size_t kernel_WgSize = (cpuDevice) ? 1 : wgSize;
std::string compileOptions;
std::ostringstream oss;
oss << " -DKERNELWORKGROUPSIZE=" << kernel_WgSize;
compileOptions = oss.str();
/**********************************************************************************
* Request Compiled Kernels
*********************************************************************************/
Transform_KernelTemplateSpecializer ts_kts;
std::vector< ::cl::Kernel > kernels = bolt::cl::getKernels(
ctl,
binaryTransformKernels,
&ts_kts,
typeDefinitions,
transform_kernels,
compileOptions);
// kernels returned in same order as added in KernelTemplaceSpecializer constructor
ALIGNED( 256 ) BinaryFunction aligned_binary( f );
control::buffPointer userFunctor = ctl.acquireBuffer( sizeof( aligned_binary ),
CL_MEM_USE_HOST_PTR|CL_MEM_READ_ONLY, &aligned_binary );
typename DVInputIterator1::Payload first1_payload = first1.gpuPayload( );
typename DVInputIterator2::Payload first2_payload = first2.gpuPayload( );
typename DVOutputIterator::Payload result_payload = result.gpuPayload( );
kernels[boundsCheck].setArg( 0, first1.getContainer().getBuffer() );
kernels[boundsCheck].setArg( 1, first1.gpuPayloadSize( ),&first1_payload);
kernels[boundsCheck].setArg( 2, first2.getContainer().getBuffer() );
kernels[boundsCheck].setArg( 3, first2.gpuPayloadSize( ),&first2_payload);
kernels[boundsCheck].setArg( 4, result.getContainer().getBuffer() );
kernels[boundsCheck].setArg( 5, result.gpuPayloadSize( ),&result_payload);
kernels[boundsCheck].setArg( 6, distVec );
kernels[boundsCheck].setArg( 7, *userFunctor);
::cl::Event transformEvent;
l_Error = ctl.getCommandQueue().enqueueNDRangeKernel(
kernels[boundsCheck],
::cl::NullRange,
::cl::NDRange(wgMultiple), // numWorkGroups*wgSize
::cl::NDRange(wgSize),
NULL,
&transformEvent );
V_OPENCL( l_Error, "enqueueNDRangeKernel() failed for transform() kernel" );
::bolt::cl::wait(ctl, transformEvent);
#if TRANSFORM_ENABLE_PROFILING
if( 0 )
{
cl_ulong start_time, stop_time;
l_Error = transformEvent.getProfilingInfo<cl_ulong>(CL_PROFILING_COMMAND_START, &start_time);
V_OPENCL( l_Error, "failed on getProfilingInfo<CL_PROFILING_COMMAND_QUEUED>()");
l_Error = transformEvent.getProfilingInfo<cl_ulong>(CL_PROFILING_COMMAND_END, &stop_time);
V_OPENCL( l_Error, "failed on getProfilingInfo<CL_PROFILING_COMMAND_END>()");
size_t time = stop_time - start_time;
std::cout << "Global Memory Bandwidth: "<<((distVec*(2.0*sizeof(iType1)+sizeof(oType)))/time)<<std::endl;
}
#endif // BOLT_ENABLE_PROFILING
};
template< typename DVInputIterator, typename DVOutputIterator, typename UnaryFunction >
void transform_unary_enqueue( ::bolt::cl::control &ctl, const DVInputIterator& first, const DVInputIterator& last,
const DVOutputIterator& result, const UnaryFunction& f, const std::string& cl_code)
{
typedef typename std::iterator_traits<DVInputIterator>::value_type iType;
typedef typename std::iterator_traits<DVOutputIterator>::value_type oType;
cl_uint distVec = static_cast< cl_uint >( std::distance( first, last ) );
if( distVec == 0 )
return;
const size_t numComputeUnits = ctl.getDevice( ).getInfo< CL_DEVICE_MAX_COMPUTE_UNITS >( );
const size_t numWorkGroupsPerComputeUnit = ctl.getWGPerComputeUnit( );
const size_t numWorkGroups = numComputeUnits * numWorkGroupsPerComputeUnit;
/**********************************************************************************
* Type Names - used in KernelTemplateSpecializer
*********************************************************************************/
std::vector<std::string> unaryTransformKernels( transform_endU );
unaryTransformKernels[transform_iType] = TypeName< iType >::get( );
unaryTransformKernels[transform_DVInputIterator] = TypeName< DVInputIterator >::get( );
unaryTransformKernels[transform_oTypeU] = TypeName< oType >::get( );
unaryTransformKernels[transform_DVOutputIteratorU] = TypeName< DVOutputIterator >::get( );
unaryTransformKernels[transform_UnaryFunction] = TypeName< UnaryFunction >::get();
/**********************************************************************************
* Type Definitions - directrly concatenated into kernel string
*********************************************************************************/
std::vector<std::string> typeDefinitions;
PUSH_BACK_UNIQUE( typeDefinitions, ClCode< iType >::get() )
PUSH_BACK_UNIQUE( typeDefinitions, ClCode< DVInputIterator >::get() )
PUSH_BACK_UNIQUE( typeDefinitions, ClCode< oType >::get() )
PUSH_BACK_UNIQUE( typeDefinitions, ClCode< DVOutputIterator >::get() )
PUSH_BACK_UNIQUE( typeDefinitions, ClCode< UnaryFunction >::get() )
/**********************************************************************************
* Calculate WG Size
*********************************************************************************/
cl_int l_Error = CL_SUCCESS;
const size_t wgSize = WAVEFRONT_SIZE;
int boundsCheck = 0;
V_OPENCL( l_Error, "Error querying kernel for CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE" );
assert( (wgSize & (wgSize-1) ) == 0 ); // The bitwise &,~ logic below requires wgSize to be a power of 2
size_t wgMultiple = distVec;
size_t lowerBits = ( distVec & (wgSize-1) );
if( lowerBits )
{
// Bump the workitem count to the next multiple of wgSize
wgMultiple &= ~lowerBits;
wgMultiple += wgSize;
}
else
{
boundsCheck = 1;
}
/**********************************************************************************
* Compile Options
*********************************************************************************/
bool cpuDevice = ctl.getDevice().getInfo<CL_DEVICE_TYPE>() == CL_DEVICE_TYPE_CPU;
//std::cout << "Device is CPU: " << (cpuDevice?"TRUE":"FALSE") << std::endl;
const size_t kernel_WgSize = (cpuDevice) ? 1 : wgSize;
std::string compileOptions;
std::ostringstream oss;
oss << " -DKERNELWORKGROUPSIZE=" << kernel_WgSize;
compileOptions = oss.str();
/**********************************************************************************
* Request Compiled Kernels
*********************************************************************************/
TransformUnary_KernelTemplateSpecializer ts_kts;
std::vector< ::cl::Kernel > kernels = bolt::cl::getKernels(
ctl,
unaryTransformKernels,
&ts_kts,
typeDefinitions,
transform_kernels,
compileOptions);
// kernels returned in same order as added in KernelTemplaceSpecializer constructor
// Create buffer wrappers so we can access the host functors, for read or writing in the kernel
ALIGNED( 256 ) UnaryFunction aligned_binary( f );
control::buffPointer userFunctor = ctl.acquireBuffer( sizeof( aligned_binary ),
CL_MEM_USE_HOST_PTR|CL_MEM_READ_ONLY, &aligned_binary );
typename DVInputIterator::Payload first_payload = first.gpuPayload( );
typename DVOutputIterator::Payload result_payload = result.gpuPayload( );
kernels[boundsCheck].setArg(0, first.getContainer().getBuffer() );
kernels[boundsCheck].setArg(1, first.gpuPayloadSize( ),&first_payload);
kernels[boundsCheck].setArg(2, result.getContainer().getBuffer() );
kernels[boundsCheck].setArg(3, result.gpuPayloadSize( ),&result_payload);
kernels[boundsCheck].setArg(4, distVec );
kernels[boundsCheck].setArg(5, *userFunctor);
//k.setArg(3, numElementsPerThread );
::cl::Event transformEvent;
l_Error = ctl.getCommandQueue().enqueueNDRangeKernel(
kernels[boundsCheck],
::cl::NullRange,
::cl::NDRange( wgMultiple ), // numThreads
::cl::NDRange( wgSize ),
NULL,
&transformEvent );
V_OPENCL( l_Error, "enqueueNDRangeKernel() failed for transform() kernel" );
::bolt::cl::wait(ctl, transformEvent);
#if TRANSFORM_ENABLE_PROFILING
if( 0 )
{
cl_ulong start_time, stop_time;
l_Error = transformEvent.getProfilingInfo<cl_ulong>(CL_PROFILING_COMMAND_START, &start_time);
V_OPENCL( l_Error, "failed on getProfilingInfo<CL_PROFILING_COMMAND_QUEUED>()");
l_Error = transformEvent.getProfilingInfo<cl_ulong>(CL_PROFILING_COMMAND_END, &stop_time);
V_OPENCL( l_Error, "failed on getProfilingInfo<CL_PROFILING_COMMAND_END>()");
size_t time = stop_time - start_time;
//std::cout << "Global Memory Bandwidth: "<<((distVec*(1.0*sizeof(iType)+sizeof(oType)))/time)<< std::endl;
}
#endif // BOLT_ENABLE_PROFILING
};
/*! \brief This template function overload is used to seperate device_vector iterators from all other iterators
\detail This template is called by the non-detail versions of inclusive_scan, it already assumes random access
* iterators. This overload is called strictly for non-device_vector iterators
*/
template< typename InputIterator1, typename InputIterator2, typename OutputIterator, typename BinaryFunction >
void transform_pick_iterator( bolt::cl::control &ctl, const InputIterator1& first1, const InputIterator1& last1,
const InputIterator2& first2, const OutputIterator& result, const BinaryFunction& f,
const std::string& user_code, std::random_access_iterator_tag, std::random_access_iterator_tag )
{
typedef typename std::iterator_traits<InputIterator1>::value_type iType1;
typedef typename std::iterator_traits<InputIterator2>::value_type iType2;
typedef typename std::iterator_traits<OutputIterator>::value_type oType;
size_t sz = std::distance( first1, last1 );
if (sz == 0)
return;
// Use host pointers memory since these arrays are only read once - no benefit to copying.
bolt::cl::control::e_RunMode runMode = ctl.getForceRunMode(); // could be dynamic choice some day.
if(runMode == bolt::cl::control::Automatic)
{
runMode = ctl.getDefaultPathToRun();
}
#if defined(BOLT_DEBUG_LOG)
BOLTLOG::CaptureLog *dblog = BOLTLOG::CaptureLog::getInstance();
#endif
if( runMode == bolt::cl::control::SerialCpu )
{
#if defined(BOLT_DEBUG_LOG)
dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_SERIAL_CPU,"::Transform::SERIAL_CPU");
#endif
std::transform( first1, last1, first2, result, f );
return;
}
else if( runMode == bolt::cl::control::MultiCoreCpu )
{
#if defined( ENABLE_TBB )
#if defined(BOLT_DEBUG_LOG)
dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_MULTICORE_CPU,"::Transform::MULTICORE_CPU");
#endif
bolt::btbb::transform(first1,last1,first2,result,f);
#else
//std::cout << "The MultiCoreCpu version of Transform is not enabled. " << std ::endl;
throw std::runtime_error( "The MultiCoreCpu version of transform is not enabled to be built! \n" );
#endif
return;
}
else
{
#if defined(BOLT_DEBUG_LOG)
dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_OPENCL_GPU,"::Transform::OPENCL_GPU");
#endif
// Map the input iterator to a device_vector
device_vector< iType1 > dvInput( first1, last1, CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY, ctl );
device_vector< iType2 > dvInput2( first2, sz, CL_MEM_USE_HOST_PTR|CL_MEM_READ_ONLY, true, ctl );
// Map the output iterator to a device_vector
device_vector< oType > dvOutput( result, sz, CL_MEM_USE_HOST_PTR|CL_MEM_WRITE_ONLY, false, ctl );
transform_enqueue(ctl,dvInput.begin( ),dvInput.end( ),dvInput2.begin( ),dvOutput.begin( ),f,user_code );
// This should immediately map/unmap the buffer
dvOutput.data( );
}
}
template< typename InputIterator1, typename InputIterator2, typename OutputIterator, typename BinaryFunction >
void transform_pick_iterator( bolt::cl::control &ctl, const InputIterator1& first1, const InputIterator1& last1,
const InputIterator2& fancyIter, const OutputIterator& result, const BinaryFunction& f,
const std::string& user_code, std::random_access_iterator_tag, bolt::cl::fancy_iterator_tag )
{
typedef typename std::iterator_traits<InputIterator1>::value_type iType1;
typedef typename std::iterator_traits<InputIterator2>::value_type iType2;
typedef typename std::iterator_traits<OutputIterator>::value_type oType;
size_t sz = std::distance( first1, last1 );
if (sz == 0)
return;
// Use host pointers memory since these arrays are only read once - no benefit to copying.
bolt::cl::control::e_RunMode runMode = ctl.getForceRunMode(); // could be dynamic choice some day.
if(runMode == bolt::cl::control::Automatic)
{
runMode = ctl.getDefaultPathToRun();
}
#if defined(BOLT_DEBUG_LOG)
BOLTLOG::CaptureLog *dblog = BOLTLOG::CaptureLog::getInstance();
#endif
if( runMode == bolt::cl::control::SerialCpu )
{
#if defined(BOLT_DEBUG_LOG)
dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_SERIAL_CPU,"::Transform::SERIAL_CPU");
#endif
std::transform( first1, last1, fancyIter, result, f );
return;
}
else if( runMode == bolt::cl::control::MultiCoreCpu )
{
#if defined( ENABLE_TBB )
#if defined(BOLT_DEBUG_LOG)
dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_MULTICORE_CPU,"::Transform::MULTICORE_CPU");
#endif
bolt::btbb::transform(first1,last1,fancyIter,result,f);
#else
//std::cout << "The MultiCoreCpu version of Transform is not enabled. " << std ::endl;
throw std::runtime_error( "The MultiCoreCpu version of transform is not enabled to be built! \n" );
#endif
return;
}
else
{
#if defined(BOLT_DEBUG_LOG)
dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_OPENCL_GPU,"::Transform::OPENCL_GPU");
#endif
// Use host pointers memory since these arrays are only read once - no benefit to copying.
// Map the input iterator to a device_vector
device_vector< iType1 > dvInput( first1, last1, CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY, ctl );
// Map the output iterator to a device_vector
device_vector< oType > dvOutput( result, sz, CL_MEM_USE_HOST_PTR|CL_MEM_WRITE_ONLY, false, ctl );
transform_enqueue( ctl, dvInput.begin( ), dvInput.end( ), fancyIter, dvOutput.begin( ), f, user_code );
// This should immediately map/unmap the buffer
dvOutput.data( );
}
}
template< typename InputIterator1, typename InputIterator2, typename OutputIterator, typename BinaryFunction >
void transform_pick_iterator( bolt::cl::control &ctl, const InputIterator1& fancyIterfirst,
const InputIterator1& fancyIterlast, const InputIterator2& first2, const OutputIterator& result,
const BinaryFunction& f, const std::string& user_code, bolt::cl::fancy_iterator_tag,
std::random_access_iterator_tag)
{
typedef typename std::iterator_traits<InputIterator1>::value_type iType1;
typedef typename std::iterator_traits<InputIterator2>::value_type iType2;
typedef typename std::iterator_traits<OutputIterator>::value_type oType;
size_t sz = std::distance( fancyIterfirst, fancyIterlast );
if (sz == 0)
return;
// Use host pointers memory since these arrays are only read once - no benefit to copying.
bolt::cl::control::e_RunMode runMode = ctl.getForceRunMode(); // could be dynamic choice some day.
if(runMode == bolt::cl::control::Automatic)
{
runMode = ctl.getDefaultPathToRun();
}
#if defined(BOLT_DEBUG_LOG)
BOLTLOG::CaptureLog *dblog = BOLTLOG::CaptureLog::getInstance();
#endif
if( runMode == bolt::cl::control::SerialCpu )
{
#if defined(BOLT_DEBUG_LOG)
dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_SERIAL_CPU,"::Transform::SERIAL_CPU");
#endif
std::transform( fancyIterfirst, fancyIterlast, first2, result, f );
return;
}
else if( runMode == bolt::cl::control::MultiCoreCpu )
{
#if defined( ENABLE_TBB )
#if defined(BOLT_DEBUG_LOG)
dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_MULTICORE_CPU,"::Transform::MULTICORE_CPU");
#endif
bolt::btbb::transform(fancyIterfirst,fancyIterlast,first2,result,f);
#else
//std::cout << "The MultiCoreCpu version of Transform is not enabled. " << std ::endl;
throw std::runtime_error( "The MultiCoreCpu version of transform is not enabled to be built! \n" );
#endif
return;
}
else
{
#if defined(BOLT_DEBUG_LOG)
dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_OPENCL_GPU,"::Transform::OPENCL_GPU");
#endif
// Use host pointers memory since these arrays are only read once - no benefit to copying.
// Map the input iterator to a device_vector
device_vector< iType2 > dvInput( first2, sz, CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY, true, ctl );
// Map the output iterator to a device_vector
device_vector< oType > dvOutput( result, sz, CL_MEM_USE_HOST_PTR|CL_MEM_WRITE_ONLY, false, ctl );
transform_enqueue( ctl, fancyIterfirst, fancyIterlast, dvInput.begin( ), dvOutput.begin( ),f,user_code );
// This should immediately map/unmap the buffer
dvOutput.data( );
}
}
// This template is called by the non-detail versions of inclusive_scan, it already assumes random access iterators
// This is called strictly for iterators that are derived from device_vector< T >::iterator
template<typename DVInputIterator1, typename DVInputIterator2, typename DVOutputIterator, typename BinaryFunction>
void transform_pick_iterator( bolt::cl::control &ctl, const DVInputIterator1& first1,
const DVInputIterator1& last1, const DVInputIterator2& first2, const DVOutputIterator& result,
const BinaryFunction& f,const std::string& user_code, bolt::cl::device_vector_tag, bolt::cl::device_vector_tag)
{
typedef typename std::iterator_traits< DVInputIterator1 >::value_type iType1;
typedef typename std::iterator_traits< DVInputIterator2 >::value_type iType2;
typedef typename std::iterator_traits< DVOutputIterator >::value_type oType;
size_t sz = std::distance( first1, last1 );
if( sz == 0 )
return;
bolt::cl::control::e_RunMode runMode = ctl.getForceRunMode(); // could be dynamic choice some day.
if(runMode == bolt::cl::control::Automatic)
{
runMode = ctl.getDefaultPathToRun();
}
#if defined(BOLT_DEBUG_LOG)
BOLTLOG::CaptureLog *dblog = BOLTLOG::CaptureLog::getInstance();
#endif
if( runMode == bolt::cl::control::SerialCpu )
{
#if defined(BOLT_DEBUG_LOG)
dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_SERIAL_CPU,"::Transform::SERIAL_CPU");
#endif
typename bolt::cl::device_vector< iType1 >::pointer firstPtr = first1.getContainer( ).data( );
typename bolt::cl::device_vector< iType2 >::pointer secPtr = first2.getContainer( ).data( );
typename bolt::cl::device_vector< oType >::pointer resPtr = result.getContainer( ).data( );
#if defined( _WIN32 )
std::transform( &firstPtr[ first1.m_Index ], &firstPtr[ last1.m_Index ], &secPtr[ first2.m_Index ],
stdext::make_checked_array_iterator( &resPtr[ result.m_Index ], sz ), f );
#else
std::transform( &firstPtr[ first1.m_Index ], &firstPtr[ last1.m_Index ],
&secPtr[ first2.m_Index ], &resPtr[ result.m_Index ], f );
#endif
return;
}
else if( runMode == bolt::cl::control::MultiCoreCpu )
{
#if defined( ENABLE_TBB )
#if defined(BOLT_DEBUG_LOG)
dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_MULTICORE_CPU,"::Transform::MULTICORE_CPU");
#endif
typename bolt::cl::device_vector< iType1 >::pointer firstPtr = first1.getContainer( ).data( );
typename bolt::cl::device_vector< iType2 >::pointer secPtr = first2.getContainer( ).data( );
typename bolt::cl::device_vector< oType >::pointer resPtr = result.getContainer( ).data( );
bolt::btbb::transform( &firstPtr[ first1.m_Index ], &firstPtr[ last1.m_Index ],
&secPtr[ first2.m_Index ],&resPtr[ result.m_Index ],f );
#else
//std::cout << "The MultiCoreCpu version of Transform is not enabled. " << std ::endl;
throw std::runtime_error( "The MultiCoreCpu version of transform is not enabled to be built! \n" );
#endif
return;
}
else
{
#if defined(BOLT_DEBUG_LOG)
dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_OPENCL_GPU,"::Transform::OPENCL_GPU");
#endif
transform_enqueue( ctl, first1, last1, first2, result, f, user_code );
}
}
// This template is called by the non-detail versions of inclusive_scan, it already assumes random access iterators
// This is called strictly for iterators that are derived from device_vector< T >::iterator
template<typename DVInputIterator1, typename DVInputIterator2, typename DVOutputIterator, typename BinaryFunction>
void transform_pick_iterator( bolt::cl::control &ctl,const DVInputIterator1& first1,const DVInputIterator1& last1,
const DVInputIterator2& fancyIter, const DVOutputIterator& result, const BinaryFunction& f,
const std::string& user_code, bolt::cl::device_vector_tag, bolt::cl::fancy_iterator_tag )
{
typedef typename std::iterator_traits< DVInputIterator1 >::value_type iType1;
typedef typename std::iterator_traits< DVInputIterator2 >::value_type iType2;
typedef typename std::iterator_traits< DVOutputIterator >::value_type oType;
size_t sz = std::distance( first1, last1 );
if( sz == 0 )
return;
bolt::cl::control::e_RunMode runMode = ctl.getForceRunMode(); // could be dynamic choice some day.
if(runMode == bolt::cl::control::Automatic)
{
runMode = ctl.getDefaultPathToRun();
}
#if defined(BOLT_DEBUG_LOG)
BOLTLOG::CaptureLog *dblog = BOLTLOG::CaptureLog::getInstance();
#endif
if( runMode == bolt::cl::control::SerialCpu )
{
#if defined(BOLT_DEBUG_LOG)
dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_SERIAL_CPU,"::Transform::SERIAL_CPU");
#endif
typename bolt::cl::device_vector< iType1 >::pointer firstPtr = first1.getContainer( ).data( );
typename bolt::cl::device_vector< oType >::pointer resPtr = result.getContainer( ).data( );
#if defined( _WIN32 )
std::transform( &firstPtr[ first1.m_Index ], &firstPtr[ last1.m_Index ], fancyIter,
stdext::make_checked_array_iterator( &resPtr[ result.m_Index ], sz ), f );
#else
std::transform( &firstPtr[ first1.m_Index ], &firstPtr[ last1.m_Index ],
fancyIter, &resPtr[ result.m_Index ], f );
#endif
return;
}
else if( runMode == bolt::cl::control::MultiCoreCpu )
{
#if defined( ENABLE_TBB )
#if defined(BOLT_DEBUG_LOG)
dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_MULTICORE_CPU,"::Transform::MULTICORE_CPU");
#endif
typename bolt::cl::device_vector< iType1 >::pointer firstPtr = first1.getContainer( ).data( );
typename bolt::cl::device_vector< oType >::pointer resPtr = result.getContainer( ).data( );
bolt::btbb::transform( &firstPtr[ first1.m_Index ], &firstPtr[ last1.m_Index ],
fancyIter, &resPtr[ result.m_Index ], f );
#else
//std::cout << "The MultiCoreCpu version of Transform is not enabled. " << std ::endl;
throw std::runtime_error( "The MultiCoreCpu version of transform is not enabled to be built! \n" );
#endif
return;
}
else
{
#if defined(BOLT_DEBUG_LOG)
dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_OPENCL_GPU,"::Transform::OPENCL_GPU");
#endif
transform_enqueue( ctl, first1, last1, fancyIter, result, f, user_code );
}
}
/*! \brief This template function overload is used to seperate device_vector iterators from all other iterators
\detail This template is called by the non-detail versions of inclusive_scan, it already assumes random access
* iterators. This overload is called strictly for non-device_vector iterators
*/
template<typename InputIterator, typename OutputIterator, typename UnaryFunction>
void
transform_unary_pick_iterator( ::bolt::cl::control &ctl, const InputIterator& first, const InputIterator& last,
const OutputIterator& result, const UnaryFunction& f, const std::string& user_code,
std::random_access_iterator_tag )
{
typedef typename std::iterator_traits<InputIterator>::value_type iType;
typedef typename std::iterator_traits<OutputIterator>::value_type oType;
size_t sz = (last - first);
if (sz == 0)
return;
bolt::cl::control::e_RunMode runMode = ctl.getForceRunMode(); // could be dynamic choice some day.
if(runMode == bolt::cl::control::Automatic)
{
runMode = ctl.getDefaultPathToRun();
}
#if defined(BOLT_DEBUG_LOG)
BOLTLOG::CaptureLog *dblog = BOLTLOG::CaptureLog::getInstance();
#endif
if( runMode == bolt::cl::control::SerialCpu )
{
#if defined(BOLT_DEBUG_LOG)
dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_SERIAL_CPU,"::Transform::SERIAL_CPU");
#endif
std::transform( first, last, result, f );
return;
}
else if( runMode == bolt::cl::control::MultiCoreCpu )
{
#if defined( ENABLE_TBB )
#if defined(BOLT_DEBUG_LOG)
dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_MULTICORE_CPU,"::Transform::MULTICORE_CPU");
#endif
bolt::btbb::transform(first, last, result, f);
#else
//std::cout << "The MultiCoreCpu version of Transform is not enabled. " << std ::endl;
throw std::runtime_error( "The MultiCoreCpu version of transform is not enabled to be built! \n" );
#endif
return;
}
else
{
#if defined(BOLT_DEBUG_LOG)
dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_OPENCL_GPU,"::Transform::OPENCL_GPU");
#endif
// Use host pointers memory since these arrays are only read once - no benefit to copying.
// Map the input iterator to a device_vector
device_vector< iType > dvInput( first, last, CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, ctl );
// Map the output iterator to a device_vector
device_vector< oType > dvOutput( result, sz, CL_MEM_USE_HOST_PTR | CL_MEM_WRITE_ONLY, false, ctl );
transform_unary_enqueue( ctl, dvInput.begin( ), dvInput.end( ), dvOutput.begin( ), f, user_code );
// This should immediately map/unmap the buffer
dvOutput.data( );
}
}
// This template is called by the non-detail versions of inclusive_scan, it already assumes random access iterators
// This is called strictly for iterators that are derived from device_vector< T >::iterator
template<typename DVInputIterator, typename DVOutputIterator, typename UnaryFunction>
void
transform_unary_pick_iterator( ::bolt::cl::control &ctl, const DVInputIterator& first, const DVInputIterator& last,
const DVOutputIterator& result, const UnaryFunction& f, const std::string& user_code,
bolt::cl::device_vector_tag )
{
typedef typename std::iterator_traits< DVInputIterator >::value_type iType;
typedef typename std::iterator_traits< DVOutputIterator >::value_type oType;
size_t sz = std::distance( first, last );
if( sz == 0 )
return;
bolt::cl::control::e_RunMode runMode = ctl.getForceRunMode(); // could be dynamic choice some day.
if(runMode == bolt::cl::control::Automatic)
{
runMode = ctl.getDefaultPathToRun();
}
#if defined(BOLT_DEBUG_LOG)
BOLTLOG::CaptureLog *dblog = BOLTLOG::CaptureLog::getInstance();
#endif
// TBB does not have an equivalent for two input iterator std::transform
if( (runMode == bolt::cl::control::SerialCpu) )
{
#if defined(BOLT_DEBUG_LOG)
dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_SERIAL_CPU,"::Transform::SERIAL_CPU");
#endif
typename bolt::cl::device_vector< iType >::pointer firstPtr = first.getContainer( ).data( );
typename bolt::cl::device_vector< oType >::pointer resPtr = result.getContainer( ).data( );
#if defined( _WIN32 )
std::transform( &firstPtr[ first.m_Index ], &firstPtr[ last.m_Index ],
stdext::make_checked_array_iterator( &resPtr[ result.m_Index ], sz ), f );
#else
std::transform( &firstPtr[ first.m_Index ], &firstPtr[ last.m_Index ], &resPtr[ result.m_Index ], f );
#endif
return;
}
else if( (runMode == bolt::cl::control::MultiCoreCpu) )
{
#if defined( ENABLE_TBB )
#if defined(BOLT_DEBUG_LOG)
dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_MULTICORE_CPU,"::Transform::MULTICORE_CPU");
#endif
typename bolt::cl::device_vector< iType >::pointer firstPtr = first.getContainer( ).data( );
typename bolt::cl::device_vector< oType >::pointer resPtr = result.getContainer( ).data( );
bolt::btbb::transform(&firstPtr[ first.m_Index ], &firstPtr[ last.m_Index ], &resPtr[ result.m_Index ], f );
#else
//std::cout << "The MultiCoreCpu version of Transform is not enabled. " << std ::endl;
throw std::runtime_error("The MultiCoreCpu version of transform is not enabled to be built! \n" );
#endif
return;
}
else
{
#if defined(BOLT_DEBUG_LOG)
dblog->CodePathTaken(BOLTLOG::BOLT_TRANSFORM,BOLTLOG::BOLT_OPENCL_GPU,"::Transform::OPENCL_GPU");
#endif
transform_unary_enqueue( ctl, first, last, result, f, user_code );
}
}
template< typename InputIterator1, typename InputIterator2, typename OutputIterator, typename BinaryFunction >
void transform_detect_random_access( bolt::cl::control& ctl, const InputIterator1& first1,
const InputIterator1& last1, const InputIterator2& first2, const OutputIterator& result,
const BinaryFunction& f, const std::string& user_code, std::random_access_iterator_tag,
std::random_access_iterator_tag )
{
transform_pick_iterator( ctl, first1, last1, first2, result, f, user_code,
typename std::iterator_traits< InputIterator1 >::iterator_category( ),
typename std::iterator_traits< InputIterator2 >::iterator_category( ) );
};
// Wrapper that uses default ::bolt::cl::control class, iterator interface
template< typename InputIterator1, typename InputIterator2, typename OutputIterator, typename BinaryFunction >
void transform_detect_random_access( bolt::cl::control& ctl, const InputIterator1& first1,
const InputIterator1& last1, const InputIterator2& first2, const OutputIterator& result,
const BinaryFunction& f,const std::string& user_code, std::input_iterator_tag, std::input_iterator_tag )
{
// TODO: It should be possible to support non-random_access_iterator_tag iterators, if we copied the data
// to a temporary buffer. Should we?
static_assert( std::is_same< InputIterator1, std::input_iterator_tag >::value, "Bolt only supports random access iterator types" );
};
template<typename InputIterator, typename OutputIterator, typename UnaryFunction>
void transform_unary_detect_random_access( ::bolt::cl::control& ctl, const InputIterator& first1,
const InputIterator& last1,const OutputIterator& result, const UnaryFunction& f,
const std::string& user_code, std::random_access_iterator_tag )
{
transform_unary_pick_iterator( ctl, first1, last1, result, f, user_code,
typename std::iterator_traits< InputIterator >::iterator_category( ) );
};
// Wrapper that uses default ::bolt::cl::control class, iterator interface
template<typename InputIterator, typename OutputIterator, typename UnaryFunction>
void transform_unary_detect_random_access( ::bolt::cl::control& ctl, const InputIterator& first1,
const InputIterator& last1, const OutputIterator& result, const UnaryFunction& f,
const std::string& user_code, std::input_iterator_tag )
{
// TODO: It should be possible to support non-random_access_iterator_tag iterators, if we copied the data
// to a temporary buffer. Should we?
static_assert( std::is_same< InputIterator, std::input_iterator_tag >::value , "Bolt only supports random access iterator types" );
};
} //End of detail namespace
// two-input transform, std:: iterator
template< typename InputIterator1, typename InputIterator2, typename OutputIterator, typename BinaryFunction >
void transform( bolt::cl::control& ctl, InputIterator1 first1, InputIterator1 last1, InputIterator2 first2,
OutputIterator result, BinaryFunction f, const std::string& user_code )
{
detail::transform_detect_random_access( ctl, first1, last1, first2, result, f, user_code,
typename std::iterator_traits< InputIterator1 >::iterator_category( ),
typename std::iterator_traits< InputIterator2 >::iterator_category( ) );
}
// default ::bolt::cl::control, two-input transform, std:: iterator
template< typename InputIterator1, typename InputIterator2, typename OutputIterator, typename BinaryFunction >
void transform( InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, OutputIterator result,
BinaryFunction f, const std::string& user_code )
{
detail::transform_detect_random_access( control::getDefault(), first1, last1, first2, result, f, user_code,
typename std::iterator_traits< InputIterator1 >::iterator_category( ),
typename std::iterator_traits< InputIterator2 >::iterator_category( ) );
}
// one-input transform, std:: iterator
template<typename InputIterator, typename OutputIterator, typename UnaryFunction>
void transform( ::bolt::cl::control& ctl, InputIterator first1, InputIterator last1, OutputIterator result,
UnaryFunction f, const std::string& user_code )
{
detail::transform_unary_detect_random_access( ctl, first1, last1, result, f, user_code,
typename std::iterator_traits< InputIterator >::iterator_category( ) );
}
// default control, one-input transform, std:: iterator
template<typename InputIterator, typename OutputIterator, typename UnaryFunction>
void transform( InputIterator first1, InputIterator last1, OutputIterator result,
UnaryFunction f, const std::string& user_code )
{
detail::transform_unary_detect_random_access( control::getDefault(), first1, last1, result, f, user_code,
typename std::iterator_traits< InputIterator >::iterator_category( ) );
}
} //End of cl namespace
} //End of bolt namespace
#endif
| 48.806584
| 143
| 0.633284
|
jayavanth
|
3c72e3f286a37d536acaa51ed811edb1aa4998aa
| 1,418
|
hpp
|
C++
|
dp/longest-common-subsequence.hpp
|
matumoto1234/library
|
a2c80516a8afe5876696c139fe0e837d8a204f69
|
[
"Unlicense"
] | 2
|
2021-06-24T11:21:08.000Z
|
2022-03-15T05:57:25.000Z
|
dp/longest-common-subsequence.hpp
|
matumoto1234/library
|
a2c80516a8afe5876696c139fe0e837d8a204f69
|
[
"Unlicense"
] | 102
|
2021-10-30T21:30:00.000Z
|
2022-03-26T18:39:47.000Z
|
dp/longest-common-subsequence.hpp
|
matumoto1234/library
|
a2c80516a8afe5876696c139fe0e837d8a204f69
|
[
"Unlicense"
] | null | null | null |
#pragma once
#include "./base.hpp"
#include <string>
#include <vector>
namespace dp {
// verify:EDPC_F
template <typename T>
struct LongestCommonSubsequence {
vector<T> s, t;
int h, w;
vector<vector<int>> dp;
LongestCommonSubsequence(vector<T> _s, vector<T> _t): s(_s), t(_t) {
h = _s.size();
w = _t.size();
}
LongestCommonSubsequence(string _s, string _t) {
h = _s.size(), w = _t.size();
for (int i = 0; i < h; i++)
s.emplace_back(_s[i]);
for (int i = 0; i < w; i++)
t.emplace_back(_t[i]);
}
int build() {
dp.assign(h + 1, vector<int>(w + 1, 0));
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
if (s[i] == t[j]) {
dp[i + 1][j + 1] = max(dp[i + 1][j + 1], dp[i][j] + 1);
continue;
}
dp[i + 1][j] = max(dp[i + 1][j], dp[i][j]);
dp[i][j + 1] = max(dp[i][j + 1], dp[i][j]);
}
}
return dp[h][w];
}
vector<T> restore() {
vector<T> res;
int i = h, j = w;
while (i > 0 and j > 0) {
if (s[i - 1] == t[j - 1]) {
res.emplace_back(s[i - 1]);
i--;
j--;
continue;
}
if (dp[i - 1][j] > dp[i][j - 1])
i--;
else
j--;
}
reverse(res.begin(), res.end());
return res;
}
};
} // namespace dp
| 23.245902
| 72
| 0.415374
|
matumoto1234
|
3c76e16dc82dd5a00270d85ce260dcad65378378
| 867
|
hpp
|
C++
|
NWNXLib/API/Mac/API/CJoiningRestrictions.hpp
|
acaos/nwnxee-unified
|
0e4c318ede64028c1825319f39c012e168e0482c
|
[
"MIT"
] | 1
|
2019-06-04T04:30:24.000Z
|
2019-06-04T04:30:24.000Z
|
NWNXLib/API/Mac/API/CJoiningRestrictions.hpp
|
presscad/nwnee
|
0f36b281524e0b7e9796bcf30f924792bf9b8a38
|
[
"MIT"
] | null | null | null |
NWNXLib/API/Mac/API/CJoiningRestrictions.hpp
|
presscad/nwnee
|
0f36b281524e0b7e9796bcf30f924792bf9b8a38
|
[
"MIT"
] | 1
|
2019-10-20T07:54:45.000Z
|
2019-10-20T07:54:45.000Z
|
#pragma once
#include <cstdint>
namespace NWNXLib {
namespace API {
struct CJoiningRestrictions
{
int32_t bAllowLocal;
int32_t bAllowServer;
int32_t bAllowVault;
int32_t bFixedParties;
int32_t bAllowFighter;
int32_t bAllowBarbarian;
int32_t bAllowRanger;
int32_t bAllowPaladin;
int32_t bAllowWizard;
int32_t bAllowSorcerer;
int32_t bAllowCleric;
int32_t bAllowDruid;
int32_t bAllowRogue;
int32_t bAllowBard;
int32_t bAllowMonk;
int32_t bAllowHuman;
int32_t bAllowElf;
int32_t bAllowDwarf;
int32_t bAllowGnome;
int32_t bAllowHalfling;
int32_t bAllowHalfOrc;
int32_t bAllowHalfElf;
int32_t nMaxPlayers;
int32_t nMaxParties;
int32_t nMaxItemPoints;
int32_t nMaxStatTotal;
int32_t nMinLevel;
int32_t nMaxLevel;
int32_t bAllowLocalVaultChars;
};
}
}
| 19.266667
| 34
| 0.727797
|
acaos
|
3c77efa73935544b65f3479175f705e0342d9da0
| 10,431
|
cpp
|
C++
|
Sources/src/SpecialAttack.cpp
|
Tifox/Grog-Knight
|
377a661286cda7ee3b2b2d0099641897938c2f8f
|
[
"Apache-2.0"
] | null | null | null |
Sources/src/SpecialAttack.cpp
|
Tifox/Grog-Knight
|
377a661286cda7ee3b2b2d0099641897938c2f8f
|
[
"Apache-2.0"
] | null | null | null |
Sources/src/SpecialAttack.cpp
|
Tifox/Grog-Knight
|
377a661286cda7ee3b2b2d0099641897938c2f8f
|
[
"Apache-2.0"
] | null | null | null |
/**
* 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.
*/
/**
* File: SpecialMoves.cpp
* Creation: 2015-06-30 09:57
* Matthieu Maudet<arkhane84@gmail.com>
*/
# include "SpecialAttack.hpp"
# include "Characters.hpp"
# include <cstdlib>
//! Base constructor
SpecialAttack::SpecialAttack(void) {
}
SpecialAttack::~SpecialAttack(void) {
theSwitchboard.UnsubscribeFrom(this, "SpecialAttackEnd");
theSwitchboard.UnsubscribeFrom(this, "linkWeapon");
}
SpecialAttack::SpecialAttack(Characters* charac) {
std::string file;
std::stringstream buffer;
std::ifstream fd;
Json::Reader read;
Json::Value json;
Json::ValueIterator i, v;
std::map<std::string, Json::Value> tmp;
this->character = charac;
file = "Resources/Elements/SpecialAttack.json";
fd.open(file.c_str());
if (!fd.is_open())
Log::error("Can't open the file for the specialmoves class.");
buffer << fd.rdbuf();
if (!read.parse(buffer, json))
Log::error("Error in json syntax :\n" + read.getFormattedErrorMessages());
for (i = json.begin(); i != json.end(); i++) {
for (v = (*i).begin(); v != (*i).end(); v++) {
tmp[v.key().asString()] = (*v);
this->character->_attr[i.key().asString()] = tmp;
}
}
theSwitchboard.SubscribeTo(this, "SpecialAttackEnd");
theSwitchboard.SubscribeTo(this, "linkWeapon");
}
void SpecialAttack::ReceiveMessage(Message *m) {
Characters *c = Game::currentGame->getHero();
if (m->GetMessageName() == "linkWeapon") {
this->_left->GetBody()->SetGravityScale(0);
this->_right->GetBody()->SetGravityScale(0);
this->_left->GetBody()->SetLinearVelocity(b2Vec2(0,0));
this->_right->GetBody()->SetLinearVelocity(b2Vec2(0,0));
b2DistanceJointDef jointDef1;
b2DistanceJointDef jointDef2;
b2DistanceJointDef jointDef3;
b2DistanceJointDef jointDef4;
jointDef1.Initialize(c->GetBody(), this->_left->GetBody(), b2Vec2(c->GetBody()->GetWorldCenter().x, c->GetBody()->GetWorldCenter().y + 0.4),
b2Vec2(this->_left->GetBody()->GetWorldCenter().x, this->_left->GetBody()->GetWorldCenter().y + 0.4));
jointDef1.collideConnected = false;
jointDef2.Initialize(c->GetBody(), this->_right->GetBody(), b2Vec2(c->GetBody()->GetWorldCenter().x, c->GetBody()->GetWorldCenter().y + 0.4),
b2Vec2(this->_right->GetBody()->GetWorldCenter().x, this->_right->GetBody()->GetWorldCenter().y + 0.4));
jointDef2.collideConnected = false;
jointDef3.Initialize(c->GetBody(), this->_left->GetBody(), b2Vec2(c->GetBody()->GetWorldCenter().x, c->GetBody()->GetWorldCenter().y - 0.4),
b2Vec2(this->_left->GetBody()->GetWorldCenter().x, this->_left->GetBody()->GetWorldCenter().y - 0.4));
jointDef3.collideConnected = false;
jointDef4.Initialize(c->GetBody(), this->_right->GetBody(), b2Vec2(c->GetBody()->GetWorldCenter().x, c->GetBody()->GetWorldCenter().y - 0.4),
b2Vec2(this->_right->GetBody()->GetWorldCenter().x, this->_right->GetBody()->GetWorldCenter().y - 0.4));
jointDef4.collideConnected = false;
b2DistanceJoint *joint1 = (b2DistanceJoint*)theWorld.GetPhysicsWorld().CreateJoint(&jointDef1);
b2DistanceJoint *joint2 = (b2DistanceJoint*)theWorld.GetPhysicsWorld().CreateJoint(&jointDef2);
b2DistanceJoint *joint3 = (b2DistanceJoint*)theWorld.GetPhysicsWorld().CreateJoint(&jointDef3);
b2DistanceJoint *joint4 = (b2DistanceJoint*)theWorld.GetPhysicsWorld().CreateJoint(&jointDef4);
}
if (m->GetMessageName() == "RapidFire") {
Game::currentGame->getHero()->getWeapon()->attack(this->character);
theSwitchboard.DeferredBroadcast(new Message("RapidFire"), this->character->_getAttr("rapidFire", "interval").asFloat());
}
if (m->GetMessageName() == "SpecialAttackEnd") {
if (this->_currentAttack == "whirlwind") {
Game::currentGame->getHero()->buff.bonusSpeed = this->_previousSpeed;
Game::currentGame->getHero()->_isWhirlwinding = false;
c->AnimCallback("base");
c->_canAttack = true;
c->_invincibility = false;
this->_currentAttack = "";
}
else if (this->_currentAttack == "shockwave") {
this->_currentAttack = "";
}
if (this->_currentAttack == "rapidFire") {
Game::currentGame->getHero()->_isRapidFiring = false;
theSwitchboard.UnsubscribeFrom(this, "RapidFire");
c->AnimCallback("base");
this->_currentAttack = "";
}
}
}
void SpecialAttack::_whirlwind(void) {
this->character->_setCategory("whirlwind");
Weapon *currentWeapon = Game::currentGame->getHero()->getWeapon();
Characters *hero = Game::currentGame->getHero();
if (this->character->_isAttacking == 0 && this->character->_canMove == 1 && this->character->_speAttReady == 1 /*&& currentWeapon->getType() == "Sword"*/) {
this->character->_speAttReady = 0;
this->character->_isWhirlwinding = true;
currentWeapon->setActive(this->character->_getAttr("whirlwind", "uptime").asFloat());
this->_right = new Weapon (Game::currentGame->getHero()->_weapon, Game::currentGame->getHero(), 1);
this->_left = new Weapon (Game::currentGame->getHero()->_weapon, Game::currentGame->getHero(), -1);
this->_previousSpeed = hero->buff.bonusSpeed;
hero->_invincibility = true;
hero->buff.bonusSpeed = -(hero->_getAttr("forward", "force").asInt() / 2);
hero->_canAttack = false;
theSwitchboard.DeferredBroadcast(new Message("SpecialAttackEnd"),
this->character->_getAttr("whirlwind", "uptime").asFloat());
theSwitchboard.DeferredBroadcast(new Message("speAttReady"),
this->character->_getAttr("cooldown").asFloat());
Game::getHUD()->speAttCooldown(this->character->_getAttr("cooldown").asFloat());
hero->changeSizeTo(Vector2(hero->_getAttr("x").asFloat(), hero->_getAttr("y").asFloat()));
hero->PlaySpriteAnimation(hero->_getAttr("time").asFloat(), SAT_Loop,
hero->_getAttr("beginFrame").asInt(),
hero->_getAttr("endFrame").asInt(), "base");
this->_currentAttack = "whirlwind";
}
}
void SpecialAttack::_throwWeapon(void) {
this->character->_setCategory("throwWeapon");
b2Vec2 pos = this->character->GetBody()->GetWorldCenter();
Weapon *currentWeapon = this->character->getWeapon();
std::string orientation;
Characters *hero = Game::currentGame->getHero();
if (this->character->_isAttacking == 0 && this->character->_canMove == 1 && this->character->_speAttReady == 1 && currentWeapon->getType() == "Spear") {
this->character->_speAttReady = 0;
if (hero->_latOrientation == Characters::RIGHT) {
new Projectile(currentWeapon->getSprite(), 50, Vector2(pos.x, pos.y), Vector2(1, 1.5f), Vector2(0, 0), "throwSpear", -1, 0.8);
}
if (hero->_latOrientation == Characters::LEFT)
new Projectile(currentWeapon->getSprite(), 50, Vector2(pos.x, pos.y), Vector2(-1, 1.5f), Vector2(0, 0), "throwSpear", 45, 0.8);
theSwitchboard.DeferredBroadcast(new Message("speAttReady"),
this->character->_getAttr("cooldown").asFloat());
Game::getHUD()->speAttCooldown(this->character->_getAttr("cooldown").asFloat());
this->_currentAttack = "throwWeapon";
}
}
void SpecialAttack::_shockwave(void) {
this->character->_setCategory("shockwave");
Weapon *currentWeapon = Game::currentGame->getHero()->getWeapon();
Characters *hero = Game::currentGame->getHero();
if (this->character->_isAttacking == 0 && this->character->_canMove == 1 && this->character->_speAttReady == 1 && currentWeapon->getType() == "Axe") {
this->character->_speAttReady = 0;
this->character->_isShockWaving = true;
theSwitchboard.DeferredBroadcast(new Message("speAttReady"),
this->character->_getAttr("cooldown").asFloat());
int dmg = this->character->_getAttr("shockwave", "damage").asInt();
Projectile *wave = new Projectile(currentWeapon, dmg);
this->_currentAttack = "shockwave";
std::string orientation;
if (hero->_latOrientation == Characters::RIGHT)
orientation = "right";
else if (hero->_latOrientation == Characters::LEFT)
orientation = "left";
hero->changeSizeTo(Vector2(hero->_getAttr("x").asInt(), hero->_getAttr("y").asInt()));
hero->PlaySpriteAnimation(hero->_getAttr("time").asFloat(), SAT_OneShot,
hero->_getAttr("beginFrame_" + orientation).asInt(),
hero->_getAttr("endFrame_" + orientation).asInt(), "base");
theSwitchboard.DeferredBroadcast(new Message("speAttReady"),
this->character->_getAttr("cooldown").asFloat());
Game::getHUD()->speAttCooldown(this->character->_getAttr("cooldown").asFloat());
}
}
void SpecialAttack::_rapidFire(void) {
this->character = Game::currentGame->getHero();
this->character->_setCategory("rapidFire");
Weapon *currentWeapon = Game::currentGame->getHero()->getWeapon();
Characters *hero = Game::currentGame->getHero();
std::string orientation;
theSwitchboard.SubscribeTo(this, "RapidFire");
if (this->character->_isAttacking == 0 && this->character->_canMove == 1 && this->character->_speAttReady == 1 && currentWeapon->getType() == "Bow") {
this->character->_speAttReady = 0;
this->character->_isRapidFiring = true;
if (hero->_latOrientation == Characters::RIGHT)
orientation = "right";
else if (hero->_latOrientation == Characters::LEFT)
orientation = "left";
hero->changeSizeTo(Vector2(hero->_getAttr("x").asInt(), hero->_getAttr("y").asInt()));
hero->PlaySpriteAnimation(hero->_getAttr("time").asFloat(), SAT_Loop,
hero->_getAttr("beginFrame_" + orientation).asInt(),
hero->_getAttr("endFrame_" + orientation).asInt());
theSwitchboard.DeferredBroadcast(new Message("speAttReady"),
this->character->_getAttr("cooldown").asFloat());
Game::getHUD()->speAttCooldown(this->character->_getAttr("cooldown").asFloat());
theSwitchboard.DeferredBroadcast(new Message("SpecialAttackEnd"),
this->character->_getAttr("rapidFire", "uptime").asFloat());
theSwitchboard.DeferredBroadcast(new Message("RapidFire"), 0);
this->_currentAttack = "rapidFire";
}
}
| 45.75
| 157
| 0.705685
|
Tifox
|
3c78bcb00b7035c0bd7a9fc3c399314fd5270126
| 1,391
|
cpp
|
C++
|
src/image/color.cpp
|
eisbehr/c10t
|
c30e55613fa0203cba84cb153392a55391279551
|
[
"BSD-3-Clause"
] | 1
|
2016-06-07T17:34:32.000Z
|
2016-06-07T17:34:32.000Z
|
src/image/color.cpp
|
eisbehr/c10t
|
c30e55613fa0203cba84cb153392a55391279551
|
[
"BSD-3-Clause"
] | null | null | null |
src/image/color.cpp
|
eisbehr/c10t
|
c30e55613fa0203cba84cb153392a55391279551
|
[
"BSD-3-Clause"
] | null | null | null |
// Distributed under the BSD License, see accompanying LICENSE.txt
// (C) Copyright 2010 John-John Tedro et al.
#include "image/color.hpp"
#include <sstream>
#include <string>
uint8_t alpha_over_c(uint8_t u, uint8_t o, uint8_t ua, uint8_t oa);
/**
* Takes two color values and does an alpha over blending without using floats.
*/
inline uint8_t alpha_over_c(uint8_t ac, uint8_t aa, uint8_t bc, uint8_t ba) {
return ((ac * aa) + ((0xff * (bc * ba) - aa * (bc * ba)) / 0xff)) / 0xff;
}
void color::blend(const color &other) {
if (other.is_invisible()) return;
if (other.is_opaque() || is_invisible()) {
r = other.r;
g = other.g;
b = other.b;
a = other.a;
return;
}
r = alpha_over_c(other.r, other.a, r, a);
g = alpha_over_c(other.g, other.a, g, a);
b = alpha_over_c(other.b, other.a, b, a);
a = a + (other.a * (0xff - a)) / 0xff;
r = ((r * 0xff) / a);
g = ((g * 0xff) / a);
b = ((b * 0xff) / a);
}
// pull color down towards black
void color::darken(uint8_t f) {
r = std::max((int)r - ((int)r * (int)f) / 0xff, 0x0);
g = std::max((int)g - ((int)g * (int)f) / 0xff, 0x0);
b = std::max((int)b - ((int)b * (int)f) / 0xff, 0x0);
}
void color::lighten(uint8_t f) {
r = std::min((int)r + ((int)r * (int)f) / 0xff, 0xff);
g = std::min((int)g + ((int)g * (int)f) / 0xff, 0xff);
b = std::min((int)b + ((int)b * (int)f) / 0xff, 0xff);
}
| 28.387755
| 79
| 0.580158
|
eisbehr
|
3c7c76ccc0b9697dfeef26c9bd802a064be5c755
| 3,526
|
cpp
|
C++
|
All Project/project1.cpp
|
jaibae21/CPE211_S2021_UAH
|
9e8e5452526288699e0d7ee22ed393857233501e
|
[
"MIT"
] | null | null | null |
All Project/project1.cpp
|
jaibae21/CPE211_S2021_UAH
|
9e8e5452526288699e0d7ee22ed393857233501e
|
[
"MIT"
] | null | null | null |
All Project/project1.cpp
|
jaibae21/CPE211_S2021_UAH
|
9e8e5452526288699e0d7ee22ed393857233501e
|
[
"MIT"
] | 1
|
2022-03-26T08:52:00.000Z
|
2022-03-26T08:52:00.000Z
|
//******************************************************************
// The following is a partial header comment block. Modify the
// appropriate parts by putting in your information. Look at
// the samples handed out to make any necessary additions
// You may delete this line and the three above it.
// Paycheck program
// Ron Bowman
// CPE112-02, L00
// Project due date: ##/##/##
// This program computes an employee's wages for the week
// If an employee works more than 40 hours they get 1.5 times
// their normal pay rate for all hours over 40.
//******************************************************************
// Put all preprocessor directives here
// The following are the necessary header files
#include <iostream> // header file for standard input output
// add modification #1 here
using namespace std;
/* This function calculates the pay in one of two ways */
/* depending on the hours worked */
void CalcPay( float, float, float& );
// Global constant declarations
const float MAX_HOURS = 40.0; // Maximum normal work hours
const float OVERTIME = 1.5; // Overtime pay rate factor
int main()
{
float payRate; // Employee's pay rate
float hours; // Hours worked
float wages; // Wages earned based on pay rate and hours worked.
// add modification #2 here
int empNum; // Employee ID number
// prompt for and read in the information for an employee
// information read is the employee number, their pay rate
// and the number of hours they have worked for the week.
cout << "Enter the employee number: ";
cin >> empNum;
cout << "Enter pay rate: ";
cin >> payRate;
cout << "Enter hours worked: ";
cin >> hours;
CalcPay(payRate, hours, wages); // call the function that Compute wages
// output the employee information and the results
// note how the output statement is broken up into multiple lines so that
// the cout statement is not too long.
// add modifications #3 here. This modification
// adds an if statement to calculate regular and overtime pay
// Modification #4 occurs here
// This modification changes the cout statement as indicated in
// the project handout
cout << "Employee: " << empNum << endl
<< "Pay rate: " << payRate << endl
<< "Hours: " << hours << endl
<< "Wages: $" << wages << endl;
return 0; // Indicate successful
} // completion of the program
//******************************************************************
//******************************************************************
// All function definitions are placed below main
//******************************************************************
//******************************************************************
void CalcPay( /* in */ float payRate, // Employee's pay rate
/* in */ float hours, // Hours worked
/* out */ float& wages ) // Wages earned
// CalcPay computes wages from the employee's pay rate
// and the hours worked, taking overtime into account
{
if (hours > MAX_HOURS) // Is there overtime?
wages = (MAX_HOURS * payRate) + // Yes
(hours - MAX_HOURS) * payRate * OVERTIME;
else
wages = hours * payRate; // No
}
| 41
| 83
| 0.533749
|
jaibae21
|
3c85d79c77277da0d6a478b6e02766ddbdaacd54
| 3,289
|
cpp
|
C++
|
ext/ruby_mapnik/_mapnik_symbolizer.rb.cpp
|
gravitystorm/Ruby-Mapnik
|
6e878ca914116ffc3f897cdb3bc94cd0b3c15281
|
[
"MIT"
] | 21
|
2015-02-04T17:22:57.000Z
|
2021-12-30T22:08:47.000Z
|
ext/ruby_mapnik/_mapnik_symbolizer.rb.cpp
|
gravitystorm/Ruby-Mapnik
|
6e878ca914116ffc3f897cdb3bc94cd0b3c15281
|
[
"MIT"
] | 20
|
2015-04-14T16:43:53.000Z
|
2019-10-01T16:18:50.000Z
|
ext/ruby_mapnik/_mapnik_symbolizer.rb.cpp
|
gravitystorm/Ruby-Mapnik
|
6e878ca914116ffc3f897cdb3bc94cd0b3c15281
|
[
"MIT"
] | 3
|
2015-05-27T11:27:50.000Z
|
2020-09-09T09:36:24.000Z
|
/*****************************************************************************
Copyright (C) 2011 Elliot Laster
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 "_mapnik_symbolizer.rb.h"
// Rice
#include <rice/Data_Type.hpp>
#include <rice/Constructor.hpp>
#include <rice/Class.hpp>
#include <rice/Enum.hpp>
// Mapnik
#include <mapnik/rule.hpp>
namespace {
// TODO: This is just terrible...
mapnik::symbolizer from_subtype(Rice::Object obj){
mapnik::symbolizer out;
std::string class_name = obj.class_of().to_s().str();
if(class_name == "Mapnik::PolygonSymbolizer") {
out = mapnik::symbolizer(from_ruby<mapnik::polygon_symbolizer>(obj));
} else if(class_name == "Mapnik::LineSymbolizer") {
out = mapnik::symbolizer(from_ruby<mapnik::line_symbolizer>(obj));
} else if(class_name == "Mapnik::TextSymbolizer"){
out = mapnik::symbolizer(from_ruby<mapnik::text_symbolizer>(obj));
} else if(class_name == "Mapnik::LinePatternSymbolizer"){
out = mapnik::symbolizer(from_ruby<mapnik::line_pattern_symbolizer>(obj));
} else if(class_name == "Mapnik::MarkersSymbolizer"){
out = mapnik::symbolizer(from_ruby<mapnik::markers_symbolizer>(obj));
} else if(class_name == "Mapnik::PointSymbolizer") {
out = mapnik::symbolizer(from_ruby<mapnik::point_symbolizer>(obj));
} else if(class_name == "Mapnik::PolygonPatternSymbolizer"){
out = mapnik::symbolizer(from_ruby<mapnik::polygon_pattern_symbolizer>(obj));
} else if(class_name == "Mapnik::RasterSymbolizer"){
out = mapnik::symbolizer(from_ruby<mapnik::raster_symbolizer>(obj));
} else if(class_name == "Mapnik::ShieldSymbolizer"){
out = mapnik::symbolizer(from_ruby<mapnik::shield_symbolizer>(obj));
}
return out;
}
}
void register_symbolizer(Rice::Module rb_mapnik){
/*
@@Module_var rb_mapnik = Mapnik
*/
Rice::Data_Type< mapnik::symbolizer > rb_csymbolizer = Rice::define_class_under< mapnik::symbolizer >(rb_mapnik, "Symbolizer");
/*
* Document-method: from_subtype
* call-seq:
* from_subtype(symbolizer)
* @return [Mapnik::Symbolizer]
*/
rb_csymbolizer.define_singleton_method("from_subtype", &from_subtype, Rice::Arg("obj"));
}
| 43.853333
| 129
| 0.697172
|
gravitystorm
|
3c8813b77a323462c1c77cf469e7e022beab5f4a
| 1,433
|
cpp
|
C++
|
startalk_ui/QuitOnCloseNotice.cpp
|
xuepingiw/open_source_startalk
|
44d962b04039f5660ec47a10313876a0754d3e72
|
[
"MIT"
] | 34
|
2019-03-18T08:09:24.000Z
|
2022-03-15T02:03:25.000Z
|
startalk_ui/QuitOnCloseNotice.cpp
|
venliong/open_source_startalk
|
51fda091a932a8adea626c312692836555753a9a
|
[
"MIT"
] | 5
|
2019-05-29T09:32:05.000Z
|
2019-08-29T03:01:33.000Z
|
startalk_ui/QuitOnCloseNotice.cpp
|
venliong/open_source_startalk
|
51fda091a932a8adea626c312692836555753a9a
|
[
"MIT"
] | 32
|
2019-03-15T09:43:22.000Z
|
2021-08-10T08:26:02.000Z
|
#include "QuitOnCloseNotice.h"
#include "CustomDefine.h"
#include "Session.h"
#include "SettingData.h"
QuitOnCloseNotice::QuitOnCloseNotice(QWidget *parent)
: LocalManDialog(parent)
{
ui.setupUi(this);
using namespace Qt;
auto remove = WindowTitleHint;
auto add = FramelessWindowHint | WindowMinMaxButtonsHint;
setAttribute(Qt::WA_AlwaysShowToolTips, true);
setAttribute(Qt::WA_TranslucentBackground, true);
overrideWindowFlags( (Qt::WindowFlags)((windowFlags() & ~remove) | add));
this->setSizeGripEnabled(false);
auto titlebar = ui.titblebar;
titlebar->setSizeable(false);
titlebar->setMinable(false);
titlebar->setWindowTitle(QStringLiteral("提示"));
setWindowTitle(QStringLiteral("提示"));
#ifdef QCHAT
setWindowIcon(QIcon(":/Images/Deal_chat.ico"));
#else
setWindowIcon(QIcon(":/Images/Deal.ico"));
#endif
auto closeOption = [this]{
bool bMin = ui.cbMinOnClose->isChecked();
int nCloseOption = bMin?Biz::QuitOnCloseOption::QOC_IGNORE:Biz::QOC_QUIT;
Biz::Session::getSettingConfig()->QuitOnClose(nCloseOption);
Biz::Session::saveSettingConfig();
};
connect(titlebar, &TitlebarWidget::sgCloseOnClicked, this, &LocalManDialog::onMin);
connect(titlebar, &TitlebarWidget::sgCloseOnClicked,closeOption);
connect(ui.cbMinOnClose,&QCheckBox::stateChanged,closeOption);
}
QuitOnCloseNotice::~QuitOnCloseNotice()
{
}
| 31.152174
| 87
| 0.718772
|
xuepingiw
|
3c8949e9b3a96b2201de99d1dc955aff51025ef6
| 9,213
|
cpp
|
C++
|
src/frontend/CameraParams.cpp
|
lefthandwriter/Kimera-VIO
|
641576fd86bdecbd663b4db3cb068f49502f3a2c
|
[
"BSD-2-Clause"
] | 1,024
|
2019-09-20T22:55:09.000Z
|
2022-03-30T13:00:14.000Z
|
src/frontend/CameraParams.cpp
|
lefthandwriter/Kimera-VIO
|
641576fd86bdecbd663b4db3cb068f49502f3a2c
|
[
"BSD-2-Clause"
] | 154
|
2019-09-23T13:10:33.000Z
|
2022-03-07T02:36:52.000Z
|
src/frontend/CameraParams.cpp
|
lefthandwriter/Kimera-VIO
|
641576fd86bdecbd663b4db3cb068f49502f3a2c
|
[
"BSD-2-Clause"
] | 314
|
2019-09-20T23:49:05.000Z
|
2022-03-30T06:21:38.000Z
|
/* ----------------------------------------------------------------------------
* Copyright 2017, Massachusetts Institute of Technology,
* Cambridge, MA 02139
* All Rights Reserved
* Authors: Luca Carlone, et al. (see THANKS for the full author list)
* See LICENSE for the license information
* -------------------------------------------------------------------------- */
/**
* @file CameraParams.cpp
* @brief Parameters describing a monocular camera.
* @author Antoni Rosinol
*/
#include "kimera-vio/frontend/CameraParams.h"
#include <fstream>
#include <iostream>
#include <gtsam/navigation/ImuBias.h>
namespace VIO {
bool CameraParams::parseYAML(const std::string& filepath) {
YamlParser yaml_parser(filepath);
yaml_parser.getYamlParam("camera_id", &camera_id_);
CHECK(!camera_id_.empty()) << "Camera id cannot be empty.";
VLOG(1) << "Parsing camera parameters for: " << camera_id_;
// Distortion parameters.
parseDistortion(yaml_parser);
// Camera resolution.
parseImgSize(yaml_parser, &image_size_);
// Camera frame rate.
parseFrameRate(yaml_parser, &frame_rate_);
// Camera pose wrt body.
parseBodyPoseCam(yaml_parser, &body_Pose_cam_);
// Intrinsics.
parseCameraIntrinsics(yaml_parser, &intrinsics_);
// Convert intrinsics to cv::Mat format.
convertIntrinsicsVectorToMatrix(intrinsics_, &K_);
// P_ = R_rectify_ * camera_matrix_;
return true;
}
void CameraParams::parseDistortion(const YamlParser& yaml_parser) {
std::string distortion_model;
yaml_parser.getYamlParam("distortion_model", &distortion_model);
yaml_parser.getYamlParam("camera_model", &camera_model_);
distortion_model_ = stringToDistortion(distortion_model, camera_model_);
CHECK(distortion_model_ == DistortionModel::RADTAN ||
distortion_model_ == DistortionModel::EQUIDISTANT)
<< "Unsupported distortion model. Expected: radtan or equidistant.";
yaml_parser.getYamlParam("distortion_coefficients", &distortion_coeff_);
convertDistortionVectorToMatrix(distortion_coeff_, &distortion_coeff_mat_);
}
const DistortionModel CameraParams::stringToDistortion(
const std::string& distortion_model,
const std::string& camera_model) {
std::string lower_case_distortion_model = distortion_model;
std::string lower_case_camera_model = camera_model;
std::transform(lower_case_distortion_model.begin(),
lower_case_distortion_model.end(),
lower_case_distortion_model.begin(),
::tolower);
std::transform(lower_case_camera_model.begin(),
lower_case_camera_model.end(),
lower_case_camera_model.begin(),
::tolower);
if (lower_case_camera_model == "pinhole") {
if (lower_case_camera_model == std::string("none")) {
return DistortionModel::NONE;
} else if ((lower_case_distortion_model == std::string("plumb_bob")) ||
(lower_case_distortion_model ==
std::string("radial-tangential")) ||
(lower_case_distortion_model == std::string("radtan"))) {
return DistortionModel::RADTAN;
} else if (lower_case_distortion_model == std::string("equidistant")) {
return DistortionModel::EQUIDISTANT;
} else {
LOG(FATAL)
<< "Unrecognized distortion model for pinhole camera. Valid "
"pinhole "
"distortion model options are 'none', 'radtan', 'equidistant'.";
}
} else {
LOG(FATAL)
<< "Unrecognized camera model. Valid camera models are 'pinhole'";
}
}
void CameraParams::convertDistortionVectorToMatrix(
const std::vector<double>& distortion_coeffs,
cv::Mat* distortion_coeffs_mat) {
CHECK_NOTNULL(distortion_coeffs_mat);
CHECK_GE(distortion_coeffs.size(), 4u);
*distortion_coeffs_mat = cv::Mat::zeros(1, distortion_coeffs.size(), CV_64F);
for (int k = 0; k < distortion_coeffs_mat->cols; k++) {
distortion_coeffs_mat->at<double>(0, k) = distortion_coeffs[k];
}
}
void CameraParams::parseImgSize(const YamlParser& yaml_parser,
cv::Size* image_size) {
CHECK_NOTNULL(image_size);
std::vector<int> resolution;
yaml_parser.getYamlParam("resolution", &resolution);
CHECK_EQ(resolution.size(), 2);
*image_size = cv::Size(resolution[0], resolution[1]);
}
void CameraParams::parseFrameRate(const YamlParser& yaml_parser,
double* frame_rate) {
CHECK_NOTNULL(frame_rate);
int rate = 0;
yaml_parser.getYamlParam("rate_hz", &rate);
CHECK_GT(rate, 0u);
*frame_rate = 1 / static_cast<double>(rate);
}
void CameraParams::parseBodyPoseCam(const YamlParser& yaml_parser,
gtsam::Pose3* body_Pose_cam) {
CHECK_NOTNULL(body_Pose_cam);
// int n_rows = 0;
// yaml_parser.getNestedYamlParam("T_BS", "rows", &n_rows);
// CHECK_EQ(n_rows, 4);
// int n_cols = 0;
// yaml_parser.getNestedYamlParam("T_BS", "cols", &n_cols);
// CHECK_EQ(n_cols, 4);
std::vector<double> vector_pose;
yaml_parser.getNestedYamlParam("T_BS", "data", &vector_pose);
*body_Pose_cam = UtilsOpenCV::poseVectorToGtsamPose3(vector_pose);
}
void CameraParams::parseCameraIntrinsics(const YamlParser& yaml_parser,
Intrinsics* intrinsics_) {
CHECK_NOTNULL(intrinsics_);
std::vector<double> intrinsics;
yaml_parser.getYamlParam("intrinsics", &intrinsics);
CHECK_EQ(intrinsics.size(), intrinsics_->size());
// Move elements from one to the other.
std::copy_n(std::make_move_iterator(intrinsics.begin()),
intrinsics_->size(),
intrinsics_->begin());
}
void CameraParams::convertIntrinsicsVectorToMatrix(const Intrinsics& intrinsics,
cv::Mat* camera_matrix) {
CHECK_NOTNULL(camera_matrix);
DCHECK_EQ(intrinsics.size(), 4);
*camera_matrix = cv::Mat::eye(3, 3, CV_64F);
camera_matrix->at<double>(0, 0) = intrinsics[0];
camera_matrix->at<double>(1, 1) = intrinsics[1];
camera_matrix->at<double>(0, 2) = intrinsics[2];
camera_matrix->at<double>(1, 2) = intrinsics[3];
}
// TODO(Toni): Check if equidistant distortion is supported as well in gtsam.
// TODO(Toni): rather remove this function as it is only used in tests for
// uncalibrating the keypoints.. Use instead opencv.
void CameraParams::createGtsamCalibration(const cv::Mat& distortion,
const Intrinsics& intrinsics,
gtsam::Cal3DS2* calibration) {
CHECK_NOTNULL(calibration);
CHECK_GE(intrinsics.size(), 4);
CHECK_GE(distortion.cols, 4);
CHECK_EQ(distortion.rows, 1);
*calibration = gtsam::Cal3DS2(intrinsics[0], // fx
intrinsics[1], // fy
0.0, // skew
intrinsics[2], // u0
intrinsics[3], // v0
distortion.at<double>(0, 0), // k1
distortion.at<double>(0, 1), // k2
distortion.at<double>(0, 2), // p1 (k3)
distortion.at<double>(0, 3)); // p2 (k4)
}
//! Display all params.
void CameraParams::print() const {
std::stringstream out;
PipelineParams::print(out,
"Camera ID ",
camera_id_,
"Intrinsics: \n- fx",
intrinsics_[0],
"- fy",
intrinsics_[1],
"- cu",
intrinsics_[2],
"- cv",
intrinsics_[3],
"frame_rate_: ",
frame_rate_,
"image_size_: \n - width",
image_size_.width,
"- height",
image_size_.height);
LOG(INFO) << out.str();
LOG(INFO) << "- body_Pose_cam_: " << body_Pose_cam_ << '\n'
<< "- K: " << K_ << '\n'
<< "- Distortion Model:" << to_underlying(distortion_model_) << '\n'
<< "- Distortion Coeff:" << distortion_coeff_mat_;
}
//! Assert equality up to a tolerance.
bool CameraParams::equals(const CameraParams& cam_par,
const double& tol) const {
bool areIntrinsicEqual = true;
for (size_t i = 0; i < intrinsics_.size(); i++) {
if (std::fabs(intrinsics_[i] - cam_par.intrinsics_[i]) > tol) {
areIntrinsicEqual = false;
break;
}
}
return camera_id_ == cam_par.camera_id_ && areIntrinsicEqual &&
body_Pose_cam_.equals(cam_par.body_Pose_cam_, tol) &&
(std::fabs(frame_rate_ - cam_par.frame_rate_) < tol) &&
(image_size_.width == cam_par.image_size_.width) &&
(image_size_.height == cam_par.image_size_.height) &&
UtilsOpenCV::compareCvMatsUpToTol(K_, cam_par.K_) &&
UtilsOpenCV::compareCvMatsUpToTol(distortion_coeff_mat_,
cam_par.distortion_coeff_mat_);
}
} // namespace VIO
| 38.873418
| 80
| 0.604798
|
lefthandwriter
|
3c92ab6b4300d500a8b9f8314224a28c3b0daa40
| 5,638
|
hpp
|
C++
|
src/include/def/defrCallBacks.hpp
|
jinwookjungs/lefdef_parser
|
32829274d247c418c080328484359a750dae4cec
|
[
"Apache-2.0"
] | 13
|
2019-04-21T08:09:32.000Z
|
2022-02-20T03:06:30.000Z
|
src/include/def/defrCallBacks.hpp
|
jinwookjungs/lefdef_parser
|
32829274d247c418c080328484359a750dae4cec
|
[
"Apache-2.0"
] | 3
|
2019-06-06T02:40:27.000Z
|
2021-12-01T04:56:20.000Z
|
src/include/def/defrCallBacks.hpp
|
jinwookjungs/lefdef_parser
|
32829274d247c418c080328484359a750dae4cec
|
[
"Apache-2.0"
] | 6
|
2016-10-21T08:39:35.000Z
|
2021-01-30T12:38:58.000Z
|
// *****************************************************************************
// *****************************************************************************
// Copyright 2013, Cadence Design Systems
//
// This file is part of the Cadence LEF/DEF Open Source
// Distribution, Product Version 5.8.
//
// 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.
//
// For updates, support, or to become part of the LEF/DEF Community,
// check www.openeda.org for details.
//
// $Author: dell $
// $Revision: #7 $
// $Date: 2015/01/27 $
// $State: $
// *****************************************************************************
// *****************************************************************************
#ifndef DEFRCALLBACKS_H
#define DEFRCALLBACKS_H 1
#include "defiKRDefs.hpp"
#include "defrReader.hpp"
#include "defrReader.hpp"
BEGIN_LEFDEF_PARSER_NAMESPACE
class defrCallbacks {
public:
defrCallbacks();
static void reset();
void SetUnusedCallbacks(defrVoidCbkFnType f);
defrStringCbkFnType DesignCbk;
defrStringCbkFnType TechnologyCbk;
defrVoidCbkFnType DesignEndCbk;
defrPropCbkFnType PropCbk;
defrVoidCbkFnType PropDefEndCbk;
defrVoidCbkFnType PropDefStartCbk;
defrStringCbkFnType ArrayNameCbk;
defrStringCbkFnType FloorPlanNameCbk;
defrDoubleCbkFnType UnitsCbk;
defrStringCbkFnType DividerCbk;
defrStringCbkFnType BusBitCbk;
defrSiteCbkFnType SiteCbk;
defrSiteCbkFnType CanplaceCbk;
defrSiteCbkFnType CannotOccupyCbk;
defrIntegerCbkFnType ComponentStartCbk;
defrVoidCbkFnType ComponentEndCbk;
defrComponentCbkFnType ComponentCbk;
defrComponentMaskShiftLayerCbkFnType ComponentMaskShiftLayerCbk;
defrIntegerCbkFnType NetStartCbk;
defrVoidCbkFnType NetEndCbk;
defrNetCbkFnType NetCbk;
defrStringCbkFnType NetNameCbk;
defrStringCbkFnType NetSubnetNameCbk;
defrStringCbkFnType NetNonDefaultRuleCbk;
defrNetCbkFnType NetPartialPathCbk;
defrPathCbkFnType PathCbk;
defrDoubleCbkFnType VersionCbk;
defrStringCbkFnType VersionStrCbk;
defrStringCbkFnType PinExtCbk;
defrStringCbkFnType ComponentExtCbk;
defrStringCbkFnType ViaExtCbk;
defrStringCbkFnType NetConnectionExtCbk;
defrStringCbkFnType NetExtCbk;
defrStringCbkFnType GroupExtCbk;
defrStringCbkFnType ScanChainExtCbk;
defrStringCbkFnType IoTimingsExtCbk;
defrStringCbkFnType PartitionsExtCbk;
defrStringCbkFnType HistoryCbk;
defrBoxCbkFnType DieAreaCbk;
defrPinCapCbkFnType PinCapCbk;
defrPinCbkFnType PinCbk;
defrIntegerCbkFnType StartPinsCbk;
defrVoidCbkFnType PinEndCbk;
defrIntegerCbkFnType DefaultCapCbk;
defrRowCbkFnType RowCbk;
defrTrackCbkFnType TrackCbk;
defrGcellGridCbkFnType GcellGridCbk;
defrIntegerCbkFnType ViaStartCbk;
defrVoidCbkFnType ViaEndCbk;
defrViaCbkFnType ViaCbk;
defrIntegerCbkFnType RegionStartCbk;
defrVoidCbkFnType RegionEndCbk;
defrRegionCbkFnType RegionCbk;
defrIntegerCbkFnType SNetStartCbk;
defrVoidCbkFnType SNetEndCbk;
defrNetCbkFnType SNetCbk;
defrNetCbkFnType SNetPartialPathCbk;
defrNetCbkFnType SNetWireCbk;
defrIntegerCbkFnType GroupsStartCbk;
defrVoidCbkFnType GroupsEndCbk;
defrStringCbkFnType GroupNameCbk;
defrStringCbkFnType GroupMemberCbk;
defrGroupCbkFnType GroupCbk;
defrIntegerCbkFnType AssertionsStartCbk;
defrVoidCbkFnType AssertionsEndCbk;
defrAssertionCbkFnType AssertionCbk;
defrIntegerCbkFnType ConstraintsStartCbk;
defrVoidCbkFnType ConstraintsEndCbk;
defrAssertionCbkFnType ConstraintCbk;
defrIntegerCbkFnType ScanchainsStartCbk;
defrVoidCbkFnType ScanchainsEndCbk;
defrScanchainCbkFnType ScanchainCbk;
defrIntegerCbkFnType IOTimingsStartCbk;
defrVoidCbkFnType IOTimingsEndCbk;
defrIOTimingCbkFnType IOTimingCbk;
defrIntegerCbkFnType FPCStartCbk;
defrVoidCbkFnType FPCEndCbk;
defrFPCCbkFnType FPCCbk;
defrIntegerCbkFnType TimingDisablesStartCbk;
defrVoidCbkFnType TimingDisablesEndCbk;
defrTimingDisableCbkFnType TimingDisableCbk;
defrIntegerCbkFnType PartitionsStartCbk;
defrVoidCbkFnType PartitionsEndCbk;
defrPartitionCbkFnType PartitionCbk;
defrIntegerCbkFnType PinPropStartCbk;
defrVoidCbkFnType PinPropEndCbk;
defrPinPropCbkFnType PinPropCbk;
defrIntegerCbkFnType CaseSensitiveCbk;
defrIntegerCbkFnType BlockageStartCbk;
defrVoidCbkFnType BlockageEndCbk;
defrBlockageCbkFnType BlockageCbk;
defrIntegerCbkFnType SlotStartCbk;
defrVoidCbkFnType SlotEndCbk;
defrSlotCbkFnType SlotCbk;
defrIntegerCbkFnType FillStartCbk;
defrVoidCbkFnType FillEndCbk;
defrFillCbkFnType FillCbk;
defrIntegerCbkFnType NonDefaultStartCbk;
defrVoidCbkFnType NonDefaultEndCbk;
defrNonDefaultCbkFnType NonDefaultCbk;
defrIntegerCbkFnType StylesStartCbk;
defrVoidCbkFnType StylesEndCbk;
defrStylesCbkFnType StylesCbk;
defrStringCbkFnType ExtensionCbk;
};
extern defrCallbacks *defCallbacks;
END_LEFDEF_PARSER_NAMESPACE
USE_LEFDEF_PARSER_NAMESPACE
#endif
| 34.802469
| 80
| 0.745654
|
jinwookjungs
|
3c963c48ed7a3b1a6d6f30426e3a72c66a7ccea8
| 15,048
|
cpp
|
C++
|
2018/Cpp/day16/part2.cpp
|
tymscar/Advent-Of-Code
|
cd7b96b0253191e236bd704b0d8b5540fb3e8ef6
|
[
"MIT"
] | 4
|
2019-12-08T08:20:53.000Z
|
2021-12-17T12:04:11.000Z
|
2018/Cpp/day16/part2.cpp
|
tymscar/AdventOfCode2018
|
9742ddb6bbbc917062baad87d6b6de75375f1ae8
|
[
"MIT"
] | null | null | null |
2018/Cpp/day16/part2.cpp
|
tymscar/AdventOfCode2018
|
9742ddb6bbbc917062baad87d6b6de75375f1ae8
|
[
"MIT"
] | 4
|
2020-12-11T22:10:24.000Z
|
2021-12-25T22:39:05.000Z
|
#include <iostream>
#include <algorithm>
#include <fstream>
#include <vector>
#include <unordered_map>
#include <string>
std::vector<int> eqrr (int inputOne, int inputTwo, int output, std::vector<int> registorState){
if(registorState[inputOne] == registorState[inputTwo])
registorState[output] = 1;
else
registorState[output] = 0;
return registorState;
}
std::vector<int> eqri (int inputOne, int inputTwo, int output, std::vector<int> registorState){
if(registorState[inputOne] == inputTwo)
registorState[output] = 1;
else
registorState[output] = 0;
return registorState;
}
std::vector<int> eqir(int inputOne, int inputTwo, int output, std::vector<int> registorState){
if(inputOne == registorState[inputTwo])
registorState[output] = 1;
else
registorState[output] = 0;
return registorState;
}
std::vector<int> gtrr (int inputOne, int inputTwo, int output, std::vector<int> registorState){
if(registorState[inputOne] > registorState[inputTwo])
registorState[output] = 1;
else
registorState[output] = 0;
return registorState;
}
std::vector<int> gtri (int inputOne, int inputTwo, int output, std::vector<int> registorState){
if(registorState[inputOne] > inputTwo)
registorState[output] = 1;
else
registorState[output] = 0;
return registorState;
}
std::vector<int> gtir(int inputOne, int inputTwo, int output, std::vector<int> registorState){
if(inputOne > registorState[inputTwo])
registorState[output] = 1;
else
registorState[output] = 0;
return registorState;
}
std::vector<int> seti(int inputOne, int inputTwo, int output, std::vector<int> registorState){
registorState[output] = inputOne;
return registorState;
}
std::vector<int> setr(int inputOne, int inputTwo, int output, std::vector<int> registorState){
registorState[output] = registorState[inputOne];
return registorState;
}
std::vector<int> bori(int inputOne, int inputTwo, int output, std::vector<int> registorState){
registorState[output] = registorState[inputOne] | inputTwo;
return registorState;
}
std::vector<int> borr(int inputOne, int inputTwo, int output, std::vector<int> registorState){
registorState[output] = registorState[inputOne] | registorState[inputTwo];
return registorState;
}
std::vector<int> bani(int inputOne, int inputTwo, int output, std::vector<int> registorState){
registorState[output] = registorState[inputOne] & inputTwo;
return registorState;
}
std::vector<int> banr(int inputOne, int inputTwo, int output, std::vector<int> registorState){
registorState[output] = registorState[inputOne] & registorState[inputTwo];
return registorState;
}
std::vector<int> mulr(int inputOne, int inputTwo, int output, std::vector<int> registorState){
registorState[output] = registorState[inputOne] * registorState[inputTwo];
return registorState;
}
std::vector<int> muli(int inputOne, int inputTwo, int output, std::vector<int> registorState){
registorState[output] = registorState[inputOne] * inputTwo;
return registorState;
}
std::vector<int> addr(int inputOne, int inputTwo, int output, std::vector<int> registorState){
registorState[output] = registorState[inputOne] + registorState[inputTwo];
return registorState;
}
std::vector<int> addi(int inputOne, int inputTwo, int output, std::vector<int> registorState){
registorState[output] = registorState[inputOne] + inputTwo;
return registorState;
}
void execute(int opcode, int A, int B, int C, std::unordered_map<int, std::string>& opcodeToNameOfFunction, std::vector<int>& registers){
if(opcodeToNameOfFunction[opcode] == "addr"){
registers = addr(A, B, C, registers);
}
if(opcodeToNameOfFunction[opcode] == "addi"){
registers = addi(A, B, C, registers);
}
if(opcodeToNameOfFunction[opcode] == "mulr"){
registers = mulr(A, B, C, registers);
}
if(opcodeToNameOfFunction[opcode] == "muli"){
registers = muli(A, B, C, registers);
}
if(opcodeToNameOfFunction[opcode] == "banr"){
registers = banr(A, B, C, registers);
}
if(opcodeToNameOfFunction[opcode] == "bani"){
registers = bani(A, B, C, registers);
}
if(opcodeToNameOfFunction[opcode] == "borr"){
registers = borr(A, B, C, registers);
}
if(opcodeToNameOfFunction[opcode] == "bori"){
registers = bori(A, B, C, registers);
}
if(opcodeToNameOfFunction[opcode] == "setr"){
registers = setr(A, B, C, registers);
}
if(opcodeToNameOfFunction[opcode] == "seti"){
registers = seti(A, B, C, registers);
}
if(opcodeToNameOfFunction[opcode] == "gtir"){
registers = gtir(A, B, C, registers);
}
if(opcodeToNameOfFunction[opcode] == "gtri"){
registers = gtri(A, B, C, registers);
}
if(opcodeToNameOfFunction[opcode] == "gtrr"){
registers = gtrr(A, B, C, registers);
}
if(opcodeToNameOfFunction[opcode] == "eqir"){
registers = eqir(A, B, C, registers);
}
if(opcodeToNameOfFunction[opcode] == "eqri"){
registers = eqri(A, B, C, registers);
}
if(opcodeToNameOfFunction[opcode] == "eqrr"){
registers = eqrr(A, B, C, registers);
}
}
int main(){
std::ifstream file;
file.open("part1in.txt");
std::string input;
std::unordered_map<int, std::vector<std::string> > opcodeNameList;
for(int i=0;i<16;i++){
opcodeNameList[i].push_back("addr");
opcodeNameList[i].push_back("addi");
opcodeNameList[i].push_back("mulr");
opcodeNameList[i].push_back("muli");
opcodeNameList[i].push_back("banr");
opcodeNameList[i].push_back("bani");
opcodeNameList[i].push_back("borr");
opcodeNameList[i].push_back("bori");
opcodeNameList[i].push_back("setr");
opcodeNameList[i].push_back("seti");
opcodeNameList[i].push_back("gtir");
opcodeNameList[i].push_back("gtri");
opcodeNameList[i].push_back("gtrr");
opcodeNameList[i].push_back("eqir");
opcodeNameList[i].push_back("eqri");
opcodeNameList[i].push_back("eqrr");
}
std::unordered_map<std::string, std::vector<int> >nameOpcodeList;
for(int i=0; i<16; i++){
nameOpcodeList["addr"].push_back(i);
nameOpcodeList["addi"].push_back(i);
nameOpcodeList["mulr"].push_back(i);
nameOpcodeList["muli"].push_back(i);
nameOpcodeList["banr"].push_back(i);
nameOpcodeList["bani"].push_back(i);
nameOpcodeList["borr"].push_back(i);
nameOpcodeList["bori"].push_back(i);
nameOpcodeList["setr"].push_back(i);
nameOpcodeList["seti"].push_back(i);
nameOpcodeList["gtir"].push_back(i);
nameOpcodeList["gtri"].push_back(i);
nameOpcodeList["gtrr"].push_back(i);
nameOpcodeList["eqir"].push_back(i);
nameOpcodeList["eqri"].push_back(i);
nameOpcodeList["eqrr"].push_back(i);
}
int opcodesLeft = 16;
std::unordered_map<std::string, int> opcodeId;
opcodeId["addr"] = -1;
opcodeId["addi"] = -1;
opcodeId["mulr"] = -1;
opcodeId["muli"] = -1;
opcodeId["banr"] = -1;
opcodeId["bani"] = -1;
opcodeId["borr"] = -1;
opcodeId["bori"] = -1;
opcodeId["setr"] = -1;
opcodeId["seti"] = -1;
opcodeId["gtir"] = -1;
opcodeId["gtri"] = -1;
opcodeId["gtrr"] = -1;
opcodeId["eqir"] = -1;
opcodeId["eqri"] = -1;
opcodeId["eqrr"] = -1;
while(file >> input){
std::vector<int> registorsOld;
file >> input;
registorsOld.push_back(input[1] - '0');
file >> input;
registorsOld.push_back(input[0] - '0');
file >> input;
registorsOld.push_back(input[0] - '0');
file >> input;
registorsOld.push_back(input[0] - '0');
int opcode, A, B, C;
file >> input;
opcode = std::stoi(input);
file >> input;
A = std::stoi(input);
file >> input;
B = std::stoi(input);
file >> input;
C = std::stoi(input);
file >> input;
std::vector<int> registorsNew;
file >> input;
registorsNew.push_back(input[1] - '0');
file >> input;
registorsNew.push_back(input[0] - '0');
file >> input;
registorsNew.push_back(input[0] - '0');
file >> input;
registorsNew.push_back(input[0] - '0');
if(addr(A, B, C, registorsOld) != registorsNew){
opcodeNameList[opcode].erase(std::remove(opcodeNameList[opcode].begin(), opcodeNameList[opcode].end(), "addr"), opcodeNameList[opcode].end());
nameOpcodeList["addr"].erase(std::remove(nameOpcodeList["addr"].begin(), nameOpcodeList["addr"].end(), opcode), nameOpcodeList["addr"].end());
}
if(addi(A, B, C, registorsOld) != registorsNew){
opcodeNameList[opcode].erase(std::remove(opcodeNameList[opcode].begin(), opcodeNameList[opcode].end(), "addi"), opcodeNameList[opcode].end());
nameOpcodeList["addi"].erase(std::remove(nameOpcodeList["addi"].begin(), nameOpcodeList["addi"].end(), opcode), nameOpcodeList["addi"].end());
}
if(mulr(A, B, C, registorsOld) != registorsNew){
opcodeNameList[opcode].erase(std::remove(opcodeNameList[opcode].begin(), opcodeNameList[opcode].end(), "mulr"), opcodeNameList[opcode].end());
nameOpcodeList["mulr"].erase(std::remove(nameOpcodeList["mulr"].begin(), nameOpcodeList["mulr"].end(), opcode), nameOpcodeList["mulr"].end());
}
if(muli(A, B, C, registorsOld) != registorsNew){
opcodeNameList[opcode].erase(std::remove(opcodeNameList[opcode].begin(), opcodeNameList[opcode].end(), "muli"), opcodeNameList[opcode].end());
nameOpcodeList["muli"].erase(std::remove(nameOpcodeList["muli"].begin(), nameOpcodeList["muli"].end(), opcode), nameOpcodeList["muli"].end());
}
if(banr(A, B, C, registorsOld) != registorsNew){
opcodeNameList[opcode].erase(std::remove(opcodeNameList[opcode].begin(), opcodeNameList[opcode].end(), "banr"), opcodeNameList[opcode].end());
nameOpcodeList["banr"].erase(std::remove(nameOpcodeList["banr"].begin(), nameOpcodeList["banr"].end(), opcode), nameOpcodeList["banr"].end());
}
if(bani(A, B, C, registorsOld) != registorsNew){
opcodeNameList[opcode].erase(std::remove(opcodeNameList[opcode].begin(), opcodeNameList[opcode].end(), "bani"), opcodeNameList[opcode].end());
nameOpcodeList["bani"].erase(std::remove(nameOpcodeList["bani"].begin(), nameOpcodeList["bani"].end(), opcode), nameOpcodeList["bani"].end());
}
if(borr(A, B, C, registorsOld) != registorsNew){
opcodeNameList[opcode].erase(std::remove(opcodeNameList[opcode].begin(), opcodeNameList[opcode].end(), "borr"), opcodeNameList[opcode].end());
nameOpcodeList["borr"].erase(std::remove(nameOpcodeList["borr"].begin(), nameOpcodeList["borr"].end(), opcode), nameOpcodeList["borr"].end());
}
if(bori(A, B, C, registorsOld) != registorsNew){
opcodeNameList[opcode].erase(std::remove(opcodeNameList[opcode].begin(), opcodeNameList[opcode].end(), "bori"), opcodeNameList[opcode].end());
nameOpcodeList["bori"].erase(std::remove(nameOpcodeList["bori"].begin(), nameOpcodeList["bori"].end(), opcode), nameOpcodeList["bori"].end());
}
if(setr(A, B, C, registorsOld) != registorsNew){
opcodeNameList[opcode].erase(std::remove(opcodeNameList[opcode].begin(), opcodeNameList[opcode].end(), "setr"), opcodeNameList[opcode].end());
nameOpcodeList["setr"].erase(std::remove(nameOpcodeList["setr"].begin(), nameOpcodeList["setr"].end(), opcode), nameOpcodeList["setr"].end());
}
if(seti(A, B, C, registorsOld) != registorsNew){
opcodeNameList[opcode].erase(std::remove(opcodeNameList[opcode].begin(), opcodeNameList[opcode].end(), "seti"), opcodeNameList[opcode].end());
nameOpcodeList["seti"].erase(std::remove(nameOpcodeList["seti"].begin(), nameOpcodeList["seti"].end(), opcode), nameOpcodeList["seti"].end());
}
if(gtir(A, B, C, registorsOld) != registorsNew){
opcodeNameList[opcode].erase(std::remove(opcodeNameList[opcode].begin(), opcodeNameList[opcode].end(), "gtir"), opcodeNameList[opcode].end());
nameOpcodeList["gtir"].erase(std::remove(nameOpcodeList["gtir"].begin(), nameOpcodeList["gtir"].end(), opcode), nameOpcodeList["gtir"].end());
}
if(gtri(A, B, C, registorsOld) != registorsNew){
opcodeNameList[opcode].erase(std::remove(opcodeNameList[opcode].begin(), opcodeNameList[opcode].end(), "gtri"), opcodeNameList[opcode].end());
nameOpcodeList["gtri"].erase(std::remove(nameOpcodeList["gtri"].begin(), nameOpcodeList["gtri"].end(), opcode), nameOpcodeList["gtri"].end());
}
if(gtrr(A, B, C, registorsOld) != registorsNew){
opcodeNameList[opcode].erase(std::remove(opcodeNameList[opcode].begin(), opcodeNameList[opcode].end(), "gtrr"), opcodeNameList[opcode].end());
nameOpcodeList["gtrr"].erase(std::remove(nameOpcodeList["gtrr"].begin(), nameOpcodeList["gtrr"].end(), opcode), nameOpcodeList["gtrr"].end());
}
if(eqir(A, B, C, registorsOld) != registorsNew){
opcodeNameList[opcode].erase(std::remove(opcodeNameList[opcode].begin(), opcodeNameList[opcode].end(), "eqir"), opcodeNameList[opcode].end());
nameOpcodeList["eqir"].erase(std::remove(nameOpcodeList["eqir"].begin(), nameOpcodeList["eqir"].end(), opcode), nameOpcodeList["eqir"].end());
}
if(eqri(A, B, C, registorsOld) != registorsNew){
opcodeNameList[opcode].erase(std::remove(opcodeNameList[opcode].begin(), opcodeNameList[opcode].end(), "eqri"), opcodeNameList[opcode].end());
nameOpcodeList["eqri"].erase(std::remove(nameOpcodeList["eqri"].begin(), nameOpcodeList["eqri"].end(), opcode), nameOpcodeList["eqri"].end());
}
if(eqrr(A, B, C, registorsOld) != registorsNew){
opcodeNameList[opcode].erase(std::remove(opcodeNameList[opcode].begin(), opcodeNameList[opcode].end(), "eqrr"), opcodeNameList[opcode].end());
nameOpcodeList["eqrr"].erase(std::remove(nameOpcodeList["eqrr"].begin(), nameOpcodeList["eqrr"].end(), opcode), nameOpcodeList["eqrr"].end());
}
}
while(opcodesLeft > -10){
for(int i=0;i<16;i++){
if(opcodeNameList[i].size() == 1){
opcodeId[opcodeNameList[i][0]] = i;
std::string opToRem = opcodeNameList[i][0];
for(int j=0; j<16; j++){
opcodeNameList[j].erase(std::remove(opcodeNameList[j].begin(), opcodeNameList[j].end(), opToRem), opcodeNameList[j].end());
}
for(auto f: nameOpcodeList){
f.second.erase(std::remove(f.second.begin(), f.second.end(), i), f.second.end());
}
opcodesLeft--;
}
}
for(auto f: nameOpcodeList){
if(f.second.size() == 1){
opcodeId[f.first] = f.second[0];
int insToRem = f.second[0];
for(int i=0; i<16; i++){
//daca gaseste
opcodeNameList[i].erase(std::remove(opcodeNameList[i].begin(), opcodeNameList[i].end(), f.first), opcodeNameList[i].end());
}
for(auto g: nameOpcodeList){
//daca gaseste
g.second.erase(std::remove(g.second.begin(), g.second.end(), insToRem), g.second.end());
}
opcodesLeft--;
}
}
}
std::unordered_map<int, std::string> opcodeToNameOfFunction;
for(int i=0; i<16; i++){
opcodeToNameOfFunction[i] = " ";
}
for(auto o: opcodeId){
opcodeToNameOfFunction[o.second] = o.first;
}
std::ifstream fileTwo;
fileTwo.open("part2in.txt");
std::string inputPart2;
std::vector<int> part2regs;
part2regs.push_back(0);
part2regs.push_back(0);
part2regs.push_back(0);
part2regs.push_back(0);
while(fileTwo >> inputPart2){
int opcode = std::stoi(inputPart2);
fileTwo >> inputPart2;
int A = std::stoi(inputPart2);
fileTwo >> inputPart2;
int B = std::stoi(inputPart2);
fileTwo >> inputPart2;
int C = std::stoi(inputPart2);
execute(opcode, A, B, C, opcodeToNameOfFunction, part2regs);
}
std::cout << part2regs[0] << std::endl;
}
| 37.064039
| 145
| 0.692517
|
tymscar
|
3ca577b50d33370110df1c57a236191a92213102
| 457
|
hpp
|
C++
|
include/commonpp/metric/reservoir/types.hpp
|
deco016/commonpp
|
ad03dcb6f7dc67359d898016c37a848c855c515b
|
[
"BSD-2-Clause"
] | 32
|
2015-09-17T20:55:58.000Z
|
2022-01-24T12:00:39.000Z
|
include/commonpp/metric/reservoir/types.hpp
|
deco016/commonpp
|
ad03dcb6f7dc67359d898016c37a848c855c515b
|
[
"BSD-2-Clause"
] | 7
|
2015-11-17T21:06:36.000Z
|
2018-01-30T09:45:15.000Z
|
include/commonpp/metric/reservoir/types.hpp
|
deco016/commonpp
|
ad03dcb6f7dc67359d898016c37a848c855c515b
|
[
"BSD-2-Clause"
] | 11
|
2015-09-18T09:11:39.000Z
|
2019-10-06T14:53:22.000Z
|
/*
* File: include/commonpp/metric/reservoir/types.hpp
* Part of commonpp.
*
* Distributed under the 2-clause BSD licence (See LICENCE.TXT file at the
* project root).
*
* Copyright (c) 2015 Thomas Sanchez. All rights reserved.
*
*/
#pragma once
namespace commonpp
{
namespace metric
{
namespace reservoir
{
struct WeightedReservoirTag
{
};
struct SimpleReservoirTag
{
};
} // namespace reservoir
} // namespace metric
} // namespace commonpp
| 14.741935
| 74
| 0.719912
|
deco016
|
3ca5ebca20592b48d04d484d09bf44e10da34824
| 8,325
|
cpp
|
C++
|
soccer/planning/tests/TrajectoryTest.cpp
|
kasohrab/robocup-software
|
73c92878baf960844b5a4b34c72804093f1ea459
|
[
"Apache-2.0"
] | null | null | null |
soccer/planning/tests/TrajectoryTest.cpp
|
kasohrab/robocup-software
|
73c92878baf960844b5a4b34c72804093f1ea459
|
[
"Apache-2.0"
] | null | null | null |
soccer/planning/tests/TrajectoryTest.cpp
|
kasohrab/robocup-software
|
73c92878baf960844b5a4b34c72804093f1ea459
|
[
"Apache-2.0"
] | null | null | null |
#include <gtest/gtest.h>
#include <rrt/planning/Path.hpp>
#include "TestingUtils.hpp"
#include "math.h"
#include "planning/Instant.hpp"
#include "planning/Trajectory.hpp"
#include "planning/planner/PathTargetPlanner.hpp"
#include "planning/primitives/PathSmoothing.hpp"
#include "planning/primitives/RRTUtil.hpp"
#include "planning/primitives/VelocityProfiling.hpp"
using namespace Planning;
using namespace Geometry2d;
using namespace Planning::TestingUtils;
TEST(Trajectory, Interpolation) {
// Test the basics of the Trajectory class, including interpolation, instant
// addition/insertion, and duration calculations.
RJ::Time start = RJ::now();
RobotInstant start_instant =
RobotInstant(Pose(0, 0, 0), Twist(1, 0, 0), start);
RobotInstant mid_instant =
RobotInstant(Pose(1, 1, 3), Twist(1, 0, 0), start + 1s);
RobotInstant end_instant =
RobotInstant(Pose(2, 0, 6), Twist(1, 0, 0), start + 1500ms);
Trajectory trajectory;
trajectory.AppendInstant(start_instant);
trajectory.AppendInstant(mid_instant);
ASSERT_EQ(*trajectory.evaluate(start), start_instant);
ASSERT_EQ(*trajectory.evaluate(trajectory.end_time()), mid_instant);
EXPECT_FALSE(
trajectory.evaluate(trajectory.begin_time() - RJ::Seconds(1e-3s)));
EXPECT_FALSE(
trajectory.evaluate(trajectory.end_time() + RJ::Seconds(1e-3s)));
EXPECT_FALSE(Trajectory{{}}.evaluate(RJ::Seconds(0s)));
EXPECT_FALSE(Trajectory{{}}.evaluate(start));
Twist mid_twist;
{
RobotInstant instant = *trajectory.evaluate(start + 500ms);
EXPECT_NEAR(instant.position().x(), 0.5, 1e-6);
EXPECT_NEAR(instant.position().y(), 0.5, 1e-6);
EXPECT_NEAR(instant.pose.heading(), 1.5, 1e-6);
mid_twist = instant.velocity;
}
// Make sure we use the right segment.
trajectory.AppendInstant(end_instant);
{
RobotInstant instant = *trajectory.evaluate(start + 1250ms);
EXPECT_NEAR(instant.position().x(), 1.5, 1e-6);
EXPECT_NEAR(instant.position().y(), 0.5, 1e-6);
EXPECT_NEAR(instant.pose.heading(), 4.5, 1e-6);
// Twist should be the same as halfway through the other segment, but
// rescaled because this segment only lasts 500ms.
EXPECT_NEAR(-mid_twist.linear().y() * 2, instant.velocity.linear().y(),
1e-6);
EXPECT_NEAR(mid_twist.angular() * 2, instant.velocity.angular(), 1e-6);
}
EXPECT_EQ(*trajectory.evaluate(trajectory.end_time()), end_instant);
EXPECT_TRUE(trajectory.CheckTime(start + 500ms));
EXPECT_FALSE(trajectory.CheckTime(start - 500ms));
EXPECT_FALSE(trajectory.CheckTime(start + 2500ms));
EXPECT_TRUE(trajectory.CheckSeconds(500ms));
EXPECT_FALSE(trajectory.CheckSeconds(-500ms));
EXPECT_FALSE(trajectory.CheckSeconds(2500ms));
EXPECT_EQ(trajectory.duration(),
RJ::Seconds(end_instant.stamp - start_instant.stamp));
}
TEST(Trajectory, TrajectoryCursor) {
std::vector<RobotInstant> instants;
RobotInstant a{Pose{{1, 1}, 1}, Twist{}, RJ::Time(1s)};
RobotInstant b{Pose{{2, 2}, 2}, Twist{}, RJ::Time(2s)};
RobotInstant c{Pose{{5, 5}, 5}, Twist{}, RJ::Time(5s)};
instants.push_back(a);
instants.push_back(b);
instants.push_back(c);
Trajectory traj{std::move(instants)};
auto cursor = traj.cursor_begin();
ASSERT_TRUE(cursor.has_value());
EXPECT_TRUE(RobotInstant::nearly_equals(cursor.value(), a));
cursor.next_knot();
ASSERT_TRUE(cursor.has_value());
EXPECT_TRUE(RobotInstant::nearly_equals(cursor.value(), b));
cursor.advance(3s);
ASSERT_TRUE(cursor.has_value());
EXPECT_TRUE(RobotInstant::nearly_equals(cursor.value(), c));
cursor.seek(c.stamp);
ASSERT_TRUE(cursor.has_value());
EXPECT_TRUE(RobotInstant::nearly_equals(cursor.value(), c));
cursor.seek(b.stamp);
ASSERT_TRUE(cursor.has_value());
EXPECT_TRUE(RobotInstant::nearly_equals(cursor.value(), b));
cursor.seek(a.stamp);
ASSERT_TRUE(cursor.has_value());
EXPECT_TRUE(RobotInstant::nearly_equals(cursor.value(), a));
// Make sure we can advance multiple steps forwards.
cursor.advance(4s);
ASSERT_TRUE(cursor.has_value());
EXPECT_TRUE(RobotInstant::nearly_equals(cursor.value(), c));
cursor.seek(a.stamp);
ASSERT_TRUE(cursor.has_value());
EXPECT_TRUE(RobotInstant::nearly_equals(cursor.value(), a));
cursor.advance(0.5s);
cursor.advance(0.5s);
ASSERT_TRUE(cursor.has_value());
EXPECT_TRUE(RobotInstant::nearly_equals(cursor.value(), b));
cursor.advance(0.5s);
cursor.advance(1.5s);
cursor.advance(1.0s);
ASSERT_TRUE(cursor.has_value());
EXPECT_TRUE(RobotInstant::nearly_equals(cursor.value(), c));
cursor.advance(0.1s);
EXPECT_FALSE(cursor.has_value());
}
TEST(Trajectory, BezierPath) {
std::vector<Point> points = {Point(0, 0), Point(1, 0.5), Point(1.5, 1),
Point(2, 2)};
Point vi(1, 0);
Point vf(0, 1);
MotionConstraints constraints;
constraints.maxSpeed = 3.0;
constraints.maxAcceleration = 3.0;
Planning::BezierPath path(points, vi, vf, constraints);
for (int i = 0; i < 4; i++) {
Point p;
Point v;
double k = 0;
path.Evaluate(i / 3.0, &p, &v, &k);
std::cout << p << ", " << v << std::endl;
EXPECT_NEAR((p - points[i]).mag(), 0, 1e-6);
if (i == 0) {
EXPECT_NEAR(v.angleBetween(vi), 0, 1e-3);
}
if (i == 3) {
EXPECT_NEAR(v.angleBetween(vf), 0, 1e-3);
}
}
}
TEST(Trajectory, SubTrajectory) {
std::vector<RobotInstant> instants;
RobotInstant a{Pose{{0, 0}, 0}, Twist{{1, 0}, 0}, RJ::Time(0s)};
RobotInstant b{Pose{{1, 1}, 0}, Twist{{2, 0}, 1}, RJ::Time(2s)};
RobotInstant c{Pose{{2, 0}, 0}, Twist{{1, 0}, 1}, RJ::Time(4s)};
instants.push_back(a);
instants.push_back(b);
instants.push_back(c);
Trajectory traj{std::move(instants)};
{
RJ::Time t0{1s};
RJ::Time t1{3s};
RobotInstant ab = traj.evaluate(t0).value();
RobotInstant bc = traj.evaluate(t1).value();
Trajectory sub = traj.subTrajectory(t0, t1);
EXPECT_TRUE(Trajectory::nearly_equal(sub, Trajectory{{ab, b, bc}}));
}
{
RJ::Time t0{3s};
RJ::Time t1{6s};
RobotInstant bc = traj.evaluate(t0).value();
Trajectory sub = traj.subTrajectory(t0, t1);
EXPECT_TRUE(Trajectory::nearly_equal(sub, Trajectory{{bc, c}}));
}
{
RJ::Time t0{4s};
RJ::Time t1{6s};
RobotInstant bc = traj.evaluate(t0).value();
Trajectory sub = traj.subTrajectory(t0, t1);
EXPECT_TRUE(Trajectory::nearly_equal(sub, Trajectory{{c}}));
}
}
TEST(Trajectory, SubTrajectoryEndpoints) {
RobotInstant a{Pose{{0, 0}, 0}, Twist{{1, 0}, 0}, RJ::Time(0s)};
RobotInstant b{Pose{{1, 1}, 0}, Twist{{2, 0}, 1}, RJ::Time(2s)};
RobotInstant c{Pose{{2, 0}, 0}, Twist{{1, 0}, 1}, RJ::Time(4s)};
Trajectory traj{{a, b, c}};
Trajectory sub = traj.subTrajectory(RJ::Time(0s), RJ::Time(4s));
EXPECT_TRUE(Trajectory::nearly_equal(sub, Trajectory{{a, b, c}}));
}
TEST(Trajectory, Combining) {
std::vector<RobotInstant> instants;
RobotInstant a{Pose{{0, 0}, 0}, Twist{{1, 0}, 0}, RJ::Time(0s)};
RobotInstant b{Pose{{1, 1}, 0}, Twist{{2, 0}, 1}, RJ::Time(2s)};
RobotInstant c{Pose{{2, 0}, 0}, Twist{{1, 0}, 1}, RJ::Time(4s)};
Trajectory traj_1{{a, b}};
Trajectory traj_2{{b, c}};
Trajectory combined(std::move(traj_1), traj_2);
EXPECT_TRUE(traj_1.empty())
<< "Should have moved out of the first trajectory";
EXPECT_TRUE(Trajectory::nearly_equal(combined, Trajectory{{a, b, c}}));
}
TEST(Trajectory, CombiningFail) {
std::vector<RobotInstant> instants;
RobotInstant a{Pose{{0, 0}, 0}, Twist{{1, 0}, 0}, RJ::Time(0s)};
RobotInstant b1{Pose{{1, 1}, 0}, Twist{{2, 0}, 1}, RJ::Time(2s)};
RobotInstant b2{Pose{{1, 0.5}, 0}, Twist{{2, 0}, 1}, RJ::Time(2s)};
RobotInstant c{Pose{{2, 0}, 0}, Twist{{1, 0}, 1}, RJ::Time(4s)};
Trajectory traj_1{{a, b1}};
Trajectory traj_2{{b2, c}};
EXPECT_THROW((Trajectory{std::move(traj_1), traj_2}),
std::invalid_argument);
}
| 35.126582
| 80
| 0.634715
|
kasohrab
|
3ca8d24dcd9171cf7ae5ca2e50cfd0a576b26358
| 2,100
|
cpp
|
C++
|
functions/+Image/borderFill.cpp
|
kkapsner/Matlab
|
98d42184f78b13a4bcb586fab48ad444028163d9
|
[
"MIT"
] | 1
|
2017-02-12T19:37:17.000Z
|
2017-02-12T19:37:17.000Z
|
functions/+Image/borderFill.cpp
|
kkapsner/Matlab
|
98d42184f78b13a4bcb586fab48ad444028163d9
|
[
"MIT"
] | 3
|
2015-01-07T20:12:07.000Z
|
2018-08-22T18:26:38.000Z
|
functions/+Image/borderFill.cpp
|
kkapsner/Matlab
|
98d42184f78b13a4bcb586fab48ad444028163d9
|
[
"MIT"
] | null | null | null |
#include "mex.h"
#include "borderFill/List.cpp"
#define idx(dx, dy) (x + dx) * h + y + dy
#define check(dx, dy){\
idx = idx(dx, dy);\
if ((image[idx] == image[idx0]) && !outImage[idx]){\
outImage[idx] = 1;\
pixelList.push(x + dx, y + dy);\
}\
}
/*
* borderFill.cpp
*/
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[] )
{
mxLogical *image, *outImage;
mwSize w, h;
borderFill::List pixelList;
if (nrhs != 1){
mexErrMsgIdAndTxt( "MATLAB:borderFill:wrongInputCount",
"One input (image) expected.");
}
/* The input must be a logical.*/
if(!mxIsLogical(prhs[0])){
mexErrMsgIdAndTxt( "MATLAB:borderFill:inputNotLogical",
"Input must be a logical.");
}
h = mxGetM(prhs[0]);
w = mxGetN(prhs[0]);
image = mxGetLogicals(prhs[0]);
/* Create matrix for the return argument. */
plhs[0] = mxCreateLogicalMatrix(h, w);
outImage = mxGetLogicals(plhs[0]);
/* first and last column */
for (int y = 0; y < h; y++){
outImage[y] = 1;
pixelList.push(0, y);
outImage[h * (w - 1) + y] = 1;
pixelList.push(w - 1, y);
}
/* first and last row */
for (int x = 1; x < w - 1; x++){
outImage[x * h] = 1;
pixelList.push(x, 0);
outImage[x * h + h - 1] = 1;
pixelList.push(x, h - 1);
}
while (pixelList.head){
int x = pixelList.head->x;
int y = pixelList.head->y;
int idx0 = idx(0, 0);
int idx;
pixelList.shift();
if (y > 0){
if (x > 0){
check(-1, -1);
}
check(0, -1);
if (x < w - 1){
check(1, -1);
}
}
if (x > 0){
check(-1, 0);
}
if (x < w - 1){
check(1, 0);
}
if (y < h - 1){
if (x > 0){
check(-1, 1);
}
check(0, 1);
if (x < w - 1){
check(1, 1);
}
}
}
}
| 22.580645
| 57
| 0.439048
|
kkapsner
|
3cb2fc5dc695c437874bf7f2b28c374e3ca55c1e
| 4,449
|
cpp
|
C++
|
src/executable/plot_shasta_alignments.cpp
|
rlorigro/overlap_analysis
|
8c8753aeba40c4ba82e0c0499fc8c2f134ba7145
|
[
"Apache-2.0"
] | null | null | null |
src/executable/plot_shasta_alignments.cpp
|
rlorigro/overlap_analysis
|
8c8753aeba40c4ba82e0c0499fc8c2f134ba7145
|
[
"Apache-2.0"
] | null | null | null |
src/executable/plot_shasta_alignments.cpp
|
rlorigro/overlap_analysis
|
8c8753aeba40c4ba82e0c0499fc8c2f134ba7145
|
[
"Apache-2.0"
] | null | null | null |
#include "SvgPlot.hpp"
#include "boost/program_options.hpp"
using boost::program_options::options_description;
using boost::program_options::variables_map;
using boost::program_options::bool_switch;
using boost::program_options::value;
#include <istream>
#include <iostream>
#include <functional>
using std::experimental::filesystem::directory_iterator;
using std::experimental::filesystem::create_directories;
using std::experimental::filesystem::absolute;
using std::experimental::filesystem::rename;
using std::experimental::filesystem::exists;
using std::experimental::filesystem::path;
using std::ifstream;
using std::function;
class AlignmentCoordinate {
public:
size_t coord_a;
size_t coord_b;
AlignmentCoordinate()=default;
};
void for_each_alignment_coordinate(path file_path, const function<void(const AlignmentCoordinate&)>& f){
ifstream file(file_path);
if (not (file.good() and file.is_open())){
throw runtime_error("ERROR: file could not be read: " + file_path.string());
}
string token;
AlignmentCoordinate alignment_coordinate;
uint64_t n_delimiters = 0;
uint64_t n_lines = 0;
char c;
// Skip first line
file.ignore(9999, '\n');
while (file.get(c)){
if (c == ',') {
if (n_delimiters == 3){
alignment_coordinate.coord_a = stoi(token);
}
else if (n_delimiters == 4){
alignment_coordinate.coord_b = stoi(token);
}
token.resize(0);
n_delimiters++;
}
else if (c == '\n'){
if (n_delimiters < 4 and n_lines > 0){
throw runtime_error(
"ERROR: file provided does not contain sufficient tab delimiters to be shasta alignment: " +
to_string(n_lines));
}
f(alignment_coordinate);
token.resize(0);
n_delimiters = 0;
n_lines++;
}
else {
token += c;
}
}
}
void plot_shasta_alignment(path input_dir, path output_dir){
if (exists(output_dir)){
throw runtime_error("ERROR: output directory already exists");
}
else{
create_directories(output_dir);
}
string type = "rect";
string color = "red";
for(auto& file_iter: directory_iterator(input_dir)){
const path& file_path = file_iter.path();
path output_path = output_dir / file_path.filename();
output_path.replace_extension(".svg");
cerr << file_path << '\n';
vector<AlignmentCoordinate> coordinates;
for_each_alignment_coordinate(file_path, [&](const AlignmentCoordinate& a){
coordinates.emplace_back(a);
});
size_t a_length = coordinates.back().coord_a;
size_t b_length = coordinates.back().coord_b;
size_t a_start = coordinates[0].coord_a;
size_t b_start = coordinates[0].coord_b;
cerr << a_length << ' ' << a_start << ' ' << b_length << ' ' << b_start << '\n';
SvgPlot plot(output_path, 1200, 1200, 0, a_length-a_start, 0, b_length-b_start);
size_t i = 0;
for (auto& item: coordinates){
plot.add_point(item.coord_a - a_start, item.coord_b - b_start, type, 20, color);
if (i < 100){
cerr << item.coord_a - a_start << ' ' << item.coord_b - b_start << ' ' << item.coord_a << ' ' << item.coord_b << '\n';
}
i++;
}
}
}
int main(int argc, char* argv[]){
path alignment_directory;
path output_directory;
options_description options("Arguments:");
options.add_options()
("input_dir",
value<path>(&alignment_directory)
->required(),
"Alignments TO BE EVALUATED: path of directory containing Shasta alignment details (one file per alignment)\n")
("output_dir",
value<path>(&output_directory)
->required(),
"Where to dump output SVG, CSV, PAF, etc")
;
variables_map vm;
store(parse_command_line(argc, argv, options), vm);
// If help was specified, or no arguments given, provide help
if (vm.count("help") || argc == 1) {
cerr << options << "\n";
return 0;
}
notify(vm);
plot_shasta_alignment(
alignment_directory,
output_directory);
return 0;
}
| 26.963636
| 134
| 0.595639
|
rlorigro
|
3cb4849b893113fc861a211801931323b02e049a
| 414
|
cpp
|
C++
|
RemoveTypeVaArgsT.cpp
|
DaemonSnake/MetaProgramming
|
6eed2293b926e4cc856263adf2ce1e00d04f362d
|
[
"MIT"
] | null | null | null |
RemoveTypeVaArgsT.cpp
|
DaemonSnake/MetaProgramming
|
6eed2293b926e4cc856263adf2ce1e00d04f362d
|
[
"MIT"
] | null | null | null |
RemoveTypeVaArgsT.cpp
|
DaemonSnake/MetaProgramming
|
6eed2293b926e4cc856263adf2ce1e00d04f362d
|
[
"MIT"
] | null | null | null |
//
// test.cpp for in /home/penava_b
//
// Made by penava_b
// Login <penava_b@epitech.net>
//
// Started on Wed Apr 20 23:55:00 2016 penava_b
// Last update Mon Jul 11 14:23:32 2016 penava_b
//
#include "Mpl.hpp"
using namespace MPL;
template <class ...Args> class TMP {};
Unit(RemoveType)
{
using OLD = TMP<float, int, double, int, void>;
print<OLD>();
print<RemoveInTemplateType<int, OLD>>();
}
| 18
| 49
| 0.657005
|
DaemonSnake
|
3cb6b170b6cb89fd04156d5a35c905f27952ebb8
| 2,593
|
cpp
|
C++
|
homescreen/src/statusbarserver.cpp
|
hungsonspkt/homescreen
|
57d13f02f6904a95fd14a3bcaf9ea80b4176f76d
|
[
"Apache-2.0"
] | null | null | null |
homescreen/src/statusbarserver.cpp
|
hungsonspkt/homescreen
|
57d13f02f6904a95fd14a3bcaf9ea80b4176f76d
|
[
"Apache-2.0"
] | null | null | null |
homescreen/src/statusbarserver.cpp
|
hungsonspkt/homescreen
|
57d13f02f6904a95fd14a3bcaf9ea80b4176f76d
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (C) 2016 The Qt Company Ltd.
* Copyright (C) 2016, 2017 Mentor Graphics Development (Deutschland) GmbH
*
* 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 "statusbarserver.h"
class StatusBarServer::Private
{
public:
Private(StatusBarServer *parent);
QString texts[SupportedCount];
QString icons[SupportedCount];
};
StatusBarServer::Private::Private(StatusBarServer *parent)
{
icons[0] = QStringLiteral("qrc:/images/Status/HMI_Status_Wifi_NoBars-01.png");
icons[1] = QStringLiteral("qrc:/images/Status/HMI_Status_Bluetooth_Inactive-01.png");
icons[2] = QStringLiteral("qrc:/images/Status/HMI_Status_Signal_NoBars-01.png");
}
StatusBarServer::StatusBarServer(QObject *parent)
: QObject(parent)
, d(new Private(this))
{
}
StatusBarServer::~StatusBarServer()
{
delete d;
}
QList<int> StatusBarServer::getAvailablePlaceholders() const
{
QList<int> ret;
for (int i = 0; i < SupportedCount; ++i) {
ret.append(i);
}
return ret;
}
QString StatusBarServer::getStatusIcon(int placeholderIndex) const
{
QString ret;
if (-1 < placeholderIndex && placeholderIndex < SupportedCount)
ret = d->icons[placeholderIndex];
return ret;
}
void StatusBarServer::setStatusIcon(int placeholderIndex, const QString &icon)
{
if (-1 < placeholderIndex && placeholderIndex < SupportedCount) {
if (d->icons[placeholderIndex] == icon) return;
d->icons[placeholderIndex] = icon;
emit statusIconChanged(placeholderIndex, icon);
}
}
QString StatusBarServer::getStatusText(int placeholderIndex) const
{
QString ret;
if (-1 < placeholderIndex && placeholderIndex < SupportedCount) {
ret = d->texts[placeholderIndex];
}
return ret;
}
void StatusBarServer::setStatusText(int placeholderIndex, const QString &text)
{
if (-1 < placeholderIndex && placeholderIndex < SupportedCount) {
if (d->texts[placeholderIndex] == text) return;
d->texts[placeholderIndex] = text;
emit statusTextChanged(placeholderIndex, text);
}
}
| 29.134831
| 89
| 0.70806
|
hungsonspkt
|
3cb71a962e4f3a3b6457b7da63990ad75ca6ab3d
| 5,490
|
cpp
|
C++
|
lib_ecm/components/cmp_text.cpp
|
OlavJDigranes/groupD
|
1d1fdd4ec0117162d777d0c020cbf4ae1718cf5f
|
[
"MIT"
] | null | null | null |
lib_ecm/components/cmp_text.cpp
|
OlavJDigranes/groupD
|
1d1fdd4ec0117162d777d0c020cbf4ae1718cf5f
|
[
"MIT"
] | null | null | null |
lib_ecm/components/cmp_text.cpp
|
OlavJDigranes/groupD
|
1d1fdd4ec0117162d777d0c020cbf4ae1718cf5f
|
[
"MIT"
] | null | null | null |
#include "cmp_text.h"
#include <system_renderer.h>
#include <system_resources.h>
using namespace sf;
//General text component
void TextComponent::update(double dt)
{
_text.setPosition(_parent->getPosition());
}
void TextComponent::render() { Renderer::queue(&_text); }
TextComponent::TextComponent(Entity* const p, const std::string& str)
: Component(p), _string(str) {
_text.setString(_string);
_font = Resources::get<sf::Font>("ShadowsIntoLight-Regular.ttf");
_text.setFont(*_font);
}
void TextComponent::SetText(const std::string& str) {
_string = str;
_text.setString(_string);
}
//ESC text component
void ESCTextComponent::update(double dt) {
_ESCtext.setPosition(_parent->getPosition());
}
void ESCTextComponent::render() {
Renderer::queue(&_ESCtext);
}
ESCTextComponent::ESCTextComponent(Entity* const p, const std::string& str) : Component(p), _ESCstring(str) {
_ESCtext.setString(_ESCstring);
_ESCfont = Resources::get<sf::Font>("ShadowsIntoLight-Regular.ttf");
_ESCtext.setFont(*_ESCfont);
_ESCtext.setCharacterSize(20);
}
void ESCTextComponent::SetText(const std::string& str) {
_ESCstring = str;
_ESCtext.setString(_ESCstring);
}
//Red Text Component
void RedTextComponent::update(double dt)
{
_text.setPosition(_parent->getPosition());
}
void RedTextComponent::render() { Renderer::queue(&_text); }
RedTextComponent::RedTextComponent(Entity* const p, const std::string& str)
: Component(p), _string(str) {
_text.setString(_string);
_text.setFillColor(Color::Red);
_text.setOutlineColor(Color::White);
_font = Resources::get<sf::Font>("ShadowsIntoLight-Regular.ttf");
_text.setFont(*_font);
_text.setCharacterSize(40);
_text.setStyle(Text::Bold);
}
void RedTextComponent::SetText(const std::string& str) {
_string = str;
_text.setString(_string);
}
//Green Text Component
void GreenTextComponent::update(double dt)
{
_text.setPosition(_parent->getPosition());
}
void GreenTextComponent::render() { Renderer::queue(&_text); }
GreenTextComponent::GreenTextComponent(Entity* const p, const std::string& str)
: Component(p), _string(str) {
_text.setString(_string);
_text.setFillColor(Color::Green);
_text.setOutlineColor(Color::White);
_font = Resources::get<sf::Font>("ShadowsIntoLight-Regular.ttf");
_text.setFont(*_font);
_text.setCharacterSize(40);
_text.setStyle(Text::Bold);
}
void GreenTextComponent::SetText(const std::string& str) {
_string = str;
_text.setString(_string);
}
//Blue Text Component
void BlueTextComponent::update(double dt)
{
_text.setPosition(_parent->getPosition());
}
void BlueTextComponent::render() { Renderer::queue(&_text); }
BlueTextComponent::BlueTextComponent(Entity* const p, const std::string& str)
: Component(p), _string(str) {
_text.setString(_string);
_text.setFillColor(Color{2,133,169,255});
_text.setOutlineColor(Color::White);
_font = Resources::get<sf::Font>("ShadowsIntoLight-Regular.ttf");
_text.setFont(*_font);
_text.setCharacterSize(40);
_text.setStyle(Text::Bold);
}
void BlueTextComponent::SetText(const std::string& str) {
_string = str;
_text.setString(_string);
}
//Yellow Text Component
void YellowTextComponent::update(double dt)
{
_text.setPosition(_parent->getPosition());
}
void YellowTextComponent::render() { Renderer::queue(&_text); }
YellowTextComponent::YellowTextComponent(Entity* const p, const std::string& str)
: Component(p), _string(str) {
_text.setString(_string);
_text.setFillColor(Color::Yellow);
_text.setOutlineColor(Color::White);
_font = Resources::get<sf::Font>("ShadowsIntoLight-Regular.ttf");
_text.setFont(*_font);
_text.setCharacterSize(40);
_text.setStyle(Text::Bold);
}
void YellowTextComponent::SetText(const std::string& str) {
_string = str;
_text.setString(_string);
}
//Magenta Text Component
void MagentaTextComponent::update(double dt)
{
_text.setPosition(_parent->getPosition());
}
void MagentaTextComponent::render() { Renderer::queue(&_text); }
MagentaTextComponent::MagentaTextComponent(Entity* const p, const std::string& str)
: Component(p), _string(str) {
_text.setString(_string);
_text.setFillColor(Color::Magenta);
_text.setOutlineColor(Color::White);
_font = Resources::get<sf::Font>("ShadowsIntoLight-Regular.ttf");
_text.setFont(*_font);
_text.setCharacterSize(40);
_text.setStyle(Text::Bold);
}
void MagentaTextComponent::SetText(const std::string& str) {
_string = str;
_text.setString(_string);
}
//Cyan Text Component
void CyanTextComponent::update(double dt)
{
_text.setPosition(_parent->getPosition());
}
void CyanTextComponent::render() { Renderer::queue(&_text); }
CyanTextComponent::CyanTextComponent(Entity* const p, const std::string& str)
: Component(p), _string(str) {
_text.setString(_string);
_text.setFillColor(Color::Cyan);
_text.setOutlineColor(Color::White);
_font = Resources::get<sf::Font>("ShadowsIntoLight-Regular.ttf");
_text.setFont(*_font);
_text.setCharacterSize(40);
_text.setStyle(Text::Bold);
}
void CyanTextComponent::SetText(const std::string& str) {
_string = str;
_text.setString(_string);
}
//Commented lines:
//_font = Resources::get<sf::Font>("RobotoMono-Regular.ttf");
//_font = Resources::get<sf::Font>("RobotoMono-Bold.ttf");
//_font = Resources::get<sf::Font>("arial.ttf");
| 28.010204
| 109
| 0.710383
|
OlavJDigranes
|
3cba9e6d5b3aa71faded3c8bbef606d2d265971b
| 3,039
|
c++
|
C++
|
extra/xftp/tests/test2.c++
|
maciek-27/Rgp
|
d28b5522e640e4c7b951f6861d97cbe52b0a35c9
|
[
"MIT"
] | null | null | null |
extra/xftp/tests/test2.c++
|
maciek-27/Rgp
|
d28b5522e640e4c7b951f6861d97cbe52b0a35c9
|
[
"MIT"
] | null | null | null |
extra/xftp/tests/test2.c++
|
maciek-27/Rgp
|
d28b5522e640e4c7b951f6861d97cbe52b0a35c9
|
[
"MIT"
] | null | null | null |
#include <libstreamcon/sctpconnection.h++>
#include <libstreamcon/databuffer.h++>
#include <libstreamcon/stream.h++>
#include <sys/time.h>
#include <libstreamcon/sctpclient.h++>
#include <libstreamcon/iofilters/tlsfilter.h++>
using namespace streamcon;
Mutex mutex;
#define KEYFILE "client.pem"
#define PASSWORD "password"
#define CA_LIST "root.pem"
#define CHUNK_SIZE 4096
unsigned long gettv()
{
struct timeval tvstart;
gettimeofday(&tvstart,0);
return tvstart.tv_sec;
}
bool bUseTls;
class DataThread : public StreamThread
{
public:
DataThread(Stream& _stream) : StreamThread(_stream) {;}
unsigned long size;
void Run() {
char buffer[CHUNK_SIZE];
if(bUseTls) {
TLSFilter* tls = new TLSFilter;
stream.PushFilter(tls);
tls->InitializeCTX(KEYFILE, PASSWORD, CA_LIST);
tls->StartTLS();
printf("TLS Started!\n");
}
printf("Thread started\n");
unsigned long t_start = gettv();
unsigned long t_last = t_start;
unsigned long old_size = 0;
float speed = 1.0;
while(1) {
size += stream.GetData(buffer, CHUNK_SIZE);
if(size - old_size > (unsigned long)speed && gettv() > t_last) {
speed=(size)/(gettv()-t_start);;
old_size = size;
t_last = gettv();
printf("%i Counter %luMB - %.2fMB/s\n", stream.GetId(),
size/1024/1024, speed/1024/1024);
}
}
}
};
class TestClient : public SCTPClient
{
public:
DataThread** threads;
int nthreads;
TestClient(int _nthreads) : nthreads(_nthreads){
threads = (DataThread**)malloc(sizeof(DataThread*)*nthreads);
}
~TestClient() {
for(int i = 0;i< nthreads;i++)
delete threads[i];
free(threads);
}
void OnConnect(Connection& conn) throw()
{
std::cout << "Client is connected!\n" << std::endl;
threads[0] = new DataThread(bUseTls?
conn.AllocStream(1):
conn.AllocStream(1));
for(int i = 1;i< nthreads;i++) {
threads[i] = new DataThread(bUseTls?
conn.AllocStream(i+1):
conn.AllocStream(i+1));
}
for(int i = 0;i<nthreads;i++) {
threads[i]->Start();
}
}
void OnDisconnect() throw()
{
std::cout << "Disconnected??" << std::endl;
for(int i = 0;i<5;i++) {
std::cout << i << " recieved " << threads[i]->size/1024
<< "KBs" << std::endl;
delete threads[i];
}
std::cout << "Client is disconnected!\n" << std::endl;
}
};
int main(int argc, char** argv)
{
int nstreams = 1;
if(argc>1) {
if(argv[1][0] == 's') {
bUseTls = true;
argv[1]++; // omit this char
}
if(argv[1][0] != 0) {
nstreams = atoi(argv[1]);
}
}
printf("Starting client with %i cuncurrent %sstreams.\n", nstreams, bUseTls?"TLS ":"");
TestClient client(nstreams);
while(1) {
try {
client.Connect(argc>2?argv[2]:"127.0.0.1", defaultPort, defaultStreams);
} catch(Connection::ConnectionSevered) {
std::cout << "Disconnected, retrying in 5 seconds." << std::endl;
sleep(5);
} catch(Connection::ConnectionRefused) {
std::cout << "Refused, retrying in 5 seconds." << std::endl;
sleep(5);
}
}
return 0;
}
| 22.021739
| 88
| 0.629483
|
maciek-27
|
3cbd6853c10d29c70ee6b9947316bb549c042402
| 411
|
cpp
|
C++
|
Alphabetic Patterns/alphabeticpattern56.cpp
|
Kajal13081/CPlusPlus-PatternHouse
|
257270f9b01e099f9c13f5bde39f07172f5474c0
|
[
"MIT"
] | 4
|
2021-09-21T03:43:26.000Z
|
2022-01-07T03:07:56.000Z
|
Alphabetic Patterns/alphabeticpattern56.cpp
|
Kajal13081/CPlusPlus-PatternHouse
|
257270f9b01e099f9c13f5bde39f07172f5474c0
|
[
"MIT"
] | 916
|
2021-09-01T15:40:24.000Z
|
2022-01-10T17:57:59.000Z
|
Alphabetic Patterns/alphabeticpattern56.cpp
|
Kajal13081/CPlusPlus-PatternHouse
|
257270f9b01e099f9c13f5bde39f07172f5474c0
|
[
"MIT"
] | 20
|
2021-09-30T18:13:58.000Z
|
2022-01-06T09:55:36.000Z
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
int cur_char=4; //(A+4 =E)
for (int i=0;i<5;i++)
{
int inc=0;
for (int j=i;j<i+5;j++)
{
inc=j;
if(inc>cur_char)
inc=inc-cur_char-1; //if char is > E , char is A
char a = 65+inc;
cout << a << " ";
}
cout << "\n";
}
}
| 21.631579
| 82
| 0.372263
|
Kajal13081
|
3cbd9c86363034b011acf78b8abdb64e698e2e43
| 3,665
|
cpp
|
C++
|
mogupro/game/src/Sound/cIntroLoopableBGM.cpp
|
desspert/mogupro
|
ac39f5ec3fb670cf5044ef501951270d7d92a748
|
[
"MIT"
] | null | null | null |
mogupro/game/src/Sound/cIntroLoopableBGM.cpp
|
desspert/mogupro
|
ac39f5ec3fb670cf5044ef501951270d7d92a748
|
[
"MIT"
] | null | null | null |
mogupro/game/src/Sound/cIntroLoopableBGM.cpp
|
desspert/mogupro
|
ac39f5ec3fb670cf5044ef501951270d7d92a748
|
[
"MIT"
] | null | null | null |
#include <Sound/cIntroLoopableBGM.h>
#include <cinder/app/App.h>
#include <Utility/cScheduler.h>
namespace Sound
{
cIntroLoopableBGM::cIntroLoopableBGM( )
{
alGenSources( 1, &source );
}
cIntroLoopableBGM::~cIntroLoopableBGM( )
{
if ( source != 0 )
{
stop( );
alDeleteSources( 1, &source );
}
if ( introId != 0 )
{
alDeleteBuffers( 1, &introId );
}
if ( mainId != 0 )
{
alDeleteBuffers( 1, &mainId );
}
}
void cIntroLoopableBGM::create( char const* const rawData, size_t rawDataByte, float loopBeginSecond, float loopEndSecond )
{
alGenBuffers( 1, &introId );
alBufferData
(
introId,
AL_FORMAT_STEREO16,
rawData,
calcOffset( loopBeginSecond ),
44100
);
alGenBuffers( 1, &mainId );
alBufferData
(
mainId,
AL_FORMAT_STEREO16,
rawData + calcOffset( loopBeginSecond ),
calcOffset( loopEndSecond ) - calcOffset( loopBeginSecond ),
44100
);
cinder::app::console( ) << "Sound: " << rawDataByte << std::endl;
cinder::app::console( ) << "Sound: " << calcOffset( loopBeginSecond ) << std::endl;
cinder::app::console( ) << "Sound: " << calcOffset( loopEndSecond ) << std::endl;
cinder::app::console( ) << "Sound: " << calcOffset( loopEndSecond ) - calcOffset( loopBeginSecond ) << std::endl;
this->loopBeginSecond = loopBeginSecond;
}
void cIntroLoopableBGM::play( ) const
{
alSourceQueueBuffers( source, 1, &introId );
alSourceQueueBuffers( source, 1, &mainId );
alSourcePlay( source );
time = 0.0F;
introDeleted = false;
}
void cIntroLoopableBGM::stop( ) const
{
alSourceStop( source );
}
void cIntroLoopableBGM::pause( ) const
{
alSourcePause( source );
}
float cIntroLoopableBGM::getPitch() const
{
ALfloat value = 0.0F;
alGetSourcef(source, AL_PITCH, &value);
return value;
}
void cIntroLoopableBGM::fadeout(float fadeSecond, float target)
{
auto decrement = (getGain() - target) / fadeSecond;
fadeHandle = Utility::cScheduler::getInstance()->applyLimitUpdate(fadeSecond, [this, decrement](float delta) { gain(getGain() - delta * decrement); }, [this] { stop(); });
}
void cIntroLoopableBGM::fadein(float fadeSecond, float target)
{
play();
auto increment = (target) / fadeSecond;
fadeHandle = Utility::cScheduler::getInstance()->applyLimitUpdate(fadeSecond, [this, increment](float delta) { gain(getGain() + delta * increment); });
}
void cIntroLoopableBGM::resume() const
{
alSourcePlay( source );
}
void cIntroLoopableBGM::gain( float const value ) const
{
alSourcef( source, AL_GAIN, value );
}
float cIntroLoopableBGM::getGain() const
{
ALfloat value = 0.0F;
alGetSourcef( source, AL_GAIN, &value );
return value;
}
void cIntroLoopableBGM::pitch( float const value ) const
{
alSourcef( source, AL_PITCH, value );
}
bool cIntroLoopableBGM::isPlaying( ) const
{
ALint state;
alGetSourcei( source, AL_SOURCE_STATE, &state );
return state == AL_PLAYING;
}
void cIntroLoopableBGM::update( float delta )
{
if ( !introDeleted )
{
if ( loopBeginSecond + 1.0F < time )
{
alSourceUnqueueBuffers( source, 1, &introId );
auto e = alGetError( );
if ( e == AL_INVALID_VALUE )
{
cinder::app::console( ) << "AL_INVALID_VALUE" << std::endl;
}
else if ( e == AL_INVALID_NAME )
{
cinder::app::console( ) << "AL_INVALID_NAME" << std::endl;
}
else if ( e == AL_INVALID_OPERATION )
{
cinder::app::console( ) << "AL_INVALID_OPERATION" << std::endl;
}
alSourcei( source, AL_LOOPING, AL_TRUE );
introDeleted = true;
}
}
if ( isPlaying( ) ) time += delta;
}
size_t cIntroLoopableBGM::calcOffset( float second )
{
size_t bit8_offset = second * 44100;
size_t byte16_offset = bit8_offset * 2;
size_t toStereo = 2;
return byte16_offset * toStereo;
}
}
| 25.10274
| 172
| 0.687312
|
desspert
|
3cbf4c7b482bbf9aad85eed5762b795f1b257b79
| 2,020
|
cpp
|
C++
|
src/ui/Windows/TBMStatic.cpp
|
rafaelx/pwsafe
|
173a5c16ae2f9071efa67f628d21c30d4486effd
|
[
"Artistic-2.0"
] | null | null | null |
src/ui/Windows/TBMStatic.cpp
|
rafaelx/pwsafe
|
173a5c16ae2f9071efa67f628d21c30d4486effd
|
[
"Artistic-2.0"
] | null | null | null |
src/ui/Windows/TBMStatic.cpp
|
rafaelx/pwsafe
|
173a5c16ae2f9071efa67f628d21c30d4486effd
|
[
"Artistic-2.0"
] | null | null | null |
/*
* Copyright (c) 2003-2019 Rony Shapiro <ronys@pwsafe.org>.
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/
// TBMStatic.cpp : implementation file
//
/*
* Transparent Bitmap Static control
*/
#include "stdafx.h"
#include "TBMStatic.h"
#ifdef _DEBUG
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif
void CTBMStatic::Init(const UINT nImageID)
{
// Save resource IDs (Static and required image)
m_nID = GetDlgCtrlID();
// Load bitmap
VERIFY(m_Bitmap.Attach(::LoadImage(
::AfxFindResourceHandle(MAKEINTRESOURCE(nImageID), RT_BITMAP),
MAKEINTRESOURCE(nImageID), IMAGE_BITMAP, 0, 0,
(LR_DEFAULTSIZE | LR_CREATEDIBSECTION | LR_SHARED))));
const COLORREF crCOLOR_3DFACE = GetSysColor(COLOR_3DFACE);
SetBitmapBackground(m_Bitmap, crCOLOR_3DFACE);
SetBitmap((HBITMAP)m_Bitmap);
}
BEGIN_MESSAGE_MAP(CTBMStatic, CStatic)
//{{AFX_MSG_MAP(CTBMStatic)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
void CTBMStatic::SetBitmapBackground(CBitmap &bm, const COLORREF newbkgrndColour)
{
// Get how many pixels in the bitmap
BITMAP bmInfo;
bm.GetBitmap(&bmInfo);
const UINT numPixels(bmInfo.bmHeight * bmInfo.bmWidth);
// get a pointer to the pixels
DIBSECTION ds;
VERIFY(bm.GetObject(sizeof(DIBSECTION), &ds) == sizeof(DIBSECTION));
RGBTRIPLE *pixels = reinterpret_cast<RGBTRIPLE*>(ds.dsBm.bmBits);
ASSERT(pixels != NULL);
const RGBTRIPLE newbkgrndColourRGB = {GetBValue(newbkgrndColour),
GetGValue(newbkgrndColour),
GetRValue(newbkgrndColour)};
for (UINT i = 0; i < numPixels; ++i) {
if (pixels[i].rgbtBlue == 192 &&
pixels[i].rgbtGreen == 192 &&
pixels[i].rgbtRed == 192) {
pixels[i] = newbkgrndColourRGB;
}
}
}
| 27.297297
| 81
| 0.676733
|
rafaelx
|
3cc475c5f1d5bdec62d26b69d397cbd2a528b9c2
| 76,727
|
cpp
|
C++
|
src/hpack.cpp
|
jonathonl/IPSuite
|
76dfd7913388851c6714645252b2caa3c5596dcc
|
[
"MIT"
] | 1
|
2016-03-01T15:23:13.000Z
|
2016-03-01T15:23:13.000Z
|
src/hpack.cpp
|
jonathonl/IPSuite
|
76dfd7913388851c6714645252b2caa3c5596dcc
|
[
"MIT"
] | null | null | null |
src/hpack.cpp
|
jonathonl/IPSuite
|
76dfd7913388851c6714645252b2caa3c5596dcc
|
[
"MIT"
] | null | null | null |
#include <cmath>
#include <assert.h>
#include <iostream>
#include "hpack.hpp"
namespace std
{
template <>
struct hash<std::pair<std::string,std::string>>
{
std::size_t operator()(const std::pair<std::string,std::string>& k) const
{
// Compute individual hash values for first,
// second and third and combine them using XOR
// and bit shifting:
return ((std::hash<std::string>()(k.first) ^ (std::hash<std::string>()(k.second) << 1)) >> 1);
}
};
}
namespace manifold
{
namespace hpack
{
//----------------------------------------------------------------//
const std::array<std::pair<std::string,std::string>, 61> static_table{{
/* 1 */ {":authority" , "" },
/* 2 */ {":method" , "GET" },
/* 3 */ {":method" , "POST" },
/* 4 */ {":path" , "/" },
/* 5 */ {":path" , "/index.html" },
/* 6 */ {":scheme" , "http" },
/* 7 */ {":scheme" , "https" },
/* 8 */ {":status" , "200" },
/* 9 */ {":status" , "204" },
/* 10 */ {":status" , "206" },
/* 11 */ {":status" , "304" },
/* 12 */ {":status" , "400" },
/* 13 */ {":status" , "404" },
/* 14 */ {":status" , "500" },
/* 15 */ {"accept-charset" , "" },
/* 16 */ {"accept-encoding" , "gzip, deflate"},
/* 17 */ {"accept-language" , "" },
/* 18 */ {"accept-ranges" , "" },
/* 19 */ {"accept" , "" },
/* 20 */ {"access-control-allow-origin" , "" },
/* 21 */ {"age" , "" },
/* 22 */ {"allow" , "" },
/* 23 */ {"authorization" , "" },
/* 24 */ {"cache-control" , "" },
/* 25 */ {"content-disposition" , "" },
/* 26 */ {"content-encoding" , "" },
/* 27 */ {"content-language" , "" },
/* 28 */ {"content-length" , "" },
/* 29 */ {"content-location" , "" },
/* 30 */ {"content-range" , "" },
/* 31 */ {"content-type" , "" },
/* 32 */ {"cookie" , "" },
/* 33 */ {"date" , "" },
/* 34 */ {"etag" , "" },
/* 35 */ {"expect" , "" },
/* 36 */ {"expires" , "" },
/* 37 */ {"from" , "" },
/* 38 */ {"host" , "" },
/* 39 */ {"if-match" , "" },
/* 40 */ {"if-modified-since" , "" },
/* 41 */ {"if-none-match" , "" },
/* 42 */ {"if-range" , "" },
/* 43 */ {"if-unmodified-since" , "" },
/* 44 */ {"last-modified" , "" },
/* 45 */ {"link" , "" },
/* 46 */ {"location" , "" },
/* 47 */ {"max-forwards" , "" },
/* 48 */ {"proxy-authenticate" , "" },
/* 49 */ {"proxy-authorization" , "" },
/* 50 */ {"range" , "" },
/* 51 */ {"referer" , "" },
/* 52 */ {"refresh" , "" },
/* 53 */ {"retry-after" , "" },
/* 54 */ {"server" , "" },
/* 55 */ {"set-cookie" , "" },
/* 56 */ {"strict-transport-security" , "" },
/* 57 */ {"transfer-encoding" , "" },
/* 58 */ {"user-agent" , "" },
/* 59 */ {"vary" , "" },
/* 60 */ {"via" , "" },
/* 61 */ {"www-authenticate" , "" }}};
//----------------------------------------------------------------//
//----------------------------------------------------------------//
const std::unordered_multimap<std::string, std::size_t> static_table_reverse_lookup_map{
{":authority" , 1 }, // ""
{":method" , 2 }, // "GET"
{":method" , 3 }, // "POST"
{":path" , 4 }, // "/"
{":path" , 5 }, // "/index.html"
{":scheme" , 6 }, // "http"
{":scheme" , 7 }, // "https"
{":status" , 8 }, // "200"
{":status" , 9 }, // "204"
{":status" , 10}, // "206"
{":status" , 11}, // "304"
{":status" , 12}, // "400"
{":status" , 13}, // "404"
{":status" , 14}, // "500"
{"accept-charset" , 15}, // ""
{"accept-encoding" , 16}, // "gzip, deflate"
{"accept-language" , 17}, // ""
{"accept-ranges" , 18}, // ""
{"accept" , 19}, // ""
{"access-control-allow-origin" , 20}, // ""
{"age" , 21}, // ""
{"allow" , 22}, // ""
{"authorization" , 23}, // ""
{"cache-control" , 24}, // ""
{"content-disposition" , 25}, // ""
{"content-encoding" , 26}, // ""
{"content-language" , 27}, // ""
{"content-length" , 28}, // ""
{"content-location" , 29}, // ""
{"content-range" , 30}, // ""
{"content-type" , 31}, // ""
{"cookie" , 32}, // ""
{"date" , 33}, // ""
{"etag" , 34}, // ""
{"expect" , 35}, // ""
{"expires" , 36}, // ""
{"from" , 37}, // ""
{"host" , 38}, // ""
{"if-match" , 39}, // ""
{"if-modified-since" , 40}, // ""
{"if-none-match" , 41}, // ""
{"if-range" , 42}, // ""
{"if-unmodified-since" , 43}, // ""
{"last-modified" , 44}, // ""
{"link" , 45}, // ""
{"location" , 46}, // ""
{"max-forwards" , 47}, // ""
{"proxy-authenticate" , 48}, // ""
{"proxy-authorization" , 49}, // ""
{"range" , 50}, // ""
{"referer" , 51}, // ""
{"refresh" , 52}, // ""
{"retry-after" , 53}, // ""
{"server" , 54}, // ""
{"set-cookie" , 55}, // ""
{"strict-transport-security" , 56}, // ""
{"transfer-encoding" , 57}, // ""
{"user-agent" , 58}, // ""
{"vary" , 59}, // ""
{"via" , 60}, // ""
{"www-authenticate" , 61}}; // ""
//----------------------------------------------------------------//
//----------------------------------------------------------------//
const std::map<huffman_code,char,huffman_code_cmp> huffman_code_tree{
/* ( 0) |11111111|11000 */ { { 0x1ff8 << (32 - 13), 13}, (char) 0 },
/* ( 1) |11111111|11111111|1011000 */ { { 0x7fffd8 << (32 - 23), 23}, (char) 1 },
/* ( 2) |11111111|11111111|11111110|0010 */ { { 0xfffffe2 << (32 - 28), 28}, (char) 2 },
/* ( 3) |11111111|11111111|11111110|0011 */ { { 0xfffffe3 << (32 - 28), 28}, (char) 3 },
/* ( 4) |11111111|11111111|11111110|0100 */ { { 0xfffffe4 << (32 - 28), 28}, (char) 4 },
/* ( 5) |11111111|11111111|11111110|0101 */ { { 0xfffffe5 << (32 - 28), 28}, (char) 5 },
/* ( 6) |11111111|11111111|11111110|0110 */ { { 0xfffffe6 << (32 - 28), 28}, (char) 6 },
/* ( 7) |11111111|11111111|11111110|0111 */ { { 0xfffffe7 << (32 - 28), 28}, (char) 7 },
/* ( 8) |11111111|11111111|11111110|1000 */ { { 0xfffffe8 << (32 - 28), 28}, (char) 8 },
/* ( 9) |11111111|11111111|11101010 */ { { 0xffffea << (32 - 24), 24}, (char) 9 },
/* ( 10) |11111111|11111111|11111111|111100 */ { { 0x3ffffffc << (32 - 30), 30}, (char) 10 },
/* ( 11) |11111111|11111111|11111110|1001 */ { { 0xfffffe9 << (32 - 28), 28}, (char) 11 },
/* ( 12) |11111111|11111111|11111110|1010 */ { { 0xfffffea << (32 - 28), 28}, (char) 12 },
/* ( 13) |11111111|11111111|11111111|111101 */ { { 0x3ffffffd << (32 - 30), 30}, (char) 13 },
/* ( 14) |11111111|11111111|11111110|1011 */ { { 0xfffffeb << (32 - 28), 28}, (char) 14 },
/* ( 15) |11111111|11111111|11111110|1100 */ { { 0xfffffec << (32 - 28), 28}, (char) 15 },
/* ( 16) |11111111|11111111|11111110|1101 */ { { 0xfffffed << (32 - 28), 28}, (char) 16 },
/* ( 17) |11111111|11111111|11111110|1110 */ { { 0xfffffee << (32 - 28), 28}, (char) 17 },
/* ( 18) |11111111|11111111|11111110|1111 */ { { 0xfffffef << (32 - 28), 28}, (char) 18 },
/* ( 19) |11111111|11111111|11111111|0000 */ { { 0xffffff0 << (32 - 28), 28}, (char) 19 },
/* ( 20) |11111111|11111111|11111111|0001 */ { { 0xffffff1 << (32 - 28), 28}, (char) 20 },
/* ( 21) |11111111|11111111|11111111|0010 */ { { 0xffffff2 << (32 - 28), 28}, (char) 21 },
/* ( 22) |11111111|11111111|11111111|111110 */ { { 0x3ffffffe << (32 - 30), 30}, (char) 22 },
/* ( 23) |11111111|11111111|11111111|0011 */ { { 0xffffff3 << (32 - 28), 28}, (char) 23 },
/* ( 24) |11111111|11111111|11111111|0100 */ { { 0xffffff4 << (32 - 28), 28}, (char) 24 },
/* ( 25) |11111111|11111111|11111111|0101 */ { { 0xffffff5 << (32 - 28), 28}, (char) 25 },
/* ( 26) |11111111|11111111|11111111|0110 */ { { 0xffffff6 << (32 - 28), 28}, (char) 26 },
/* ( 27) |11111111|11111111|11111111|0111 */ { { 0xffffff7 << (32 - 28), 28}, (char) 27 },
/* ( 28) |11111111|11111111|11111111|1000 */ { { 0xffffff8 << (32 - 28), 28}, (char) 28 },
/* ( 29) |11111111|11111111|11111111|1001 */ { { 0xffffff9 << (32 - 28), 28}, (char) 29 },
/* ( 30) |11111111|11111111|11111111|1010 */ { { 0xffffffa << (32 - 28), 28}, (char) 30 },
/* ( 31) |11111111|11111111|11111111|1011 */ { { 0xffffffb << (32 - 28), 28}, (char) 31 },
/* ' ' ( 32) |010100 */ { { 0x14 << (32 - 6), 6}, (char) 32 },
/* '!' ( 33) |11111110|00 */ { { 0x3f8 << (32 - 10), 10}, (char) 33 },
/* '"' ( 34) |11111110|01 */ { { 0x3f9 << (32 - 10), 10}, (char) 34 },
/* '#' ( 35) |11111111|1010 */ { { 0xffa << (32 - 12), 12}, (char) 35 },
/* '$' ( 36) |11111111|11001 */ { { 0x1ff9 << (32 - 13), 13}, (char) 36 },
/* '%' ( 37) |010101 */ { { 0x15 << (32 - 6), 6}, (char) 37 },
/* '&' ( 38) |11111000 */ { { 0xf8 << (32 - 8), 8}, (char) 38 },
/* ''' ( 39) |11111111|010 */ { { 0x7fa << (32 - 11), 11}, (char) 39 },
/* '(' ( 40) |11111110|10 */ { { 0x3fa << (32 - 10), 10}, (char) 40 },
/* ')' ( 41) |11111110|11 */ { { 0x3fb << (32 - 10), 10}, (char) 41 },
/* '*' ( 42) |11111001 */ { { 0xf9 << (32 - 8), 8}, (char) 42 },
/* '+' ( 43) |11111111|011 */ { { 0x7fb << (32 - 11), 11}, (char) 43 },
/* ',' ( 44) |11111010 */ { { 0xfa << (32 - 8), 8}, (char) 44 },
/* '-' ( 45) |010110 */ { { 0x16 << (32 - 6), 6}, (char) 45 },
/* '.' ( 46) |010111 */ { { 0x17 << (32 - 6), 6}, (char) 46 },
/* '/' ( 47) |011000 */ { { 0x18 << (32 - 6), 6}, (char) 47 },
/* '0' ( 48) |00000 */ { { 0x0 << (32 - 5), 5}, (char) 48 },
/* '1' ( 49) |00001 */ { { 0x1 << (32 - 5), 5}, (char) 49 },
/* '2' ( 50) |00010 */ { { 0x2 << (32 - 5), 5}, (char) 50 },
/* '3' ( 51) |011001 */ { { 0x19 << (32 - 6), 6}, (char) 51 },
/* '4' ( 52) |011010 */ { { 0x1a << (32 - 6), 6}, (char) 52 },
/* '5' ( 53) |011011 */ { { 0x1b << (32 - 6), 6}, (char) 53 },
/* '6' ( 54) |011100 */ { { 0x1c << (32 - 6), 6}, (char) 54 },
/* '7' ( 55) |011101 */ { { 0x1d << (32 - 6), 6}, (char) 55 },
/* '8' ( 56) |011110 */ { { 0x1e << (32 - 6), 6}, (char) 56 },
/* '9' ( 57) |011111 */ { { 0x1f << (32 - 6), 6}, (char) 57 },
/* ':' ( 58) |1011100 */ { { 0x5c << (32 - 7), 7}, (char) 58 },
/* ';' ( 59) |11111011 */ { { 0xfb << (32 - 8), 8}, (char) 59 },
/* '<' ( 60) |11111111|1111100 */ { { 0x7ffc << (32 - 15), 15}, (char) 60 },
/* '=' ( 61) |100000 */ { { 0x20 << (32 - 6), 6}, (char) 61 },
/* '>' ( 62) |11111111|1011 */ { { 0xffb << (32 - 12), 12}, (char) 62 },
/* '?' ( 63) |11111111|00 */ { { 0x3fc << (32 - 10), 10}, (char) 63 },
/* '@' ( 64) |11111111|11010 */ { { 0x1ffa << (32 - 13), 13}, (char) 64 },
/* 'A' ( 65) |100001 */ { { 0x21 << (32 - 6), 6}, (char) 65 },
/* 'B' ( 66) |1011101 */ { { 0x5d << (32 - 7), 7}, (char) 66 },
/* 'C' ( 67) |1011110 */ { { 0x5e << (32 - 7), 7}, (char) 67 },
/* 'D' ( 68) |1011111 */ { { 0x5f << (32 - 7), 7}, (char) 68 },
/* 'E' ( 69) |1100000 */ { { 0x60 << (32 - 7), 7}, (char) 69 },
/* 'F' ( 70) |1100001 */ { { 0x61 << (32 - 7), 7}, (char) 70 },
/* 'G' ( 71) |1100010 */ { { 0x62 << (32 - 7), 7}, (char) 71 },
/* 'H' ( 72) |1100011 */ { { 0x63 << (32 - 7), 7}, (char) 72 },
/* 'I' ( 73) |1100100 */ { { 0x64 << (32 - 7), 7}, (char) 73 },
/* 'J' ( 74) |1100101 */ { { 0x65 << (32 - 7), 7}, (char) 74 },
/* 'K' ( 75) |1100110 */ { { 0x66 << (32 - 7), 7}, (char) 75 },
/* 'L' ( 76) |1100111 */ { { 0x67 << (32 - 7), 7}, (char) 76 },
/* 'M' ( 77) |1101000 */ { { 0x68 << (32 - 7), 7}, (char) 77 },
/* 'N' ( 78) |1101001 */ { { 0x69 << (32 - 7), 7}, (char) 78 },
/* 'O' ( 79) |1101010 */ { { 0x6a << (32 - 7), 7}, (char) 79 },
/* 'P' ( 80) |1101011 */ { { 0x6b << (32 - 7), 7}, (char) 80 },
/* 'Q' ( 81) |1101100 */ { { 0x6c << (32 - 7), 7}, (char) 81 },
/* 'R' ( 82) |1101101 */ { { 0x6d << (32 - 7), 7}, (char) 82 },
/* 'S' ( 83) |1101110 */ { { 0x6e << (32 - 7), 7}, (char) 83 },
/* 'T' ( 84) |1101111 */ { { 0x6f << (32 - 7), 7}, (char) 84 },
/* 'U' ( 85) |1110000 */ { { 0x70 << (32 - 7), 7}, (char) 85 },
/* 'V' ( 86) |1110001 */ { { 0x71 << (32 - 7), 7}, (char) 86 },
/* 'W' ( 87) |1110010 */ { { 0x72 << (32 - 7), 7}, (char) 87 },
/* 'X' ( 88) |11111100 */ { { 0xfc << (32 - 8), 8}, (char) 88 },
/* 'Y' ( 89) |1110011 */ { { 0x73 << (32 - 7), 7}, (char) 89 },
/* 'Z' ( 90) |11111101 */ { { 0xfd << (32 - 8), 8}, (char) 90 },
/* '[' ( 91) |11111111|11011 */ { { 0x1ffb << (32 - 13), 13}, (char) 91 },
/* '\' ( 92) |11111111|11111110|000 */ { { 0x7fff0 << (32 - 19), 19}, (char) 92 },
/* ']' ( 93) |11111111|11100 */ { { 0x1ffc << (32 - 13), 13}, (char) 93 },
/* '^' ( 94) |11111111|111100 */ { { 0x3ffc << (32 - 14), 14}, (char) 94 },
/* '_' ( 95) |100010 */ { { 0x22 << (32 - 6), 6}, (char) 95 },
/* '`' ( 96) |11111111|1111101 */ { { 0x7ffd << (32 - 15), 15}, (char) 96 },
/* 'a' ( 97) |00011 */ { { 0x3 << (32 - 5), 5}, (char) 97 },
/* 'b' ( 98) |100011 */ { { 0x23 << (32 - 6), 6}, (char) 98 },
/* 'c' ( 99) |00100 */ { { 0x4 << (32 - 5), 5}, (char) 99 },
/* 'd' (100) |100100 */ { { 0x24 << (32 - 6), 6}, (char)100 },
/* 'e' (101) |00101 */ { { 0x5 << (32 - 5), 5}, (char)101 },
/* 'f' (102) |100101 */ { { 0x25 << (32 - 6), 6}, (char)102 },
/* 'g' (103) |100110 */ { { 0x26 << (32 - 6), 6}, (char)103 },
/* 'h' (104) |100111 */ { { 0x27 << (32 - 6), 6}, (char)104 },
/* 'i' (105) |00110 */ { { 0x6 << (32 - 5), 5}, (char)105 },
/* 'j' (106) |1110100 */ { { 0x74 << (32 - 7), 7}, (char)106 },
/* 'k' (107) |1110101 */ { { 0x75 << (32 - 7), 7}, (char)107 },
/* 'l' (108) |101000 */ { { 0x28 << (32 - 6), 6}, (char)108 },
/* 'm' (109) |101001 */ { { 0x29 << (32 - 6), 6}, (char)109 },
/* 'n' (110) |101010 */ { { 0x2a << (32 - 6), 6}, (char)110 },
/* 'o' (111) |00111 */ { { 0x7 << (32 - 5), 5}, (char)111 },
/* 'p' (112) |101011 */ { { 0x2b << (32 - 6), 6}, (char)112 },
/* 'q' (113) |1110110 */ { { 0x76 << (32 - 7), 7}, (char)113 },
/* 'r' (114) |101100 */ { { 0x2c << (32 - 6), 6}, (char)114 },
/* 's' (115) |01000 */ { { 0x8 << (32 - 5), 5}, (char)115 },
/* 't' (116) |01001 */ { { 0x9 << (32 - 5), 5}, (char)116 },
/* 'u' (117) |101101 */ { { 0x2d << (32 - 6), 6}, (char)117 },
/* 'v' (118) |1110111 */ { { 0x77 << (32 - 7), 7}, (char)118 },
/* 'w' (119) |1111000 */ { { 0x78 << (32 - 7), 7}, (char)119 },
/* 'x' (120) |1111001 */ { { 0x79 << (32 - 7), 7}, (char)120 },
/* 'y' (121) |1111010 */ { { 0x7a << (32 - 7), 7}, (char)121 },
/* 'z' (122) |1111011 */ { { 0x7b << (32 - 7), 7}, (char)122 },
/* '{' (123) |11111111|1111110 */ { { 0x7ffe << (32 - 15), 15}, (char)123 },
/* '|' (124) |11111111|100 */ { { 0x7fc << (32 - 11), 11}, (char)124 },
/* '}' (125) |11111111|111101 */ { { 0x3ffd << (32 - 14), 14}, (char)125 },
/* '~' (126) |11111111|11101 */ { { 0x1ffd << (32 - 13), 13}, (char)126 },
/* (127) |11111111|11111111|11111111|1100 */ { { 0xffffffc << (32 - 28), 28}, (char)127 },
/* (128) |11111111|11111110|0110 */ { { 0xfffe6 << (32 - 20), 20}, (char)128 },
/* (129) |11111111|11111111|010010 */ { { 0x3fffd2 << (32 - 22), 22}, (char)129 },
/* (130) |11111111|11111110|0111 */ { { 0xfffe7 << (32 - 20), 20}, (char)130 },
/* (131) |11111111|11111110|1000 */ { { 0xfffe8 << (32 - 20), 20}, (char)131 },
/* (132) |11111111|11111111|010011 */ { { 0x3fffd3 << (32 - 22), 22}, (char)132 },
/* (133) |11111111|11111111|010100 */ { { 0x3fffd4 << (32 - 22), 22}, (char)133 },
/* (134) |11111111|11111111|010101 */ { { 0x3fffd5 << (32 - 22), 22}, (char)134 },
/* (135) |11111111|11111111|1011001 */ { { 0x7fffd9 << (32 - 23), 23}, (char)135 },
/* (136) |11111111|11111111|010110 */ { { 0x3fffd6 << (32 - 22), 22}, (char)136 },
/* (137) |11111111|11111111|1011010 */ { { 0x7fffda << (32 - 23), 23}, (char)137 },
/* (138) |11111111|11111111|1011011 */ { { 0x7fffdb << (32 - 23), 23}, (char)138 },
/* (139) |11111111|11111111|1011100 */ { { 0x7fffdc << (32 - 23), 23}, (char)139 },
/* (140) |11111111|11111111|1011101 */ { { 0x7fffdd << (32 - 23), 23}, (char)140 },
/* (141) |11111111|11111111|1011110 */ { { 0x7fffde << (32 - 23), 23}, (char)141 },
/* (142) |11111111|11111111|11101011 */ { { 0xffffeb << (32 - 24), 24}, (char)142 },
/* (143) |11111111|11111111|1011111 */ { { 0x7fffdf << (32 - 23), 23}, (char)143 },
/* (144) |11111111|11111111|11101100 */ { { 0xffffec << (32 - 24), 24}, (char)144 },
/* (145) |11111111|11111111|11101101 */ { { 0xffffed << (32 - 24), 24}, (char)145 },
/* (146) |11111111|11111111|010111 */ { { 0x3fffd7 << (32 - 22), 22}, (char)146 },
/* (147) |11111111|11111111|1100000 */ { { 0x7fffe0 << (32 - 23), 23}, (char)147 },
/* (148) |11111111|11111111|11101110 */ { { 0xffffee << (32 - 24), 24}, (char)148 },
/* (149) |11111111|11111111|1100001 */ { { 0x7fffe1 << (32 - 23), 23}, (char)149 },
/* (150) |11111111|11111111|1100010 */ { { 0x7fffe2 << (32 - 23), 23}, (char)150 },
/* (151) |11111111|11111111|1100011 */ { { 0x7fffe3 << (32 - 23), 23}, (char)151 },
/* (152) |11111111|11111111|1100100 */ { { 0x7fffe4 << (32 - 23), 23}, (char)152 },
/* (153) |11111111|11111110|11100 */ { { 0x1fffdc << (32 - 21), 21}, (char)153 },
/* (154) |11111111|11111111|011000 */ { { 0x3fffd8 << (32 - 22), 22}, (char)154 },
/* (155) |11111111|11111111|1100101 */ { { 0x7fffe5 << (32 - 23), 23}, (char)155 },
/* (156) |11111111|11111111|011001 */ { { 0x3fffd9 << (32 - 22), 22}, (char)156 },
/* (157) |11111111|11111111|1100110 */ { { 0x7fffe6 << (32 - 23), 23}, (char)157 },
/* (158) |11111111|11111111|1100111 */ { { 0x7fffe7 << (32 - 23), 23}, (char)158 },
/* (159) |11111111|11111111|11101111 */ { { 0xffffef << (32 - 24), 24}, (char)159 },
/* (160) |11111111|11111111|011010 */ { { 0x3fffda << (32 - 22), 22}, (char)160 },
/* (161) |11111111|11111110|11101 */ { { 0x1fffdd << (32 - 21), 21}, (char)161 },
/* (162) |11111111|11111110|1001 */ { { 0xfffe9 << (32 - 20), 20}, (char)162 },
/* (163) |11111111|11111111|011011 */ { { 0x3fffdb << (32 - 22), 22}, (char)163 },
/* (164) |11111111|11111111|011100 */ { { 0x3fffdc << (32 - 22), 22}, (char)164 },
/* (165) |11111111|11111111|1101000 */ { { 0x7fffe8 << (32 - 23), 23}, (char)165 },
/* (166) |11111111|11111111|1101001 */ { { 0x7fffe9 << (32 - 23), 23}, (char)166 },
/* (167) |11111111|11111110|11110 */ { { 0x1fffde << (32 - 21), 21}, (char)167 },
/* (168) |11111111|11111111|1101010 */ { { 0x7fffea << (32 - 23), 23}, (char)168 },
/* (169) |11111111|11111111|011101 */ { { 0x3fffdd << (32 - 22), 22}, (char)169 },
/* (170) |11111111|11111111|011110 */ { { 0x3fffde << (32 - 22), 22}, (char)170 },
/* (171) |11111111|11111111|11110000 */ { { 0xfffff0 << (32 - 24), 24}, (char)171 },
/* (172) |11111111|11111110|11111 */ { { 0x1fffdf << (32 - 21), 21}, (char)172 },
/* (173) |11111111|11111111|011111 */ { { 0x3fffdf << (32 - 22), 22}, (char)173 },
/* (174) |11111111|11111111|1101011 */ { { 0x7fffeb << (32 - 23), 23}, (char)174 },
/* (175) |11111111|11111111|1101100 */ { { 0x7fffec << (32 - 23), 23}, (char)175 },
/* (176) |11111111|11111111|00000 */ { { 0x1fffe0 << (32 - 21), 21}, (char)176 },
/* (177) |11111111|11111111|00001 */ { { 0x1fffe1 << (32 - 21), 21}, (char)177 },
/* (178) |11111111|11111111|100000 */ { { 0x3fffe0 << (32 - 22), 22}, (char)178 },
/* (179) |11111111|11111111|00010 */ { { 0x1fffe2 << (32 - 21), 21}, (char)179 },
/* (180) |11111111|11111111|1101101 */ { { 0x7fffed << (32 - 23), 23}, (char)180 },
/* (181) |11111111|11111111|100001 */ { { 0x3fffe1 << (32 - 22), 22}, (char)181 },
/* (182) |11111111|11111111|1101110 */ { { 0x7fffee << (32 - 23), 23}, (char)182 },
/* (183) |11111111|11111111|1101111 */ { { 0x7fffef << (32 - 23), 23}, (char)183 },
/* (184) |11111111|11111110|1010 */ { { 0xfffea << (32 - 20), 20}, (char)184 },
/* (185) |11111111|11111111|100010 */ { { 0x3fffe2 << (32 - 22), 22}, (char)185 },
/* (186) |11111111|11111111|100011 */ { { 0x3fffe3 << (32 - 22), 22}, (char)186 },
/* (187) |11111111|11111111|100100 */ { { 0x3fffe4 << (32 - 22), 22}, (char)187 },
/* (188) |11111111|11111111|1110000 */ { { 0x7ffff0 << (32 - 23), 23}, (char)188 },
/* (189) |11111111|11111111|100101 */ { { 0x3fffe5 << (32 - 22), 22}, (char)189 },
/* (190) |11111111|11111111|100110 */ { { 0x3fffe6 << (32 - 22), 22}, (char)190 },
/* (191) |11111111|11111111|1110001 */ { { 0x7ffff1 << (32 - 23), 23}, (char)191 },
/* (192) |11111111|11111111|11111000|00 */ { { 0x3ffffe0 << (32 - 26), 26}, (char)192 },
/* (193) |11111111|11111111|11111000|01 */ { { 0x3ffffe1 << (32 - 26), 26}, (char)193 },
/* (194) |11111111|11111110|1011 */ { { 0xfffeb << (32 - 20), 20}, (char)194 },
/* (195) |11111111|11111110|001 */ { { 0x7fff1 << (32 - 19), 19}, (char)195 },
/* (196) |11111111|11111111|100111 */ { { 0x3fffe7 << (32 - 22), 22}, (char)196 },
/* (197) |11111111|11111111|1110010 */ { { 0x7ffff2 << (32 - 23), 23}, (char)197 },
/* (198) |11111111|11111111|101000 */ { { 0x3fffe8 << (32 - 22), 22}, (char)198 },
/* (199) |11111111|11111111|11110110|0 */ { { 0x1ffffec << (32 - 25), 25}, (char)199 },
/* (200) |11111111|11111111|11111000|10 */ { { 0x3ffffe2 << (32 - 26), 26}, (char)200 },
/* (201) |11111111|11111111|11111000|11 */ { { 0x3ffffe3 << (32 - 26), 26}, (char)201 },
/* (202) |11111111|11111111|11111001|00 */ { { 0x3ffffe4 << (32 - 26), 26}, (char)202 },
/* (203) |11111111|11111111|11111011|110 */ { { 0x7ffffde << (32 - 27), 27}, (char)203 },
/* (204) |11111111|11111111|11111011|111 */ { { 0x7ffffdf << (32 - 27), 27}, (char)204 },
/* (205) |11111111|11111111|11111001|01 */ { { 0x3ffffe5 << (32 - 26), 26}, (char)205 },
/* (206) |11111111|11111111|11110001 */ { { 0xfffff1 << (32 - 24), 24}, (char)206 },
/* (207) |11111111|11111111|11110110|1 */ { { 0x1ffffed << (32 - 25), 25}, (char)207 },
/* (208) |11111111|11111110|010 */ { { 0x7fff2 << (32 - 19), 19}, (char)208 },
/* (209) |11111111|11111111|00011 */ { { 0x1fffe3 << (32 - 21), 21}, (char)209 },
/* (210) |11111111|11111111|11111001|10 */ { { 0x3ffffe6 << (32 - 26), 26}, (char)210 },
/* (211) |11111111|11111111|11111100|000 */ { { 0x7ffffe0 << (32 - 27), 27}, (char)211 },
/* (212) |11111111|11111111|11111100|001 */ { { 0x7ffffe1 << (32 - 27), 27}, (char)212 },
/* (213) |11111111|11111111|11111001|11 */ { { 0x3ffffe7 << (32 - 26), 26}, (char)213 },
/* (214) |11111111|11111111|11111100|010 */ { { 0x7ffffe2 << (32 - 27), 27}, (char)214 },
/* (215) |11111111|11111111|11110010 */ { { 0xfffff2 << (32 - 24), 24}, (char)215 },
/* (216) |11111111|11111111|00100 */ { { 0x1fffe4 << (32 - 21), 21}, (char)216 },
/* (217) |11111111|11111111|00101 */ { { 0x1fffe5 << (32 - 21), 21}, (char)217 },
/* (218) |11111111|11111111|11111010|00 */ { { 0x3ffffe8 << (32 - 26), 26}, (char)218 },
/* (219) |11111111|11111111|11111010|01 */ { { 0x3ffffe9 << (32 - 26), 26}, (char)219 },
/* (220) |11111111|11111111|11111111|1101 */ { { 0xffffffd << (32 - 28), 28}, (char)220 },
/* (221) |11111111|11111111|11111100|011 */ { { 0x7ffffe3 << (32 - 27), 27}, (char)221 },
/* (222) |11111111|11111111|11111100|100 */ { { 0x7ffffe4 << (32 - 27), 27}, (char)222 },
/* (223) |11111111|11111111|11111100|101 */ { { 0x7ffffe5 << (32 - 27), 27}, (char)223 },
/* (224) |11111111|11111110|1100 */ { { 0xfffec << (32 - 20), 20}, (char)224 },
/* (225) |11111111|11111111|11110011 */ { { 0xfffff3 << (32 - 24), 24}, (char)225 },
/* (226) |11111111|11111110|1101 */ { { 0xfffed << (32 - 20), 20}, (char)226 },
/* (227) |11111111|11111111|00110 */ { { 0x1fffe6 << (32 - 21), 21}, (char)227 },
/* (228) |11111111|11111111|101001 */ { { 0x3fffe9 << (32 - 22), 22}, (char)228 },
/* (229) |11111111|11111111|00111 */ { { 0x1fffe7 << (32 - 21), 21}, (char)229 },
/* (230) |11111111|11111111|01000 */ { { 0x1fffe8 << (32 - 21), 21}, (char)230 },
/* (231) |11111111|11111111|1110011 */ { { 0x7ffff3 << (32 - 23), 23}, (char)231 },
/* (232) |11111111|11111111|101010 */ { { 0x3fffea << (32 - 22), 22}, (char)232 },
/* (233) |11111111|11111111|101011 */ { { 0x3fffeb << (32 - 22), 22}, (char)233 },
/* (234) |11111111|11111111|11110111|0 */ { { 0x1ffffee << (32 - 25), 25}, (char)234 },
/* (235) |11111111|11111111|11110111|1 */ { { 0x1ffffef << (32 - 25), 25}, (char)235 },
/* (236) |11111111|11111111|11110100 */ { { 0xfffff4 << (32 - 24), 24}, (char)236 },
/* (237) |11111111|11111111|11110101 */ { { 0xfffff5 << (32 - 24), 24}, (char)237 },
/* (238) |11111111|11111111|11111010|10 */ { { 0x3ffffea << (32 - 26), 26}, (char)238 },
/* (239) |11111111|11111111|1110100 */ { { 0x7ffff4 << (32 - 23), 23}, (char)239 },
/* (240) |11111111|11111111|11111010|11 */ { { 0x3ffffeb << (32 - 26), 26}, (char)240 },
/* (241) |11111111|11111111|11111100|110 */ { { 0x7ffffe6 << (32 - 27), 27}, (char)241 },
/* (242) |11111111|11111111|11111011|00 */ { { 0x3ffffec << (32 - 26), 26}, (char)242 },
/* (243) |11111111|11111111|11111011|01 */ { { 0x3ffffed << (32 - 26), 26}, (char)243 },
/* (244) |11111111|11111111|11111100|111 */ { { 0x7ffffe7 << (32 - 27), 27}, (char)244 },
/* (245) |11111111|11111111|11111101|000 */ { { 0x7ffffe8 << (32 - 27), 27}, (char)245 },
/* (246) |11111111|11111111|11111101|001 */ { { 0x7ffffe9 << (32 - 27), 27}, (char)246 },
/* (247) |11111111|11111111|11111101|010 */ { { 0x7ffffea << (32 - 27), 27}, (char)247 },
/* (248) |11111111|11111111|11111101|011 */ { { 0x7ffffeb << (32 - 27), 27}, (char)248 },
/* (249) |11111111|11111111|11111111|1110 */ { { 0xffffffe << (32 - 28), 28}, (char)249 },
/* (250) |11111111|11111111|11111101|100 */ { { 0x7ffffec << (32 - 27), 27}, (char)250 },
/* (251) |11111111|11111111|11111101|101 */ { { 0x7ffffed << (32 - 27), 27}, (char)251 },
/* (252) |11111111|11111111|11111101|110 */ { { 0x7ffffee << (32 - 27), 27}, (char)252 },
/* (253) |11111111|11111111|11111101|111 */ { { 0x7ffffef << (32 - 27), 27}, (char)253 },
/* (254) |11111111|11111111|11111110|000 */ { { 0x7fffff0 << (32 - 27), 27}, (char)254 },
/* (255) |11111111|11111111|11111011|10 */ { { 0x3ffffee << (32 - 26), 26}, (char)255 }};
//----------------------------------------------------------------//
//----------------------------------------------------------------//
const huffman_tree huffman_code_tree2{
/* ( 0) |11111111|11000 */ { { 0x1ff8u << (32 - 13), 13}, (char) 0 },
/* ( 1) |11111111|11111111|1011000 */ { { 0x7fffd8u << (32 - 23), 23}, (char) 1 },
/* ( 2) |11111111|11111111|11111110|0010 */ { { 0xfffffe2u << (32 - 28), 28}, (char) 2 },
/* ( 3) |11111111|11111111|11111110|0011 */ { { 0xfffffe3u << (32 - 28), 28}, (char) 3 },
/* ( 4) |11111111|11111111|11111110|0100 */ { { 0xfffffe4u << (32 - 28), 28}, (char) 4 },
/* ( 5) |11111111|11111111|11111110|0101 */ { { 0xfffffe5u << (32 - 28), 28}, (char) 5 },
/* ( 6) |11111111|11111111|11111110|0110 */ { { 0xfffffe6u << (32 - 28), 28}, (char) 6 },
/* ( 7) |11111111|11111111|11111110|0111 */ { { 0xfffffe7u << (32 - 28), 28}, (char) 7 },
/* ( 8) |11111111|11111111|11111110|1000 */ { { 0xfffffe8u << (32 - 28), 28}, (char) 8 },
/* ( 9) |11111111|11111111|11101010 */ { { 0xffffeau << (32 - 24), 24}, (char) 9 },
/* ( 10) |11111111|11111111|11111111|111100 */ { { 0x3ffffffcu << (32 - 30), 30}, (char) 10 },
/* ( 11) |11111111|11111111|11111110|1001 */ { { 0xfffffe9u << (32 - 28), 28}, (char) 11 },
/* ( 12) |11111111|11111111|11111110|1010 */ { { 0xfffffeau << (32 - 28), 28}, (char) 12 },
/* ( 13) |11111111|11111111|11111111|111101 */ { { 0x3ffffffdu << (32 - 30), 30}, (char) 13 },
/* ( 14) |11111111|11111111|11111110|1011 */ { { 0xfffffebu << (32 - 28), 28}, (char) 14 },
/* ( 15) |11111111|11111111|11111110|1100 */ { { 0xfffffecu << (32 - 28), 28}, (char) 15 },
/* ( 16) |11111111|11111111|11111110|1101 */ { { 0xfffffedu << (32 - 28), 28}, (char) 16 },
/* ( 17) |11111111|11111111|11111110|1110 */ { { 0xfffffeeu << (32 - 28), 28}, (char) 17 },
/* ( 18) |11111111|11111111|11111110|1111 */ { { 0xfffffefu << (32 - 28), 28}, (char) 18 },
/* ( 19) |11111111|11111111|11111111|0000 */ { { 0xffffff0u << (32 - 28), 28}, (char) 19 },
/* ( 20) |11111111|11111111|11111111|0001 */ { { 0xffffff1u << (32 - 28), 28}, (char) 20 },
/* ( 21) |11111111|11111111|11111111|0010 */ { { 0xffffff2u << (32 - 28), 28}, (char) 21 },
/* ( 22) |11111111|11111111|11111111|111110 */ { { 0x3ffffffeu << (32 - 30), 30}, (char) 22 },
/* ( 23) |11111111|11111111|11111111|0011 */ { { 0xffffff3u << (32 - 28), 28}, (char) 23 },
/* ( 24) |11111111|11111111|11111111|0100 */ { { 0xffffff4u << (32 - 28), 28}, (char) 24 },
/* ( 25) |11111111|11111111|11111111|0101 */ { { 0xffffff5u << (32 - 28), 28}, (char) 25 },
/* ( 26) |11111111|11111111|11111111|0110 */ { { 0xffffff6u << (32 - 28), 28}, (char) 26 },
/* ( 27) |11111111|11111111|11111111|0111 */ { { 0xffffff7u << (32 - 28), 28}, (char) 27 },
/* ( 28) |11111111|11111111|11111111|1000 */ { { 0xffffff8u << (32 - 28), 28}, (char) 28 },
/* ( 29) |11111111|11111111|11111111|1001 */ { { 0xffffff9u << (32 - 28), 28}, (char) 29 },
/* ( 30) |11111111|11111111|11111111|1010 */ { { 0xffffffau << (32 - 28), 28}, (char) 30 },
/* ( 31) |11111111|11111111|11111111|1011 */ { { 0xffffffbu << (32 - 28), 28}, (char) 31 },
/* ' ' ( 32) |010100 */ { { 0x14u << (32 - 6), 6}, (char) 32 },
/* '!' ( 33) |11111110|00 */ { { 0x3f8u << (32 - 10), 10}, (char) 33 },
/* '"' ( 34) |11111110|01 */ { { 0x3f9u << (32 - 10), 10}, (char) 34 },
/* '#' ( 35) |11111111|1010 */ { { 0xffau << (32 - 12), 12}, (char) 35 },
/* '$' ( 36) |11111111|11001 */ { { 0x1ff9u << (32 - 13), 13}, (char) 36 },
/* '%' ( 37) |010101 */ { { 0x15u << (32 - 6), 6}, (char) 37 },
/* '&' ( 38) |11111000 */ { { 0xf8u << (32 - 8), 8}, (char) 38 },
/* ''' ( 39) |11111111|010 */ { { 0x7fau << (32 - 11), 11}, (char) 39 },
/* '(' ( 40) |11111110|10 */ { { 0x3fau << (32 - 10), 10}, (char) 40 },
/* ')' ( 41) |11111110|11 */ { { 0x3fbu << (32 - 10), 10}, (char) 41 },
/* '*' ( 42) |11111001 */ { { 0xf9u << (32 - 8), 8}, (char) 42 },
/* '+' ( 43) |11111111|011 */ { { 0x7fbu << (32 - 11), 11}, (char) 43 },
/* ',' ( 44) |11111010 */ { { 0xfau << (32 - 8), 8}, (char) 44 },
/* '-' ( 45) |010110 */ { { 0x16u << (32 - 6), 6}, (char) 45 },
/* '.' ( 46) |010111 */ { { 0x17u << (32 - 6), 6}, (char) 46 },
/* '/' ( 47) |011000 */ { { 0x18u << (32 - 6), 6}, (char) 47 },
/* '0' ( 48) |00000 */ { { 0x0u << (32 - 5), 5}, (char) 48 },
/* '1' ( 49) |00001 */ { { 0x1u << (32 - 5), 5}, (char) 49 },
/* '2' ( 50) |00010 */ { { 0x2u << (32 - 5), 5}, (char) 50 },
/* '3' ( 51) |011001 */ { { 0x19u << (32 - 6), 6}, (char) 51 },
/* '4' ( 52) |011010 */ { { 0x1au << (32 - 6), 6}, (char) 52 },
/* '5' ( 53) |011011 */ { { 0x1bu << (32 - 6), 6}, (char) 53 },
/* '6' ( 54) |011100 */ { { 0x1cu << (32 - 6), 6}, (char) 54 },
/* '7' ( 55) |011101 */ { { 0x1du << (32 - 6), 6}, (char) 55 },
/* '8' ( 56) |011110 */ { { 0x1eu << (32 - 6), 6}, (char) 56 },
/* '9' ( 57) |011111 */ { { 0x1fu << (32 - 6), 6}, (char) 57 },
/* ':' ( 58) |1011100 */ { { 0x5cu << (32 - 7), 7}, (char) 58 },
/* ';' ( 59) |11111011 */ { { 0xfbu << (32 - 8), 8}, (char) 59 },
/* '<' ( 60) |11111111|1111100 */ { { 0x7ffcu << (32 - 15), 15}, (char) 60 },
/* '=' ( 61) |100000 */ { { 0x20u << (32 - 6), 6}, (char) 61 },
/* '>' ( 62) |11111111|1011 */ { { 0xffbu << (32 - 12), 12}, (char) 62 },
/* '?' ( 63) |11111111|00 */ { { 0x3fcu << (32 - 10), 10}, (char) 63 },
/* '@' ( 64) |11111111|11010 */ { { 0x1ffau << (32 - 13), 13}, (char) 64 },
/* 'A' ( 65) |100001 */ { { 0x21u << (32 - 6), 6}, (char) 65 },
/* 'B' ( 66) |1011101 */ { { 0x5du << (32 - 7), 7}, (char) 66 },
/* 'C' ( 67) |1011110 */ { { 0x5eu << (32 - 7), 7}, (char) 67 },
/* 'D' ( 68) |1011111 */ { { 0x5fu << (32 - 7), 7}, (char) 68 },
/* 'E' ( 69) |1100000 */ { { 0x60u << (32 - 7), 7}, (char) 69 },
/* 'F' ( 70) |1100001 */ { { 0x61u << (32 - 7), 7}, (char) 70 },
/* 'G' ( 71) |1100010 */ { { 0x62u << (32 - 7), 7}, (char) 71 },
/* 'H' ( 72) |1100011 */ { { 0x63u << (32 - 7), 7}, (char) 72 },
/* 'I' ( 73) |1100100 */ { { 0x64u << (32 - 7), 7}, (char) 73 },
/* 'J' ( 74) |1100101 */ { { 0x65u << (32 - 7), 7}, (char) 74 },
/* 'K' ( 75) |1100110 */ { { 0x66u << (32 - 7), 7}, (char) 75 },
/* 'L' ( 76) |1100111 */ { { 0x67u << (32 - 7), 7}, (char) 76 },
/* 'M' ( 77) |1101000 */ { { 0x68u << (32 - 7), 7}, (char) 77 },
/* 'N' ( 78) |1101001 */ { { 0x69u << (32 - 7), 7}, (char) 78 },
/* 'O' ( 79) |1101010 */ { { 0x6au << (32 - 7), 7}, (char) 79 },
/* 'P' ( 80) |1101011 */ { { 0x6bu << (32 - 7), 7}, (char) 80 },
/* 'Q' ( 81) |1101100 */ { { 0x6cu << (32 - 7), 7}, (char) 81 },
/* 'R' ( 82) |1101101 */ { { 0x6du << (32 - 7), 7}, (char) 82 },
/* 'S' ( 83) |1101110 */ { { 0x6eu << (32 - 7), 7}, (char) 83 },
/* 'T' ( 84) |1101111 */ { { 0x6fu << (32 - 7), 7}, (char) 84 },
/* 'U' ( 85) |1110000 */ { { 0x70u << (32 - 7), 7}, (char) 85 },
/* 'V' ( 86) |1110001 */ { { 0x71u << (32 - 7), 7}, (char) 86 },
/* 'W' ( 87) |1110010 */ { { 0x72u << (32 - 7), 7}, (char) 87 },
/* 'X' ( 88) |11111100 */ { { 0xfcu << (32 - 8), 8}, (char) 88 },
/* 'Y' ( 89) |1110011 */ { { 0x73u << (32 - 7), 7}, (char) 89 },
/* 'Z' ( 90) |11111101 */ { { 0xfdu << (32 - 8), 8}, (char) 90 },
/* '[' ( 91) |11111111|11011 */ { { 0x1ffbu << (32 - 13), 13}, (char) 91 },
/* '\' ( 92) |11111111|11111110|000 */ { { 0x7fff0u << (32 - 19), 19}, (char) 92 },
/* ']' ( 93) |11111111|11100 */ { { 0x1ffcu << (32 - 13), 13}, (char) 93 },
/* '^' ( 94) |11111111|111100 */ { { 0x3ffcu << (32 - 14), 14}, (char) 94 },
/* '_' ( 95) |100010 */ { { 0x22u << (32 - 6), 6}, (char) 95 },
/* '`' ( 96) |11111111|1111101 */ { { 0x7ffdu << (32 - 15), 15}, (char) 96 },
/* 'a' ( 97) |00011 */ { { 0x3u << (32 - 5), 5}, (char) 97 },
/* 'b' ( 98) |100011 */ { { 0x23u << (32 - 6), 6}, (char) 98 },
/* 'c' ( 99) |00100 */ { { 0x4u << (32 - 5), 5}, (char) 99 },
/* 'd' (100) |100100 */ { { 0x24u << (32 - 6), 6}, (char)100 },
/* 'e' (101) |00101 */ { { 0x5u << (32 - 5), 5}, (char)101 },
/* 'f' (102) |100101 */ { { 0x25u << (32 - 6), 6}, (char)102 },
/* 'g' (103) |100110 */ { { 0x26u << (32 - 6), 6}, (char)103 },
/* 'h' (104) |100111 */ { { 0x27u << (32 - 6), 6}, (char)104 },
/* 'i' (105) |00110 */ { { 0x6u << (32 - 5), 5}, (char)105 },
/* 'j' (106) |1110100 */ { { 0x74u << (32 - 7), 7}, (char)106 },
/* 'k' (107) |1110101 */ { { 0x75u << (32 - 7), 7}, (char)107 },
/* 'l' (108) |101000 */ { { 0x28u << (32 - 6), 6}, (char)108 },
/* 'm' (109) |101001 */ { { 0x29u << (32 - 6), 6}, (char)109 },
/* 'n' (110) |101010 */ { { 0x2au << (32 - 6), 6}, (char)110 },
/* 'o' (111) |00111 */ { { 0x7u << (32 - 5), 5}, (char)111 },
/* 'p' (112) |101011 */ { { 0x2bu << (32 - 6), 6}, (char)112 },
/* 'q' (113) |1110110 */ { { 0x76u << (32 - 7), 7}, (char)113 },
/* 'r' (114) |101100 */ { { 0x2cu << (32 - 6), 6}, (char)114 },
/* 's' (115) |01000 */ { { 0x8u << (32 - 5), 5}, (char)115 },
/* 't' (116) |01001 */ { { 0x9u << (32 - 5), 5}, (char)116 },
/* 'u' (117) |101101 */ { { 0x2du << (32 - 6), 6}, (char)117 },
/* 'v' (118) |1110111 */ { { 0x77u << (32 - 7), 7}, (char)118 },
/* 'w' (119) |1111000 */ { { 0x78u << (32 - 7), 7}, (char)119 },
/* 'x' (120) |1111001 */ { { 0x79u << (32 - 7), 7}, (char)120 },
/* 'y' (121) |1111010 */ { { 0x7au << (32 - 7), 7}, (char)121 },
/* 'z' (122) |1111011 */ { { 0x7bu << (32 - 7), 7}, (char)122 },
/* '{' (123) |11111111|1111110 */ { { 0x7ffeu << (32 - 15), 15}, (char)123 },
/* '|' (124) |11111111|100 */ { { 0x7fcu << (32 - 11), 11}, (char)124 },
/* '}' (125) |11111111|111101 */ { { 0x3ffdu << (32 - 14), 14}, (char)125 },
/* '~' (126) |11111111|11101 */ { { 0x1ffdu << (32 - 13), 13}, (char)126 },
/* (127) |11111111|11111111|11111111|1100 */ { { 0xffffffcu << (32 - 28), 28}, (char)127 },
/* (128) |11111111|11111110|0110 */ { { 0xfffe6u << (32 - 20), 20}, (char)128 },
/* (129) |11111111|11111111|010010 */ { { 0x3fffd2u << (32 - 22), 22}, (char)129 },
/* (130) |11111111|11111110|0111 */ { { 0xfffe7u << (32 - 20), 20}, (char)130 },
/* (131) |11111111|11111110|1000 */ { { 0xfffe8u << (32 - 20), 20}, (char)131 },
/* (132) |11111111|11111111|010011 */ { { 0x3fffd3u << (32 - 22), 22}, (char)132 },
/* (133) |11111111|11111111|010100 */ { { 0x3fffd4u << (32 - 22), 22}, (char)133 },
/* (134) |11111111|11111111|010101 */ { { 0x3fffd5u << (32 - 22), 22}, (char)134 },
/* (135) |11111111|11111111|1011001 */ { { 0x7fffd9u << (32 - 23), 23}, (char)135 },
/* (136) |11111111|11111111|010110 */ { { 0x3fffd6u << (32 - 22), 22}, (char)136 },
/* (137) |11111111|11111111|1011010 */ { { 0x7fffdau << (32 - 23), 23}, (char)137 },
/* (138) |11111111|11111111|1011011 */ { { 0x7fffdbu << (32 - 23), 23}, (char)138 },
/* (139) |11111111|11111111|1011100 */ { { 0x7fffdcu << (32 - 23), 23}, (char)139 },
/* (140) |11111111|11111111|1011101 */ { { 0x7fffddu << (32 - 23), 23}, (char)140 },
/* (141) |11111111|11111111|1011110 */ { { 0x7fffdeu << (32 - 23), 23}, (char)141 },
/* (142) |11111111|11111111|11101011 */ { { 0xffffebu << (32 - 24), 24}, (char)142 },
/* (143) |11111111|11111111|1011111 */ { { 0x7fffdfu << (32 - 23), 23}, (char)143 },
/* (144) |11111111|11111111|11101100 */ { { 0xffffecu << (32 - 24), 24}, (char)144 },
/* (145) |11111111|11111111|11101101 */ { { 0xffffedu << (32 - 24), 24}, (char)145 },
/* (146) |11111111|11111111|010111 */ { { 0x3fffd7u << (32 - 22), 22}, (char)146 },
/* (147) |11111111|11111111|1100000 */ { { 0x7fffe0u << (32 - 23), 23}, (char)147 },
/* (148) |11111111|11111111|11101110 */ { { 0xffffeeu << (32 - 24), 24}, (char)148 },
/* (149) |11111111|11111111|1100001 */ { { 0x7fffe1u << (32 - 23), 23}, (char)149 },
/* (150) |11111111|11111111|1100010 */ { { 0x7fffe2u << (32 - 23), 23}, (char)150 },
/* (151) |11111111|11111111|1100011 */ { { 0x7fffe3u << (32 - 23), 23}, (char)151 },
/* (152) |11111111|11111111|1100100 */ { { 0x7fffe4u << (32 - 23), 23}, (char)152 },
/* (153) |11111111|11111110|11100 */ { { 0x1fffdcu << (32 - 21), 21}, (char)153 },
/* (154) |11111111|11111111|011000 */ { { 0x3fffd8u << (32 - 22), 22}, (char)154 },
/* (155) |11111111|11111111|1100101 */ { { 0x7fffe5u << (32 - 23), 23}, (char)155 },
/* (156) |11111111|11111111|011001 */ { { 0x3fffd9u << (32 - 22), 22}, (char)156 },
/* (157) |11111111|11111111|1100110 */ { { 0x7fffe6u << (32 - 23), 23}, (char)157 },
/* (158) |11111111|11111111|1100111 */ { { 0x7fffe7u << (32 - 23), 23}, (char)158 },
/* (159) |11111111|11111111|11101111 */ { { 0xffffefu << (32 - 24), 24}, (char)159 },
/* (160) |11111111|11111111|011010 */ { { 0x3fffdau << (32 - 22), 22}, (char)160 },
/* (161) |11111111|11111110|11101 */ { { 0x1fffddu << (32 - 21), 21}, (char)161 },
/* (162) |11111111|11111110|1001 */ { { 0xfffe9u << (32 - 20), 20}, (char)162 },
/* (163) |11111111|11111111|011011 */ { { 0x3fffdbu << (32 - 22), 22}, (char)163 },
/* (164) |11111111|11111111|011100 */ { { 0x3fffdcu << (32 - 22), 22}, (char)164 },
/* (165) |11111111|11111111|1101000 */ { { 0x7fffe8u << (32 - 23), 23}, (char)165 },
/* (166) |11111111|11111111|1101001 */ { { 0x7fffe9u << (32 - 23), 23}, (char)166 },
/* (167) |11111111|11111110|11110 */ { { 0x1fffdeu << (32 - 21), 21}, (char)167 },
/* (168) |11111111|11111111|1101010 */ { { 0x7fffeau << (32 - 23), 23}, (char)168 },
/* (169) |11111111|11111111|011101 */ { { 0x3fffddu << (32 - 22), 22}, (char)169 },
/* (170) |11111111|11111111|011110 */ { { 0x3fffdeu << (32 - 22), 22}, (char)170 },
/* (171) |11111111|11111111|11110000 */ { { 0xfffff0u << (32 - 24), 24}, (char)171 },
/* (172) |11111111|11111110|11111 */ { { 0x1fffdfu << (32 - 21), 21}, (char)172 },
/* (173) |11111111|11111111|011111 */ { { 0x3fffdfu << (32 - 22), 22}, (char)173 },
/* (174) |11111111|11111111|1101011 */ { { 0x7fffebu << (32 - 23), 23}, (char)174 },
/* (175) |11111111|11111111|1101100 */ { { 0x7fffecu << (32 - 23), 23}, (char)175 },
/* (176) |11111111|11111111|00000 */ { { 0x1fffe0u << (32 - 21), 21}, (char)176 },
/* (177) |11111111|11111111|00001 */ { { 0x1fffe1u << (32 - 21), 21}, (char)177 },
/* (178) |11111111|11111111|100000 */ { { 0x3fffe0u << (32 - 22), 22}, (char)178 },
/* (179) |11111111|11111111|00010 */ { { 0x1fffe2u << (32 - 21), 21}, (char)179 },
/* (180) |11111111|11111111|1101101 */ { { 0x7fffedu << (32 - 23), 23}, (char)180 },
/* (181) |11111111|11111111|100001 */ { { 0x3fffe1u << (32 - 22), 22}, (char)181 },
/* (182) |11111111|11111111|1101110 */ { { 0x7fffeeu << (32 - 23), 23}, (char)182 },
/* (183) |11111111|11111111|1101111 */ { { 0x7fffefu << (32 - 23), 23}, (char)183 },
/* (184) |11111111|11111110|1010 */ { { 0xfffeau << (32 - 20), 20}, (char)184 },
/* (185) |11111111|11111111|100010 */ { { 0x3fffe2u << (32 - 22), 22}, (char)185 },
/* (186) |11111111|11111111|100011 */ { { 0x3fffe3u << (32 - 22), 22}, (char)186 },
/* (187) |11111111|11111111|100100 */ { { 0x3fffe4u << (32 - 22), 22}, (char)187 },
/* (188) |11111111|11111111|1110000 */ { { 0x7ffff0u << (32 - 23), 23}, (char)188 },
/* (189) |11111111|11111111|100101 */ { { 0x3fffe5u << (32 - 22), 22}, (char)189 },
/* (190) |11111111|11111111|100110 */ { { 0x3fffe6u << (32 - 22), 22}, (char)190 },
/* (191) |11111111|11111111|1110001 */ { { 0x7ffff1u << (32 - 23), 23}, (char)191 },
/* (192) |11111111|11111111|11111000|00 */ { { 0x3ffffe0u << (32 - 26), 26}, (char)192 },
/* (193) |11111111|11111111|11111000|01 */ { { 0x3ffffe1u << (32 - 26), 26}, (char)193 },
/* (194) |11111111|11111110|1011 */ { { 0xfffebu << (32 - 20), 20}, (char)194 },
/* (195) |11111111|11111110|001 */ { { 0x7fff1u << (32 - 19), 19}, (char)195 },
/* (196) |11111111|11111111|100111 */ { { 0x3fffe7u << (32 - 22), 22}, (char)196 },
/* (197) |11111111|11111111|1110010 */ { { 0x7ffff2u << (32 - 23), 23}, (char)197 },
/* (198) |11111111|11111111|101000 */ { { 0x3fffe8u << (32 - 22), 22}, (char)198 },
/* (199) |11111111|11111111|11110110|0 */ { { 0x1ffffecu << (32 - 25), 25}, (char)199 },
/* (200) |11111111|11111111|11111000|10 */ { { 0x3ffffe2u << (32 - 26), 26}, (char)200 },
/* (201) |11111111|11111111|11111000|11 */ { { 0x3ffffe3u << (32 - 26), 26}, (char)201 },
/* (202) |11111111|11111111|11111001|00 */ { { 0x3ffffe4u << (32 - 26), 26}, (char)202 },
/* (203) |11111111|11111111|11111011|110 */ { { 0x7ffffdeu << (32 - 27), 27}, (char)203 },
/* (204) |11111111|11111111|11111011|111 */ { { 0x7ffffdfu << (32 - 27), 27}, (char)204 },
/* (205) |11111111|11111111|11111001|01 */ { { 0x3ffffe5u << (32 - 26), 26}, (char)205 },
/* (206) |11111111|11111111|11110001 */ { { 0xfffff1u << (32 - 24), 24}, (char)206 },
/* (207) |11111111|11111111|11110110|1 */ { { 0x1ffffedu << (32 - 25), 25}, (char)207 },
/* (208) |11111111|11111110|010 */ { { 0x7fff2u << (32 - 19), 19}, (char)208 },
/* (209) |11111111|11111111|00011 */ { { 0x1fffe3u << (32 - 21), 21}, (char)209 },
/* (210) |11111111|11111111|11111001|10 */ { { 0x3ffffe6u << (32 - 26), 26}, (char)210 },
/* (211) |11111111|11111111|11111100|000 */ { { 0x7ffffe0u << (32 - 27), 27}, (char)211 },
/* (212) |11111111|11111111|11111100|001 */ { { 0x7ffffe1u << (32 - 27), 27}, (char)212 },
/* (213) |11111111|11111111|11111001|11 */ { { 0x3ffffe7u << (32 - 26), 26}, (char)213 },
/* (214) |11111111|11111111|11111100|010 */ { { 0x7ffffe2u << (32 - 27), 27}, (char)214 },
/* (215) |11111111|11111111|11110010 */ { { 0xfffff2u << (32 - 24), 24}, (char)215 },
/* (216) |11111111|11111111|00100 */ { { 0x1fffe4u << (32 - 21), 21}, (char)216 },
/* (217) |11111111|11111111|00101 */ { { 0x1fffe5u << (32 - 21), 21}, (char)217 },
/* (218) |11111111|11111111|11111010|00 */ { { 0x3ffffe8u << (32 - 26), 26}, (char)218 },
/* (219) |11111111|11111111|11111010|01 */ { { 0x3ffffe9u << (32 - 26), 26}, (char)219 },
/* (220) |11111111|11111111|11111111|1101 */ { { 0xffffffdu << (32 - 28), 28}, (char)220 },
/* (221) |11111111|11111111|11111100|011 */ { { 0x7ffffe3u << (32 - 27), 27}, (char)221 },
/* (222) |11111111|11111111|11111100|100 */ { { 0x7ffffe4u << (32 - 27), 27}, (char)222 },
/* (223) |11111111|11111111|11111100|101 */ { { 0x7ffffe5u << (32 - 27), 27}, (char)223 },
/* (224) |11111111|11111110|1100 */ { { 0xfffecu << (32 - 20), 20}, (char)224 },
/* (225) |11111111|11111111|11110011 */ { { 0xfffff3u << (32 - 24), 24}, (char)225 },
/* (226) |11111111|11111110|1101 */ { { 0xfffedu << (32 - 20), 20}, (char)226 },
/* (227) |11111111|11111111|00110 */ { { 0x1fffe6u << (32 - 21), 21}, (char)227 },
/* (228) |11111111|11111111|101001 */ { { 0x3fffe9u << (32 - 22), 22}, (char)228 },
/* (229) |11111111|11111111|00111 */ { { 0x1fffe7u << (32 - 21), 21}, (char)229 },
/* (230) |11111111|11111111|01000 */ { { 0x1fffe8u << (32 - 21), 21}, (char)230 },
/* (231) |11111111|11111111|1110011 */ { { 0x7ffff3u << (32 - 23), 23}, (char)231 },
/* (232) |11111111|11111111|101010 */ { { 0x3fffeau << (32 - 22), 22}, (char)232 },
/* (233) |11111111|11111111|101011 */ { { 0x3fffebu << (32 - 22), 22}, (char)233 },
/* (234) |11111111|11111111|11110111|0 */ { { 0x1ffffeeu << (32 - 25), 25}, (char)234 },
/* (235) |11111111|11111111|11110111|1 */ { { 0x1ffffefu << (32 - 25), 25}, (char)235 },
/* (236) |11111111|11111111|11110100 */ { { 0xfffff4u << (32 - 24), 24}, (char)236 },
/* (237) |11111111|11111111|11110101 */ { { 0xfffff5u << (32 - 24), 24}, (char)237 },
/* (238) |11111111|11111111|11111010|10 */ { { 0x3ffffeau << (32 - 26), 26}, (char)238 },
/* (239) |11111111|11111111|1110100 */ { { 0x7ffff4u << (32 - 23), 23}, (char)239 },
/* (240) |11111111|11111111|11111010|11 */ { { 0x3ffffebu << (32 - 26), 26}, (char)240 },
/* (241) |11111111|11111111|11111100|110 */ { { 0x7ffffe6u << (32 - 27), 27}, (char)241 },
/* (242) |11111111|11111111|11111011|00 */ { { 0x3ffffecu << (32 - 26), 26}, (char)242 },
/* (243) |11111111|11111111|11111011|01 */ { { 0x3ffffedu << (32 - 26), 26}, (char)243 },
/* (244) |11111111|11111111|11111100|111 */ { { 0x7ffffe7u << (32 - 27), 27}, (char)244 },
/* (245) |11111111|11111111|11111101|000 */ { { 0x7ffffe8u << (32 - 27), 27}, (char)245 },
/* (246) |11111111|11111111|11111101|001 */ { { 0x7ffffe9u << (32 - 27), 27}, (char)246 },
/* (247) |11111111|11111111|11111101|010 */ { { 0x7ffffeau << (32 - 27), 27}, (char)247 },
/* (248) |11111111|11111111|11111101|011 */ { { 0x7ffffebu << (32 - 27), 27}, (char)248 },
/* (249) |11111111|11111111|11111111|1110 */ { { 0xffffffeu << (32 - 28), 28}, (char)249 },
/* (250) |11111111|11111111|11111101|100 */ { { 0x7ffffecu << (32 - 27), 27}, (char)250 },
/* (251) |11111111|11111111|11111101|101 */ { { 0x7ffffedu << (32 - 27), 27}, (char)251 },
/* (252) |11111111|11111111|11111101|110 */ { { 0x7ffffeeu << (32 - 27), 27}, (char)252 },
/* (253) |11111111|11111111|11111101|111 */ { { 0x7ffffefu << (32 - 27), 27}, (char)253 },
/* (254) |11111111|11111111|11111110|000 */ { { 0x7fffff0u << (32 - 27), 27}, (char)254 },
/* (255) |11111111|11111111|11111011|10 */ { { 0x3ffffeeu << (32 - 26), 26}, (char)255 }};
//----------------------------------------------------------------//
//----------------------------------------------------------------//
void context::table_evict()
{
this->current_dynamic_table_size_ -= (32 + this->dynamic_table_.back().first.size() + this->dynamic_table_.back().second.size());
this->dynamic_table_.pop_back();
assert(this->dynamic_table_.size() > 0 || this->current_dynamic_table_size_ == 0);
}
//----------------------------------------------------------------//
//----------------------------------------------------------------//
void context::table_insert(const std::pair<std::string,std::string>& entry)
{
this->table_insert(std::pair<std::string,std::string>(entry));
}
//----------------------------------------------------------------//
//----------------------------------------------------------------//
void context::table_insert(std::pair<std::string,std::string>&& entry)
{
std::size_t entry_size = 32 + entry.first.size() + entry.second.size();
while ((entry_size + this->current_dynamic_table_size_) > this->max_dynamic_table_size_ && this->dynamic_table_.size() != 0)
this->table_evict();
// Entrys that are larger than max table size leave the table empty.
if ((entry_size + this->current_dynamic_table_size_) <= this->max_dynamic_table_size_)
{
this->current_dynamic_table_size_ += entry_size;
this->dynamic_table_.push_front(std::move(entry));
}
}
//----------------------------------------------------------------//
//----------------------------------------------------------------//
void encoder::encode_integer(prefix_mask prfx_mask, std::uint64_t input, std::string& output)
{
if (input < (std::uint8_t)prfx_mask)
{
output.back() |= ((std::uint8_t)prfx_mask & (std::uint8_t)input);
}
else
{
output.back() |= (std::uint8_t)prfx_mask;
input = input - (std::uint8_t)prfx_mask;
while (input >= 128)
{
output.push_back((std::uint8_t)(input % 128 + 128));
input = input / 128;
}
output.push_back((std::uint8_t)input);
}
}
//----------------------------------------------------------------//
//----------------------------------------------------------------//
void encoder::huffman_encode(std::string::const_iterator begin, std::string::const_iterator end, std::string& output)
{
// std::uint8_t bits_avail_in_current_byte = 0;
//
// for ( std::size_t current_index = output.size(); begin != end; ++begin)
// {
// std::size_t ascii_code = (std::size_t)*begin;
// std::pair<std::uint32_t, std::uint8_t> huff_code_pair = huffman_code_array[ascii_code];
// std::uint32_t msb_alligned = huff_code_pair.first << (32 - huff_code_pair.second);
// std::size_t new_bytes_required = (huff_code_pair.second > bits_avail_in_current_byte ? (std::size_t)std::ceil(static_cast<float>(huff_code_pair.second - bits_avail_in_current_byte) / 8.0 ) : 0);
// output.append(new_bytes_required, (char)0x0);
//
// for (std::size_t i = 0; i + current_index < output.size(); ++i)
// {
// output[i] = output[i] | ((msb_alligned >> ((8 * (3 - i)) + (8 - bits_avail_in_current_byte))) & 0xFF);
// std::cout << std::hex << (output[i + current_index] & 0xFF) << std::dec << std::endl;
// }
//
// if (new_bytes_required)
// bits_avail_in_current_byte = (std::uint8_t)((huff_code_pair.second - bits_avail_in_current_byte) % 8);
// else
// bits_avail_in_current_byte -= huff_code_pair.second;
//
// current_index = (bits_avail_in_current_byte == 0 ? output.size() : output.size() -1);
// }
//
// if (bits_avail_in_current_byte != 0)
// {
// output.back() = output.back() | (char)(0xFF >> (8 - bits_avail_in_current_byte));
// }
}
//----------------------------------------------------------------//
//----------------------------------------------------------------//
encoder::find_result encoder::find(const header_field& header_to_find)
{
find_result ret;
auto static_table_find_range = static_table_reverse_lookup_map.equal_range(header_to_find.name);
if (static_table_find_range.first != static_table_find_range.second)
{
ret.name_index = static_table_find_range.first->second;
for( auto it = static_table_find_range.first; ret.name_and_value_index == 0 && it != static_table_find_range.second; ++it)
{
if (header_to_find.value == this->at(it->second).second)
{
ret.name_and_value_index = it->second;
}
}
}
if (ret.name_and_value_index == 0)
{
std::size_t current_index = static_table.size() + 1;
for (auto it = this->dynamic_table_.begin(); ret.name_and_value_index == 0 && it != this->dynamic_table_.end(); ++it,++current_index)
{
if (it->first == header_to_find.name)
{
if (ret.name_index == 0)
{
ret.name_index = current_index;
}
if (it->second == header_to_find.value)
{
ret.name_and_value_index = current_index;
}
}
}
}
return ret;
};
//----------------------------------------------------------------//
//----------------------------------------------------------------//
void encoder::encode(const std::list<header_field>& headers, std::string& output)
{
// TODO: Estimate output size and reserve contiguous array in output container.
while (this->table_size_updates_.size())
{
output.push_back((char)0x20);
this->max_dynamic_table_size_ = this->table_size_updates_.front();
encode_integer(prefix_mask::five_bit, this->max_dynamic_table_size_, output);
while (this->current_dynamic_table_size_ > this->max_dynamic_table_size_)
this->table_evict();
this->table_size_updates_.pop();
}
for (std::list<header_field>::const_iterator header_itr= headers.begin(); header_itr != headers.end(); ++header_itr)
{
find_result res = this->find(*header_itr);
if (res.name_and_value_index)
{
output.push_back((char)0x80);
encode_integer(prefix_mask::seven_bit, res.name_and_value_index, output);
}
else
{
prefix_mask pfx_mask;
if (header_itr->cache == cacheability::yes)
{
pfx_mask = prefix_mask::six_bit;
output.push_back((char)0x40);
this->table_insert(std::pair<std::string,std::string>(header_itr->name, header_itr->value));
}
else if (header_itr->cache == cacheability::never)
{
pfx_mask = prefix_mask::four_bit;
output.push_back((char)0);
}
else
{
pfx_mask = prefix_mask::four_bit;
output.push_back((char)0x10);
}
if (res.name_index)
{
encode_integer(pfx_mask, res.name_index, output);
}
else
{
output.push_back((char)0x0); // no huffman.
encode_integer(prefix_mask::seven_bit, header_itr->name.size(), output);
output += header_itr->name;
}
output.push_back((char)0x0); // no huffman.
encode_integer(prefix_mask::seven_bit, header_itr->value.size(), output);
output += header_itr->value;
}
}
}
//----------------------------------------------------------------//
//----------------------------------------------------------------//
// TODO: Decide whether to deal with pos greather than input size.
std::uint64_t decoder::decode_integer(prefix_mask prfx_mask, std::string::const_iterator& itr)
{
auto a = (std::uint8_t)*itr;
std::uint64_t ret = (std::uint8_t)prfx_mask & *itr;
if (ret == (std::uint8_t)prfx_mask)
{
std::uint64_t m = 0;
do
{
++itr;
ret = ret + ((*itr & 127) * (std::uint64_t)std::pow(2,m));
m = m + 7;
}
while ((*itr & 128) == 128);
}
++itr;
return ret;
}
//----------------------------------------------------------------//
//----------------------------------------------------------------//
bool decoder::decode_string_literal(std::string::const_iterator& itr, std::string& output)
{
bool ret = true;
bool huffman_encoded = (*itr & 0x80) != 0;
std::size_t name_sz = decode_integer(prefix_mask::seven_bit, itr);
if (huffman_encoded)
{
std::string tmp(itr, itr + name_sz);
itr += name_sz;
if (tmp.size() != name_sz)
ret = false;
else
huffman_decode(tmp.begin(), tmp.end(), output);
}
else
{
output.assign(itr, itr + name_sz);
itr += name_sz;
if (output.size() != name_sz)
ret = false;
}
return ret;
}
//----------------------------------------------------------------//
//----------------------------------------------------------------//
bool decoder::decode_nvp(std::size_t table_index, cacheability cache_header, std::string::const_iterator& itr, std::list<header_field>& headers)
{
bool ret = true;
std::string n;
std::string v;
if (table_index)
{
if (table_index <= this->header_list_length())
n = this->at(table_index).first;
else
ret = false;
}
else
{
ret = this->decode_string_literal(itr, n);
}
if (ret)
{
ret = this->decode_string_literal(itr, v);
if (ret)
{
if (cache_header == cacheability::yes)
this->table_insert(std::pair<std::string,std::string>(n, v));
headers.emplace_back(std::move(n), std::move(v), cache_header);
}
}
return ret;
}
//----------------------------------------------------------------//
//----------------------------------------------------------------//
void decoder::huffman_decode(std::string::const_iterator begin, std::string::const_iterator end, std::string& output)
{
std::uint8_t bit_pos = 7;
while (begin != end)
{
char next;
if (hpack::huffman_code_tree2.lookup(begin, end, bit_pos, next))
output.push_back(next);
else
break;
}
}
//----------------------------------------------------------------//
//----------------------------------------------------------------//
bool decoder::decode(std::string::const_iterator itr, std::string::const_iterator end, std::list<header_field>& headers)
{
bool ret = true;
while (ret && itr != end)
{
if (*itr & 0x80)
{
// Indexed Header Field Representation
//
std::uint64_t table_index = decode_integer(prefix_mask::seven_bit, itr);
if (table_index && table_index <= this->header_list_length())
{
const std::pair<std::string,std::string>& p = this->at(table_index);
headers.emplace_back(p.first, p.second);
}
else
ret = false;
}
else if ((*itr & 0xC0) == 0x40)
{
// Literal Header Field with Incremental Indexing
//
std::uint64_t table_index = decode_integer(prefix_mask::six_bit, itr);
ret = this->decode_nvp(table_index, cacheability::yes, itr, headers);
}
else if ((*itr & 0xF0) == 0x0)
{
// Literal Header Field without Indexing
//
std::uint64_t table_index = decode_integer(prefix_mask::four_bit, itr);
ret = this->decode_nvp(table_index, cacheability::no, itr, headers);
}
else if ((*itr & 0xF0) == 0x10)
{
// Literal Header Field never Indexed
//
std::uint64_t table_index = decode_integer(prefix_mask::four_bit, itr);
ret = this->decode_nvp(table_index, cacheability::never, itr, headers);
}
else if ((*itr & 0xE0) == 0x20)
{
// Dynamic Table Size Update
//
std::uint64_t new_max_size = decode_integer(prefix_mask::five_bit, itr);
this->max_dynamic_table_size_ = new_max_size;
while (this->current_dynamic_table_size_ > this->max_dynamic_table_size_)
this->table_evict();
}
else
{
ret = false;
}
}
return ret;
}
//----------------------------------------------------------------//
};
}
| 74.132367
| 204
| 0.37855
|
jonathonl
|
3cc56bf3287b00c9261fbea80a9f7b9177dab509
| 10,096
|
cpp
|
C++
|
source/deepnetvideo/source/deepnetvideo.cpp
|
hyphaproject/hyphaplugins
|
b41b396392c5546e3c2802bfc34213c5da04fdf4
|
[
"MIT"
] | null | null | null |
source/deepnetvideo/source/deepnetvideo.cpp
|
hyphaproject/hyphaplugins
|
b41b396392c5546e3c2802bfc34213c5da04fdf4
|
[
"MIT"
] | 1
|
2017-02-18T10:51:07.000Z
|
2017-02-18T10:51:07.000Z
|
source/deepnetvideo/source/deepnetvideo.cpp
|
hyphaproject/hyphaplugins
|
b41b396392c5546e3c2802bfc34213c5da04fdf4
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2015-2016 Hypha
#include "hyphaplugins/deepnetvideo/deepnetvideo.h"
#include <cmath>
#include <cstdlib>
#include <exception>
#include <fstream>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <thread>
#include <vector>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include <dlib/opencv.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/opencv.hpp>
#include <Poco/ClassLibrary.h>
#include <Poco/DateTime.h>
#include <Poco/DateTimeFormatter.h>
#include <Poco/LocalDateTime.h>
#include <Poco/Timezone.h>
#include <hypha/plugin/hyphaplugin.h>
#include <hypha/utils/logger.h>
using namespace hypha::utils;
using namespace hypha::plugin;
using namespace hypha::plugin::deepnetvideo;
using namespace cv;
using namespace cv::dnn;
using namespace std;
DeepNetVideo::~DeepNetVideo() {}
/* Find best class for the blob (i. e. class with maximal probability) */
void getMaxClass(dnn::Blob &probBlob, int *classId, double *classProb) {
Mat probMat = probBlob.matRefConst().reshape(
1, 1); // reshape the blob to 1x1000 matrix
Point classNumber;
minMaxLoc(probMat, NULL, classProb, NULL, &classNumber);
*classId = classNumber.x;
}
std::vector<String> readClassNames(const char *filename = "synset_words.txt") {
std::vector<String> classNames;
std::ifstream fp(filename);
if (!fp.is_open()) {
std::cerr << "File with classes labels not found: " << filename
<< std::endl;
throw std::runtime_error("File with classes labels not found");
}
std::string name;
while (!fp.eof()) {
std::getline(fp, name);
if (name.length()) classNames.push_back(name.substr(name.find(' ') + 1));
}
fp.close();
return classNames;
}
void DeepNetVideo::doWork() {
std::this_thread::sleep_for(std::chrono::seconds(1) / fps);
try {
std::thread captureT = std::thread([this] { captureCamera(); });
if (captureT.joinable()) captureT.join();
currentImage_mutex.lock();
currentImage = captureMat;
currentImage_mutex.unlock();
} catch (cv::Exception &e) {
Logger::error(e.what());
} catch (std::exception e) {
Logger::error(e.what());
} catch (...) {
Logger::error("Something terrible happened.");
}
std::vector<std::string> classes = classify();
Logger::info("current class: ");
for (std::string className : classes) Logger::info(className);
// sendMessage(className);
}
void DeepNetVideo::captureCamera() {
if (getFilmState() == FILM) {
if (filmCounter++ >= 100) setFilmState(IDLE);
if (capture_mutex.try_lock()) {
try {
cv::Mat capt;
if (capture.isOpened()) {
// read five times to clear buffered old images
capture.read(capt);
capture.read(capt);
capture.read(capt);
capture.read(capt);
capture.read(capt);
}
if (captureMat_mutex.try_lock()) {
captureMat = capt.clone();
captureMat_mutex.unlock();
}
capture_mutex.unlock();
} catch (cv::Exception &e) {
Logger::error("Could not capture from camera");
Logger::error(e.what());
} catch (std::exception &e) {
Logger::warning("Could not capture from camera");
}
}
}
}
cv::Mat DeepNetVideo::rotateMat(cv::Mat mat) {
if (mat.rows < 1) return mat;
cv::Point2f src_center(mat.cols / 2.0F, mat.rows / 2.0F);
cv::Mat rot_mat = cv::getRotationMatrix2D(src_center, 180, 1.0);
cv::warpAffine(mat, mat, rot_mat, mat.size());
return mat;
}
cv::Mat DeepNetVideo::fillMat(cv::Mat mat) {
if (mat.rows != height)
cv::vconcat(mat, cv::Mat(height - mat.rows, mat.cols, mat.type()), mat);
if (mat.cols != width)
cv::hconcat(mat, cv::Mat(mat.rows, width - mat.cols, mat.type()), mat);
return mat;
}
void DeepNetVideo::setup() {
if (!device.empty()) {
capture.open(std::stoi(device));
capture.set(CV_CAP_PROP_FRAME_WIDTH, width);
capture.set(CV_CAP_PROP_FRAME_HEIGHT, height);
capture.set(CV_CAP_PROP_FPS, fps);
captureMat = cv::Mat(height, width, CV_8UC3);
}
filmCounter = 0;
filmState = FILM;
loadNet();
}
std::string DeepNetVideo::communicate(std::string UNUSED(message)) {
return "SUCCESS";
}
void DeepNetVideo::loadConfig(std::string json) {
boost::property_tree::ptree pt;
std::stringstream ss(json);
boost::property_tree::read_json(ss, pt);
if (pt.get_optional<int>("fps")) {
fps = pt.get<int>("fps");
}
if (pt.get_optional<int>("width")) {
width = pt.get<int>("width");
}
if (pt.get_optional<int>("height")) {
height = pt.get<int>("height");
}
if (pt.get_optional<std::string>("device")) {
device = pt.get<std::string>("device");
}
if (pt.get_optional<std::string>("modelTxt")) {
modelTxt = pt.get<std::string>("modelTxt");
}
if (pt.get_optional<std::string>("modelBin")) {
modelBin = pt.get<std::string>("modelBin");
}
if (pt.get_optional<std::string>("classNamesFile")) {
classNamesFile = pt.get<std::string>("classNamesFile");
}
}
std::string DeepNetVideo::getConfig() { return "{}"; }
HyphaPlugin *DeepNetVideo::getInstance(std::string id) {
DeepNetVideo *instance = new DeepNetVideo();
instance->setId(id);
return instance;
}
void DeepNetVideo::receiveMessage(std::string message) {
try {
boost::property_tree::ptree pt;
std::stringstream ss(message);
boost::property_tree::read_json(ss, pt);
if (pt.get_optional<bool>("run")) {
if (pt.get<bool>("run")) {
setState(FILM);
} else {
setState(IDLE);
}
}
} catch (std::exception &e) {
Logger::error(e.what());
}
}
void DeepNetVideo::loadNet() {
deserialize(this->modelBin) >> net >> labels;
snet.subnet() = net.subnet();
}
// ----------------------------------------------------------------------------------------
dlib::rectangle make_random_cropping_rect_resnet(const matrix<rgb_pixel> &img,
dlib::rand &rnd) {
// figure out what rectangle we want to crop from the image
double mins = 0.466666666, maxs = 0.875;
auto scale = mins + rnd.get_random_double() * (maxs - mins);
auto size = scale * std::min(img.nr(), img.nc());
dlib::rectangle rect(size, size);
// randomly shift the box around
point offset(rnd.get_random_32bit_number() % (img.nc() - rect.width()),
rnd.get_random_32bit_number() % (img.nr() - rect.height()));
return move_rect(rect, offset);
}
// ----------------------------------------------------------------------------------------
void randomly_crop_images(const matrix<rgb_pixel> &img,
dlib::array<matrix<rgb_pixel>> &crops,
dlib::rand &rnd, long num_crops) {
std::vector<chip_details> dets;
for (long i = 0; i < num_crops; ++i) {
auto rect = make_random_cropping_rect_resnet(img, rnd);
dets.push_back(chip_details(rect, chip_dims(227, 227)));
}
extract_image_chips(img, dets, crops);
for (auto &&img : crops) {
// Also randomly flip the image
if (rnd.get_random_double() > 0.5) img = fliplr(img);
// And then randomly adjust the colors.
apply_random_color_offset(img, rnd);
}
}
dlib::matrix<rgb_pixel> MatToMatrix(cv::Mat mat) {
dlib::matrix<rgb_pixel> result(mat.rows, mat.cols);
rgb_pixel *p;
for (int i = 0; i < mat.rows; i++) {
p = mat.ptr<rgb_pixel>(i);
for (int j = 0; j < mat.cols; j++) {
result(i, j) = p[j];
}
}
return result;
}
// ----------------------------------------------------------------------------------------
std::vector<std::string> DeepNetVideo::classify() {
std::vector<std::string> tags;
Mat cvimg = getCurrentImage();
if (cvimg.empty()) {
std::cerr << "can't get image" << std::endl;
throw std::runtime_error("can't get image");
}
// cv_image<bgr_pixel> cimg(img);
dlib::array<matrix<rgb_pixel>> images;
matrix<rgb_pixel> mimg, crop;
cv::cvtColor(cvimg, cvimg, CV_BGR2RGB);
mimg = MatToMatrix(cvimg);
const int num_crops = 8;
// Grab 16 random crops from the image. We will run all of them through the
// network and average the results.
randomly_crop_images(mimg, images, rnd, num_crops);
// p(i) == the probability the image contains object of class i.
matrix<float, 1, 1000> p =
sum_rows(dlib::mat(snet(images.begin(), images.end()))) / num_crops;
win.set_image(mimg);
// Print the 5 most probable labels
for (int k = 0; k < 1; ++k) {
unsigned long predicted_label = index_of_max(p);
cout << p(predicted_label) << ": " << labels[predicted_label] << endl;
p(predicted_label) = 0;
}
return tags;
}
cv::Mat DeepNetVideo::getCurrentImage() {
setFilmState(FILM);
cv::Mat frame;
currentImage_mutex.lock();
frame = currentImage.clone();
currentImage_mutex.unlock();
return frame;
}
DeepNetVideo::State DeepNetVideo::getState() {
State state = IDLE;
state_mutex.lock();
state = currentState;
state_mutex.unlock();
return state;
}
void DeepNetVideo::setState(State state) {
state_mutex.lock();
currentState = state;
state_mutex.unlock();
}
DeepNetVideo::State DeepNetVideo::getFilmState() {
State state = IDLE;
state_mutex.lock();
state = filmState;
state_mutex.unlock();
return state;
}
void DeepNetVideo::setFilmState(State state) {
state_mutex.lock();
if (filmState == IDLE && state == FILM) {
filmState = FILM;
if (!device.empty()) {
capture.open(std::stoi(device));
capture.set(CV_CAP_PROP_FRAME_WIDTH, width);
capture.set(CV_CAP_PROP_FRAME_HEIGHT, height);
capture.set(CV_CAP_PROP_FPS, fps);
cameras++;
}
} else if (filmState == FILM && state == IDLE) {
filmState = IDLE;
if (!device.empty()) {
capture.release();
}
cameras = 0;
}
state_mutex.unlock();
}
POCO_BEGIN_MANIFEST(HyphaPlugin)
POCO_EXPORT_CLASS(DeepNetVideo)
POCO_END_MANIFEST
| 28.280112
| 91
| 0.630349
|
hyphaproject
|
3cc5e04a4bf2135ad3f0d4602ff3053dd7b68376
| 3,533
|
cpp
|
C++
|
FallingSandSurvival/IngameUI.cpp
|
PieKing1215/FallingSandSurvival
|
04e11940b5bd6bc867e880d7dd656ab32035a241
|
[
"BSD-3-Clause"
] | 70
|
2020-06-06T16:13:41.000Z
|
2022-03-24T15:49:09.000Z
|
FallingSandSurvival/IngameUI.cpp
|
PieKing1215/FallingEverythingSurvival
|
e2c8a0761794c9603591a5670d08c07c7ffb3b90
|
[
"BSD-3-Clause"
] | 13
|
2020-05-06T23:05:41.000Z
|
2022-02-21T19:47:09.000Z
|
FallingSandSurvival/IngameUI.cpp
|
PieKing1215/FallingEverythingSurvival
|
e2c8a0761794c9603591a5670d08c07c7ffb3b90
|
[
"BSD-3-Clause"
] | 19
|
2020-09-04T02:18:16.000Z
|
2022-03-24T22:19:11.000Z
|
#include "UIs.hpp"
#include "DiscordIntegration.hpp"
#define timegm _mkgmtime
#define BUILD_WITH_EASY_PROFILER
#include <easy/profiler.h>
#include "ProfilerConfig.hpp"
int IngameUI::state = 0;
bool IngameUI::visible = false;
bool IngameUI::setup = false;
void IngameUI::Setup() {
}
void IngameUI::Draw(Game* game) {
EASY_FUNCTION(UI_PROFILER_COLOR);
if(!visible) return;
if(state == 0) {
DrawIngame(game);
} else if(state == 1) {
DrawOptions(game);
}
}
void IngameUI::DrawIngame(Game* game) {
EASY_FUNCTION(UI_PROFILER_COLOR);
if(!setup) {
Setup();
}
ImGui::SetNextWindowSize(ImVec2(400, 300));
ImGui::SetNextWindowPos(ImVec2(game->WIDTH / 2 - 200, game->HEIGHT / 2 - 250), ImGuiCond_FirstUseEver);
if(!ImGui::Begin("Pause Menu", NULL, ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse)) {
ImGui::End();
return;
}
ImGui::PushFont(ImGui::GetIO().Fonts->Fonts[1]);
ImGui::SetCursorPosX(ImGui::GetWindowWidth() / 2 - ImGui::CalcTextSize("Options").x / 2);
ImGui::Text("Options");
ImGui::PopFont();
ImGui::SetCursorPosY(ImGui::GetCursorPosY() + 10);
int mainMenuButtonsWidth = 250;
int mainMenuButtonsYOffset = 50;
ImVec2 selPos;
ImGui::SetCursorPos(ImVec2(200 - mainMenuButtonsWidth / 2, 25 + mainMenuButtonsYOffset * 1));
selPos = ImGui::GetCursorPos();
ImGui::PushFont(ImGui::GetIO().Fonts->Fonts[1]);
ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1.0f);
if(ImGui::Button("##continue", ImVec2(mainMenuButtonsWidth, 36))) {
visible = false;
}
ImGui::PopStyleVar();
ImGui::SetCursorPos(ImVec2(selPos.x + mainMenuButtonsWidth / 2 - ImGui::CalcTextSize("Continue").x / 2, selPos.y));
ImGui::Text("Continue");
ImGui::PopFont();
ImGui::SetCursorPos(ImVec2(200 - mainMenuButtonsWidth / 2, 25 + mainMenuButtonsYOffset * 2));
selPos = ImGui::GetCursorPos();
ImGui::PushFont(ImGui::GetIO().Fonts->Fonts[1]);
ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1.0f);
if(ImGui::Button("##options", ImVec2(mainMenuButtonsWidth, 36))) {
state = 1;
}
ImGui::PopStyleVar();
ImGui::SetCursorPos(ImVec2(selPos.x + mainMenuButtonsWidth / 2 - ImGui::CalcTextSize("Options").x / 2, selPos.y));
ImGui::Text("Options");
ImGui::PopFont();
ImGui::SetCursorPos(ImVec2(200 - mainMenuButtonsWidth / 2, 25 + mainMenuButtonsYOffset * 4));
selPos = ImGui::GetCursorPos();
ImGui::PushFont(ImGui::GetIO().Fonts->Fonts[1]);
ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1.0f);
if(ImGui::Button("##quit", ImVec2(mainMenuButtonsWidth, 36))) {
visible = false;
game->quitToMainMenu();
}
ImGui::PopStyleVar();
ImGui::SetCursorPos(ImVec2(selPos.x + mainMenuButtonsWidth / 2 - ImGui::CalcTextSize("Quit to Main Menu").x / 2, selPos.y));
ImGui::Text("Quit to Main Menu");
ImGui::PopFont();
ImGui::End();
}
void IngameUI::DrawOptions(Game* game) {
ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0.11f, 0.11f, 0.11f, 0.9f));
ImGui::SetNextWindowSize(ImVec2(400, 400));
if(!ImGui::Begin("Pause Menu", NULL, ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse)) {
ImGui::End();
ImGui::PopStyleColor();
return;
}
OptionsUI::Draw(game);
ImGui::End();
ImGui::PopStyleColor();
}
| 31.265487
| 165
| 0.667988
|
PieKing1215
|
3cc61b71355a32cd0cd93491fbd5e80ad54be055
| 11,005
|
cc
|
C++
|
src/common/zp_conf.cc
|
CatKang/zeppelin
|
25b329d910d55465a04959e21daa92790ed7b361
|
[
"Apache-2.0"
] | 413
|
2017-03-21T00:31:26.000Z
|
2022-03-07T12:03:25.000Z
|
src/common/zp_conf.cc
|
CatKang/zeppelin
|
25b329d910d55465a04959e21daa92790ed7b361
|
[
"Apache-2.0"
] | 21
|
2017-05-10T14:40:46.000Z
|
2018-02-03T18:19:15.000Z
|
src/common/zp_conf.cc
|
CatKang/zeppelin
|
25b329d910d55465a04959e21daa92790ed7b361
|
[
"Apache-2.0"
] | 92
|
2017-03-22T09:57:14.000Z
|
2022-02-10T01:20:57.000Z
|
#include "include/zp_conf.h"
#include "include/zp_const.h"
#include "slash/include/base_conf.h"
static int64_t BoundaryLimit(int64_t target, int64_t floor, int64_t ceil) {
target = (target < floor) ? floor : target;
target = (target > ceil) ? ceil : target;
return target;
}
ZpConf::ZpConf(const std::string& path)
: conf_adaptor_(path),
local_ip_("127.0.0.1"),
local_port_(9999),
timeout_(100),
data_path_("data"),
log_path_("log"),
trash_path_("trash"),
daemonize_(false),
pid_file_(log_path_ + "/" + kZpPidFile),
lock_file_(log_path_ + "/" + kZpLockFile),
enable_data_delete_(true),
meta_thread_num_(4),
data_thread_num_(6),
sync_recv_thread_num_(4),
sync_send_thread_num_(4),
max_background_flushes_(24),
max_background_compactions_(24),
binlog_remain_days_(kBinlogRemainMaxDay),
binlog_remain_min_count_(kBinlogRemainMinCount),
binlog_remain_max_count_(kBinlogRemainMaxCount),
db_write_buffer_size_(256 * 1024), // 256KB
db_max_write_buffer_(20 * 1024 * 1024), // 20MB
db_target_file_size_base_(256 * 1024), // 256KB
db_max_open_files_(4096),
db_block_size_(16), // 16 B
slowlog_slower_than_(-1),
stuck_offset_dist_(kMetaOffsetStuckDist), // 100KB
slowdown_delay_radio_(kSlowdownDelayRatio), // 60%
migrate_count_once_(kMetaMigrateOnceCount), // 2
floyd_check_leader_us_(15000000),
floyd_heartbeat_us_(6000000),
floyd_append_entries_size_once_(1024000),
floyd_append_entries_count_once_(128) {
pthread_rwlock_init(&rwlock_, NULL);
}
ZpConf::~ZpConf() {
pthread_rwlock_destroy(&rwlock_);
}
void ZpConf::Dump() const {
auto iter = meta_addr_.begin();
while (iter != meta_addr_.end()) {
fprintf(stderr, " Config.meta_addr : %s\n", iter->c_str());
iter++;
}
fprintf (stderr, " Config.local_ip : %s\n", local_ip_.c_str());
fprintf (stderr, " Config.local_port : %d\n", local_port_);
fprintf (stderr, " Config.data_path : %s\n", data_path_.c_str());
fprintf (stderr, " Config.log_path : %s\n", log_path_.c_str());
fprintf (stderr, " Config.trash_path : %s\n", trash_path_.c_str());
fprintf (stderr, " Config.daemonize : %s\n", daemonize_? "true":"false");
fprintf (stderr, " Config.pid_file : %s\n", pid_file_.c_str());
fprintf (stderr, " Config.lock_file : %s\n", lock_file_.c_str());
fprintf (stderr, " Config.enable_data_delete : %s\n", enable_data_delete_ ? "true":"false");
fprintf (stderr, " Config.meta_thread_num : %d\n", meta_thread_num_);
fprintf (stderr, " Config.data_thread_num : %d\n", data_thread_num_);
fprintf (stderr, " Config.sync_recv_thread_num : %d\n", sync_recv_thread_num_);
fprintf (stderr, " Config.sync_send_thread_num : %d\n", sync_send_thread_num_);
fprintf (stderr, " Config.max_background_flushes : %d\n", max_background_flushes_);
fprintf (stderr, " Config.max_background_compactions : %d\n", max_background_compactions_);
fprintf (stderr, " Config.binlog_remain_days : %d\n", binlog_remain_days_);
fprintf (stderr, " Config.binlog_remain_min_count : %d\n", binlog_remain_min_count_);
fprintf (stderr, " Config.binlog_remain_max_count : %d\n", binlog_remain_max_count_);
fprintf (stderr, " Config.db_write_buffer_size : %dKB\n", db_write_buffer_size_ / 1024);
fprintf (stderr, " Config.db_max_write_buffer : %dMB\n", db_max_write_buffer_ / 1024 / 1024);
fprintf (stderr, " Config.db_target_file_size_base : %dKB\n", db_target_file_size_base_ / 1024);
fprintf (stderr, " Config.db_max_open_files : %d\n", db_max_open_files_);
fprintf (stderr, " Config.db_block_size : %dB\n", db_block_size_);
fprintf (stderr, " Config.slowlog_slower_than : %d\n", slowlog_slower_than_);
fprintf (stderr, " Config.stuck_offset_dist : %dKB\n", stuck_offset_dist_ / 1024);
fprintf (stderr, " Config.slowdown_delay_radio : %d%%\n", slowdown_delay_radio_);
fprintf (stderr, " Config.migrate_count_once : %d\n", migrate_count_once_);
fprintf (stderr, " Config.floyd_check_leader_us : %d\n", floyd_check_leader_us_);
fprintf (stderr, " Config.floyd_heartbeat_us : %d\n", floyd_heartbeat_us_);
fprintf (stderr, " Config.floyd_append_entries_size_once_ : %d\n", floyd_append_entries_size_once_);
fprintf (stderr, " Config.floyd_append_entries_count_once_ : %d\n", floyd_append_entries_count_once_);
}
bool ZpConf::Rewrite() {
conf_adaptor_.SetConfStr("local_ip", local_ip_);
conf_adaptor_.SetConfInt("local_port", local_port_);
conf_adaptor_.SetConfStr("data_path", data_path_);
conf_adaptor_.SetConfStr("log_path", log_path_);
conf_adaptor_.SetConfStr("trash_path", trash_path_);
conf_adaptor_.SetConfBool("daemonize", daemonize_);
conf_adaptor_.SetConfStrVec("meta_addr", meta_addr_);
conf_adaptor_.SetConfBool("enable_data_delete", enable_data_delete_);
conf_adaptor_.SetConfInt("meta_thread_num", meta_thread_num_);
conf_adaptor_.SetConfInt("data_thread_num", data_thread_num_);
conf_adaptor_.SetConfInt("sync_recv_thread_num", sync_recv_thread_num_);
conf_adaptor_.SetConfInt("sync_send_thread_num", sync_send_thread_num_);
conf_adaptor_.SetConfInt("max_background_flushes", max_background_flushes_);
conf_adaptor_.SetConfInt("max_background_compactions", max_background_compactions_);
conf_adaptor_.SetConfInt("binlog_remain_days", binlog_remain_days_);
conf_adaptor_.SetConfInt("binlog_remain_min_count", binlog_remain_min_count_);
conf_adaptor_.SetConfInt("binlog_remain_max_count", binlog_remain_max_count_);
conf_adaptor_.SetConfInt("db_write_buffer_size", db_write_buffer_size_);
conf_adaptor_.SetConfInt("db_max_write_buffer", db_max_write_buffer_);
conf_adaptor_.SetConfInt("db_target_file_size_base", db_target_file_size_base_);
conf_adaptor_.SetConfInt("db_max_open_files", db_max_open_files_);
conf_adaptor_.SetConfInt("db_block_size", db_block_size_);
conf_adaptor_.SetConfInt("slowlog_slower_than", slowlog_slower_than_);
conf_adaptor_.SetConfInt("stuck_offset_dist", stuck_offset_dist_);
conf_adaptor_.SetConfInt("slowdown_delay_radio", slowdown_delay_radio_);
conf_adaptor_.SetConfInt("migrate_count_once", migrate_count_once_);
conf_adaptor_.SetConfInt("floyd_check_leader_us", floyd_check_leader_us_);
conf_adaptor_.SetConfInt("floyd_heartbeat_us", floyd_heartbeat_us_);
conf_adaptor_.SetConfInt("floyd_append_entries_size_once", floyd_append_entries_size_once_);
conf_adaptor_.SetConfInt("floyd_append_entries_count_once", floyd_append_entries_count_once_);
return conf_adaptor_.WriteBack();
}
int ZpConf::Load() {
int res = conf_adaptor_.LoadConf();
if (res != 0) {
return res;
}
bool ret = false;
ret = conf_adaptor_.GetConfStr("local_ip", &local_ip_);
ret = conf_adaptor_.GetConfInt("local_port", &local_port_);
ret = conf_adaptor_.GetConfStr("data_path", &data_path_);
ret = conf_adaptor_.GetConfStr("log_path", &log_path_);
ret = conf_adaptor_.GetConfStr("trash_path", &trash_path_);
ret = conf_adaptor_.GetConfBool("daemonize", &daemonize_);
ret = conf_adaptor_.GetConfStrVec("meta_addr", &meta_addr_);
ret = conf_adaptor_.GetConfBool("enable_data_delete", &enable_data_delete_);
ret = conf_adaptor_.GetConfInt("meta_thread_num", &meta_thread_num_);
ret = conf_adaptor_.GetConfInt("data_thread_num", &data_thread_num_);
ret = conf_adaptor_.GetConfInt("sync_recv_thread_num", &sync_recv_thread_num_);
ret = conf_adaptor_.GetConfInt("sync_send_thread_num", &sync_send_thread_num_);
ret = conf_adaptor_.GetConfInt("max_background_flushes", &max_background_flushes_);
ret = conf_adaptor_.GetConfInt("max_background_compactions", &max_background_compactions_);
ret = conf_adaptor_.GetConfInt("binlog_remain_days", &binlog_remain_days_);
ret = conf_adaptor_.GetConfInt("binlog_remain_min_count", &binlog_remain_min_count_);
ret = conf_adaptor_.GetConfInt("binlog_remain_max_count", &binlog_remain_max_count_);
ret = conf_adaptor_.GetConfInt("db_write_buffer_size", &db_write_buffer_size_);
ret = conf_adaptor_.GetConfInt("db_max_write_buffer", &db_max_write_buffer_);
ret = conf_adaptor_.GetConfInt("db_target_file_size_base", &db_target_file_size_base_);
ret = conf_adaptor_.GetConfInt("db_max_open_files", &db_max_open_files_);
ret = conf_adaptor_.GetConfInt("db_block_size", &db_block_size_);
ret = conf_adaptor_.GetConfInt("slowlog_slower_than", &slowlog_slower_than_);
ret = conf_adaptor_.GetConfInt("stuck_offset_dist", &stuck_offset_dist_);
ret = conf_adaptor_.GetConfInt("slowdown_delay_radio", &slowdown_delay_radio_);
ret = conf_adaptor_.GetConfInt("migrate_count_once", &migrate_count_once_);
ret = conf_adaptor_.GetConfInt("floyd_check_leader_us", &floyd_check_leader_us_);
ret = conf_adaptor_.GetConfInt("floyd_heartbeat_us", &floyd_heartbeat_us_);
ret = conf_adaptor_.GetConfInt("floyd_append_entries_size_once", &floyd_append_entries_size_once_);
ret = conf_adaptor_.GetConfInt("floyd_append_entries_count_once", &floyd_append_entries_count_once_);
if (data_path_.back() != '/') {
data_path_.append("/");
}
if (log_path_.back() != '/') {
log_path_.append("/");
}
if (trash_path_.back() != '/') {
trash_path_.append("/");
}
std::string lock_path = log_path_;
pid_file_ = lock_path + "pid";
lock_file_ = lock_path + "lock";
meta_thread_num_ = BoundaryLimit(meta_thread_num_, 1, 100);
data_thread_num_ = BoundaryLimit(data_thread_num_, 1, 100);
sync_recv_thread_num_ = BoundaryLimit(sync_recv_thread_num_, 1, 100);
sync_send_thread_num_ = BoundaryLimit(sync_send_thread_num_, 1, 100);
max_background_flushes_ = BoundaryLimit(max_background_flushes_, 10, 100);
max_background_compactions_ = BoundaryLimit(max_background_compactions_, 10, 100);
binlog_remain_days_ = BoundaryLimit(binlog_remain_days_, 0, 30);
binlog_remain_min_count_ = BoundaryLimit(binlog_remain_min_count_, 10, 60);
binlog_remain_max_count_ = BoundaryLimit(binlog_remain_max_count_, 10, 60);
binlog_remain_min_count_ = binlog_remain_min_count_ > binlog_remain_max_count_ ?
binlog_remain_max_count_ : binlog_remain_min_count_;
slowlog_slower_than_ = BoundaryLimit(slowlog_slower_than_, -1, 10000000);
stuck_offset_dist_ = BoundaryLimit(stuck_offset_dist_, 1, 100 * 1024 * 1024);
slowdown_delay_radio_ = BoundaryLimit(slowdown_delay_radio_, 1, 100);
migrate_count_once_ = BoundaryLimit(migrate_count_once_, 1, 100);
db_write_buffer_size_ = BoundaryLimit(db_write_buffer_size_, 4 * 1024, 10 * 1024 * 1024); // 4M ~ 10G
db_max_write_buffer_ = BoundaryLimit(db_max_write_buffer_, 1024 * 1024, 500 * 1024 * 1024); // 1G ~ 500G
db_target_file_size_base_ = BoundaryLimit(db_target_file_size_base_, 4 * 1024, 10 * 1024 * 1024); // 4M ~ 10G
db_block_size_ = BoundaryLimit(db_block_size_, 4, 1024 * 1024); // 14K ~ 1G
return ret;
}
| 54.480198
| 111
| 0.750204
|
CatKang
|
3cc97f66eafcd6fce27974d471ff9df22021f2e1
| 2,079
|
cxx
|
C++
|
examples/40-numcxx-pde/40-stationary-heat-fe.cxx
|
j-fu/numcxx
|
463ef36ee0744af5513e6b5b24342f5323be6ff0
|
[
"MIT"
] | null | null | null |
examples/40-numcxx-pde/40-stationary-heat-fe.cxx
|
j-fu/numcxx
|
463ef36ee0744af5513e6b5b24342f5323be6ff0
|
[
"MIT"
] | null | null | null |
examples/40-numcxx-pde/40-stationary-heat-fe.cxx
|
j-fu/numcxx
|
463ef36ee0744af5513e6b5b24342f5323be6ff0
|
[
"MIT"
] | null | null | null |
///
/// \example 40-stationary-heat-fe.cxx
///
/// Finite element method for stationary heat equation
///
#include <cstdio>
#include <iostream>
#include <ctime>
#include <cmath>
#include <numcxx/numcxx.hxx>
#include <numcxx/simplegrid.hxx>
#include <numcxx/fem2d.hxx>
#ifdef VTKFIG
#include "numcxx/vtkfig-simplegrid.hxx"
#endif
#include "vtkfigFrame.h"
#include "vtkfigDataSet.h"
#include "vtkfigGridView.h"
#include "vtkfigScalarView.h"
int main(void)
{
numcxx::Geometry Geometry;
Geometry.set_points({
{-2,0},
{0,0},
{2,0},
{2,2},
{0.5,2},
{0,1},
{-0.5,2},
{-2,2}
});
Geometry.set_bfaces({
{0,1},
{1,2},
{2,3},
{3,4},
{4,5},
{5,6},
{6,7},
{7,0},
{5,1},
});
Geometry.set_bfaceregions({1,1,2,3,4,4,3,2,5});
Geometry.set_regionpoints({
{-0.5,1},
{0.5,1}
});
Geometry.set_regionnumbers({1,2});
Geometry.set_regionvolumes({0.1,0.1});
numcxx::SimpleGrid grid(Geometry,"zpaAqDV");
numcxx::DArray1 bcfac(6);
numcxx::DArray1 bcval(6);
bcfac=0;
bcval=0;
bcfac(4)=fem2d::Dirichlet;
bcfac(1)=fem2d::Dirichlet;
bcval(4)=1.0;
bcval(1)=0.0;
auto nnodes=grid.npoints();
numcxx::DArray1 source(nnodes);
numcxx::DArray1 kappa(nnodes);
kappa=1;
source=0;
numcxx::DSparseMatrix SGlobal(nnodes,nnodes);
numcxx::DArray1 Rhs(nnodes);
numcxx::DArray1 Sol(nnodes);
fem2d::assemble_heat_problem(grid,bcfac,bcval,source,kappa,SGlobal, Rhs);
numcxx::DSolverUMFPACK Solver(SGlobal);
Solver.update(SGlobal);
Solver.solve(Sol,Rhs);
#ifdef VTKFIG
auto griddata=numcxx::vtkfigDataSet(grid);
griddata->SetPointScalar(Sol ,"Sol");
auto frame=vtkfig::Frame::New();
frame->SetSize(800,400);
frame->SetLayout(2,1);
auto gridview=vtkfig::GridView::New();
gridview->SetData(griddata);
frame->AddFigure(gridview,0);
auto solview=vtkfig::ScalarView::New();
solview->SetData(griddata,"Sol");
frame->AddFigure(solview,1);
frame->Interact();
#endif
}
| 17.922414
| 75
| 0.619529
|
j-fu
|
3cce0ade454ad1af19c8bdb9f4c304f18994e4aa
| 577
|
hpp
|
C++
|
src/Components/SatteliteBody.hpp
|
ananace/LD45
|
73687658323c81e563ead4e8f36afb89cbf27232
|
[
"MIT"
] | null | null | null |
src/Components/SatteliteBody.hpp
|
ananace/LD45
|
73687658323c81e563ead4e8f36afb89cbf27232
|
[
"MIT"
] | null | null | null |
src/Components/SatteliteBody.hpp
|
ananace/LD45
|
73687658323c81e563ead4e8f36afb89cbf27232
|
[
"MIT"
] | 1
|
2020-03-30T05:00:54.000Z
|
2020-03-30T05:00:54.000Z
|
#pragma once
#include <entt/entity/fwd.hpp>
namespace Components
{
struct SatteliteBody
{
entt::entity Orbiting;
float Distance, Speed;
float CurrentAngle;
SatteliteBody() : Distance{}, Speed{}, CurrentAngle{} { }
SatteliteBody(entt::entity aOrbiting, float aDistance, float aSpeed) : Orbiting(aOrbiting), Distance(aDistance), Speed(aSpeed), CurrentAngle{} { }
SatteliteBody(entt::entity aOrbiting, float aDistance, float aSpeed, float aCurrentAngle) : Orbiting(aOrbiting), Distance(aDistance), Speed(aSpeed), CurrentAngle(aCurrentAngle) { }
};
}
| 27.47619
| 184
| 0.729636
|
ananace
|
3cced1a593e29b215c4b5d63e17fbc685eba9ae6
| 528
|
cpp
|
C++
|
shared/offline_compiler/source/utilities/linux/get_path.cpp
|
raiyanla/compute-runtime
|
43433244f9d17e9c989116808757705754ddbfee
|
[
"MIT"
] | 1
|
2020-04-17T05:46:04.000Z
|
2020-04-17T05:46:04.000Z
|
shared/offline_compiler/source/utilities/linux/get_path.cpp
|
dkjiang2018/compute-runtime
|
310947e6ddefc4bb9a7a268fc1ee8639155b730c
|
[
"MIT"
] | null | null | null |
shared/offline_compiler/source/utilities/linux/get_path.cpp
|
dkjiang2018/compute-runtime
|
310947e6ddefc4bb9a7a268fc1ee8639155b730c
|
[
"MIT"
] | 1
|
2020-05-25T21:57:51.000Z
|
2020-05-25T21:57:51.000Z
|
/*
* Copyright (C) 2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include <sstream>
#include <string>
#include <sys/types.h>
#include <unistd.h>
std::string getPath() {
char exepath[128] = {0};
std::stringstream ss;
ss << "/proc/" << getpid() << "/exe";
if (readlink(ss.str().c_str(), exepath, 128) != -1) {
std::string path = std::string(exepath);
path = path.substr(0, path.find_last_of('/') + 1);
return path;
} else {
return std::string("");
}
}
| 21.12
| 58
| 0.558712
|
raiyanla
|
3cd0ed5b8d8c9e4a5324fb75f2189e190ff8ac36
| 149
|
hpp
|
C++
|
pagerank.hpp
|
gbossi/Pagerank-DOBFS
|
bfeb88e8778349dee66308a75d9acb2cfc7f57d0
|
[
"MIT"
] | 3
|
2018-11-19T02:15:40.000Z
|
2021-04-10T09:40:01.000Z
|
pagerank.hpp
|
gbossi/Pagerank-DOBFS
|
bfeb88e8778349dee66308a75d9acb2cfc7f57d0
|
[
"MIT"
] | null | null | null |
pagerank.hpp
|
gbossi/Pagerank-DOBFS
|
bfeb88e8778349dee66308a75d9acb2cfc7f57d0
|
[
"MIT"
] | 1
|
2021-09-19T02:01:03.000Z
|
2021-09-19T02:01:03.000Z
|
#ifndef _PAGERANK_HPP_
#define _PAGERANK_HPP_
#include "graph.hpp"
#include <boost/graph/page_rank.hpp>
void pagerank(Graph&, double, int);
#endif
| 16.555556
| 36
| 0.771812
|
gbossi
|
3cd1f94d974c2298039d4de584a8e42861372ace
| 546
|
cpp
|
C++
|
Data_Structures/Stacks/largest_area_hist.cpp
|
abhishekjha786/ds_algo
|
38355ca12e8ac20c4baa8baccf8ad189effaa6ae
|
[
"MIT"
] | 11
|
2020-03-20T17:24:28.000Z
|
2022-01-08T02:43:24.000Z
|
Data_Structures/Stacks/largest_area_hist.cpp
|
abhishekjha786/ds_algo
|
38355ca12e8ac20c4baa8baccf8ad189effaa6ae
|
[
"MIT"
] | 1
|
2021-07-25T11:24:46.000Z
|
2021-07-25T12:09:25.000Z
|
Data_Structures/Stacks/largest_area_hist.cpp
|
abhishekjha786/ds_algo
|
38355ca12e8ac20c4baa8baccf8ad189effaa6ae
|
[
"MIT"
] | 4
|
2020-03-20T17:24:36.000Z
|
2021-12-07T19:22:59.000Z
|
// Given an array of integers A of size N. A represents a histogram i.e A[i] denotes height of
// the ith histogram’s bar. Width of each bar is 1.
// Largest Rectangle in Histogram: Example 1
// Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].
//
// | | | | | |
// | | | | |
// | | |
// | |
// | |
// |
// Largest Rectangle in Histogram: Example 2
// The largest rectangle is shown in the shaded area, which has area = 10 unit.
// Find the area of largest rectangle in the histogram.
| 24.818182
| 94
| 0.611722
|
abhishekjha786
|
3cd35c24450e778221b75c946dbf8b72a7134df7
| 1,023
|
cpp
|
C++
|
Outer.Tlibc/puts.cpp
|
lusores/ABRViewer
|
64d3172651a904908589fc91276366ef3ef0489e
|
[
"MIT"
] | 15
|
2017-05-15T15:52:24.000Z
|
2022-03-23T06:48:48.000Z
|
Outer.Tlibc/puts.cpp
|
lusores/ABRViewer
|
64d3172651a904908589fc91276366ef3ef0489e
|
[
"MIT"
] | null | null | null |
Outer.Tlibc/puts.cpp
|
lusores/ABRViewer
|
64d3172651a904908589fc91276366ef3ef0489e
|
[
"MIT"
] | 4
|
2017-09-07T10:55:36.000Z
|
2021-01-29T08:51:01.000Z
|
// puts.cpp
// based on:
// LIBCTINY - Matt Pietrek 2001
// MSDN Magazine, January 2001
// 08/12/06 (mv)
#include <windows.h>
#include <stdio.h>
#include "libct.h"
EXTERN_C int puts(const char *s)
{
//DWORD cbWritten;
//HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
int bw = fwrite(s, lstrlenA(s), 1, stdout);
bw += fwrite("\n", 1, 1, stdout);
return bw;
//WriteFile(hStdOut, s, lstrlenA(s)*sizeof(char), &cbWritten, 0);
//WriteFile(hStdOut, "\r\n", 2, &cbWritten, 0);
//return (int)(cbWritten ? cbWritten : EOF);
}
EXTERN_C int _putws(const wchar_t *s)
{
//DWORD bw;
//HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
// _putws converts unicode to ascii before writing to stdout!
char bfr[1024];
WideCharToMultiByte(CP_ACP, 0, s, -1, bfr, sizeof(bfr), 0, 0);
return puts(bfr);
//WriteFile(hStdOut, s, lstrlenW(s)*sizeof(wchar_t), &bw, 0);
//WriteFile(hStdOut, L"\r\n", 2*sizeof(wchar_t), &bw, 0);
//return (int)(bw ? bw : EOF);
}
| 23.25
| 70
| 0.621701
|
lusores
|
3cd65db0773149765563238fdcc2b5d83f2573f5
| 1,186
|
hpp
|
C++
|
src/io/ValueReader.hpp
|
spraetor/amdis2
|
53c45c81a65752a8fafbb54f9ae6724a86639dcd
|
[
"MIT"
] | 2
|
2018-07-04T16:44:04.000Z
|
2021-01-03T07:26:27.000Z
|
src/io/ValueReader.hpp
|
spraetor/amdis2
|
53c45c81a65752a8fafbb54f9ae6724a86639dcd
|
[
"MIT"
] | null | null | null |
src/io/ValueReader.hpp
|
spraetor/amdis2
|
53c45c81a65752a8fafbb54f9ae6724a86639dcd
|
[
"MIT"
] | null | null | null |
#pragma once
#include <cstring>
#include "DOFVector.hpp"
#include "Mesh.hpp"
namespace AMDiS
{
namespace io
{
/** \ingroup Input
*
* \brief
* Namespace of methods which read a value file in AMDiS format and copies
* the data to a DOF vector.
*/
namespace ValueReader
{
template<typename Container>
void readValue(std::string /*filename*/,
Mesh* /*mesh*/,
Container& /*vec*/,
MacroInfo* /*macroFileInfo*/)
{
ERROR_EXIT("ValueReader not implemented for this container type!\n");
}
/// Copies the values of a value file to a DOF vector.
void readValue(std::string filename,
Mesh* mesh,
DOFVector<double>* dofVector,
MacroInfo* macroFileInfo);
inline void readValue(std::string filename,
Mesh* mesh,
DOFVector<double>& dofVector,
MacroInfo* macroFileInfo)
{
readValue(filename, mesh, &dofVector, macroFileInfo);
}
} // end namespace ValueReader
}
} // end namespace io, AMDiS
| 24.708333
| 78
| 0.546374
|
spraetor
|
3cde63f230a04be8f62f33b544448e08f254b472
| 996
|
cpp
|
C++
|
925-long-pressed-name/925-long-pressed-name.cpp
|
shreydevep/DSA
|
688af414c1fada1b82a4b4e9506747352007c894
|
[
"MIT"
] | null | null | null |
925-long-pressed-name/925-long-pressed-name.cpp
|
shreydevep/DSA
|
688af414c1fada1b82a4b4e9506747352007c894
|
[
"MIT"
] | null | null | null |
925-long-pressed-name/925-long-pressed-name.cpp
|
shreydevep/DSA
|
688af414c1fada1b82a4b4e9506747352007c894
|
[
"MIT"
] | null | null | null |
class Solution {
public:
vector<pair<char,int>> compress(string &s){
vector<pair<char,int>> res;
int curr = 0;
int i = 0;
while(i < s.length()){
int cnt = 0;
while(i < s.length() && i >= curr && s[curr] == s[i]){
i++;
cnt++;
}
res.push_back({s[curr],cnt});
curr = i;
}
return res;
}
bool isLongPressedName(string name, string typed) {
auto name_new = compress(name);
auto typed_new = compress(typed);
if(name_new.size() != typed_new.size()) return false;
for(int i=0;i<name_new.size();++i){
if(name_new[i].first == typed_new[i].first){
if(name_new[i].second > typed_new[i].second){
return false;
}
}
else{
return false;
}
}
return true;
}
};
| 26.918919
| 66
| 0.420683
|
shreydevep
|
c9e530ef0c6abc1ee26d229f30a47cd02010ea87
| 1,315
|
cpp
|
C++
|
core/src/Buffer.cpp
|
marlinprotocol/OpenWeaver
|
7a8c668cccc933d652fabe8a141e702b8a0fd066
|
[
"MIT"
] | 60
|
2020-07-01T17:37:34.000Z
|
2022-02-16T03:56:55.000Z
|
core/src/Buffer.cpp
|
marlinpro/openweaver
|
0aca30fbda3121a8e507f48a52b718b5664a5bbc
|
[
"MIT"
] | 5
|
2020-10-12T05:17:49.000Z
|
2021-05-25T15:47:01.000Z
|
core/src/Buffer.cpp
|
marlinpro/openweaver
|
0aca30fbda3121a8e507f48a52b718b5664a5bbc
|
[
"MIT"
] | 18
|
2020-07-01T17:43:18.000Z
|
2022-01-09T14:29:08.000Z
|
#include "marlin/core/Buffer.hpp"
#include "marlin/core/Endian.hpp"
#include <cstring>
#include <cassert>
#include <algorithm>
namespace marlin {
namespace core {
Buffer::Buffer(size_t size) :
BaseBuffer(new uint8_t[size], size) {}
Buffer::Buffer(std::initializer_list<uint8_t> il, size_t size) :
BaseBuffer(new uint8_t[size], size) {
assert(il.size() <= size);
std::copy(il.begin(), il.end(), buf);
}
Buffer::Buffer(uint8_t *buf, size_t size) :
BaseBuffer(buf, size) {}
Buffer::Buffer(Buffer &&b) noexcept :
BaseBuffer(static_cast<BaseBuffer&&>(std::move(b))) {
b.buf = nullptr;
b.capacity = 0;
b.start_index = 0;
b.end_index = 0;
}
Buffer &Buffer::operator=(Buffer &&b) noexcept {
// Destroy old
delete[] buf;
// Assign from new
buf = b.buf;
capacity = b.capacity;
start_index = b.start_index;
end_index = b.end_index;
b.buf = nullptr;
b.capacity = 0;
b.start_index = 0;
b.end_index = 0;
return *this;
}
Buffer::~Buffer() {
delete[] buf;
}
WeakBuffer Buffer::payload_buffer() & {
return *this;
}
WeakBuffer const Buffer::payload_buffer() const& {
return *this;
}
Buffer Buffer::payload_buffer() && {
return std::move(*this);
}
uint8_t* Buffer::payload() {
return data();
}
uint8_t const* Buffer::payload() const {
return data();
}
} // namespace core
} // namespace marlin
| 17.77027
| 64
| 0.676806
|
marlinprotocol
|
c9e575ea04e3456f55c807006ae051c5563336a5
| 913
|
cpp
|
C++
|
tests/fixtures.cpp
|
quotekio/quotek-ig
|
df27a3a5c7295f8652482b54d20c2f7462cbdad8
|
[
"BSD-3-Clause"
] | 1
|
2019-04-27T08:20:15.000Z
|
2019-04-27T08:20:15.000Z
|
tests/fixtures.cpp
|
quotekio/quotek-ig
|
df27a3a5c7295f8652482b54d20c2f7462cbdad8
|
[
"BSD-3-Clause"
] | null | null | null |
tests/fixtures.cpp
|
quotekio/quotek-ig
|
df27a3a5c7295f8652482b54d20c2f7462cbdad8
|
[
"BSD-3-Clause"
] | null | null | null |
#include "fixtures.hpp"
igConnector* get_igconnector(string broker_params) {
return new igConnector(broker_params, false, false, "poll");
}
igConnector* get_igconnector_connected_pollmode(string broker_params) {
igConnector* c = new igConnector(broker_params, false, false, "poll");
c->connect();
return c;
}
igConnector* get_igconnector_connected_pushmode(string broker_params, std::vector<std::string> ilist) {
igConnector* c = new igConnector(broker_params, false, false, "push");
c->setIndicesList(ilist);
c->connect();
return c;
}
igConnector* get_igconnector_connected_logging(string broker_params) {
igConnector* c = new igConnector(broker_params, true, false, "pull");
c->connect();
return c;
}
igConnector* get_igconnector_connected_profiling(string broker_params) {
igConnector* c = new igConnector(broker_params, false, true, "pull");
c->connect();
return c;
}
| 29.451613
| 103
| 0.743702
|
quotekio
|
c9e90f4638a387a1a8b0c70f4d25ad0e598e5754
| 2,022
|
hpp
|
C++
|
libs/muddle/internal/routing_message.hpp
|
devjsc/ledger
|
5681480faf6e2aeee577f149c17745d6ab4d4ab3
|
[
"Apache-2.0"
] | 1
|
2019-09-11T09:46:04.000Z
|
2019-09-11T09:46:04.000Z
|
libs/muddle/internal/routing_message.hpp
|
devjsc/ledger
|
5681480faf6e2aeee577f149c17745d6ab4d4ab3
|
[
"Apache-2.0"
] | null | null | null |
libs/muddle/internal/routing_message.hpp
|
devjsc/ledger
|
5681480faf6e2aeee577f149c17745d6ab4d4ab3
|
[
"Apache-2.0"
] | 1
|
2019-09-19T12:38:46.000Z
|
2019-09-19T12:38:46.000Z
|
#pragma once
//------------------------------------------------------------------------------
//
// Copyright 2018-2019 Fetch.AI Limited
//
// 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 "core/serializers/map_interface.hpp"
#include <cstdint>
namespace fetch {
namespace muddle {
struct RoutingMessage
{
enum class Type
{
PING = 0,
PONG,
ROUTING_REQUEST,
ROUTING_ACCEPTED,
DISCONNECT_REQUEST,
MAX_NUM_TYPES
};
Type type{Type::PING};
};
} // namespace muddle
namespace serializers {
template <typename D>
struct MapSerializer<muddle::RoutingMessage, D>
{
public:
using Type = muddle::RoutingMessage;
using DriverType = D;
using EnumType = uint64_t;
static const uint8_t TYPE = 1;
template <typename T>
static void Serialize(T &map_constructor, Type const &msg)
{
auto map = map_constructor(1);
map.Append(TYPE, static_cast<EnumType>(msg.type));
}
template <typename T>
static void Deserialize(T &map, Type &msg)
{
static constexpr auto MAX_TYPE_VALUE = static_cast<EnumType>(Type::Type::MAX_NUM_TYPES);
EnumType raw_type{0};
map.ExpectKeyGetValue(TYPE, raw_type);
// validate the type enum
if (raw_type >= MAX_TYPE_VALUE)
{
throw std::runtime_error("Invalid type value");
}
msg.type = static_cast<Type::Type>(raw_type);
}
};
} // namespace serializers
} // namespace fetch
| 24.071429
| 92
| 0.637982
|
devjsc
|
c9ea29fbc34909304d6ef9fd554c3785101d4a3d
| 17,753
|
cpp
|
C++
|
SampleFramework12/v1.02/Graphics/Sampling.cpp
|
BalazsJako/DXRPathTracer
|
948693d73c7f9474d98482e99e85416750b29286
|
[
"MIT"
] | 456
|
2018-10-29T03:51:23.000Z
|
2022-03-21T02:26:20.000Z
|
SampleFramework12/v1.02/Graphics/Sampling.cpp
|
BalazsJako/DXRPathTracer
|
948693d73c7f9474d98482e99e85416750b29286
|
[
"MIT"
] | 8
|
2018-10-31T05:31:19.000Z
|
2020-03-31T21:00:27.000Z
|
SampleFramework12/v1.02/Graphics/Sampling.cpp
|
BalazsJako/DXRPathTracer
|
948693d73c7f9474d98482e99e85416750b29286
|
[
"MIT"
] | 48
|
2018-10-29T05:36:41.000Z
|
2022-02-10T23:42:25.000Z
|
//=================================================================================================
//
// MJP's DX12 Sample Framework
// http://mynameismjp.wordpress.com/
//
// All code licensed under the MIT license
//
//=================================================================================================
#include "PCH.h"
#include "Sampling.h"
namespace SampleFramework12
{
#define RadicalInverse_(base) \
{ \
const float radical = 1.0f / float(base); \
uint64 value = 0; \
float factor = 1.0f; \
while(sampleIdx) { \
uint64 next = sampleIdx / base; \
uint64 digit = sampleIdx - next * base; \
value = value * base + digit; \
factor *= radical; \
sampleIdx = next; \
} \
inverse = float(value) * factor; \
}
static const float OneMinusEpsilon = 0.9999999403953552f;
float RadicalInverseFast(uint64 baseIdx, uint64 sampleIdx)
{
Assert_(baseIdx < 64);
float inverse = 0.0f;
switch (baseIdx)
{
case 0: RadicalInverse_(2); break;
case 1: RadicalInverse_(3); break;
case 2: RadicalInverse_(5); break;
case 3: RadicalInverse_(7); break;
case 4: RadicalInverse_(11); break;
case 5: RadicalInverse_(13); break;
case 6: RadicalInverse_(17); break;
case 7: RadicalInverse_(19); break;
case 8: RadicalInverse_(23); break;
case 9: RadicalInverse_(29); break;
case 10: RadicalInverse_(31); break;
case 11: RadicalInverse_(37); break;
case 12: RadicalInverse_(41); break;
case 13: RadicalInverse_(43); break;
case 14: RadicalInverse_(47); break;
case 15: RadicalInverse_(53); break;
case 16: RadicalInverse_(59); break;
case 17: RadicalInverse_(61); break;
case 18: RadicalInverse_(67); break;
case 19: RadicalInverse_(71); break;
case 20: RadicalInverse_(73); break;
case 21: RadicalInverse_(79); break;
case 22: RadicalInverse_(83); break;
case 23: RadicalInverse_(89); break;
case 24: RadicalInverse_(97); break;
case 25: RadicalInverse_(101); break;
case 26: RadicalInverse_(103); break;
case 27: RadicalInverse_(107); break;
case 28: RadicalInverse_(109); break;
case 29: RadicalInverse_(113); break;
case 30: RadicalInverse_(127); break;
case 31: RadicalInverse_(131); break;
case 32: RadicalInverse_(137); break;
case 33: RadicalInverse_(139); break;
case 34: RadicalInverse_(149); break;
case 35: RadicalInverse_(151); break;
case 36: RadicalInverse_(157); break;
case 37: RadicalInverse_(163); break;
case 38: RadicalInverse_(167); break;
case 39: RadicalInverse_(173); break;
case 40: RadicalInverse_(179); break;
case 41: RadicalInverse_(181); break;
case 42: RadicalInverse_(191); break;
case 43: RadicalInverse_(193); break;
case 44: RadicalInverse_(197); break;
case 45: RadicalInverse_(199); break;
case 46: RadicalInverse_(211); break;
case 47: RadicalInverse_(223); break;
case 48: RadicalInverse_(227); break;
case 49: RadicalInverse_(229); break;
case 50: RadicalInverse_(233); break;
case 51: RadicalInverse_(239); break;
case 52: RadicalInverse_(241); break;
case 53: RadicalInverse_(251); break;
case 54: RadicalInverse_(257); break;
case 55: RadicalInverse_(263); break;
case 56: RadicalInverse_(269); break;
case 57: RadicalInverse_(271); break;
case 58: RadicalInverse_(277); break;
case 59: RadicalInverse_(281); break;
case 60: RadicalInverse_(283); break;
case 61: RadicalInverse_(293); break;
case 62: RadicalInverse_(307); break;
case 63: RadicalInverse_(311); break;
}
return std::min(inverse, OneMinusEpsilon);
}
// Maps a value inside the square [0,1]x[0,1] to a value in a disk of radius 1 using concentric squares.
// This mapping preserves area, bi continuity, and minimizes deformation.
// Based off the algorithm "A Low Distortion Map Between Disk and Square" by Peter Shirley and
// Kenneth Chiu. Also includes polygon morphing modification from "CryEngine3 Graphics Gems"
// by Tiago Sousa
Float2 SquareToConcentricDiskMapping(float x, float y, float numSides, float polygonAmount)
{
float phi, r;
// -- (a,b) is now on [-1,1]ˆ2
float a = 2.0f * x - 1.0f;
float b = 2.0f * y - 1.0f;
if(a > -b) // region 1 or 2
{
if(a > b) // region 1, also |a| > |b|
{
r = a;
phi = (Pi / 4.0f) * (b / a);
}
else // region 2, also |b| > |a|
{
r = b;
phi = (Pi / 4.0f) * (2.0f - (a / b));
}
}
else // region 3 or 4
{
if(a < b) // region 3, also |a| >= |b|, a != 0
{
r = -a;
phi = (Pi / 4.0f) * (4.0f + (b / a));
}
else // region 4, |b| >= |a|, but a==0 and b==0 could occur.
{
r = -b;
if(b != 0)
phi = (Pi / 4.0f) * (6.0f - (a / b));
else
phi = 0;
}
}
const float N = numSides;
float polyModifier = std::cos(Pi / N) / std::cos(phi - (Pi2 / N) * std::floor((N * phi + Pi) / Pi2));
r *= Lerp(1.0f, polyModifier, polygonAmount);
Float2 result;
result.x = r * std::cos(phi);
result.y = r * std::sin(phi);
return result;
}
// Maps a value inside the square [0,1]x[0,1] to a value in a disk of radius 1 using concentric squares.
// This mapping preserves area, bi continuity, and minimizes deformation.
// Based off the algorithm "A Low Distortion Map Between Disk and Square" by Peter Shirley and
// Kenneth Chiu.
Float2 SquareToConcentricDiskMapping(float x, float y)
{
float phi = 0.0f;
float r = 0.0f;
// -- (a,b) is now on [-1,1]ˆ2
float a = 2.0f * x - 1.0f;
float b = 2.0f * y - 1.0f;
if(a > -b) // region 1 or 2
{
if(a > b) // region 1, also |a| > |b|
{
r = a;
phi = (Pi / 4.0f) * (b / a);
}
else // region 2, also |b| > |a|
{
r = b;
phi = (Pi / 4.0f) * (2.0f - (a / b));
}
}
else // region 3 or 4
{
if(a < b) // region 3, also |a| >= |b|, a != 0
{
r = -a;
phi = (Pi / 4.0f) * (4.0f + (b / a));
}
else // region 4, |b| >= |a|, but a==0 and b==0 could occur.
{
r = -b;
if(b != 0)
phi = (Pi / 4.0f) * (6.0f - (a / b));
else
phi = 0;
}
}
Float2 result;
result.x = r * std::cos(phi);
result.y = r * std::sin(phi);
return result;
}
// Returns a random direction for sampling a GGX distribution.
// Does everything in world space.
Float3 SampleDirectionGGX(const Float3& v, const Float3& n, float roughness, const Float3x3& tangentToWorld, float u1, float u2)
{
float theta = std::atan2(roughness * std::sqrt(u1), std::sqrt(1 - u1));
float phi = 2 * Pi * u2;
Float3 h;
h.x = std::sin(theta) * std::cos(phi);
h.y = std::sin(theta) * std::sin(phi);
h.z = std::cos(theta);
h = Float3::Normalize(Float3::Transform(h, tangentToWorld));
float hDotV = Float3::Dot(h, v);
Float3 sampleDir = 2.0f * hDotV * h - v;
return Float3::Normalize(sampleDir);
}
// Returns a point inside of a unit sphere
Float3 SampleSphere(float x1, float x2, float x3, float u1)
{
Float3 xyz = Float3(x1, x2, x3) * 2.0f - 1.0f;
float scale = std::pow(u1, 1.0f / 3.0f) / Float3::Length(xyz);
return xyz * scale;
}
// Returns a random direction on the unit sphere
Float3 SampleDirectionSphere(float u1, float u2)
{
float z = u1 * 2.0f - 1.0f;
float r = std::sqrt(std::max(0.0f, 1.0f - z * z));
float phi = 2 * Pi * u2;
float x = r * std::cos(phi);
float y = r * std::sin(phi);
return Float3(x, y, z);
}
// Returns a random direction on the hemisphere around z = 1
Float3 SampleDirectionHemisphere(float u1, float u2)
{
float z = u1;
float r = std::sqrt(std::max(0.0f, 1.0f - z * z));
float phi = 2 * Pi * u2;
float x = r * std::cos(phi);
float y = r * std::sin(phi);
return Float3(x, y, z);
}
// Returns a random cosine-weighted direction on the hemisphere around z = 1
Float3 SampleDirectionCosineHemisphere(float u1, float u2)
{
Float2 uv = SquareToConcentricDiskMapping(u1, u2);
float u = uv.x;
float v = uv.y;
// Project samples on the disk to the hemisphere to get a
// cosine weighted distribution
Float3 dir;
float r = u * u + v * v;
dir.x = u;
dir.y = v;
dir.z = std::sqrt(std::max(0.0f, 1.0f - r));
return dir;
}
// Returns a random direction from within a cone with angle == theta
Float3 SampleDirectionCone(float u1, float u2, float cosThetaMax)
{
float cosTheta = (1.0f - u1) + u1 * cosThetaMax;
float sinTheta = std::sqrt(1.0f - cosTheta * cosTheta);
float phi = u2 * 2.0f * Pi;
return Float3(std::cos(phi) * sinTheta, std::sin(phi) * sinTheta, cosTheta);
}
// Returns a direction that samples a rectangular area light
Float3 SampleDirectionRectangularLight(float u1, float u2, const Float3& sourcePos,
const Float2& lightSize, const Float3& lightPos,
const Quaternion lightOrientation, float& distanceToLight)
{
float x = u1 - 0.5f;
float y = u2 - 0.5f;
Float3x3 lightBasis = lightOrientation.ToFloat3x3();
Float3 lightBasisX = lightBasis.Right();
Float3 lightBasisY = lightBasis.Up();
Float3 lightBasisZ = lightBasis.Forward();
// Pick random sample point
Float3 samplePos = lightPos +
lightBasisX * x * lightSize.x +
lightBasisY * y * lightSize.y;
Float3 sampleDir = samplePos - sourcePos;
distanceToLight = Float3::Length(sampleDir);
if(distanceToLight > 0.0f)
sampleDir /= distanceToLight;
return sampleDir;
}
// Returns the PDF for a particular GGX sample
float SampleDirectionGGX_PDF(const Float3& n, const Float3& h, const Float3& v, float roughness)
{
float nDotH = Saturate(Float3::Dot(n, h));
float hDotV = Saturate(Float3::Dot(h, v));
float m2 = roughness * roughness;
float d = m2 / (Pi * Square(nDotH * nDotH * (m2 - 1) + 1));
float pM = d * nDotH;
return pM / (4 * hDotV);
}
// Returns the (constant) PDF of sampling uniform directions on the unit sphere
float SampleDirectionSphere_PDF()
{
return 1.0f / (Pi * 4.0f);
}
// Returns the (constant) PDF of sampling uniform directions on a unit hemisphere
float SampleDirectionHemisphere_PDF()
{
return 1.0f / (Pi * 2.0f);
}
// Returns the PDF of of a single sample on a cosine-weighted hemisphere
float SampleDirectionCosineHemisphere_PDF(float cosTheta)
{
return cosTheta / Pi;
}
// Returns the PDF of of a single sample on a cosine-weighted hemisphere
float SampleDirectionCosineHemisphere_PDF(const Float3& normal, const Float3& sampleDir)
{
return Saturate(Float3::Dot(normal, sampleDir)) / Pi;
}
// Returns the PDF of of a single uniform sample within a cone
float SampleDirectionCone_PDF(float cosThetaMax)
{
return 1.0f / (2.0f * Pi * (1.0f - cosThetaMax));
}
// Returns the PDF of of a single sample on a rectangular area light
float SampleDirectionRectangularLight_PDF(const Float2& lightSize, const Float3& sampleDir,
const Quaternion lightOrientation, float distanceToLight)
{
Float3 lightBasisZ = Float3::Transform(Float3(0.0f, 0.0f, -1.0f), lightOrientation);
float areaNDotL = Saturate(Float3::Dot(sampleDir, lightBasisZ));
return (distanceToLight * distanceToLight) / (areaNDotL * lightSize.x * lightSize.y);
}
// Computes a radical inverse with base 2 using crazy bit-twiddling from "Hacker's Delight"
float RadicalInverseBase2(uint32 bits)
{
bits = (bits << 16u) | (bits >> 16u);
bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);
bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);
bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);
bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);
return float(bits) * 2.3283064365386963e-10f; // / 0x100000000
}
// Returns a single 2D point in a Hammersley sequence of length "numSamples", using base 1 and base 2
Float2 Hammersley2D(uint64 sampleIdx, uint64 numSamples)
{
return Float2(float(sampleIdx) / float(numSamples), RadicalInverseBase2(uint32(sampleIdx)));
}
static uint32 CMJPermute(uint32 i, uint32 l, uint32 p)
{
uint32 w = l - 1;
w |= w >> 1;
w |= w >> 2;
w |= w >> 4;
w |= w >> 8;
w |= w >> 16;
do
{
i ^= p; i *= 0xe170893d;
i ^= p >> 16;
i ^= (i & w) >> 4;
i ^= p >> 8; i *= 0x0929eb3f;
i ^= p >> 23;
i ^= (i & w) >> 1; i *= 1 | p >> 27;
i *= 0x6935fa69;
i ^= (i & w) >> 11; i *= 0x74dcb303;
i ^= (i & w) >> 2; i *= 0x9e501cc3;
i ^= (i & w) >> 2; i *= 0xc860a3df;
i &= w;
i ^= i >> 5;
}
while (i >= l);
return (i + p) % l;
}
static float CMJRandFloat(uint32 i, uint32 p)
{
i ^= p;
i ^= i >> 17;
i ^= i >> 10; i *= 0xb36534e5;
i ^= i >> 12;
i ^= i >> 21; i *= 0x93fc4795;
i ^= 0xdf6e307f;
i ^= i >> 17; i *= 1 | p >> 18;
return i * (1.0f / 4294967808.0f);
}
// Returns a 2D sample from a particular pattern using correlated multi-jittered sampling [Kensler 2013]
Float2 SampleCMJ2D(uint32 sampleIdx, uint32 numSamplesX, uint32 numSamplesY, uint32 pattern)
{
uint32 N = numSamplesX * numSamplesY;
sampleIdx = CMJPermute(sampleIdx, N, pattern * 0x51633e2d);
uint32 sx = CMJPermute(sampleIdx % numSamplesX, numSamplesX, pattern * 0x68bc21eb);
uint32 sy = CMJPermute(sampleIdx / numSamplesX, numSamplesY, pattern * 0x02e5be93);
float jx = CMJRandFloat(sampleIdx, pattern * 0x967a889b);
float jy = CMJRandFloat(sampleIdx, pattern * 0x368cc8b7);
return Float2((sx + (sy + jx) / numSamplesY) / numSamplesX, (sampleIdx + jy) / N);
}
void GenerateRandomSamples2D(Float2* samples, uint64 numSamples, Random& randomGenerator)
{
for(uint64 i = 0; i < numSamples; ++i)
samples[i] = randomGenerator.RandomFloat2();
}
void GenerateStratifiedSamples2D(Float2* samples, uint64 numSamplesX, uint64 numSamplesY, Random& randomGenerator)
{
const Float2 delta = Float2(1.0f / numSamplesX, 1.0f / numSamplesY);
uint64 sampleIdx = 0;
for(uint64 y = 0; y < numSamplesY; ++y)
{
for(uint64 x = 0; x < numSamplesX; ++x)
{
Float2& currSample = samples[sampleIdx];
currSample = Float2(float(x), float(y)) + randomGenerator.RandomFloat2();
currSample *= delta;
currSample = Float2::Clamp(currSample, 0.0f, OneMinusEpsilon);
++sampleIdx;
}
}
}
void GenerateGridSamples2D(Float2* samples, uint64 numSamplesX, uint64 numSamplesY)
{
const Float2 delta = Float2(1.0f / numSamplesX, 1.0f / numSamplesY);
uint64 sampleIdx = 0;
for(uint64 y = 0; y < numSamplesY; ++y)
{
for(uint64 x = 0; x < numSamplesX; ++x)
{
Float2& currSample = samples[sampleIdx];
currSample = Float2(float(x), float(y));
currSample *= delta;
++sampleIdx;
}
}
}
// Generates hammersley using base 1 and 2
void GenerateHammersleySamples2D(Float2* samples, uint64 numSamples)
{
for(uint64 i = 0; i < numSamples; ++i)
samples[i] = Hammersley2D(i, numSamples);
}
// Generates hammersley using arbitrary bases
void GenerateHammersleySamples2D(Float2* samples, uint64 numSamples, uint64 dimIdx)
{
if(dimIdx == 0)
{
GenerateHammersleySamples2D(samples, numSamples);
}
else
{
uint64 baseIdx0 = dimIdx * 2 - 1;
uint64 baseIdx1 = baseIdx0 + 1;
for(uint64 i = 0; i < numSamples; ++i)
samples[i] = Float2(RadicalInverseFast(baseIdx0, i), RadicalInverseFast(baseIdx1, i));
}
}
void GenerateLatinHypercubeSamples2D(Float2* samples, uint64 numSamples, Random& rng)
{
// Generate LHS samples along diagonal
const Float2 delta = Float2(1.0f / numSamples, 1.0f / numSamples);
for(uint64 i = 0; i < numSamples; ++i)
{
Float2 currSample = Float2(float(i)) + rng.RandomFloat2();
currSample *= delta;
samples[i] = Float2::Clamp(currSample, 0.0f, OneMinusEpsilon);
}
// Permute LHS samples in each dimension
float* samples1D = reinterpret_cast<float*>(samples);
const uint64 numDims = 2;
for(uint64 i = 0; i < numDims; ++i)
{
for(uint64 j = 0; j < numSamples; ++j)
{
uint64 other = j + (rng.RandomUint() % (numSamples - j));
Swap(samples1D[numDims * j + i], samples1D[numDims * other + i]);
}
}
}
void GenerateCMJSamples2D(Float2* samples, uint64 numSamplesX, uint64 numSamplesY, uint32 pattern)
{
const uint64 numSamples = numSamplesX * numSamplesY;
for(uint64 i = 0; i < numSamples; ++i)
samples[i] = SampleCMJ2D(int32(i), int32(numSamplesX), int32(numSamplesY), int32(pattern));
}
}
| 33.559546
| 128
| 0.581198
|
BalazsJako
|
c9eaf4debea92386c086cef9890988a1e15e5b2a
| 1,859
|
hpp
|
C++
|
include/bptree/internal/map_traits.hpp
|
jason2506/bptree
|
388156024d4df32cc88c188e5801b1b460be083d
|
[
"MIT"
] | null | null | null |
include/bptree/internal/map_traits.hpp
|
jason2506/bptree
|
388156024d4df32cc88c188e5801b1b460be083d
|
[
"MIT"
] | null | null | null |
include/bptree/internal/map_traits.hpp
|
jason2506/bptree
|
388156024d4df32cc88c188e5801b1b460be083d
|
[
"MIT"
] | null | null | null |
/************************************************
* map_traits.hpp
* bptree
*
* Copyright (c) 2017, Chi-En Wu
* Distributed under MIT License
************************************************/
#ifndef BPTREE_INTERNAL_MAP_TRAITS_HPP_
#define BPTREE_INTERNAL_MAP_TRAITS_HPP_
#include <functional>
#include <utility>
namespace bptree {
namespace internal {
/************************************************
* Declaration: struct map_traits<K, T, C>
************************************************/
template <typename Key, typename T, typename Compare = std::less<Key>>
struct map_traits {
public: // Public Type(s)
using key_type = Key;
using mapped_type = T;
using value_type = std::pair<key_type const, mapped_type>;
using key_compare = Compare;
class value_compare : protected key_compare {
protected: // Protected Method(s)
explicit value_compare(key_compare comp)
: key_compare(comp)
{ /* do nothing */ }
public: // Public Method(s)
bool operator()(value_type const& lhs, value_type const& rhs) const {
return key_compare::operator()(lhs.first, rhs.first);
}
};
protected: // Protected Type(s)
class core_compare {
public: // Public Method(s)
explicit core_compare(key_compare comp)
: comp_(comp)
{ /* do nothing */ }
template <typename K>
bool operator()(K const& lhs, value_type const& rhs) const {
return comp_(lhs, rhs.first);
}
template <typename K>
bool operator()(value_type const& lhs, K const& rhs) const {
return comp_(lhs.first, rhs);
}
private: // Private Method(s)
key_compare const& comp_;
};
};
} // namespace internal
} // namespace bptree
#endif // BPTREE_INTERNAL_MAP_TRAITS_HPP_
| 26.183099
| 77
| 0.56213
|
jason2506
|
c9f05ef3dbf4d1636a8b3ba4790e0e5ac37adc73
| 1,030
|
cpp
|
C++
|
Source/Rotary_Slider.cpp
|
Silver92/My-Delay
|
96afc7eab81d11c7b59b6a270c40741124afa9db
|
[
"MIT"
] | null | null | null |
Source/Rotary_Slider.cpp
|
Silver92/My-Delay
|
96afc7eab81d11c7b59b6a270c40741124afa9db
|
[
"MIT"
] | null | null | null |
Source/Rotary_Slider.cpp
|
Silver92/My-Delay
|
96afc7eab81d11c7b59b6a270c40741124afa9db
|
[
"MIT"
] | null | null | null |
/*
==============================================================================
Slider.cpp
Created: 6 Sep 2019 7:11:44am
Author: Silver
==============================================================================
*/
#include "Rotary_Slider.h"
#include "UIDemensions.h"
RotarySlider::RotarySlider(AudioProcessorValueTreeState& stateToControl,
int parameterName)
: juce::Slider(ParameterLabel[parameterName])
{
setSliderStyle(SliderStyle::RotaryHorizontalVerticalDrag);
setTextBoxStyle(Slider::NoTextBox, false, SLIDER_SIZE, SLIDER_SIZE / 3);
setRange(0.0f, 1.0f, 0.001f);
mAttachment.reset(
new AudioProcessorValueTreeState::SliderAttachment(stateToControl,
ParameterID[parameterName],
*this));
}
RotarySlider::~RotarySlider()
{
}
void RotarySlider::setInterval()
{
setRange(0.0f, 1.0f, 1.f/ 13.f);
}
| 28.611111
| 83
| 0.493204
|
Silver92
|
c9f836d17615390c1da31bb2e36b20ffc1cfaf1e
| 2,437
|
cpp
|
C++
|
export/release/windows/obj/src/webm/WebmEvent.cpp
|
bobisdabbing/Vs-The-United-Lands-stable
|
0807e58b6d8ad1440bdd350bf006b37a1b7ca9b5
|
[
"MIT"
] | null | null | null |
export/release/windows/obj/src/webm/WebmEvent.cpp
|
bobisdabbing/Vs-The-United-Lands-stable
|
0807e58b6d8ad1440bdd350bf006b37a1b7ca9b5
|
[
"MIT"
] | null | null | null |
export/release/windows/obj/src/webm/WebmEvent.cpp
|
bobisdabbing/Vs-The-United-Lands-stable
|
0807e58b6d8ad1440bdd350bf006b37a1b7ca9b5
|
[
"MIT"
] | null | null | null |
// Generated by Haxe 4.1.5
#include <hxcpp.h>
#ifndef INCLUDED_openfl_events_Event
#include <openfl/events/Event.h>
#endif
#ifndef INCLUDED_webm_WebmEvent
#include <webm/WebmEvent.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_a611475ca79daef8_14_new,"webm.WebmEvent","new",0x3feaff7e,"webm.WebmEvent.new","webm/WebmEvent.hx",14,0x67547733)
namespace webm{
void WebmEvent_obj::__construct(::String type,::hx::Null< bool > __o_bubbles,::hx::Null< bool > __o_cancelable){
bool bubbles = __o_bubbles.Default(false);
bool cancelable = __o_cancelable.Default(false);
HX_STACKFRAME(&_hx_pos_a611475ca79daef8_14_new)
HXDLIN( 14) super::__construct(type,bubbles,cancelable);
}
Dynamic WebmEvent_obj::__CreateEmpty() { return new WebmEvent_obj; }
void *WebmEvent_obj::_hx_vtable = 0;
Dynamic WebmEvent_obj::__Create(::hx::DynamicArray inArgs)
{
::hx::ObjectPtr< WebmEvent_obj > _hx_result = new WebmEvent_obj();
_hx_result->__construct(inArgs[0],inArgs[1],inArgs[2]);
return _hx_result;
}
bool WebmEvent_obj::_hx_isInstanceOf(int inClassId) {
if (inClassId<=(int)0x08ec4c31) {
return inClassId==(int)0x00000001 || inClassId==(int)0x08ec4c31;
} else {
return inClassId==(int)0x1af6f1a8;
}
}
WebmEvent_obj::WebmEvent_obj()
{
}
#ifdef HXCPP_SCRIPTABLE
static ::hx::StorageInfo *WebmEvent_obj_sMemberStorageInfo = 0;
static ::hx::StaticInfo *WebmEvent_obj_sStaticStorageInfo = 0;
#endif
::hx::Class WebmEvent_obj::__mClass;
void WebmEvent_obj::__register()
{
WebmEvent_obj _hx_dummy;
WebmEvent_obj::_hx_vtable = *(void **)&_hx_dummy;
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("webm.WebmEvent",8c,28,e2,64);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField;
__mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = ::hx::Class_obj::dupFunctions(0 /* sMemberFields */);
__mClass->mCanCast = ::hx::TCanCast< WebmEvent_obj >;
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = WebmEvent_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = WebmEvent_obj_sStaticStorageInfo;
#endif
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace webm
| 32.065789
| 143
| 0.74682
|
bobisdabbing
|
c9fb517c3105e4973b205960ccaff1c3bb645f86
| 5,439
|
cpp
|
C++
|
src/SpotLight.cpp
|
lemurni/Engine186-Linux
|
2c1569aecee76974078ffba1df2ac38e6b3f9238
|
[
"CC0-1.0"
] | 3
|
2020-03-10T16:41:41.000Z
|
2021-12-13T11:36:12.000Z
|
src/SpotLight.cpp
|
lemurni/Engine186-Linux
|
2c1569aecee76974078ffba1df2ac38e6b3f9238
|
[
"CC0-1.0"
] | null | null | null |
src/SpotLight.cpp
|
lemurni/Engine186-Linux
|
2c1569aecee76974078ffba1df2ac38e6b3f9238
|
[
"CC0-1.0"
] | 1
|
2021-10-20T02:18:38.000Z
|
2021-10-20T02:18:38.000Z
|
#include "SpotLight.h"
namespace e186
{
const float SpotLight::k_max_outer_angle = glm::pi<float>() - 0.4f;
SpotLight::SpotLight(const glm::vec3& color, const glm::vec3& position, const glm::vec3& direction)
: m_position(position),
m_direction(glm::normalize(direction)),
m_light_color(color),
m_attenuation(1.0f, 0.1f, 0.01f, 0.0f),
m_outer_angle(glm::half_pi<float>()),
m_inner_angle(0.0f),
m_falloff(1.0f),
m_enabled{ true }
{
}
SpotLight::SpotLight(const glm::vec3& color, const glm::vec3& position, const glm::vec3& direction,
float const_atten, float lin_atten, float quad_atten, float cub_atten,
float outer_angle, float inner_angle, float falloff)
: m_position(position),
m_direction(glm::normalize(direction)),
m_light_color(color),
m_attenuation(const_atten, lin_atten, quad_atten, cub_atten),
m_outer_angle(outer_angle),
m_inner_angle(inner_angle),
m_falloff(falloff),
m_enabled{ true }
{
}
SpotLight::SpotLight(const glm::vec3& color, const glm::vec3& position, const glm::vec3& direction,
const glm::vec4& attenuation, float outer_angle, float inner_angle, float falloff)
: m_position(position),
m_direction(glm::normalize(direction)),
m_light_color(color),
m_attenuation(attenuation),
m_outer_angle(outer_angle),
m_inner_angle(inner_angle),
m_falloff(falloff),
m_enabled{ true }
{
}
SpotLight::SpotLight(const glm::vec3& color, Transform transform,
float const_atten, float lin_atten, float quad_atten, float cub_atten,
float outer_angle, float inner_angle, float falloff)
: m_position(transform.GetPosition()),
m_direction(transform.GetFrontVector()),
m_light_color(color),
m_attenuation(const_atten, lin_atten, quad_atten, cub_atten),
m_outer_angle(outer_angle),
m_inner_angle(inner_angle),
m_falloff(falloff),
m_enabled{ true }
{
}
SpotLight::~SpotLight()
{
}
void SpotLight::set_position(glm::vec3 position)
{
m_position = std::move(position);
}
void SpotLight::set_direction(glm::vec3 direction)
{
m_direction = std::move(glm::normalize(direction));
}
void SpotLight::set_light_color(glm::vec3 color)
{
m_light_color = std::move(color);
}
void SpotLight::set_attenuation(glm::vec4 attenuation)
{
m_attenuation = std::move(attenuation);
}
void SpotLight::set_const_attenuation(float attenuation)
{
m_attenuation = glm::vec4(attenuation, m_attenuation[1], m_attenuation[2], m_attenuation[3]);
}
void SpotLight::set_linear_attenuation(float attenuation)
{
m_attenuation = glm::vec4(m_attenuation[0], attenuation, m_attenuation[2], m_attenuation[3]);
}
void SpotLight::set_quadratic_attenuation(float attenuation)
{
m_attenuation = glm::vec4(m_attenuation[0], m_attenuation[1], attenuation, m_attenuation[3]);
}
void SpotLight::set_cubic_attenuation(float attenuation)
{
m_attenuation = glm::vec4(m_attenuation[0], m_attenuation[1], m_attenuation[2], attenuation);
}
void SpotLight::set_outer_angle(float outer_angle)
{
m_outer_angle = outer_angle;
m_outer_angle = glm::clamp(m_outer_angle, 0.0f, k_max_outer_angle);
m_inner_angle = glm::min(m_inner_angle, m_outer_angle);
}
void SpotLight::set_inner_angle(float inner_angle)
{
m_inner_angle = inner_angle;
m_inner_angle = glm::clamp(m_inner_angle, 0.0f, m_outer_angle);
}
void SpotLight::set_falloff(float falloff)
{
m_falloff = falloff;
}
void SpotLight::set_enabled(bool is_enabled)
{
m_enabled = is_enabled;
}
SpotLightGpuData SpotLight::GetGpuData() const
{
SpotLightGpuData gdata;
FillGpuDataIntoTarget(gdata);
return gdata;
}
SpotLightGpuData SpotLight::GetGpuData(const glm::mat4& mat) const
{
SpotLightGpuData gdata;
FillGpuDataIntoTarget(gdata, mat);
return gdata;
}
void SpotLight::FillGpuDataIntoTarget(SpotLightGpuData& target) const
{
if (m_enabled)
{
target.m_position_and_cos_outer_angle_half = glm::vec4(m_position, glm::cos(m_outer_angle / 2.0f));
target.m_direction_and_cos_inner_angle_half = glm::vec4(m_direction, glm::cos(m_inner_angle / 2.0f));
target.m_light_color_and_falloff = glm::vec4(m_light_color, m_falloff);
target.m_attenuation = m_attenuation;
}
else
{
target.m_position_and_cos_outer_angle_half = glm::vec4(0.0f);
target.m_direction_and_cos_inner_angle_half = glm::vec4(0.0f);
target.m_light_color_and_falloff = glm::vec4(0.0f);
target.m_attenuation = glm::vec4(1.0f);
}
}
void SpotLight::FillGpuDataIntoTarget(SpotLightGpuData& target, const glm::mat4& mat) const
{
if (m_enabled)
{
target.m_position_and_cos_outer_angle_half = mat * glm::vec4(m_position, 1.0f);
target.m_position_and_cos_outer_angle_half.w = glm::cos(m_outer_angle / 2.0f);
target.m_direction_and_cos_inner_angle_half = glm::vec4(glm::mat3(mat) * m_direction, glm::cos(m_inner_angle / 2.0f));
target.m_light_color_and_falloff = glm::vec4(m_light_color, m_falloff);
target.m_attenuation = m_attenuation;
}
else
{
target.m_position_and_cos_outer_angle_half = glm::vec4(0.0f);
target.m_direction_and_cos_inner_angle_half = glm::vec4(0.0f);
target.m_light_color_and_falloff = glm::vec4(0.0f);
target.m_attenuation = glm::vec4(1.0f);
}
}
SpotLight::operator SpotLightGpuData() const
{
return GetGpuData();
}
}
| 29.721311
| 122
| 0.720169
|
lemurni
|
c9fceef901b20ec1fb7883d7985fb2b7bb9020f2
| 360
|
cpp
|
C++
|
src/triangulo.cpp
|
Italo1994/Laboratorio2-IMD0030
|
ebe3df127ec78914d2feca77f92bf398e61c023c
|
[
"MIT"
] | null | null | null |
src/triangulo.cpp
|
Italo1994/Laboratorio2-IMD0030
|
ebe3df127ec78914d2feca77f92bf398e61c023c
|
[
"MIT"
] | null | null | null |
src/triangulo.cpp
|
Italo1994/Laboratorio2-IMD0030
|
ebe3df127ec78914d2feca77f92bf398e61c023c
|
[
"MIT"
] | null | null | null |
#include "triangulo.h"
Triangulo::Triangulo(int b, int a, int l1, int l2, int l3): base (b), altura(a), lado1(l1), lado2(l2), lado3(l3) {
area = (base * altura) / 2;
perimetro = lado1 + lado2 + lado3;
}
Triangulo::~Triangulo(){
}
int Triangulo::getAreaTriangulo(){
return area;
}
int Triangulo::getPerimetroTriangulo(){
return perimetro;
}
| 20
| 115
| 0.65
|
Italo1994
|
c9fcf751bcf9da261f8b409fd9bc9e802f0eabb5
| 15,449
|
cpp
|
C++
|
windows/wrapper/impl_org_webRtc_WebRtcFactory.cpp
|
tallestorange/webrtc-apis
|
e3b06e3f1d3cbe7fdcbffa026d6e0fd4f6dd5efd
|
[
"BSD-3-Clause"
] | null | null | null |
windows/wrapper/impl_org_webRtc_WebRtcFactory.cpp
|
tallestorange/webrtc-apis
|
e3b06e3f1d3cbe7fdcbffa026d6e0fd4f6dd5efd
|
[
"BSD-3-Clause"
] | null | null | null |
windows/wrapper/impl_org_webRtc_WebRtcFactory.cpp
|
tallestorange/webrtc-apis
|
e3b06e3f1d3cbe7fdcbffa026d6e0fd4f6dd5efd
|
[
"BSD-3-Clause"
] | null | null | null |
#include "impl_org_webRtc_WebRtcFactory.h"
#include "impl_org_webRtc_WebRtcFactoryConfiguration.h"
#include "impl_org_webRtc_WebRtcLib.h"
#include "impl_org_webRtc_AudioBufferEvent.h"
#include "impl_org_webRtc_AudioProcessingInitializeEvent.h"
#include "impl_org_webRtc_AudioProcessingRuntimeSettingEvent.h"
#include "impl_org_webRtc_helpers.h"
#include "impl_webrtc_IAudioDeviceWasapi.h"
#include "impl_org_webRtc_pre_include.h"
#include "api/audio_codecs/builtin_audio_decoder_factory.h"
#include "api/audio_codecs/builtin_audio_encoder_factory.h"
#include "api/peerconnectioninterface.h"
#include "api/peerconnectionfactoryproxy.h"
#include "api/test/fakeconstraints.h"
#include "rtc_base/event_tracer.h"
#include "third_party/winuwp_h264/winuwp_h264_factory.h"
#include "media/engine/webrtcvideocapturerfactory.h"
#include "pc/peerconnectionfactory.h"
#include "modules/audio_device/include/audio_device.h"
#include "impl_org_webRtc_post_include.h"
#include <zsLib/eventing/IHelper.h>
#include <zsLib/SafeInt.h>
using ::zsLib::String;
using ::zsLib::Optional;
using ::zsLib::Any;
using ::zsLib::AnyPtr;
using ::zsLib::AnyHolder;
using ::zsLib::Promise;
using ::zsLib::PromisePtr;
using ::zsLib::PromiseWithHolder;
using ::zsLib::PromiseWithHolderPtr;
using ::zsLib::eventing::SecureByteBlock;
using ::zsLib::eventing::SecureByteBlockPtr;
using ::std::shared_ptr;
using ::std::weak_ptr;
using ::std::make_shared;
using ::std::list;
using ::std::set;
using ::std::map;
// borrow definitions from class
ZS_DECLARE_TYPEDEF_PTR(wrapper::impl::org::webRtc::WebRtcFactory::WrapperImplType, WrapperImplType);
ZS_DECLARE_TYPEDEF_PTR(WrapperImplType::WrapperType, WrapperType);
ZS_DECLARE_TYPEDEF_PTR(wrapper::impl::org::webRtc::WebRtcLib, UseWebRtcLib);
ZS_DECLARE_TYPEDEF_PTR(wrapper::impl::org::webRtc::WebRtcFactoryConfiguration, UseFactoryConfiguration);
typedef WrapperImplType::PeerConnectionFactoryInterfaceScopedPtr PeerConnectionFactoryInterfaceScopedPtr;
typedef WrapperImplType::PeerConnectionFactoryScopedPtr PeerConnectionFactoryScopedPtr;
ZS_DECLARE_TYPEDEF_PTR(::webrtc::PeerConnectionFactory, NativePeerConnectionFactory)
ZS_DECLARE_TYPEDEF_PTR(::webrtc::PeerConnectionFactoryInterface, NativePeerConnectionFactoryInterface)
ZS_DECLARE_TYPEDEF_PTR(WrapperImplType::UseVideoDeviceCaptureFacrtory, UseVideoDeviceCaptureFacrtory);
ZS_DECLARE_TYPEDEF_PTR(::cricket::WebRtcVideoDeviceCapturerFactory, UseWebrtcVideoDeviceCaptureFacrtory);
ZS_DECLARE_TYPEDEF_PTR(WrapperImplType::UseAudioBufferEvent, UseAudioBufferEvent);
ZS_DECLARE_TYPEDEF_PTR(WrapperImplType::UseAudioInitEvent, UseAudioInitEvent);
ZS_DECLARE_TYPEDEF_PTR(WrapperImplType::UseAudioRuntimeEvent, UseAudioRuntimeEvent);
namespace wrapper { namespace impl { namespace org { namespace webRtc { ZS_DECLARE_SUBSYSTEM(wrapper_org_webRtc); } } } }
//------------------------------------------------------------------------------
WrapperImplType::WebrtcObserver::WebrtcObserver(
WrapperImplTypePtr wrapper,
zsLib::IMessageQueuePtr queue,
std::function<void(UseAudioBufferEventPtr)> bufferEvent,
std::function<void(UseAudioInitEventPtr)> initEvent,
std::function<void(UseAudioRuntimeEventPtr)> runtimeEvent
) noexcept :
outer_(wrapper),
queue_(queue),
bufferEvent_(std::move(bufferEvent)),
initEvent_(std::move(initEvent)),
runtimeEvent_(std::move(runtimeEvent))
{
}
//------------------------------------------------------------------------------
void WrapperImplType::WebrtcObserver::Initialize(int sample_rate_hz, int num_channels)
{
if (!enabled_) return;
auto outer = outer_.lock();
if (!outer) return;
WebrtcObserver *pThis = this;
HANDLE handle = ::CreateEventEx(NULL, NULL, 0, EVENT_ALL_ACCESS);
std::function<void(void)> callback = [handle]() { ::SetEvent(handle); };
auto event = UseAudioInitEvent::toWrapper(std::move(callback), SafeInt<size_t>(sample_rate_hz), SafeInt<size_t>(num_channels));
queue_->postClosure([outer, event, pThis]() { pThis->initEvent_(event); });
event.reset();
::WaitForSingleObjectEx(handle, INFINITE, FALSE /* ALERTABLE */);
::CloseHandle(handle);
}
//------------------------------------------------------------------------------
void WrapperImplType::WebrtcObserver::Process(NativeAudioBufferType* audio)
{
if (!enabled_) return;
auto outer = outer_.lock();
if (!outer) return;
WebrtcObserver *pThis = this;
HANDLE handle = ::CreateEventEx(NULL, NULL, 0, EVENT_ALL_ACCESS);
std::function<void(void)> callback = [handle]() { ::SetEvent(handle); };
auto event = UseAudioBufferEvent::toWrapper(std::move(callback), audio);
queue_->postClosure([outer, event, pThis]() { pThis->bufferEvent_(event); });
event.reset();
::WaitForSingleObjectEx(handle, INFINITE, FALSE /* ALERTABLE */);
::CloseHandle(handle);
}
//------------------------------------------------------------------------------
std::string WrapperImplType::WebrtcObserver::ToString() const
{
return "WrapperImplType::WebrtcObserver";
}
//------------------------------------------------------------------------------
void WrapperImplType::WebrtcObserver::SetRuntimeSetting(::webrtc::AudioProcessing::RuntimeSetting setting)
{
if (!enabled_) return;
auto outer = outer_.lock();
if (!outer) return;
WebrtcObserver *pThis = this;
HANDLE handle = ::CreateEventEx(NULL, NULL, 0, EVENT_ALL_ACCESS);
std::function<void(void)> callback = [handle]() { ::SetEvent(handle); };
auto event = UseAudioRuntimeEvent::toWrapper(std::move(callback), setting);
queue_->postClosure([outer, event, pThis]() { pThis->runtimeEvent_(event); });
event.reset();
::WaitForSingleObjectEx(handle, INFINITE, FALSE /* ALERTABLE */);
::CloseHandle(handle);
}
//------------------------------------------------------------------------------
NativePeerConnectionFactoryInterface *unproxy(NativePeerConnectionFactoryInterface *native)
{
if (!native) return native;
return WRAPPER_DEPROXIFY_CLASS(::webrtc::PeerConnectionFactory, ::webrtc::PeerConnectionFactory, native);
}
//------------------------------------------------------------------------------
wrapper::impl::org::webRtc::WebRtcFactory::WebRtcFactory() noexcept
{
}
//------------------------------------------------------------------------------
wrapper::org::webRtc::WebRtcFactoryPtr wrapper::org::webRtc::WebRtcFactory::wrapper_create() noexcept
{
auto pThis = make_shared<wrapper::impl::org::webRtc::WebRtcFactory>();
pThis->thisWeak_ = pThis;
return pThis;
}
//------------------------------------------------------------------------------
wrapper::impl::org::webRtc::WebRtcFactory::~WebRtcFactory() noexcept
{
thisWeak_.reset();
wrapper_dispose();
}
//------------------------------------------------------------------------------
void wrapper::impl::org::webRtc::WebRtcFactory::wrapper_dispose() noexcept
{
zsLib::AutoRecursiveLock lock(lock_);
if (!peerConnectionFactory_) return;
// Peer connection factory holds ownership of these objects so the observers
// are no longer accessible.
audioPostCapture_ = NULL;
audioPreRender_ = NULL;
// reset the factory (cannot be used anymore)...
peerConnectionFactory_ = PeerConnectionFactoryInterfaceScopedPtr();
videoDeviceCaptureFactory_.reset();
#pragma ZS_BUILD_NOTE("TODO","(mosa) shutdown threads need something more?")
networkThread.reset();
workerThread.reset();
signalingThread.reset();
configuration_.reset();
audioPostCaptureInit_.reset();
audioPreRenderInit_.reset();
}
//------------------------------------------------------------------------------
void wrapper::impl::org::webRtc::WebRtcFactory::wrapper_init_org_webRtc_WebRtcFactory(wrapper::org::webRtc::WebRtcFactoryConfigurationPtr inConfiguration) noexcept
{
configuration_ = UseFactoryConfiguration::clone(inConfiguration);
audioPostCaptureInit_ = std::make_unique<WebrtcObserver>(
thisWeak_.lock(),
UseWebRtcLib::audioCaptureFrameProcessingQueue(),
[this](UseAudioBufferEventPtr event) { this->onAudioPostCapture_Process(std::move(event)); },
[this](UseAudioInitEventPtr event) { this->onAudioPostCapture_Init(std::move(event)); },
[this](UseAudioRuntimeEventPtr event) { this->onAudioPostCapture_SetRuntimeSetting(std::move(event)); }
);
audioPreRenderInit_ = std::make_unique<WebrtcObserver>(
thisWeak_.lock(),
UseWebRtcLib::audioRenderFrameProcessingQueue(),
[this](UseAudioBufferEventPtr event) { this->onAudioPreRender_Process(std::move(event)); },
[this](UseAudioInitEventPtr event) { this->onAudioPreRender_Init(std::move(event)); },
[this](UseAudioRuntimeEventPtr event) { this->onAudioPreRender_SetRuntimeSetting(std::move(event)); }
);
audioPostCapture_ = audioPostCaptureInit_.get();
audioPreRender_ = audioPreRenderInit_.get();
}
//------------------------------------------------------------------------------
void wrapper::impl::org::webRtc::WebRtcFactory::wrapper_onObserverCountChanged(size_t count) noexcept
{
zsLib::AutoRecursiveLock lock(lock_);
if ((NULL == audioPostCapture_) ||
(NULL == audioPreRender_))
return;
if ((configuration_) &&
(count > 0)) {
configuration_->enableAudioBufferEvents = true;
}
audioPostCapture_->enabled(count > 0);
audioPreRender_->enabled(count > 0);
}
//------------------------------------------------------------------------------
PeerConnectionFactoryInterfaceScopedPtr WrapperImplType::peerConnectionFactory() noexcept
{
zsLib::AutoRecursiveLock lock(lock_);
setup();
return peerConnectionFactory_;
}
//------------------------------------------------------------------------------
PeerConnectionFactoryScopedPtr WrapperImplType::realPeerConnectionFactory() noexcept
{
zsLib::AutoRecursiveLock lock(lock_);
setup();
auto realInterface = unproxy(peerConnectionFactory_);
return dynamic_cast<NativePeerConnectionFactory *>(realInterface);
}
//------------------------------------------------------------------------------
UseVideoDeviceCaptureFacrtoryPtr WrapperImplType::videoDeviceCaptureFactory() noexcept
{
zsLib::AutoRecursiveLock lock(lock_);
setup();
return videoDeviceCaptureFactory_;
}
//------------------------------------------------------------------------------
void WrapperImplType::onAudioPostCapture_Init(UseAudioInitEventPtr event)
{
onAudioPostCaptureInitialize(std::move(event));
}
//------------------------------------------------------------------------------
void WrapperImplType::onAudioPostCapture_SetRuntimeSetting(UseAudioRuntimeEventPtr event)
{
onAudioPostCaptureRuntimeSetting(std::move(event));
}
//------------------------------------------------------------------------------
void WrapperImplType::onAudioPostCapture_Process(UseAudioBufferEventPtr event)
{
onAudioPostCapture(std::move(event));
}
//------------------------------------------------------------------------------
void WrapperImplType::onAudioPreRender_Init(UseAudioInitEventPtr event)
{
onAudioPreRenderInitialize(std::move(event));
}
//------------------------------------------------------------------------------
void WrapperImplType::onAudioPreRender_SetRuntimeSetting(UseAudioRuntimeEventPtr event)
{
onAudioPreRenderRuntimeSetting(std::move(event));
}
//------------------------------------------------------------------------------
void WrapperImplType::onAudioPreRender_Process(UseAudioBufferEventPtr event)
{
onAudioPreRender(std::move(event));
}
//------------------------------------------------------------------------------
void WrapperImplType::setup() noexcept
{
zsLib::AutoRecursiveLock lock(lock_);
// already setup?
if ((!audioPostCaptureInit_) ||
(!audioPreRenderInit_))
return;
bool audioCapturingEnabled = configuration_ ? configuration_->audioCapturingEnabled : true;
bool audioRenderingEnabled = configuration_ ? configuration_->audioRenderingEnabled : true;
String audioCaptureDeviceId = configuration_ ? configuration_->audioCaptureDeviceId : String();
String audioRenderDeviceId = configuration_ ? configuration_->audioRenderDeviceId : String();
bool enableAudioProcessingEvents = configuration_ ? configuration_->enableAudioBufferEvents : false;
networkThread = rtc::Thread::CreateWithSocketServer();
networkThread->Start();
workerThread = rtc::Thread::Create();
workerThread->Start();
signalingThread = rtc::Thread::Create();
signalingThread->Start();
auto encoderFactory = new ::webrtc::WinUWPH264EncoderFactory();
auto decoderFactory = new ::webrtc::WinUWPH264DecoderFactory();
rtc::scoped_refptr<::webrtc::AudioDeviceModule> audioDeviceModule;
audioDeviceModule = workerThread->Invoke<rtc::scoped_refptr<::webrtc::AudioDeviceModule>>(
RTC_FROM_HERE, [audioCapturingEnabled, audioRenderingEnabled]() {
webrtc::IAudioDeviceWasapi::CreationProperties props;
props.id_ = "";
props.playoutEnabled_ = audioRenderingEnabled;
props.recordingEnabled_ = audioCapturingEnabled;
return rtc::scoped_refptr<::webrtc::AudioDeviceModule>(webrtc::IAudioDeviceWasapi::create(props));
});
if (audioCaptureDeviceId.size() != 0) {
int deviceCount = audioDeviceModule->RecordingDevices();
char deviceName[::webrtc::kAdmMaxDeviceNameSize];
char deviceId[::webrtc::kAdmMaxGuidSize];
uint16_t deviceIndex = USHRT_MAX;
for (uint16_t i = 0; i < deviceCount; i++) {
audioDeviceModule->RecordingDeviceName(i, deviceName, deviceId);
if (strcmp(audioCaptureDeviceId.c_str(), deviceId) == 0) {
deviceIndex = i;
break;
}
}
if (deviceIndex != USHRT_MAX)
audioDeviceModule->SetRecordingDevice(deviceIndex);
}
if (audioRenderDeviceId.size() != 0) {
int deviceCount = audioDeviceModule->PlayoutDevices();
char deviceName[::webrtc::kAdmMaxDeviceNameSize];
char deviceId[::webrtc::kAdmMaxGuidSize];
uint16_t deviceIndex = USHRT_MAX;
for (uint16_t i = 0; i < deviceCount; i++) {
audioDeviceModule->PlayoutDeviceName(i, deviceName, deviceId);
if (strcmp(audioRenderDeviceId.c_str(), deviceId) == 0) {
deviceIndex = i;
break;
}
}
if (deviceIndex != USHRT_MAX)
audioDeviceModule->SetPlayoutDevice(deviceIndex);
}
rtc::scoped_refptr<::webrtc::AudioProcessing> audioProcessing;
if (enableAudioProcessingEvents)
audioProcessing = rtc::scoped_refptr<::webrtc::AudioProcessing>{::webrtc::AudioProcessingBuilder().SetCapturePostProcessing(std::move(audioPostCaptureInit_)).SetRenderPreProcessing(std::move(audioPreRenderInit_)).Create() };
audioPostCaptureInit_.reset();
audioPreRenderInit_.reset();
peerConnectionFactory_ = ::webrtc::CreatePeerConnectionFactory(
networkThread.get(),
workerThread.get(),
signalingThread.get(),
audioDeviceModule.release(),
::webrtc::CreateBuiltinAudioEncoderFactory(),
::webrtc::CreateBuiltinAudioDecoderFactory(),
encoderFactory,
decoderFactory,
nullptr,
enableAudioProcessingEvents ? audioProcessing : nullptr
);
#ifdef _WIN32
videoDeviceCaptureFactory_ = make_shared<::cricket::WebRtcVideoDeviceCapturerFactory>();
#else
#error PLATFORM REQUIRES FACTORY
#endif //_WIN32
}
//------------------------------------------------------------------------------
WrapperImplTypePtr WrapperImplType::toWrapper(WrapperTypePtr wrapper) noexcept
{
if (!wrapper) return WrapperImplTypePtr();
auto converted = ZS_DYNAMIC_PTR_CAST(WrapperImplType, wrapper);
return converted;
}
| 36.609005
| 228
| 0.677131
|
tallestorange
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.